export.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 streamToPromise = require('stream-to-promise');
  5. const archiver = require('archiver');
  6. const toArrayIfNot = require('../../lib/util/toArrayIfNot');
  7. class ExportService {
  8. constructor(crowi) {
  9. this.crowi = crowi;
  10. this.appService = crowi.appService;
  11. this.baseDir = path.join(crowi.tmpDir, 'downloads');
  12. this.zipFileName = 'GROWI.zip';
  13. this.metaFileName = 'meta.json';
  14. this.encoding = 'utf-8';
  15. this.per = 100;
  16. this.zlibLevel = 9; // 0(min) - 9(max)
  17. // { pages: Page, users: User, ... }
  18. this.collectionMap = {};
  19. this.initCollectionMap(crowi.models);
  20. // this.files = {
  21. // configs: path.join(this.baseDir, 'configs.json'),
  22. // pages: path.join(this.baseDir, 'pages.json'),
  23. // pagetagrelations: path.join(this.baseDir, 'pagetagrelations.json'),
  24. // ...
  25. // };
  26. this.files = {};
  27. Object.values(crowi.models).forEach((m) => {
  28. const name = m.collection.collectionName;
  29. this.files[name] = path.join(this.baseDir, `${name}.json`);
  30. });
  31. }
  32. /**
  33. * initialize collection map
  34. *
  35. * @memberOf ExportService
  36. * @param {object} models from models/index.js
  37. */
  38. initCollectionMap(models) {
  39. for (const model of Object.values(models)) {
  40. this.collectionMap[model.collection.collectionName] = model;
  41. }
  42. }
  43. /**
  44. * dump a collection into json
  45. *
  46. * @memberOf ExportService
  47. * @return {object} cache info for exported zip files
  48. */
  49. getStatus() {
  50. const status = {};
  51. const collections = Object.keys(this.files);
  52. collections.forEach((file) => {
  53. status[path.basename(file, '.zip')] = null;
  54. });
  55. // extract ${collectionName}.zip
  56. const files = fs.readdirSync(this.baseDir).filter((file) => { return path.extname(file) === '.zip' && collections.includes(path.basename(file, '.zip')) });
  57. files.forEach((file) => {
  58. status[path.basename(file, '.zip')] = file;
  59. });
  60. files.forEach((file) => {
  61. const stats = fs.statSync(path.join(this.baseDir, file));
  62. stats.name = file;
  63. status[path.basename(file, '.zip')] = stats;
  64. });
  65. return status;
  66. }
  67. /**
  68. * create meta.json
  69. *
  70. * @memberOf ExportService
  71. * @return {string} path to meta.json
  72. */
  73. async createMetaJson() {
  74. const metaJson = this.getMetaJson();
  75. const writeStream = fs.createWriteStream(metaJson, { encoding: this.encoding });
  76. const metaData = {
  77. version: this.crowi.version,
  78. url: this.appService.getSiteUrl(),
  79. passwordSeed: this.crowi.env.PASSWORD_SEED,
  80. exportedAt: new Date(),
  81. };
  82. writeStream.write(JSON.stringify(metaData));
  83. writeStream.close();
  84. await streamToPromise(writeStream);
  85. return metaJson;
  86. }
  87. /**
  88. * dump a collection into json
  89. *
  90. * @memberOf ExportService
  91. * @param {string} file path to json file to be written
  92. * @param {readStream} readStream read stream
  93. * @param {number} [total] number of target items (optional)
  94. * @return {string} path to the exported json file
  95. */
  96. async export(file, readStream, total) {
  97. let n = 0;
  98. const ws = fs.createWriteStream(file, { encoding: this.encoding });
  99. // open an array
  100. ws.write('[');
  101. readStream.on('data', (chunk) => {
  102. if (n !== 0) ws.write(',');
  103. ws.write(JSON.stringify(chunk));
  104. n++;
  105. this.logProgress(n, total);
  106. });
  107. readStream.on('end', () => {
  108. // close the array
  109. ws.write(']');
  110. ws.close();
  111. });
  112. await streamToPromise(readStream);
  113. return file;
  114. }
  115. /**
  116. * dump a mongodb collection into json
  117. *
  118. * @memberOf ExportService
  119. * @param {object} Model instance of mongoose model
  120. * @return {string} path to zip file
  121. */
  122. async exportCollectionToJson(Model) {
  123. const { collectionName } = Model.collection;
  124. const targetFile = this.files[collectionName];
  125. const total = await Model.countDocuments();
  126. const readStream = Model.find().cursor();
  127. const file = await this.export(targetFile, readStream, total);
  128. return file;
  129. }
  130. /**
  131. * export multiple collections
  132. *
  133. * @memberOf ExportService
  134. * @param {number} models number of items exported
  135. * @return {Array.<string>} paths to json files created
  136. */
  137. async exportMultipleCollectionsToJsons(models) {
  138. const jsonFiles = await Promise.all(models.map(Model => this.exportCollectionToJson(Model)));
  139. return jsonFiles;
  140. }
  141. /**
  142. * log export progress
  143. *
  144. * @memberOf ExportService
  145. * @param {number} n number of items exported
  146. * @param {number} [total] number of target items (optional)
  147. */
  148. logProgress(n, total) {
  149. let output;
  150. if (total) {
  151. output = `${n}/${total} written`;
  152. }
  153. else {
  154. output = `${n} items written`;
  155. }
  156. // output every this.per items
  157. if (n % this.per === 0) logger.debug(output);
  158. // output last item
  159. else if (n === total) logger.info(output);
  160. }
  161. /**
  162. * zip files into one zip file
  163. *
  164. * @memberOf ExportService
  165. * @param {object|array<object>} configs array of object { from: "path to source file", as: "file name after unzipped" }
  166. * @return {string} path to zip file
  167. * @see https://www.archiverjs.com/#quick-start
  168. */
  169. async zipFiles(_configs) {
  170. const configs = toArrayIfNot(_configs);
  171. const zipFile = this.getZipFile();
  172. const archive = archiver('zip', {
  173. zlib: { level: this.zlibLevel },
  174. });
  175. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  176. archive.on('warning', (err) => {
  177. if (err.code === 'ENOENT') logger.error(err);
  178. else throw err;
  179. });
  180. // good practice to catch this error explicitly
  181. archive.on('error', (err) => { throw err });
  182. for (const { from, as } of configs) {
  183. const input = fs.createReadStream(from);
  184. // append a file from stream
  185. archive.append(input, { name: as });
  186. }
  187. const output = fs.createWriteStream(zipFile);
  188. // pipe archive data to the file
  189. archive.pipe(output);
  190. // finalize the archive (ie we are done appending files but streams have to finish yet)
  191. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  192. archive.finalize();
  193. await streamToPromise(archive);
  194. logger.debug(`zipped growi data into ${zipFile} (${archive.pointer()} bytes)`);
  195. return zipFile;
  196. }
  197. /**
  198. * get the absolute path to the zip file
  199. *
  200. * @memberOf ImportService
  201. * @param {boolean} [validate=false] boolean to check if the file exists
  202. * @return {string} absolute path to the zip file
  203. */
  204. getZipFile(validate = false) {
  205. const zipFile = path.join(this.baseDir, this.zipFileName);
  206. if (validate) {
  207. try {
  208. fs.accessSync(zipFile);
  209. }
  210. catch (err) {
  211. if (err.code === 'ENOENT') {
  212. logger.error(`${zipFile} does not exist`, err);
  213. }
  214. else {
  215. logger.error(err);
  216. }
  217. throw err;
  218. }
  219. }
  220. return zipFile;
  221. }
  222. /**
  223. * get the absolute path to the zip file
  224. *
  225. * @memberOf ImportService
  226. * @param {boolean} [validate=false] boolean to check if the file exists
  227. * @return {string} absolute path to meta.json
  228. */
  229. getMetaJson(validate = false) {
  230. const jsonFile = path.join(this.baseDir, this.metaFileName);
  231. if (validate) {
  232. try {
  233. fs.accessSync(jsonFile);
  234. }
  235. catch (err) {
  236. if (err.code === 'ENOENT') {
  237. logger.error(`${jsonFile} does not exist`, err);
  238. }
  239. else {
  240. logger.error(err);
  241. }
  242. throw err;
  243. }
  244. }
  245. return jsonFile;
  246. }
  247. /**
  248. * get a model from collection name
  249. *
  250. * @memberOf ExportService
  251. * @param {object} collectionName collection name
  252. * @return {object} instance of mongoose model
  253. */
  254. getModelFromCollectionName(collectionName) {
  255. const Model = this.collectionMap[collectionName];
  256. if (Model == null) {
  257. throw new Error(`cannot find a model for collection name "${collectionName}"`);
  258. }
  259. return Model;
  260. }
  261. }
  262. module.exports = ExportService;