UNPKG

@adinsure-ops/ops-cli

Version:

Operations CLI for working with AdInsure

164 lines (163 loc) 6.89 kB
import { __awaiter } from "tslib"; import { Args, Flags, ux } from '@oclif/core'; import axios from 'axios'; import chalk from 'chalk'; import fs from 'fs-extra'; import JSZip from 'jszip'; import path from 'path'; import CommandBase from '../command.base.js'; class Translate extends CommandBase { getFormat(format) { if (format === 'json') { return 'text/json'; } if (format === 'xml') { return 'text/xml'; } return this.error(`Format ${format} not supported.`); } /** * Gets resources, checks a response and returns a response stream. * @param languages list of translations to download * @param format format of translations * @param modules list of modules to download * @returns arhive as an byte array response stream */ // eslint-disable-next-line @typescript-eslint/no-explicit-any getTranslations(languages, format, modules) { return __awaiter(this, void 0, void 0, function* () { const requestOptions = { headers: { Authorization: 'Bearer ' + (yield this.security.getToken()), 'Content-Type': this.getFormat(format), }, responseType: 'arraybuffer', params: Object.assign({ languages }, (modules && { modules })), }; try { return (yield axios.get(`https://dictionary.adinsure.com/api/Translations`, requestOptions)); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error) { let errorMessage; try { const errorJson = JSON.parse(error.error); errorMessage = `An error has occurred: ${errorJson.ExceptionMessage}`; } catch (_a) { errorMessage = error.message; } this.log(chalk.red(errorMessage)); throw error; } }); } /** * Read from response stream and extract files into output directory. * @param content zip file or a stream * @param destinationDir final destination to extract files * @param {string} [xmlFilename=false] XML filename * @returns {Promise<void>} Void * @throws Error message */ // eslint-disable-next-line @typescript-eslint/no-explicit-any extractFiles(content_1, destinationDir_1) { return __awaiter(this, arguments, void 0, function* (content, destinationDir, xmlFilename = '') { const zip = yield JSZip.loadAsync(content); for (const fileName of Object.keys(zip.files)) { const buffer = yield zip.files[fileName].async('nodebuffer'); // Rename from translations..Xml to Translations..xml to respect naming in mono if (fileName.includes('Xml')) { let finalFileName = fileName; if (xmlFilename !== '') { finalFileName = xmlFilename; } const dest = destinationDir + '/' + finalFileName; yield fs.writeFile(dest, buffer); } else { const dest = destinationDir + '/' + zip.files[fileName].name; yield fs.writeFile(dest, buffer); } } }); } run() { const _super = Object.create(null, { run: { get: () => super.run } }); return __awaiter(this, void 0, void 0, function* () { _super.run.call(this); const { args, flags } = yield this.parse(Translate); const destination = flags.output; if (flags.format === 'json' && flags.module === undefined) { this.error(`${chalk.red('You need to specify `\'module\' when choosing client `\'json\' format.')}`); } try { // Get translations ux.action.start('Fetching translations from AdDictionary', undefined, { stdout: true }); const response = yield this.getTranslations(args.language, flags.format, flags.module); ux.action.stop(`${chalk.green('done')}`); if (!(yield fs.pathExists(destination))) { yield fs.mkdirp(destination); } // Extract files ux.action.start('Extracting translation zip files', undefined, { stdout: true }); let finalFileName = 'Translations..xml'; if (flags.filename) { finalFileName = flags.filename; } // set finalFileName to empty string to indicate filename needs to be taken from server response if (flags.respectServerFilename) { finalFileName = ''; } yield this.extractFiles(response.data, destination, finalFileName); ux.action.stop(`${chalk.green('done')}`); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error) { ux.action.stop(`${chalk.red('error')}`); this.error(error.message); } this.log(`Translations extracted into ${chalk.cyan(path.resolve(destination))}`); this.log(`${chalk.green('Done.')}`); }); } } Translate.description = 'downloads translate from AdDictionary service'; Translate.usage = 'translate <language> [flags]'; Translate.examples = [ `$ ops translate "en-US=en-US;ru-Ru=ru-RU" -f json -m "Client business accounting;Client business base;"`, `$ ops translate "en-US=en-US;ru-Ru=ru-RU" -f xml -o translationDestination`, ]; Translate.args = { language: Args.string({ required: true, description: 'Language id you want to download. Values must be semi-colon (;) separated.', }), }; Translate.flags = { format: Flags.string({ char: 'f', description: 'translations format [xml - server translations, json - client translations]', options: ['json', 'xml'], required: true, }), module: Flags.string({ char: 'm', description: 'module name you want to download. Values must be semi-colon (;) separated.', }), output: Flags.string({ char: 'o', default: '.', description: 'absolute or relative destination path to a folder where translations are extracted.', }), filename: Flags.string({ description: 'specify filename of output (XML only).', }), respectServerFilename: Flags.boolean({ default: false, description: 'respect filename that is returned from AdDictionary server (XML only).', }), }; export default Translate;