export.js 10.0 KB

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