export.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 beginning brace
  115. if (isFirst) {
  116. this.push('[');
  117. }
  118. // write ending brace
  119. this.push(']');
  120. callback();
  121. },
  122. });
  123. return transformStream;
  124. }
  125. /**
  126. * dump a mongodb collection into json
  127. *
  128. * @memberOf ExportService
  129. * @param {string} collectionName collection name
  130. * @return {string} path to zip file
  131. */
  132. async exportCollectionToJson(collectionName) {
  133. const collection = mongoose.connection.collection(collectionName);
  134. const nativeCursor = collection.find();
  135. const readStream = nativeCursor
  136. .snapshot()
  137. .stream({ transform: JSON.stringify });
  138. // get TransformStream
  139. const transformStream = this.generateTransformStream();
  140. // log configuration
  141. const exportProgress = this.currentProgressingStatus.progressMap[collectionName];
  142. const logStream = this.generateLogStream(exportProgress);
  143. // create WritableStream
  144. const jsonFileToWrite = path.join(this.baseDir, `${collectionName}.json`);
  145. const writeStream = fs.createWriteStream(jsonFileToWrite, { encoding: this.growiBridgeService.getEncoding() });
  146. readStream
  147. .pipe(logStream)
  148. .pipe(transformStream)
  149. .pipe(writeStream);
  150. await streamToPromise(writeStream);
  151. return writeStream.path;
  152. }
  153. /**
  154. * export multiple Collections into json and Zip
  155. *
  156. * @memberOf ExportService
  157. * @param {Array.<string>} collections array of collection name
  158. * @return {Array.<string>} paths to json files created
  159. */
  160. async exportCollectionsToZippedJson(collections) {
  161. const metaJson = await this.createMetaJson();
  162. const promises = collections.map(collectionName => this.exportCollectionToJson(collectionName));
  163. const jsonFiles = await Promise.all(promises);
  164. // send terminate event
  165. this.emitStartZippingEvent();
  166. // zip json
  167. const configs = jsonFiles.map((jsonFile) => { return { from: jsonFile, as: path.basename(jsonFile) } });
  168. // add meta.json in zip
  169. configs.push({ from: metaJson, as: path.basename(metaJson) });
  170. // exec zip
  171. const zipFile = await this.zipFiles(configs);
  172. // get stats for the zip file
  173. const addedZipFileStat = await this.growiBridgeService.parseZipFile(zipFile);
  174. // send terminate event
  175. this.emitTerminateEvent(addedZipFileStat);
  176. // TODO: remove broken zip file
  177. }
  178. async export(collections) {
  179. if (this.currentProgressingStatus != null) {
  180. throw new Error('There is an exporting process running.');
  181. }
  182. this.currentProgressingStatus = new ExportProgressingStatus(collections);
  183. await this.currentProgressingStatus.init();
  184. try {
  185. await this.exportCollectionsToZippedJson(collections);
  186. }
  187. finally {
  188. this.currentProgressingStatus = null;
  189. }
  190. }
  191. /**
  192. * log export progress
  193. *
  194. * @memberOf ExportService
  195. *
  196. * @param {CollectionProgress} collectionProgress
  197. * @param {number} currentCount number of items exported
  198. */
  199. logProgress(collectionProgress, currentCount) {
  200. const output = `${collectionProgress.collectionName}: ${currentCount}/${collectionProgress.totalCount} written`;
  201. // update exportProgress.currentCount
  202. collectionProgress.currentCount = currentCount;
  203. // output every this.per items
  204. if (currentCount % this.per === 0) {
  205. logger.debug(output);
  206. this.emitProgressEvent();
  207. }
  208. // output last item
  209. else if (currentCount === collectionProgress.totalCount) {
  210. logger.info(output);
  211. this.emitProgressEvent();
  212. }
  213. }
  214. /**
  215. * emit progress event
  216. */
  217. emitProgressEvent() {
  218. const { currentCount, totalCount, progressList } = this.currentProgressingStatus;
  219. const data = {
  220. currentCount,
  221. totalCount,
  222. progressList,
  223. };
  224. // send event (in progress in global)
  225. this.adminEvent.emit('onProgressForExport', data);
  226. }
  227. /**
  228. * emit start zipping event
  229. */
  230. emitStartZippingEvent() {
  231. this.adminEvent.emit('onStartZippingForExport', {});
  232. }
  233. /**
  234. * emit terminate event
  235. * @param {object} zipFileStat added zip file status data
  236. */
  237. emitTerminateEvent(zipFileStat) {
  238. this.adminEvent.emit('onTerminateForExport', { addedZipFileStat: zipFileStat });
  239. }
  240. /**
  241. * zip files into one zip file
  242. *
  243. * @memberOf ExportService
  244. * @param {object|array<object>} configs object or array of object { from: "path to source file", as: "file name after unzipped" }
  245. * @return {string} absolute path to the zip file
  246. * @see https://www.archiverjs.com/#quick-start
  247. */
  248. async zipFiles(_configs) {
  249. const configs = toArrayIfNot(_configs);
  250. const appTitle = this.appService.getAppTitle();
  251. const timeStamp = (new Date()).getTime();
  252. const zipFile = path.join(this.baseDir, `${appTitle}-${timeStamp}.growi.zip`);
  253. const archive = archiver('zip', {
  254. zlib: { level: this.zlibLevel },
  255. });
  256. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  257. archive.on('warning', (err) => {
  258. if (err.code === 'ENOENT') logger.error(err);
  259. else throw err;
  260. });
  261. // good practice to catch this error explicitly
  262. archive.on('error', (err) => { throw err });
  263. for (const { from, as } of configs) {
  264. const input = fs.createReadStream(from);
  265. // append a file from stream
  266. archive.append(input, { name: as });
  267. }
  268. const output = fs.createWriteStream(zipFile);
  269. // pipe archive data to the file
  270. archive.pipe(output);
  271. // finalize the archive (ie we are done appending files but streams have to finish yet)
  272. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  273. archive.finalize();
  274. await streamToPromise(archive);
  275. logger.info(`zipped growi data into ${zipFile} (${archive.pointer()} bytes)`);
  276. // delete json files
  277. for (const { from } of configs) {
  278. fs.unlinkSync(from);
  279. }
  280. return zipFile;
  281. }
  282. }
  283. module.exports = ExportService;