export.js 10 KB

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