AdGuardHome/scripts/translations/download.js

119 lines
2.8 KiB
JavaScript
Raw Normal View History

const fs = require('fs');
const path = require('path');
const requestPromise = require('request-promise');
const LOCALES_DIR = '../../client/src/__locales';
2019-01-03 02:55:15 -07:00
const LOCALES_LIST = [
'en',
'ru',
'vi',
'es',
'fr',
'ja',
'sv',
'pt-br',
'zh-tw',
'bg',
'zh-cn',
2019-01-03 02:55:15 -07:00
];
2019-07-18 08:35:23 -07:00
const BASE_FILE = 'en.json';
const TWOSKY_URI = process.env.TWOSKY_URI;
const TWOSKY_PROJECT_ID = 'home';
/**
2019-07-18 08:35:23 -07:00
* Prepare params to get translations from twosky
* @param {string} locale language shortcut
2019-07-18 08:35:23 -07:00
* @param {object} twosky config twosky
*/
2019-07-18 08:35:23 -07:00
const getRequestUrl = (locale, url, projectId) => {
return `${url}/download?format=json&language=${locale}&filename=${BASE_FILE}&project=${projectId}`;
};
/**
* Promise wrapper for writing in file
* @param {string} filename
* @param {any} body
*/
function writeInFile(filename, body) {
2019-07-18 08:35:23 -07:00
let normalizedBody = removeEmpty(JSON.parse(body));
return new Promise((resolve, reject) => {
2019-07-18 08:35:23 -07:00
if (typeof normalizedBody !== 'string') {
try {
2019-07-18 08:35:23 -07:00
normalizedBody = JSON.stringify(normalizedBody, null, 4); // eslint-disable-line
} catch (err) {
reject(err);
}
}
2019-07-18 08:35:23 -07:00
fs.writeFile(filename, normalizedBody, (err) => {
if (err) reject(err);
resolve('Ok');
});
});
}
/**
2019-07-18 08:35:23 -07:00
* Clear initial from empty value keys
* @param {object} initialObject
*/
function removeEmpty(initialObject) {
let processedObject = {};
Object.keys(initialObject).forEach(prop => {
if (initialObject[prop]) {
processedObject[prop] = initialObject[prop];
}
});
return processedObject;
}
/**
* Request twosky
* @param {string} url
* @param {string} locale
*/
const request = (url, locale) => (
requestPromise.get(url)
.then((res) => {
if (res.length) {
const pathToFile = path.join(LOCALES_DIR, `${locale}.json`);
return writeInFile(pathToFile, res);
}
return null;
})
.then((res) => {
let result = locale;
result += res ? ' - OK' : ' - Empty';
return result;
})
.catch((err) => {
console.log(err);
return `${locale} - Not OK`;
}));
/**
* Download locales
*/
const download = () => {
const locales = LOCALES_LIST;
2019-07-18 08:35:23 -07:00
if (!TWOSKY_URI) {
console.error('No credentials');
return;
}
const requests = locales.map((locale) => {
2019-07-18 08:35:23 -07:00
const url = getRequestUrl(locale, TWOSKY_URI, TWOSKY_PROJECT_ID);
return request(url, locale);
});
Promise
.all(requests)
.then((res) => {
res.forEach(item => console.log(item));
})
.catch(err => console.log(err));
};
download();