export.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.baseDir = path.join(crowi.tmpDir, 'downloads');
  13. this.metaFileName = 'meta.json';
  14. this.encoding = 'utf-8';
  15. this.per = 100;
  16. this.zlibLevel = 9; // 0(min) - 9(max)
  17. // { pages: Page, users: User, ... }
  18. this.collectionMap = {};
  19. this.initCollectionMap(crowi.models);
  20. // this.files = {
  21. // configs: path.join(this.baseDir, 'configs.json'),
  22. // pages: path.join(this.baseDir, 'pages.json'),
  23. // pagetagrelations: path.join(this.baseDir, 'pagetagrelations.json'),
  24. // ...
  25. // };
  26. this.files = {};
  27. Object.values(crowi.models).forEach((m) => {
  28. const name = m.collection.collectionName;
  29. this.files[name] = path.join(this.baseDir, `${name}.json`);
  30. });
  31. }
  32. /**
  33. * initialize collection map
  34. *
  35. * @memberOf ExportService
  36. * @param {object} models from models/index.js
  37. */
  38. initCollectionMap(models) {
  39. for (const model of Object.values(models)) {
  40. this.collectionMap[model.collection.collectionName] = model;
  41. }
  42. }
  43. /**
  44. * parse all zip files in downloads dir
  45. *
  46. * @memberOf ExportService
  47. * @return {Array.<object>} info for zip files
  48. */
  49. async getStatus() {
  50. const zipFiles = fs.readdirSync(this.baseDir).filter((file) => { return path.extname(file) === '.zip' });
  51. const zipFileStats = await Promise.all(zipFiles.map((file) => {
  52. const zipFile = this.getFile(file);
  53. return this.growiBridgeService.parseZipFile(zipFile);
  54. }));
  55. return zipFileStats;
  56. }
  57. /**
  58. * create meta.json
  59. *
  60. * @memberOf ExportService
  61. * @return {string} path to meta.json
  62. */
  63. async createMetaJson() {
  64. const metaJson = path.join(this.baseDir, this.metaFileName);
  65. const writeStream = fs.createWriteStream(metaJson, { encoding: this.encoding });
  66. const metaData = {
  67. version: this.crowi.version,
  68. url: this.appService.getSiteUrl(),
  69. passwordSeed: this.crowi.env.PASSWORD_SEED,
  70. exportedAt: new Date(),
  71. };
  72. writeStream.write(JSON.stringify(metaData));
  73. writeStream.close();
  74. await streamToPromise(writeStream);
  75. return metaJson;
  76. }
  77. /**
  78. * dump a collection into json
  79. *
  80. * @memberOf ExportService
  81. * @param {string} file path to json file to be written
  82. * @param {readStream} readStream read stream
  83. * @param {number} [total] number of target items (optional)
  84. * @return {string} path to the exported json file
  85. */
  86. async export(file, readStream, total) {
  87. let n = 0;
  88. const ws = fs.createWriteStream(file, { encoding: this.encoding });
  89. // open an array
  90. ws.write('[');
  91. readStream.on('data', (chunk) => {
  92. if (n !== 0) ws.write(',');
  93. ws.write(JSON.stringify(chunk));
  94. n++;
  95. this.logProgress(n, total);
  96. });
  97. readStream.on('end', () => {
  98. // close the array
  99. ws.write(']');
  100. ws.close();
  101. });
  102. await streamToPromise(readStream);
  103. return file;
  104. }
  105. /**
  106. * dump a mongodb collection into json
  107. *
  108. * @memberOf ExportService
  109. * @param {object} Model instance of mongoose model
  110. * @return {string} path to zip file
  111. */
  112. async exportCollectionToJson(Model) {
  113. const { collectionName } = Model.collection;
  114. const targetFile = this.files[collectionName];
  115. const total = await Model.countDocuments();
  116. const readStream = Model.find().cursor();
  117. const file = await this.export(targetFile, readStream, total);
  118. return file;
  119. }
  120. /**
  121. * export multiple collections
  122. *
  123. * @memberOf ExportService
  124. * @param {Array.<object>} models array of instances of mongoose model
  125. * @return {Array.<string>} paths to json files created
  126. */
  127. async exportMultipleCollectionsToJsons(models) {
  128. const jsonFiles = await Promise.all(models.map(Model => this.exportCollectionToJson(Model)));
  129. return jsonFiles;
  130. }
  131. /**
  132. * log export progress
  133. *
  134. * @memberOf ExportService
  135. * @param {number} n number of items exported
  136. * @param {number} [total] number of target items (optional)
  137. */
  138. logProgress(n, total) {
  139. let output;
  140. if (total) {
  141. output = `${n}/${total} written`;
  142. }
  143. else {
  144. output = `${n} items written`;
  145. }
  146. // output every this.per items
  147. if (n % this.per === 0) logger.debug(output);
  148. // output last item
  149. else if (n === total) logger.info(output);
  150. }
  151. /**
  152. * zip files into one zip file
  153. *
  154. * @memberOf ExportService
  155. * @param {object|array<object>} configs object or array of object { from: "path to source file", as: "file name after unzipped" }
  156. * @return {string} absolute path to the zip file
  157. * @see https://www.archiverjs.com/#quick-start
  158. */
  159. async zipFiles(_configs) {
  160. const configs = toArrayIfNot(_configs);
  161. const appTitle = this.appService.getAppTitle();
  162. const timeStamp = (new Date()).getTime();
  163. const zipFile = path.join(this.baseDir, `${appTitle}-${timeStamp}.zip`);
  164. const archive = archiver('zip', {
  165. zlib: { level: this.zlibLevel },
  166. });
  167. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  168. archive.on('warning', (err) => {
  169. if (err.code === 'ENOENT') logger.error(err);
  170. else throw err;
  171. });
  172. // good practice to catch this error explicitly
  173. archive.on('error', (err) => { throw err });
  174. for (const { from, as } of configs) {
  175. const input = fs.createReadStream(from);
  176. // append a file from stream
  177. archive.append(input, { name: as });
  178. }
  179. const output = fs.createWriteStream(zipFile);
  180. // pipe archive data to the file
  181. archive.pipe(output);
  182. // finalize the archive (ie we are done appending files but streams have to finish yet)
  183. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  184. archive.finalize();
  185. await streamToPromise(archive);
  186. logger.debug(`zipped growi data into ${zipFile} (${archive.pointer()} bytes)`);
  187. return zipFile;
  188. }
  189. /**
  190. * get the absolute path to a file
  191. *
  192. * @memberOf ExportService
  193. * @param {string} fileName base name of file
  194. * @return {string} absolute path to the file
  195. */
  196. getFile(fileName) {
  197. const jsonFile = path.join(this.baseDir, fileName);
  198. // throws err if the file does not exist
  199. fs.accessSync(jsonFile);
  200. return jsonFile;
  201. }
  202. /**
  203. * get a model from collection name
  204. *
  205. * @memberOf ExportService
  206. * @param {string} collectionName collection name
  207. * @return {object} instance of mongoose model
  208. */
  209. getModelFromCollectionName(collectionName) {
  210. const Model = this.collectionMap[collectionName];
  211. if (Model == null) {
  212. throw new Error(`cannot find a model for collection name "${collectionName}"`);
  213. }
  214. return Model;
  215. }
  216. /**
  217. * remove zip file from downloads dir
  218. *
  219. * @param {string} zipFile absolute path to zip file
  220. * @memberOf ExportService
  221. */
  222. deleteZipFile(zipFile) {
  223. fs.unlinkSync(zipFile);
  224. }
  225. }
  226. module.exports = ExportService;