export.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 mongoose = require('mongoose');
  5. const { Transform } = require('stream');
  6. const streamToPromise = require('stream-to-promise');
  7. const archiver = require('archiver');
  8. const toArrayIfNot = require('../../lib/util/toArrayIfNot');
  9. const CollectionProgressingStatus = require('../models/vo/collection-progressing-status');
  10. class ExportProgressingStatus extends CollectionProgressingStatus {
  11. async init() {
  12. // retrieve total document count from each collections
  13. const promises = this.progressList.map(async(collectionProgress) => {
  14. const collection = mongoose.connection.collection(collectionProgress.collectionName);
  15. collectionProgress.totalCount = await collection.count();
  16. });
  17. await Promise.all(promises);
  18. this.recalculateTotalCount();
  19. }
  20. }
  21. class ExportService {
  22. constructor(crowi) {
  23. this.crowi = crowi;
  24. this.appService = crowi.appService;
  25. this.growiBridgeService = crowi.growiBridgeService;
  26. this.getFile = this.growiBridgeService.getFile.bind(this);
  27. this.baseDir = path.join(crowi.tmpDir, 'downloads');
  28. this.per = 100;
  29. this.zlibLevel = 9; // 0(min) - 9(max)
  30. this.adminEvent = crowi.event('admin');
  31. this.currentProgressingStatus = null;
  32. }
  33. /**
  34. * parse all zip files in downloads dir
  35. *
  36. * @memberOf ExportService
  37. * @return {object} info for zip files and whether currentProgressingStatus exists
  38. */
  39. async getStatus() {
  40. const zipFiles = fs.readdirSync(this.baseDir).filter((file) => { return path.extname(file) === '.zip' });
  41. const zipFileStats = await Promise.all(zipFiles.map((file) => {
  42. const zipFile = this.getFile(file);
  43. return this.growiBridgeService.parseZipFile(zipFile);
  44. }));
  45. // filter null object (broken zip)
  46. const filtered = zipFileStats.filter(element => element != null);
  47. const isExporting = this.currentProgressingStatus != null;
  48. return {
  49. zipFileStats: filtered,
  50. isExporting,
  51. progressList: isExporting ? this.currentProgressingStatus.progressList : null,
  52. };
  53. }
  54. /**
  55. * create meta.json
  56. *
  57. * @memberOf ExportService
  58. * @return {string} path to meta.json
  59. */
  60. async createMetaJson() {
  61. const metaJson = path.join(this.baseDir, this.growiBridgeService.getMetaFileName());
  62. const writeStream = fs.createWriteStream(metaJson, { encoding: this.growiBridgeService.getEncoding() });
  63. const metaData = {
  64. version: this.crowi.version,
  65. url: this.appService.getSiteUrl(),
  66. passwordSeed: this.crowi.env.PASSWORD_SEED,
  67. exportedAt: new Date(),
  68. };
  69. writeStream.write(JSON.stringify(metaData));
  70. writeStream.close();
  71. await streamToPromise(writeStream);
  72. return metaJson;
  73. }
  74. /**
  75. *
  76. * @param {ExportProgress} exportProgress
  77. * @return {Transform}
  78. */
  79. generateLogStream(exportProgress) {
  80. const logProgress = this.logProgress.bind(this);
  81. let count = 0;
  82. return new Transform({
  83. transform(chunk, encoding, callback) {
  84. count++;
  85. logProgress(exportProgress, count);
  86. this.push(chunk);
  87. callback();
  88. },
  89. });
  90. }
  91. /**
  92. * insert beginning/ending brackets and comma separator for Json Array
  93. *
  94. * @memberOf ExportService
  95. * @return {TransformStream}
  96. */
  97. generateTransformStream() {
  98. let isFirst = true;
  99. const transformStream = new Transform({
  100. transform(chunk, encoding, callback) {
  101. // write beginning brace
  102. if (isFirst) {
  103. this.push('[');
  104. isFirst = false;
  105. }
  106. // write separator
  107. else {
  108. this.push(',');
  109. }
  110. this.push(chunk);
  111. callback();
  112. },
  113. final(callback) {
  114. // write ending brace
  115. this.push(']');
  116. callback();
  117. },
  118. });
  119. return transformStream;
  120. }
  121. /**
  122. * dump a mongodb collection into json
  123. *
  124. * @memberOf ExportService
  125. * @param {string} collectionName collection name
  126. * @return {string} path to zip file
  127. */
  128. async exportCollectionToJson(collectionName) {
  129. const collection = mongoose.connection.collection(collectionName);
  130. const nativeCursor = collection.find();
  131. const readStream = nativeCursor
  132. .snapshot()
  133. .stream({ transform: JSON.stringify });
  134. // get TransformStream
  135. const transformStream = this.generateTransformStream();
  136. // log configuration
  137. const exportProgress = this.currentProgressingStatus.progressMap[collectionName];
  138. const logStream = this.generateLogStream(exportProgress);
  139. // create WritableStream
  140. const jsonFileToWrite = path.join(this.baseDir, `${collectionName}.json`);
  141. const writeStream = fs.createWriteStream(jsonFileToWrite, { encoding: this.growiBridgeService.getEncoding() });
  142. readStream
  143. .pipe(logStream)
  144. .pipe(transformStream)
  145. .pipe(writeStream);
  146. await streamToPromise(writeStream);
  147. return writeStream.path;
  148. }
  149. /**
  150. * export multiple Collections into json and Zip
  151. *
  152. * @memberOf ExportService
  153. * @param {Array.<string>} collections array of collection name
  154. * @return {Array.<string>} paths to json files created
  155. */
  156. async exportCollectionsToZippedJson(collections) {
  157. const metaJson = await this.createMetaJson();
  158. const promises = collections.map(collectionName => this.exportCollectionToJson(collectionName));
  159. const jsonFiles = await Promise.all(promises);
  160. // send terminate event
  161. this.emitStartZippingEvent();
  162. // zip json
  163. const configs = jsonFiles.map((jsonFile) => { return { from: jsonFile, as: path.basename(jsonFile) } });
  164. // add meta.json in zip
  165. configs.push({ from: metaJson, as: path.basename(metaJson) });
  166. // exec zip
  167. const zipFile = await this.zipFiles(configs);
  168. // get stats for the zip file
  169. const addedZipFileStat = await this.growiBridgeService.parseZipFile(zipFile);
  170. // send terminate event
  171. this.emitTerminateEvent(addedZipFileStat);
  172. // TODO: remove broken zip file
  173. }
  174. async export(collections) {
  175. if (this.currentProgressingStatus != null) {
  176. throw new Error('There is an exporting process running.');
  177. }
  178. this.currentProgressingStatus = new ExportProgressingStatus(collections);
  179. await this.currentProgressingStatus.init();
  180. try {
  181. await this.exportCollectionsToZippedJson(collections);
  182. }
  183. finally {
  184. this.currentProgressingStatus = null;
  185. }
  186. }
  187. /**
  188. * log export progress
  189. *
  190. * @memberOf ExportService
  191. *
  192. * @param {CollectionProgress} collectionProgress
  193. * @param {number} currentCount number of items exported
  194. */
  195. logProgress(collectionProgress, currentCount) {
  196. const output = `${collectionProgress.collectionName}: ${currentCount}/${collectionProgress.totalCount} written`;
  197. // update exportProgress.currentCount
  198. collectionProgress.currentCount = currentCount;
  199. // output every this.per items
  200. if (currentCount % this.per === 0) {
  201. logger.debug(output);
  202. this.emitProgressEvent();
  203. }
  204. // output last item
  205. else if (currentCount === collectionProgress.totalCount) {
  206. logger.info(output);
  207. this.emitProgressEvent();
  208. }
  209. }
  210. /**
  211. * emit progress event
  212. */
  213. emitProgressEvent() {
  214. const { currentCount, totalCount, progressList } = this.currentProgressingStatus;
  215. const data = {
  216. currentCount,
  217. totalCount,
  218. progressList,
  219. };
  220. // send event (in progress in global)
  221. this.adminEvent.emit('onProgressForExport', data);
  222. }
  223. /**
  224. * emit start zipping event
  225. */
  226. emitStartZippingEvent() {
  227. this.adminEvent.emit('onStartZippingForExport', {});
  228. }
  229. /**
  230. * emit terminate event
  231. * @param {object} zipFileStat added zip file status data
  232. */
  233. emitTerminateEvent(zipFileStat) {
  234. this.adminEvent.emit('onTerminateForExport', { addedZipFileStat: zipFileStat });
  235. }
  236. /**
  237. * zip files into one zip file
  238. *
  239. * @memberOf ExportService
  240. * @param {object|array<object>} configs object or array of object { from: "path to source file", as: "file name after unzipped" }
  241. * @return {string} absolute path to the zip file
  242. * @see https://www.archiverjs.com/#quick-start
  243. */
  244. async zipFiles(_configs) {
  245. const configs = toArrayIfNot(_configs);
  246. const appTitle = this.appService.getAppTitle();
  247. const timeStamp = (new Date()).getTime();
  248. const zipFile = path.join(this.baseDir, `${appTitle}-${timeStamp}.growi.zip`);
  249. const archive = archiver('zip', {
  250. zlib: { level: this.zlibLevel },
  251. });
  252. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  253. archive.on('warning', (err) => {
  254. if (err.code === 'ENOENT') logger.error(err);
  255. else throw err;
  256. });
  257. // good practice to catch this error explicitly
  258. archive.on('error', (err) => { throw err });
  259. for (const { from, as } of configs) {
  260. const input = fs.createReadStream(from);
  261. // append a file from stream
  262. archive.append(input, { name: as });
  263. }
  264. const output = fs.createWriteStream(zipFile);
  265. // pipe archive data to the file
  266. archive.pipe(output);
  267. // finalize the archive (ie we are done appending files but streams have to finish yet)
  268. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  269. archive.finalize();
  270. await streamToPromise(archive);
  271. logger.info(`zipped growi data into ${zipFile} (${archive.pointer()} bytes)`);
  272. // delete json files
  273. for (const { from } of configs) {
  274. fs.unlinkSync(from);
  275. }
  276. return zipFile;
  277. }
  278. }
  279. module.exports = ExportService;