@mindconnect/mindconnect-nodejs
Version:
MindConnect Library for NodeJS (community based)
90 lines • 5.6 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const console_1 = require("console");
const fs = require("fs");
const path = require("path");
const util = require("util");
const sdk_1 = require("../../api/sdk/");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
const ora = require("ora");
const streamPipeline = util.promisify(require("stream").pipeline);
const color = command_utils_1.getColor("magenta");
exports.default = (program) => {
program
.command("download-file")
.alias("df")
.option("-f, --file <fileToDownload>", "file to download from the file service")
.option("-h, --filepath [filepath]", "file path in the mindsphere", "")
.option("-i, --assetid <assetid>", "asset id from the mindsphere")
.option("-p, --passkey <passkey>", `passkey`)
.option("-y, --retry <number>", "retry attempts before giving up", 3)
.option("-v, --verbose", "verbose output")
.description(`${color("download the file from mindsphere file service *")}`)
.action(options => {
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
checkParameters(options);
const auth = utils_1.loadAuth();
const sdk = new sdk_1.MindSphereSdk({
gateway: auth.gateway,
basicAuth: utils_1.decrypt(auth, options.passkey),
tenant: auth.tenant
});
const iotFileClient = sdk.GetIoTFileClient();
let fullpath = options.filepath ? `${options.filepath}/${options.file}` : `${options.file}`;
fullpath = fullpath.replace("//", "/");
let filter = `name eq ${path.basename(fullpath)}`;
if (path.dirname(fullpath) !== ".")
filter += ` and path eq ${path.dirname(fullpath)}/`;
const fileInfo = yield iotFileClient.GetFiles(options.assetid, {
filter: filter
});
fileInfo.length !== 1 &&
command_utils_1.errorLog(`There were ${color(fileInfo.length)} files found with that name and path.`, true);
const spinner = ora("downloading file");
!options.verbose && spinner.start();
command_utils_1.verboseLog(JSON.stringify(fileInfo, null, 2), options.verbose);
command_utils_1.verboseLog(`Downloading file ${color(fileInfo[0].name)} with size of ${color(command_utils_1.humanFileSize(fileInfo[0].size || 0))} from MindSphere.`, options.verbose, spinner);
const startDate = new Date();
const download = yield utils_1.retry(options.retry, () => iotFileClient.GetFile(options.assetid, fullpath));
!download.ok && utils_1.throwError(`Unexpected response ${download.statusText}`);
const outputfile = fileInfo[0].name || "output.bin";
const file = fs.createWriteStream(outputfile);
yield streamPipeline(download.body, file);
const endDate = new Date();
!options.verbose && spinner.succeed("Done");
const hash = yield utils_1.checksumFile("md5", outputfile);
console_1.log(`Download time: ${(endDate.getTime() - startDate.getTime()) / 1000} seconds`);
console_1.log(`\nYour file ${color(outputfile)} with md5 hash ${hash} was successfully downloaded`);
}
catch (err) {
command_utils_1.errorLog(err, options.verbose);
}
}))();
})
.on("--help", () => {
console_1.log("\n Examples:\n");
console_1.log(` mc download-file -f CHANGELOG.md --assetid 5..f \t\t\t\t download file ${color("CHANGELOG.md")} from specified asset`);
console_1.log(` mc download-file --file CHANGELOG.md --assetid 5...f --filepath upload \t download file ${color("upload/CHANGELOG.md")} from specified asset`);
console_1.log(` mc download-file --file upload/CHANGELOG.md --assetid 5...f \t\t download file ${color("upload/CHANGELOG.md")} from specified asset`);
command_utils_1.serviceCredentialLog();
});
};
function checkParameters(options) {
!options.passkey &&
command_utils_1.errorLog("you have to provide a passkey to get the service token (run mc df --help for full description)", true);
!options.file &&
command_utils_1.errorLog("Missing file name for download-file command. Run mc df --help for full syntax and examples.", true);
!options.assetid && command_utils_1.errorLog(" You have to specify assetid. Run mc df --help for full syntax and examples.", true);
}
//# sourceMappingURL=mc-download-file.js.map