export.js 11 KB

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