import.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. // eslint-disable-next-line no-unused-vars
  6. const { ObjectId } = require('mongoose').Types;
  7. const express = require('express');
  8. const router = express.Router();
  9. /**
  10. * @swagger
  11. * tags:
  12. * name: Import
  13. */
  14. /**
  15. * @swagger
  16. *
  17. * components:
  18. * schemas:
  19. * 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. module.exports = (crowi) => {
  35. const { growiBridgeService, importService } = crowi;
  36. const accessTokenParser = require('../../middleware/access-token-parser')(crowi);
  37. const loginRequired = require('../../middleware/login-required')(crowi);
  38. const adminRequired = require('../../middleware/admin-required')(crowi);
  39. const csrf = require('../../middleware/csrf')(crowi);
  40. this.adminEvent = crowi.event('admin');
  41. // setup event
  42. this.adminEvent.on('onProgressForImport', (data) => {
  43. crowi.getIo().sockets.emit('admin:onProgressForImport', data);
  44. });
  45. this.adminEvent.on('onTerminateForImport', (data) => {
  46. crowi.getIo().sockets.emit('admin:onTerminateForImport', data);
  47. });
  48. const uploads = multer({
  49. storage: multer.diskStorage({
  50. destination: (req, file, cb) => {
  51. cb(null, importService.baseDir);
  52. },
  53. filename(req, file, cb) {
  54. // to prevent hashing the file name. files with same name will be overwritten.
  55. cb(null, file.originalname);
  56. },
  57. }),
  58. fileFilter: (req, file, cb) => {
  59. if (path.extname(file.originalname) === '.zip') {
  60. return cb(null, true);
  61. }
  62. cb(new Error('Only ".zip" is allowed'));
  63. },
  64. });
  65. /**
  66. * defined overwrite params for each collection
  67. * all imported documents are overwriten by this value
  68. * each value can be any value or a function (_value, { _document, key, schema }) { return newValue }
  69. *
  70. * @param {string} collectionName MongoDB collection name
  71. * @param {object} req request object
  72. * @return {object} document to be persisted
  73. */
  74. const overwriteParamsFn = (collectionName, schema, req) => {
  75. /* eslint-disable no-case-declarations */
  76. switch (collectionName) {
  77. case 'pages':
  78. // TODO: use schema and req to generate overwriteParams
  79. // e.g. { creator: schema.creator === 'me' ? ObjectId(req.user._id) : importService.keepOriginal }
  80. return {
  81. status: 'published', // FIXME when importing users and user groups
  82. grant: 1, // FIXME when importing users and user groups
  83. grantedUsers: [], // FIXME when importing users and user groups
  84. grantedGroup: null, // FIXME when importing users and user groups
  85. creator: ObjectId(req.user._id), // FIXME when importing users
  86. lastUpdateUser: ObjectId(req.user._id), // FIXME when importing users
  87. liker: [], // FIXME when importing users
  88. seenUsers: [], // FIXME when importing users
  89. commentCount: 0, // FIXME when importing comments
  90. extended: {}, // FIXME when ?
  91. pageIdOnHackmd: undefined, // FIXME when importing hackmd?
  92. revisionHackmdSynced: undefined, // FIXME when importing hackmd?
  93. hasDraftOnHackmd: undefined, // FIXME when importing hackmd?
  94. };
  95. // case 'revisoins':
  96. // return {};
  97. // case 'users':
  98. // return {};
  99. // ... add more cases
  100. default:
  101. return {};
  102. }
  103. /* eslint-enable no-case-declarations */
  104. };
  105. /**
  106. * @swagger
  107. *
  108. * /import/status:
  109. * get:
  110. * tags: [Import]
  111. * description: Get properties of stored zip files for import
  112. * responses:
  113. * 200:
  114. * description: the zip file statuses
  115. * content:
  116. * application/json:
  117. * schema:
  118. * properties:
  119. * status:
  120. * $ref: '#/components/schemas/ImportStatus'
  121. */
  122. router.get('/status', accessTokenParser, loginRequired, adminRequired, async(req, res) => {
  123. try {
  124. const status = await importService.getStatus();
  125. return res.apiv3(status);
  126. }
  127. catch (err) {
  128. return res.apiv3Err(err, 500);
  129. }
  130. });
  131. /**
  132. * @swagger
  133. *
  134. * /import:
  135. * post:
  136. * tags: [Import]
  137. * description: import a collection from a zipped json
  138. * parameters:
  139. * - name: fileName
  140. * in: path
  141. * description: the file name of zip file
  142. * required: true
  143. * schema:
  144. * type: string
  145. * - name: collections
  146. * description: collection names to import
  147. * required: true
  148. * schema:
  149. * type: array
  150. * items:
  151. * type: string
  152. * - name: optionsMap
  153. * description: the map object of importing option
  154. * schema:
  155. * type: object
  156. * responses:
  157. * 200:
  158. * description: the data is successfully imported
  159. * content:
  160. * application/json:
  161. * schema:
  162. * properties:
  163. * results:
  164. * type: array
  165. * items:
  166. * type: object
  167. * description: collectionName, insertedIds, failedIds
  168. */
  169. router.post('/', accessTokenParser, loginRequired, adminRequired, csrf, async(req, res) => {
  170. // TODO: add express validator
  171. const { fileName, collections, optionsMap } = req.body;
  172. const zipFile = importService.getFile(fileName);
  173. /*
  174. * unzip, parse
  175. */
  176. let meta = null;
  177. let fileStatsToImport = null;
  178. try {
  179. // unzip
  180. await importService.unzip(zipFile);
  181. // eslint-disable-next-line no-unused-vars
  182. const { meta: parsedMeta, fileStats, innerFileStats } = await growiBridgeService.parseZipFile(zipFile);
  183. meta = parsedMeta;
  184. // filter innerFileStats
  185. fileStatsToImport = innerFileStats.filter(({ fileName, collectionName, size }) => {
  186. return collections.includes(collectionName);
  187. });
  188. }
  189. catch (err) {
  190. logger.error(err);
  191. return res.apiv3Err(err, 500);
  192. }
  193. /*
  194. * validate with meta.json
  195. */
  196. try {
  197. importService.validate(meta);
  198. }
  199. catch (err) {
  200. logger.error(err);
  201. return res.apiv3Err(err);
  202. }
  203. // generate maps of ImportOptions to import
  204. const importOptionsMap = {};
  205. fileStatsToImport.forEach(({ fileName, collectionName }) => {
  206. const options = optionsMap[collectionName];
  207. // generate options
  208. const importOptions = importService.generateImportOptions(options.mode);
  209. importOptions.jsonFileName = fileName;
  210. importOptions.overwriteParams = overwriteParamsFn(collectionName, options.schema, req);
  211. importOptionsMap[collectionName] = importOptions;
  212. });
  213. /*
  214. * import
  215. */
  216. try {
  217. importService.import(collections, importOptionsMap);
  218. return res.apiv3();
  219. }
  220. catch (err) {
  221. logger.error(err);
  222. return res.apiv3Err(err, 500);
  223. }
  224. });
  225. /**
  226. * @swagger
  227. *
  228. * /import/upload:
  229. * post:
  230. * tags: [Import]
  231. * description: upload a zip file
  232. * responses:
  233. * 200:
  234. * description: the file is uploaded
  235. * content:
  236. * application/json:
  237. * schema:
  238. * properties:
  239. * meta:
  240. * type: object
  241. * description: the meta data of the uploaded file
  242. * fileName:
  243. * type: string
  244. * description: the base name of the uploaded file
  245. * fileStats:
  246. * type: array
  247. * items:
  248. * type: object
  249. * description: the property of each extracted file
  250. */
  251. router.post('/upload', uploads.single('file'), accessTokenParser, loginRequired, adminRequired, csrf, async(req, res) => {
  252. const { file } = req;
  253. const zipFile = importService.getFile(file.filename);
  254. try {
  255. const data = await growiBridgeService.parseZipFile(zipFile);
  256. // validate with meta.json
  257. importService.validate(data.meta);
  258. return res.apiv3(data);
  259. }
  260. catch (err) {
  261. // TODO: use ApiV3Error
  262. logger.error(err);
  263. return res.status(500).send({ status: 'ERROR' });
  264. }
  265. });
  266. /**
  267. * @swagger
  268. *
  269. * /import/all:
  270. * delete:
  271. * tags: [Import]
  272. * description: Delete all zip files
  273. * responses:
  274. * 200:
  275. * description: all files are deleted
  276. */
  277. router.delete('/all', accessTokenParser, loginRequired, adminRequired, csrf, async(req, res) => {
  278. try {
  279. importService.deleteAllZipFiles();
  280. return res.apiv3();
  281. }
  282. catch (err) {
  283. logger.error(err);
  284. return res.apiv3Err(err, 500);
  285. }
  286. });
  287. return router;
  288. };