import.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. const loggerFactory = require('@alias/logger');
  2. const logger = loggerFactory('growi:routes:apiv3:import'); // eslint-disable-line no-unused-vars
  3. const path = require('path');
  4. const multer = require('multer');
  5. const express = require('express');
  6. const GrowiArchiveImportOption = require('@commons/models/admin/growi-archive-import-option');
  7. const router = express.Router();
  8. /**
  9. * @swagger
  10. * tags:
  11. * name: Import
  12. */
  13. /**
  14. * @swagger
  15. *
  16. * components:
  17. * schemas:
  18. * ImportStatus:
  19. * description: ImportStatus
  20. * type: object
  21. * properties:
  22. * zipFileStat:
  23. * type: object
  24. * description: the property object
  25. * progressList:
  26. * type: array
  27. * items:
  28. * type: object
  29. * description: progress data for each exporting collections
  30. * isImporting:
  31. * type: boolean
  32. * description: whether the current importing job exists or not
  33. */
  34. /**
  35. * generate overwrite params with overwrite-params/* modules
  36. * @param {string} collectionName
  37. * @param {object} req Request Object
  38. * @param {GrowiArchiveImportOption} options GrowiArchiveImportOption instance
  39. */
  40. const generateOverwriteParams = (collectionName, req, options) => {
  41. switch (collectionName) {
  42. case 'pages':
  43. return require('./overwrite-params/pages')(req, options);
  44. case 'revisions':
  45. return require('./overwrite-params/revisions')(req, options);
  46. case 'attachmentFiles.chunks':
  47. return require('./overwrite-params/attachmentFiles.chunks')(req, options);
  48. default:
  49. return {};
  50. }
  51. };
  52. module.exports = (crowi) => {
  53. const { growiBridgeService, importService } = crowi;
  54. const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
  55. const loginRequired = require('../../middlewares/login-required')(crowi);
  56. const adminRequired = require('../../middlewares/admin-required')(crowi);
  57. const csrf = require('../../middlewares/csrf')(crowi);
  58. this.adminEvent = crowi.event('admin');
  59. // setup event
  60. this.adminEvent.on('onProgressForImport', (data) => {
  61. crowi.getIo().sockets.emit('admin:onProgressForImport', data);
  62. });
  63. this.adminEvent.on('onTerminateForImport', (data) => {
  64. crowi.getIo().sockets.emit('admin:onTerminateForImport', data);
  65. });
  66. this.adminEvent.on('onErrorForImport', (data) => {
  67. crowi.getIo().sockets.emit('admin:onErrorForImport', data);
  68. });
  69. const uploads = multer({
  70. storage: multer.diskStorage({
  71. destination: (req, file, cb) => {
  72. cb(null, importService.baseDir);
  73. },
  74. filename(req, file, cb) {
  75. // to prevent hashing the file name. files with same name will be overwritten.
  76. cb(null, file.originalname);
  77. },
  78. }),
  79. fileFilter: (req, file, cb) => {
  80. if (path.extname(file.originalname) === '.zip') {
  81. return cb(null, true);
  82. }
  83. cb(new Error('Only ".zip" is allowed'));
  84. },
  85. });
  86. /**
  87. * @swagger
  88. *
  89. * /import/status:
  90. * get:
  91. * tags: [Import]
  92. * operationId: getImportStatus
  93. * summary: /import/status
  94. * description: Get properties of stored zip files for import
  95. * responses:
  96. * 200:
  97. * description: the zip file statuses
  98. * content:
  99. * application/json:
  100. * schema:
  101. * properties:
  102. * status:
  103. * $ref: '#/components/schemas/ImportStatus'
  104. */
  105. router.get('/status', accessTokenParser, loginRequired, adminRequired, async(req, res) => {
  106. try {
  107. const status = await importService.getStatus();
  108. return res.apiv3(status);
  109. }
  110. catch (err) {
  111. return res.apiv3Err(err, 500);
  112. }
  113. });
  114. /**
  115. * @swagger
  116. *
  117. * /import:
  118. * post:
  119. * tags: [Import]
  120. * operationId: executeImport
  121. * summary: /import
  122. * description: import a collection from a zipped json
  123. * requestBody:
  124. * required: true
  125. * content:
  126. * application/json:
  127. * schema:
  128. * type: object
  129. * properties:
  130. * fileName:
  131. * description: the file name of zip file
  132. * type: string
  133. * collections:
  134. * description: collection names to import
  135. * type: array
  136. * items:
  137. * type: string
  138. * optionsMap:
  139. * description: |
  140. * the map object of importing option that have collection name as the key
  141. * additionalProperties:
  142. * type: object
  143. * properties:
  144. * mode:
  145. * description: Import mode
  146. * type: string
  147. * enum: [insert, upsert, flushAndInsert]
  148. * responses:
  149. * 200:
  150. * description: Import process has requested
  151. */
  152. router.post('/', accessTokenParser, loginRequired, adminRequired, csrf, async(req, res) => {
  153. // TODO: add express validator
  154. const { fileName, collections, optionsMap } = req.body;
  155. const zipFile = importService.getFile(fileName);
  156. // return response first
  157. res.apiv3();
  158. /*
  159. * unzip, parse
  160. */
  161. let meta = null;
  162. let fileStatsToImport = null;
  163. try {
  164. // unzip
  165. await importService.unzip(zipFile);
  166. // eslint-disable-next-line no-unused-vars
  167. const { meta: parsedMeta, fileStats, innerFileStats } = await growiBridgeService.parseZipFile(zipFile);
  168. meta = parsedMeta;
  169. // filter innerFileStats
  170. fileStatsToImport = innerFileStats.filter(({ fileName, collectionName, size }) => {
  171. return collections.includes(collectionName);
  172. });
  173. }
  174. catch (err) {
  175. logger.error(err);
  176. this.adminEvent.emit('onErrorForImport', { message: err.message });
  177. return;
  178. }
  179. /*
  180. * validate with meta.json
  181. */
  182. try {
  183. importService.validate(meta);
  184. }
  185. catch (err) {
  186. logger.error(err);
  187. this.adminEvent.emit('onErrorForImport', { message: err.message });
  188. return;
  189. }
  190. // generate maps of ImportSettings to import
  191. const importSettingsMap = {};
  192. fileStatsToImport.forEach(({ fileName, collectionName }) => {
  193. // instanciate GrowiArchiveImportOption
  194. const options = new GrowiArchiveImportOption(null, optionsMap[collectionName]);
  195. // generate options
  196. const importSettings = importService.generateImportSettings(options.mode);
  197. importSettings.jsonFileName = fileName;
  198. // generate overwrite params
  199. importSettings.overwriteParams = generateOverwriteParams(collectionName, req, options);
  200. importSettingsMap[collectionName] = importSettings;
  201. });
  202. /*
  203. * import
  204. */
  205. try {
  206. importService.import(collections, importSettingsMap);
  207. }
  208. catch (err) {
  209. logger.error(err);
  210. this.adminEvent.emit('onErrorForImport', { message: err.message });
  211. }
  212. });
  213. /**
  214. * @swagger
  215. *
  216. * /import/upload:
  217. * post:
  218. * tags: [Import]
  219. * operationId: uploadImport
  220. * summary: /import/upload
  221. * description: upload a zip file
  222. * responses:
  223. * 200:
  224. * description: the file is uploaded
  225. * content:
  226. * application/json:
  227. * schema:
  228. * properties:
  229. * meta:
  230. * type: object
  231. * description: the meta data of the uploaded file
  232. * fileName:
  233. * type: string
  234. * description: the base name of the uploaded file
  235. * fileStats:
  236. * type: array
  237. * items:
  238. * type: object
  239. * description: the property of each extracted file
  240. */
  241. router.post('/upload', uploads.single('file'), accessTokenParser, loginRequired, adminRequired, csrf, async(req, res) => {
  242. const { file } = req;
  243. const zipFile = importService.getFile(file.filename);
  244. try {
  245. const data = await growiBridgeService.parseZipFile(zipFile);
  246. // validate with meta.json
  247. importService.validate(data.meta);
  248. return res.apiv3(data);
  249. }
  250. catch (err) {
  251. // TODO: use ApiV3Error
  252. logger.error(err);
  253. return res.status(500).send({ status: 'ERROR' });
  254. }
  255. });
  256. /**
  257. * @swagger
  258. *
  259. * /import/all:
  260. * delete:
  261. * tags: [Import]
  262. * operationId: deleteImportAll
  263. * summary: /import/all
  264. * description: Delete all zip files
  265. * responses:
  266. * 200:
  267. * description: all files are deleted
  268. */
  269. router.delete('/all', accessTokenParser, loginRequired, adminRequired, csrf, async(req, res) => {
  270. try {
  271. importService.deleteAllZipFiles();
  272. return res.apiv3();
  273. }
  274. catch (err) {
  275. logger.error(err);
  276. return res.apiv3Err(err, 500);
  277. }
  278. });
  279. return router;
  280. };