UNPKG

@mindconnect/mindconnect-nodejs

Version:

MindConnect Library for NodeJS (community based)

146 lines 8.62 kB
"use strict"; 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 __1 = require("../.."); const sdk_1 = require("../../api/sdk"); const utils_1 = require("../../api/utils"); const command_utils_1 = require("./command-utils"); const ora = require("ora"); const mime = require("mime-types"); let color = command_utils_1.getColor("cyan"); const adminColor = command_utils_1.getColor("magenta"); exports.default = (program) => { program .command("upload-file") .alias("uf") .option("-c, --config <agentconfig>", "config file with agent configuration", "agentconfig.json") .option("-r, --cert [privatekey]", "required for agents with RSA_3072 profile. create with: openssl genrsa -out private.key 3072") .option("-f, --file <fileToUpload>", "file to upload to the file service") .option("-h, --filepath <filepath>", "file path in the mindsphere") .option("-l, --parallel <number>", "parallel chunk uploads", 3) .option("-i, --assetid [assetid]", "asset id from the mindsphere (default: upload to the agent)") .option("-m, --mime [mime-type]", "mime type of the file (default: automatic recognition)") .option("-d, --desc [description]", "description") .option("-k, --chunked", "Use chunked upload") .option("-y, --retry <number>", "retry attempts before giving up", 3) .option("-p, --passkey <passkey>", `passkey (optional, file upload uses ${adminColor("service credentials *")})`) .option("-v, --verbose", "verbose output") .description(`${color("upload the file to the mindsphere file service")} ${adminColor("(optional: passkey) *")}`) .action(options => { (() => __awaiter(void 0, void 0, void 0, function* () { try { color = options.passkey ? adminColor : color; checkParameters(options); command_utils_1.homeDirLog(options.verbose, color); command_utils_1.proxyLog(options.verbose, color); const spinner = ora("uploadingFile"); !options.verbose && spinner.start(); const uploadFile = path.resolve(options.file); command_utils_1.verboseLog(`File to upload: ${color(uploadFile)}.`, options.verbose, spinner); if (!fs.existsSync(uploadFile)) { throw new Error(`Can't find file ${uploadFile}`); } let uploader; let assetid = options.assetid; const chunked = options.chunked ? true : false; if (options.passkey === undefined) { ({ assetid, uploader } = yield getMindConnectAgent(assetid, options, spinner, color)); } else { uploader = getIotFileUploader(options); } const mimeType = options.mime || mime.lookup(uploadFile) || "application/octet-stream"; const description = options.desc || `File uploaded on ${new Date().toUTCString()} using mindconnect CLI`; if (!fs.existsSync(uploadFile)) { throw new Error(`Can't find file ${uploadFile}`); } command_utils_1.verboseLog(`Uploading the file: ${color(uploadFile)} with mime type ${mimeType}.`, options.verbose, spinner); command_utils_1.verboseLog(`Description ${description}`, options.verbose, spinner); command_utils_1.verboseLog(`AssetId ${assetid}`, options.verbose, spinner); command_utils_1.verboseLog(options.assetid === undefined ? "Uploading to agent." : "Uploading to another asset.", options.verbose, spinner); command_utils_1.verboseLog(chunked ? `Using chunked upload` : `No chunked upload`, options.verbose, spinner); const startDate = new Date(); const filePath = options.filepath ? options.filepath : path.basename(uploadFile); const result = yield __1.retry(options.retry, () => uploader.UploadFile(assetid, filePath, uploadFile, { description: description, chunk: chunked, retry: options.retry, type: mimeType, parallelUploads: options.parallel, logFunction: (p) => { command_utils_1.verboseLog(p, options.verbose, spinner); }, verboseFunction: (p) => { command_utils_1.verboseLog(p, options.verbose, spinner); } }, 300, command_utils_1.retrylog("retrying"))); const endDate = new Date(); !options.verbose && spinner.succeed("Done"); console_1.log(`Upload time: ${(endDate.getTime() - startDate.getTime()) / 1000} seconds`); console_1.log(`\nYour file ${color(uploadFile)} with ${color(result)} md5 hash was succesfully uploaded.\n`); } catch (err) { command_utils_1.errorLog(err, options.verbose); } }))(); }) .on("--help", () => { console_1.log("\n Examples:\n"); console_1.log(` mc uf -f CHANGELOG.md \t\t\t\t\t\t\t upload file CHANGELOG.md to the agent`); console_1.log(` mc upload-file --file CHANGELOG.md --assetid 5...f --mime text/plain \t upload file to a specified asset with custom mime type`); console_1.log(` mc upload-file --file CHANGELOG.md --chunked \t\t\t\t upload file using experimental chunked upload`); }); }; function getIotFileUploader(options) { const auth = utils_1.loadAuth(); const sdk = new sdk_1.MindSphereSdk({ tenant: auth.tenant, basicAuth: utils_1.decrypt(auth, options.passkey), gateway: auth.gateway }); const uploader = sdk.GetIoTFileClient(); return uploader; } function getMindConnectAgent(assetid, options, spinner, color) { return __awaiter(this, void 0, void 0, function* () { const configFile = path.resolve(options.config); command_utils_1.verboseLog(`Upload using the agent configuration stored in: ${color(configFile)}.`, options.verbose, spinner); if (!fs.existsSync(configFile)) { throw new Error(`Can't find file ${configFile}`); } const configuration = require(configFile); const profile = utils_1.checkCertificate(configuration, options); const agentFolder = utils_1.getAgentDir(path.dirname(options.config)); command_utils_1.verboseLog(`Using .mc folder for agent: ${color(agentFolder)}`, options.verbose); const agent = new __1.MindConnectAgent(configuration, undefined, agentFolder); if (profile) { agent.SetupAgentCertificate(fs.readFileSync(options.cert)); } if (!agent.IsOnBoarded()) { yield __1.retry(options.retry, () => agent.OnBoard(), 300, command_utils_1.retrylog("OnBoard")); console_1.log(color(`Your agent with id ${agent.ClientId()} was succesfully onboarded.`)); } assetid = options.assetid || agent.ClientId(); return { assetid, uploader: agent }; }); } exports.getMindConnectAgent = getMindConnectAgent; function checkParameters(options) { !options.file && command_utils_1.errorLog("Missing file name for upload-file command. Run mc uf --help for full syntax and examples.", true); options.passkey && !options.assetid && command_utils_1.errorLog(" You have to specify assetid when using service credential upload", true); } //# sourceMappingURL=mc-upload-file.js.map