index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const fs = require("fs");
  2. const config = require("config");
  3. const request = require("request");
  4. const async = require("async");
  5. const localesFolder = __dirname.substr(0, __dirname.lastIndexOf("translation")) + "locales/";
  6. const deleteFolderRecursive = (path) => {
  7. if (fs.existsSync(path)) {
  8. fs.readdirSync(path).forEach((file,index) => {
  9. const curPath = path + "/" + file;
  10. if (fs.lstatSync(curPath).isDirectory()) {
  11. deleteFolderRecursive(curPath);
  12. } else {
  13. fs.unlinkSync(curPath);
  14. }
  15. });
  16. fs.rmdirSync(path);
  17. }
  18. };
  19. deleteFolderRecursive(localesFolder);
  20. async.waterfall([
  21. (next) => {
  22. fs.mkdirSync(localesFolder);
  23. next();
  24. },
  25. (next) => {
  26. request.post(`https://api.poeditor.com/v2/languages/list`, {form: {api_token: config.get("poeditor.api_token"), id: config.get("poeditor.project_id")}}, next);
  27. },
  28. (res, body, next) => {
  29. body = JSON.parse(body);
  30. if (body.response.status !== "success") return next(body.response.message);
  31. let languages = body.result.languages.map((language) => {
  32. return language.code;
  33. });
  34. next(null, languages);
  35. },
  36. (languages, next) => {
  37. async.each(
  38. languages,
  39. (language, next) => {
  40. async.waterfall([
  41. (next) => {
  42. fs.mkdirSync(`${localesFolder}${language}`);
  43. next();
  44. },
  45. (next) => {
  46. request.post(`https://api.poeditor.com/v2/projects/export`, {form: {api_token: config.get("poeditor.api_token"), id: config.get("poeditor.project_id"), language, type: "key_value_json", filters: "translated"}}, next);
  47. },
  48. (res, body, next) => {
  49. body = JSON.parse(body);
  50. if (body.response.status !== "success") return next(body.response.message);
  51. request(body.result.url, next);
  52. },
  53. (res, body, next) => {
  54. if (!body) body = "{}";
  55. body = JSON.parse(body);
  56. const files = [];
  57. Object.keys(body).forEach((namespace) => {
  58. files.push({
  59. namespace,
  60. content: body[namespace]
  61. });
  62. });
  63. next(null, files);
  64. },
  65. (files, next) => {
  66. async.each(
  67. files,
  68. (file, next) => {
  69. fs.writeFile(`${localesFolder}${language}/${file.namespace}.json`, JSON.stringify(file.content), function(err) {
  70. if(err) console.err(`Failed to write namespace ${file.namespace} for language ${language}.`);
  71. next();
  72. });
  73. },
  74. () => {
  75. next();
  76. }
  77. );
  78. }
  79. ], () => {
  80. next();
  81. });
  82. },
  83. () => {
  84. next();
  85. }
  86. );
  87. }
  88. ], (err, res) => {
  89. console.log(err, res);
  90. });