export.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. const logger = require('@alias/logger')('growi:services:ExportService'); // eslint-disable-line no-unused-vars
  2. const fs = require('fs');
  3. const path = require('path');
  4. const streamToPromise = require('stream-to-promise');
  5. const archiver = require('archiver');
  6. const toArrayIfNot = require('../../lib/util/toArrayIfNot');
  7. class ExportService {
  8. constructor(crowi) {
  9. this.crowi = crowi;
  10. this.appService = crowi.appService;
  11. this.growiBridgeService = crowi.growiBridgeService;
  12. this.getFile = this.growiBridgeService.getFile.bind(this);
  13. this.baseDir = path.join(crowi.tmpDir, 'downloads');
  14. this.per = 100;
  15. this.zlibLevel = 9; // 0(min) - 9(max)
  16. // this.files = {
  17. // configs: path.join(this.baseDir, 'configs.json'),
  18. // pages: path.join(this.baseDir, 'pages.json'),
  19. // pagetagrelations: path.join(this.baseDir, 'pagetagrelations.json'),
  20. // ...
  21. // };
  22. this.files = {};
  23. Object.values(crowi.models).forEach((m) => {
  24. const name = m.collection.collectionName;
  25. this.files[name] = path.join(this.baseDir, `${name}.json`);
  26. });
  27. }
  28. /**
  29. * parse all zip files in downloads dir
  30. *
  31. * @memberOf ExportService
  32. * @return {Array.<object>} info for zip files
  33. */
  34. async getStatus() {
  35. const zipFiles = fs.readdirSync(this.baseDir).filter((file) => { return path.extname(file) === '.zip' });
  36. const zipFileStats = await Promise.all(zipFiles.map((file) => {
  37. const zipFile = this.getFile(file);
  38. return this.growiBridgeService.parseZipFile(zipFile);
  39. }));
  40. return zipFileStats;
  41. }
  42. /**
  43. * create meta.json
  44. *
  45. * @memberOf ExportService
  46. * @return {string} path to meta.json
  47. */
  48. async createMetaJson() {
  49. const metaJson = path.join(this.baseDir, this.growiBridgeService.getMetaFileName());
  50. const writeStream = fs.createWriteStream(metaJson, { encoding: this.growiBridgeService.getEncoding() });
  51. const metaData = {
  52. version: this.crowi.version,
  53. url: this.appService.getSiteUrl(),
  54. passwordSeed: this.crowi.env.PASSWORD_SEED,
  55. exportedAt: new Date(),
  56. };
  57. writeStream.write(JSON.stringify(metaData));
  58. writeStream.close();
  59. await streamToPromise(writeStream);
  60. return metaJson;
  61. }
  62. /**
  63. * dump a collection into json
  64. *
  65. * @memberOf ExportService
  66. * @param {string} file path to json file to be written
  67. * @param {readStream} readStream read stream
  68. * @param {number} [total] number of target items (optional)
  69. * @return {string} path to the exported json file
  70. */
  71. async export(file, readStream, total) {
  72. let n = 0;
  73. const ws = fs.createWriteStream(file, { encoding: this.growiBridgeService.getEncoding() });
  74. // open an array
  75. ws.write('[');
  76. readStream.on('data', (chunk) => {
  77. if (n !== 0) ws.write(',');
  78. ws.write(JSON.stringify(chunk));
  79. n++;
  80. this.logProgress(n, total);
  81. });
  82. readStream.on('end', () => {
  83. // close the array
  84. ws.write(']');
  85. ws.close();
  86. });
  87. await streamToPromise(readStream);
  88. return file;
  89. }
  90. /**
  91. * dump a mongodb collection into json
  92. *
  93. * @memberOf ExportService
  94. * @param {object} Model instance of mongoose model
  95. * @return {string} path to zip file
  96. */
  97. async exportCollectionToJson(Model) {
  98. const { collectionName } = Model.collection;
  99. const targetFile = this.files[collectionName];
  100. const total = await Model.countDocuments();
  101. const readStream = Model.find().cursor();
  102. const file = await this.export(targetFile, readStream, total);
  103. return file;
  104. }
  105. /**
  106. * export multiple collections
  107. *
  108. * @memberOf ExportService
  109. * @param {Array.<object>} models array of instances of mongoose model
  110. * @return {Array.<string>} paths to json files created
  111. */
  112. async exportMultipleCollectionsToJsons(models) {
  113. const jsonFiles = await Promise.all(models.map(Model => this.exportCollectionToJson(Model)));
  114. return jsonFiles;
  115. }
  116. /**
  117. * log export progress
  118. *
  119. * @memberOf ExportService
  120. * @param {number} n number of items exported
  121. * @param {number} [total] number of target items (optional)
  122. */
  123. logProgress(n, total) {
  124. let output;
  125. if (total) {
  126. output = `${n}/${total} written`;
  127. }
  128. else {
  129. output = `${n} items written`;
  130. }
  131. // output every this.per items
  132. if (n % this.per === 0) logger.debug(output);
  133. // output last item
  134. else if (n === total) logger.info(output);
  135. }
  136. /**
  137. * zip files into one zip file
  138. *
  139. * @memberOf ExportService
  140. * @param {object|array<object>} configs object or array of object { from: "path to source file", as: "file name after unzipped" }
  141. * @return {string} absolute path to the zip file
  142. * @see https://www.archiverjs.com/#quick-start
  143. */
  144. async zipFiles(_configs) {
  145. const configs = toArrayIfNot(_configs);
  146. const appTitle = this.appService.getAppTitle();
  147. const timeStamp = (new Date()).getTime();
  148. const zipFile = path.join(this.baseDir, `${appTitle}-${timeStamp}.zip`);
  149. const archive = archiver('zip', {
  150. zlib: { level: this.zlibLevel },
  151. });
  152. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  153. archive.on('warning', (err) => {
  154. if (err.code === 'ENOENT') logger.error(err);
  155. else throw err;
  156. });
  157. // good practice to catch this error explicitly
  158. archive.on('error', (err) => { throw err });
  159. for (const { from, as } of configs) {
  160. const input = fs.createReadStream(from);
  161. // append a file from stream
  162. archive.append(input, { name: as });
  163. }
  164. const output = fs.createWriteStream(zipFile);
  165. // pipe archive data to the file
  166. archive.pipe(output);
  167. // finalize the archive (ie we are done appending files but streams have to finish yet)
  168. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  169. archive.finalize();
  170. await streamToPromise(archive);
  171. logger.debug(`zipped growi data into ${zipFile} (${archive.pointer()} bytes)`);
  172. return zipFile;
  173. }
  174. }
  175. module.exports = ExportService;