@mindconnect/mindconnect-nodejs
Version:
NodeJS Library for Siemens Insights Hub Connectivity - TypeScript SDK for Insights Hub and Industrial IoT - Command Line Interface - Insights Hub Development Proxy (Siemens Insights Hub was formerly known as MindSphere)
138 lines • 8.45 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 });
exports.getMindConnectAgent = void 0;
const console_1 = require("console");
const fs = require("fs");
const path = require("path");
const __1 = require("../..");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
const ora = require("ora-classic");
const mime = require("mime-types");
let color = (0, command_utils_1.getColor)("cyan");
let adminColor = (0, command_utils_1.getColor)("magenta");
exports.default = (program) => {
program
.command("upload-file")
.alias("uf")
.option("-c, --config <agentconfig>", "config file with agent configuration")
.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]", "mindsphere asset id (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 {
adminColor = (0, command_utils_1.adjustColor)(adminColor, options);
color = options.config === undefined ? adminColor : color;
checkParameters(options);
(0, command_utils_1.homeDirLog)(options.verbose, color);
(0, command_utils_1.proxyLog)(options.verbose, color);
const spinner = ora("uploadingFile");
!options.verbose && spinner.start();
const uploadFile = path.resolve(options.file);
(0, 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.config) {
({ assetid, uploader } = yield getMindConnectAgent(assetid, options, spinner, color));
}
else {
const sdk = (0, command_utils_1.getSdk)(options);
uploader = sdk.GetIoTFileClient();
}
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}`);
}
(0, command_utils_1.verboseLog)(`Uploading the file: ${color(uploadFile)} with mime type ${mimeType}.`, options.verbose, spinner);
(0, command_utils_1.verboseLog)(`Description ${description}`, options.verbose, spinner);
(0, command_utils_1.verboseLog)(`AssetId ${assetid}`, options.verbose, spinner);
(0, command_utils_1.verboseLog)(options.assetid === undefined ? "Uploading to agent." : "Uploading to another asset.", options.verbose, spinner);
(0, 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 (0, __1.retry)(options.retry, () => uploader.UploadFile(assetid, filePath, uploadFile, {
description: description,
chunk: chunked,
retry: options.retry,
type: mimeType,
parallelUploads: options.parallel,
logFunction: (p) => {
(0, command_utils_1.verboseLog)(p, options.verbose, spinner);
},
verboseFunction: (p) => {
(0, command_utils_1.verboseLog)(p, options.verbose, spinner);
},
}, 300, (0, command_utils_1.retrylog)("retrying")));
const endDate = new Date();
!options.verbose && spinner.succeed("Done");
(0, console_1.log)(`Upload time: ${(endDate.getTime() - startDate.getTime()) / 1000} seconds`);
(0, console_1.log)(`\nYour file ${color(uploadFile)} with ${color(result)} md5 hash was succesfully uploaded.\n`);
}
catch (err) {
(0, command_utils_1.errorLog)(err, options.verbose);
}
}))();
})
.on("--help", () => {
(0, console_1.log)("\n Examples:\n");
(0, console_1.log)(` mdsp uf -f CHANGELOG.md \t\t\t\t\t\t\t upload file CHANGELOG.md to the agent`);
(0, console_1.log)(` mdsp upload-file --file CHANGELOG.md --assetid 5...f --mime text/plain \t upload file to a specified asset with custom mime type`);
(0, console_1.log)(` mdsp upload-file --file CHANGELOG.md --chunked \t\t\t\t upload file using experimental chunked upload`);
});
};
function getMindConnectAgent(assetid, options, spinner, color) {
return __awaiter(this, void 0, void 0, function* () {
const configFile = path.resolve(options.config);
(0, 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 = (0, utils_1.checkCertificate)(configuration, options);
const agentFolder = (0, utils_1.getAgentDir)(path.dirname(options.config));
(0, 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 (0, __1.retry)(options.retry, () => agent.OnBoard(), 300, (0, command_utils_1.retrylog)("OnBoard"));
(0, 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 &&
(0, command_utils_1.errorLog)("Missing file name for upload-file command. Run mdsp uf --help for full syntax and examples.", true);
!options.config &&
!options.assetid &&
(0, command_utils_1.errorLog)(" You have to specify assetid when using service credential upload", true);
}
//# sourceMappingURL=mc-upload-file.js.map