attachment.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. /* eslint-disable no-use-before-define */
  2. const logger = require('@alias/logger')('growi:routes:attachment');
  3. const ApiResponse = require('../util/apiResponse');
  4. /**
  5. * @swagger
  6. * tags:
  7. * name: Attachments
  8. */
  9. /**
  10. * @swagger
  11. *
  12. * components:
  13. * schemas:
  14. * Attachment:
  15. * description: Attachment
  16. * type: object
  17. * properties:
  18. * _id:
  19. * type: string
  20. * description: attachment ID
  21. * example: 5e0734e072560e001761fa67
  22. * __v:
  23. * type: number
  24. * description: attachment version
  25. * example: 0
  26. * fileFormat:
  27. * type: string
  28. * description: file format in MIME
  29. * example: text/plain
  30. * fileName:
  31. * type: string
  32. * description: file name
  33. * example: 601b7c59d43a042c0117e08dd37aad0aimage.txt
  34. * originalName:
  35. * type: string
  36. * description: original file name
  37. * example: file.txt
  38. * creator:
  39. * $ref: '#/components/schemas/User'
  40. * page:
  41. * type: string
  42. * description: page ID attached at
  43. * example: 5e07345972560e001761fa63
  44. * createdAt:
  45. * type: string
  46. * description: date created at
  47. * example: 2010-01-01T00:00:00.000Z
  48. * fileSize:
  49. * type: number
  50. * description: file size
  51. * example: 3494332
  52. * url:
  53. * type: string
  54. * description: attachment URL
  55. * example: http://localhost/files/5e0734e072560e001761fa67
  56. * filePathProxied:
  57. * type: string
  58. * description: file path proxied
  59. * example: "/attachment/5e0734e072560e001761fa67"
  60. * downloadPathProxied:
  61. * type: string
  62. * description: download path proxied
  63. * example: "/download/5e0734e072560e001761fa67"
  64. */
  65. /**
  66. * @swagger
  67. *
  68. * components:
  69. * schemas:
  70. * AttachmentProfile:
  71. * description: Attachment
  72. * type: object
  73. * properties:
  74. * id:
  75. * type: string
  76. * description: attachment ID
  77. * example: 5e0734e072560e001761fa67
  78. * _id:
  79. * type: string
  80. * description: attachment ID
  81. * example: 5e0734e072560e001761fa67
  82. * __v:
  83. * type: number
  84. * description: attachment version
  85. * example: 0
  86. * fileFormat:
  87. * type: string
  88. * description: file format in MIME
  89. * example: image/png
  90. * fileName:
  91. * type: string
  92. * description: file name
  93. * example: 601b7c59d43a042c0117e08dd37aad0a.png
  94. * originalName:
  95. * type: string
  96. * description: original file name
  97. * example: profile.png
  98. * creator:
  99. * $ref: '#/components/schemas/User/properties/_id'
  100. * page:
  101. * type: string
  102. * description: page ID attached at
  103. * example: null
  104. * createdAt:
  105. * type: string
  106. * description: date created at
  107. * example: 2010-01-01T00:00:00.000Z
  108. * fileSize:
  109. * type: number
  110. * description: file size
  111. * example: 3494332
  112. * filePathProxied:
  113. * type: string
  114. * description: file path proxied
  115. * example: "/attachment/5e0734e072560e001761fa67"
  116. * downloadPathProxied:
  117. * type: string
  118. * description: download path proxied
  119. * example: "/download/5e0734e072560e001761fa67"
  120. */
  121. module.exports = function(crowi, app) {
  122. const Attachment = crowi.model('Attachment');
  123. const Page = crowi.model('Page');
  124. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  125. const { fileUploadService, attachmentService, globalNotificationService } = crowi;
  126. /**
  127. * Check the user is accessible to the related page
  128. *
  129. * @param {User} user
  130. * @param {Attachment} attachment
  131. */
  132. async function isAccessibleByViewer(user, attachment) {
  133. if (attachment.page != null) {
  134. // eslint-disable-next-line no-return-await
  135. return await Page.isAccessiblePageByViewer(attachment.page, user);
  136. }
  137. return true;
  138. }
  139. /**
  140. * Check the user is accessible to the related page
  141. *
  142. * @param {User} user
  143. * @param {Attachment} attachment
  144. */
  145. async function isDeletableByUser(user, attachment) {
  146. // deletable if creator is null
  147. if (attachment.creator == null) {
  148. return true;
  149. }
  150. const ownerId = attachment.creator._id || attachment.creator;
  151. if (attachment.page == null) { // when profile image
  152. return user.id === ownerId.toString();
  153. }
  154. // eslint-disable-next-line no-return-await
  155. return await Page.isAccessiblePageByViewer(attachment.page, user);
  156. }
  157. /**
  158. * Common method to response
  159. *
  160. * @param {Request} req
  161. * @param {Response} res
  162. * @param {User} user
  163. * @param {Attachment} attachment
  164. * @param {boolean} forceDownload
  165. */
  166. async function responseForAttachment(req, res, attachment, forceDownload) {
  167. if (attachment == null) {
  168. return res.json(ApiResponse.error('attachment not found'));
  169. }
  170. const user = req.user;
  171. const isAccessible = await isAccessibleByViewer(user, attachment);
  172. if (!isAccessible) {
  173. return res.json(ApiResponse.error(`Forbidden to access to the attachment '${attachment.id}'`));
  174. }
  175. // add headers before evaluating 'req.fresh'
  176. setHeaderToRes(res, attachment, forceDownload);
  177. // return 304 if request is "fresh"
  178. // see: http://expressjs.com/en/5x/api.html#req.fresh
  179. if (req.fresh) {
  180. return res.sendStatus(304);
  181. }
  182. if (fileUploadService.canRespond()) {
  183. return fileUploadService.respond(res, attachment);
  184. }
  185. let fileStream;
  186. try {
  187. fileStream = await fileUploadService.findDeliveryFile(attachment);
  188. }
  189. catch (e) {
  190. logger.error(e);
  191. return res.json(ApiResponse.error(e.message));
  192. }
  193. return fileStream.pipe(res);
  194. }
  195. /**
  196. * set http response header
  197. *
  198. * @param {Response} res
  199. * @param {Attachment} attachment
  200. * @param {boolean} forceDownload
  201. */
  202. function setHeaderToRes(res, attachment, forceDownload) {
  203. res.set({
  204. ETag: `Attachment-${attachment._id}`,
  205. 'Last-Modified': attachment.createdAt.toUTCString(),
  206. });
  207. // download
  208. if (forceDownload) {
  209. res.set({
  210. 'Content-Disposition': `attachment;filename*=UTF-8''${encodeURIComponent(attachment.originalName)}`,
  211. });
  212. }
  213. // reference
  214. else {
  215. res.set({
  216. 'Content-Type': attachment.fileFormat,
  217. 'Content-Security-Policy': "script-src 'unsafe-hashes'",
  218. });
  219. }
  220. }
  221. async function removeAttachment(attachmentId) {
  222. const { fileUploadService } = crowi;
  223. // retrieve data from DB to get a completely populated instance
  224. const attachment = await Attachment.findById(attachmentId);
  225. await fileUploadService.deleteFile(attachment);
  226. return attachment.remove();
  227. }
  228. const actions = {};
  229. const api = {};
  230. actions.api = api;
  231. api.download = async function(req, res) {
  232. const id = req.params.id;
  233. const attachment = await Attachment.findById(id);
  234. return responseForAttachment(req, res, attachment, true);
  235. };
  236. /**
  237. * @api {get} /attachments.get get attachments
  238. * @apiName get
  239. * @apiGroup Attachment
  240. *
  241. * @apiParam {String} id
  242. */
  243. api.get = async function(req, res) {
  244. const id = req.params.id;
  245. const attachment = await Attachment.findById(id);
  246. return responseForAttachment(req, res, attachment);
  247. };
  248. /**
  249. * @api {get} /attachments.obsoletedGetForMongoDB get attachments from mongoDB
  250. * @apiName get
  251. * @apiGroup Attachment
  252. *
  253. * @apiParam {String} pageId, fileName
  254. */
  255. api.obsoletedGetForMongoDB = async function(req, res) {
  256. if (process.env.FILE_UPLOAD !== 'mongodb') {
  257. return res.status(400);
  258. }
  259. const pageId = req.params.pageId;
  260. const fileName = req.params.fileName;
  261. const filePath = `attachment/${pageId}/${fileName}`;
  262. const attachment = await Attachment.findOne({ filePath });
  263. return responseForAttachment(req, res, attachment);
  264. };
  265. /**
  266. * @swagger
  267. *
  268. * /attachments.limit:
  269. * get:
  270. * tags: [Attachments]
  271. * operationId: getAttachmentsLimit
  272. * summary: /attachments.limit
  273. * description: Get available capacity of uploaded file with GridFS
  274. * parameters:
  275. * - in: query
  276. * name: fileSize
  277. * schema:
  278. * type: number
  279. * description: file size
  280. * example: 23175
  281. * required: true
  282. * responses:
  283. * 200:
  284. * description: Succeeded to get available capacity of uploaded file with GridFS.
  285. * content:
  286. * application/json:
  287. * schema:
  288. * properties:
  289. * isUploadable:
  290. * type: boolean
  291. * description: uploadable
  292. * example: true
  293. * ok:
  294. * $ref: '#/components/schemas/V1Response/properties/ok'
  295. * 403:
  296. * $ref: '#/components/responses/403'
  297. * 500:
  298. * $ref: '#/components/responses/500'
  299. */
  300. /**
  301. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  302. * @apiName AddAttachments
  303. * @apiGroup Attachment
  304. */
  305. api.limit = async function(req, res) {
  306. const fileSize = Number(req.query.fileSize);
  307. return res.json(ApiResponse.success(await fileUploadService.checkLimit(fileSize)));
  308. };
  309. /**
  310. * @swagger
  311. *
  312. * /attachments.add:
  313. * post:
  314. * tags: [Attachments, CrowiCompatibles]
  315. * operationId: addAttachment
  316. * summary: /attachments.add
  317. * description: Add attachment to the page
  318. * requestBody:
  319. * content:
  320. * "multipart/form-data":
  321. * schema:
  322. * properties:
  323. * page_id:
  324. * nullable: true
  325. * type: string
  326. * path:
  327. * nullable: true
  328. * type: string
  329. * file:
  330. * type: string
  331. * format: binary
  332. * description: attachment data
  333. * encoding:
  334. * path:
  335. * contentType: application/x-www-form-urlencoded
  336. * "*\/*":
  337. * schema:
  338. * properties:
  339. * page_id:
  340. * nullable: true
  341. * type: string
  342. * path:
  343. * nullable: true
  344. * type: string
  345. * file:
  346. * type: string
  347. * format: binary
  348. * description: attachment data
  349. * encoding:
  350. * path:
  351. * contentType: application/x-www-form-urlencoded
  352. * responses:
  353. * 200:
  354. * description: Succeeded to add attachment.
  355. * content:
  356. * application/json:
  357. * schema:
  358. * properties:
  359. * ok:
  360. * $ref: '#/components/schemas/V1Response/properties/ok'
  361. * page:
  362. * $ref: '#/components/schemas/Page'
  363. * attachment:
  364. * $ref: '#/components/schemas/Attachment'
  365. * url:
  366. * $ref: '#/components/schemas/Attachment/properties/url'
  367. * pageCreated:
  368. * type: boolean
  369. * description: whether the page was created
  370. * example: false
  371. * 403:
  372. * $ref: '#/components/responses/403'
  373. * 500:
  374. * $ref: '#/components/responses/500'
  375. */
  376. /**
  377. * @api {post} /attachments.add Add attachment to the page
  378. * @apiName AddAttachments
  379. * @apiGroup Attachment
  380. *
  381. * @apiParam {String} page_id
  382. * @apiParam {File} file
  383. */
  384. api.add = async function(req, res) {
  385. let pageId = req.body.page_id || null;
  386. const pagePath = req.body.path || null;
  387. let pageCreated = false;
  388. // check params
  389. if (pageId == null && pagePath == null) {
  390. return res.json(ApiResponse.error('Either page_id or path is required.'));
  391. }
  392. if (!req.file) {
  393. return res.json(ApiResponse.error('File error.'));
  394. }
  395. const file = req.file;
  396. let page;
  397. if (pageId == null) {
  398. logger.debug('Create page before file upload');
  399. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  400. pageCreated = true;
  401. pageId = page._id;
  402. }
  403. else {
  404. page = await Page.findById(pageId);
  405. // check the user is accessible
  406. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  407. if (!isAccessible) {
  408. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  409. }
  410. }
  411. let attachment;
  412. try {
  413. attachment = await attachmentService.createAttachment(file, req.user, pageId);
  414. }
  415. catch (err) {
  416. logger.error(err);
  417. return res.json(ApiResponse.error(err.message));
  418. }
  419. const result = {
  420. page: page.toObject(),
  421. attachment: attachment.toObject({ virtuals: true }),
  422. pageCreated,
  423. };
  424. res.json(ApiResponse.success(result));
  425. if (pageCreated) {
  426. // global notification
  427. try {
  428. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, page, req.user);
  429. }
  430. catch (err) {
  431. logger.error('Create notification failed', err);
  432. }
  433. }
  434. };
  435. /**
  436. * @swagger
  437. *
  438. * /attachments.uploadProfileImage:
  439. * post:
  440. * tags: [Attachments]
  441. * operationId: uploadProfileImage
  442. * summary: /attachments.uploadProfileImage
  443. * description: Upload profile image
  444. * requestBody:
  445. * content:
  446. * "multipart/form-data":
  447. * schema:
  448. * properties:
  449. * file:
  450. * type: string
  451. * format: binary
  452. * description: attachment data
  453. * user:
  454. * type: string
  455. * description: user to set profile image
  456. * encoding:
  457. * path:
  458. * contentType: application/x-www-form-urlencoded
  459. * "*\/*":
  460. * schema:
  461. * properties:
  462. * file:
  463. * type: string
  464. * format: binary
  465. * description: attachment data
  466. * user:
  467. * type: string
  468. * description: user to set profile
  469. * encoding:
  470. * path:
  471. * contentType: application/x-www-form-urlencoded
  472. * responses:
  473. * 200:
  474. * description: Succeeded to add attachment.
  475. * content:
  476. * application/json:
  477. * schema:
  478. * properties:
  479. * ok:
  480. * $ref: '#/components/schemas/V1Response/properties/ok'
  481. * attachment:
  482. * $ref: '#/components/schemas/AttachmentProfile'
  483. * 403:
  484. * $ref: '#/components/responses/403'
  485. * 500:
  486. * $ref: '#/components/responses/500'
  487. */
  488. /**
  489. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  490. * @apiName UploadProfileImage
  491. * @apiGroup Attachment
  492. *
  493. * @apiParam {File} file
  494. */
  495. api.uploadProfileImage = async function(req, res) {
  496. // check params
  497. if (!req.file) {
  498. return res.json(ApiResponse.error('File error.'));
  499. }
  500. if (!req.user) {
  501. return res.json(ApiResponse.error('param "user" must be set.'));
  502. }
  503. const file = req.file;
  504. // check type
  505. const acceptableFileType = /image\/.+/;
  506. if (!file.mimetype.match(acceptableFileType)) {
  507. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  508. }
  509. let attachment;
  510. try {
  511. req.user.deleteImage();
  512. attachment = await attachmentService.createAttachment(file, req.user);
  513. await req.user.updateImage(attachment);
  514. }
  515. catch (err) {
  516. logger.error(err);
  517. return res.json(ApiResponse.error(err.message));
  518. }
  519. const result = {
  520. attachment: attachment.toObject({ virtuals: true }),
  521. };
  522. return res.json(ApiResponse.success(result));
  523. };
  524. /**
  525. * @swagger
  526. *
  527. * /attachments.remove:
  528. * post:
  529. * tags: [Attachments, CrowiCompatibles]
  530. * operationId: removeAttachment
  531. * summary: /attachments.remove
  532. * description: Remove attachment
  533. * requestBody:
  534. * content:
  535. * application/json:
  536. * schema:
  537. * properties:
  538. * attachment_id:
  539. * $ref: '#/components/schemas/Attachment/properties/_id'
  540. * required:
  541. * - attachment_id
  542. * responses:
  543. * 200:
  544. * description: Succeeded to remove attachment.
  545. * content:
  546. * application/json:
  547. * schema:
  548. * properties:
  549. * ok:
  550. * $ref: '#/components/schemas/V1Response/properties/ok'
  551. * 403:
  552. * $ref: '#/components/responses/403'
  553. * 500:
  554. * $ref: '#/components/responses/500'
  555. */
  556. /**
  557. * @api {post} /attachments.remove Remove attachments
  558. * @apiName RemoveAttachments
  559. * @apiGroup Attachment
  560. *
  561. * @apiParam {String} attachment_id
  562. */
  563. api.remove = async function(req, res) {
  564. const id = req.body.attachment_id;
  565. const attachment = await Attachment.findById(id);
  566. if (attachment == null) {
  567. return res.json(ApiResponse.error('attachment not found'));
  568. }
  569. const isDeletable = await isDeletableByUser(req.user, attachment);
  570. if (!isDeletable) {
  571. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  572. }
  573. try {
  574. await removeAttachment(attachment);
  575. }
  576. catch (err) {
  577. logger.error(err);
  578. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  579. }
  580. return res.json(ApiResponse.success({}));
  581. };
  582. /**
  583. * @swagger
  584. *
  585. * /attachments.removeProfileImage:
  586. * post:
  587. * tags: [Attachments]
  588. * operationId: removeProfileImage
  589. * summary: /attachments.removeProfileImage
  590. * description: Remove profile image
  591. * requestBody:
  592. * content:
  593. * application/json:
  594. * schema:
  595. * properties:
  596. * user:
  597. * type: string
  598. * description: user to remove profile image
  599. * responses:
  600. * 200:
  601. * description: Succeeded to add attachment.
  602. * content:
  603. * application/json:
  604. * schema:
  605. * properties:
  606. * ok:
  607. * $ref: '#/components/schemas/V1Response/properties/ok'
  608. * 403:
  609. * $ref: '#/components/responses/403'
  610. * 500:
  611. * $ref: '#/components/responses/500'
  612. */
  613. /**
  614. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  615. * @apiGroup Attachment
  616. * @apiParam {String} attachment_id
  617. */
  618. api.removeProfileImage = async function(req, res) {
  619. const user = req.user;
  620. const attachment = await Attachment.findById(user.imageAttachment);
  621. if (attachment == null) {
  622. return res.json(ApiResponse.error('attachment not found'));
  623. }
  624. const isDeletable = await isDeletableByUser(user, attachment);
  625. if (!isDeletable) {
  626. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  627. }
  628. try {
  629. await user.deleteImage();
  630. }
  631. catch (err) {
  632. logger.error(err);
  633. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  634. }
  635. return res.json(ApiResponse.success({}));
  636. };
  637. return actions;
  638. };