export.js 9.8 KB

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