attachment.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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 User = crowi.model('User');
  124. const Page = crowi.model('Page');
  125. const { fileUploadService, attachmentService } = 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. const ownerId = attachment.creator._id || attachment.creator;
  147. if (attachment.page == null) { // when profile image
  148. return user.id === ownerId.toString();
  149. }
  150. // eslint-disable-next-line no-return-await
  151. return await Page.isAccessiblePageByViewer(attachment.page, user);
  152. }
  153. /**
  154. * Common method to response
  155. *
  156. * @param {Request} req
  157. * @param {Response} res
  158. * @param {User} user
  159. * @param {Attachment} attachment
  160. * @param {boolean} forceDownload
  161. */
  162. async function responseForAttachment(req, res, attachment, forceDownload) {
  163. if (attachment == null) {
  164. return res.json(ApiResponse.error('attachment not found'));
  165. }
  166. const user = req.user;
  167. const isAccessible = await isAccessibleByViewer(user, attachment);
  168. if (!isAccessible) {
  169. return res.json(ApiResponse.error(`Forbidden to access to the attachment '${attachment.id}'`));
  170. }
  171. // add headers before evaluating 'req.fresh'
  172. setHeaderToRes(res, attachment, forceDownload);
  173. // return 304 if request is "fresh"
  174. // see: http://expressjs.com/en/5x/api.html#req.fresh
  175. if (req.fresh) {
  176. return res.sendStatus(304);
  177. }
  178. if (fileUploadService.canRespond()) {
  179. return fileUploadService.respond(res, attachment);
  180. }
  181. let fileStream;
  182. try {
  183. fileStream = await fileUploadService.findDeliveryFile(attachment);
  184. }
  185. catch (e) {
  186. logger.error(e);
  187. return res.json(ApiResponse.error(e.message));
  188. }
  189. return fileStream.pipe(res);
  190. }
  191. /**
  192. * set http response header
  193. *
  194. * @param {Response} res
  195. * @param {Attachment} attachment
  196. * @param {boolean} forceDownload
  197. */
  198. function setHeaderToRes(res, attachment, forceDownload) {
  199. res.set({
  200. ETag: `Attachment-${attachment._id}`,
  201. 'Last-Modified': attachment.createdAt.toUTCString(),
  202. });
  203. // download
  204. if (forceDownload) {
  205. res.set({
  206. 'Content-Disposition': `attachment;filename*=UTF-8''${encodeURIComponent(attachment.originalName)}`,
  207. });
  208. }
  209. // reference
  210. else {
  211. res.set('Content-Type', attachment.fileFormat);
  212. }
  213. }
  214. async function removeAttachment(attachmentId) {
  215. const { fileUploadService } = crowi;
  216. // retrieve data from DB to get a completely populated instance
  217. const attachment = await Attachment.findById(attachmentId);
  218. await fileUploadService.deleteFile(attachment);
  219. return attachment.remove();
  220. }
  221. const actions = {};
  222. const api = {};
  223. actions.api = api;
  224. api.download = async function(req, res) {
  225. const id = req.params.id;
  226. const attachment = await Attachment.findById(id);
  227. return responseForAttachment(req, res, attachment, true);
  228. };
  229. /**
  230. * @api {get} /attachments.get get attachments
  231. * @apiName get
  232. * @apiGroup Attachment
  233. *
  234. * @apiParam {String} id
  235. */
  236. api.get = async function(req, res) {
  237. const id = req.params.id;
  238. const attachment = await Attachment.findById(id);
  239. return responseForAttachment(req, res, attachment);
  240. };
  241. /**
  242. * @api {get} /attachments.obsoletedGetForMongoDB get attachments from mongoDB
  243. * @apiName get
  244. * @apiGroup Attachment
  245. *
  246. * @apiParam {String} pageId, fileName
  247. */
  248. api.obsoletedGetForMongoDB = async function(req, res) {
  249. if (process.env.FILE_UPLOAD !== 'mongodb') {
  250. return res.status(400);
  251. }
  252. const pageId = req.params.pageId;
  253. const fileName = req.params.fileName;
  254. const filePath = `attachment/${pageId}/${fileName}`;
  255. const attachment = await Attachment.findOne({ filePath });
  256. return responseForAttachment(req, res, attachment);
  257. };
  258. /**
  259. * @swagger
  260. *
  261. * /attachments.list:
  262. * get:
  263. * tags: [Attachments, CrowiCompatibles]
  264. * operationId: listAttachments
  265. * summary: /attachments.list
  266. * description: Get list of attachments in page
  267. * parameters:
  268. * - in: query
  269. * name: page_id
  270. * schema:
  271. * $ref: '#/components/schemas/Page/properties/_id'
  272. * required: true
  273. * responses:
  274. * 200:
  275. * description: Succeeded to get list of attachments.
  276. * content:
  277. * application/json:
  278. * schema:
  279. * properties:
  280. * ok:
  281. * $ref: '#/components/schemas/V1Response/properties/ok'
  282. * attachments:
  283. * type: array
  284. * items:
  285. * $ref: '#/components/schemas/Attachment'
  286. * description: attachment list
  287. * 403:
  288. * $ref: '#/components/responses/403'
  289. * 500:
  290. * $ref: '#/components/responses/500'
  291. */
  292. /**
  293. * @api {get} /attachments.list Get attachments of the page
  294. * @apiName ListAttachments
  295. * @apiGroup Attachment
  296. *
  297. * @apiParam {String} page_id
  298. */
  299. api.list = async function(req, res) {
  300. const id = req.query.page_id || null;
  301. if (!id) {
  302. return res.json(ApiResponse.error('Parameters page_id is required.'));
  303. }
  304. let attachments = await Attachment.find({ page: id })
  305. .sort({ updatedAt: 1 })
  306. .populate({ path: 'creator', select: User.USER_PUBLIC_FIELDS });
  307. attachments = attachments.map((attachment) => {
  308. return attachment.toObject({ virtuals: true });
  309. });
  310. return res.json(ApiResponse.success({ attachments }));
  311. };
  312. /**
  313. * @swagger
  314. *
  315. * /attachments.limit:
  316. * get:
  317. * tags: [Attachments]
  318. * operationId: getAttachmentsLimit
  319. * summary: /attachments.limit
  320. * description: Get available capacity of uploaded file with GridFS
  321. * parameters:
  322. * - in: query
  323. * name: fileSize
  324. * schema:
  325. * type: number
  326. * description: file size
  327. * example: 23175
  328. * required: true
  329. * responses:
  330. * 200:
  331. * description: Succeeded to get available capacity of uploaded file with GridFS.
  332. * content:
  333. * application/json:
  334. * schema:
  335. * properties:
  336. * isUploadable:
  337. * type: boolean
  338. * description: uploadable
  339. * example: true
  340. * ok:
  341. * $ref: '#/components/schemas/V1Response/properties/ok'
  342. * 403:
  343. * $ref: '#/components/responses/403'
  344. * 500:
  345. * $ref: '#/components/responses/500'
  346. */
  347. /**
  348. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  349. * @apiName AddAttachments
  350. * @apiGroup Attachment
  351. */
  352. api.limit = async function(req, res) {
  353. const fileSize = Number(req.query.fileSize);
  354. return res.json(ApiResponse.success(await fileUploadService.checkLimit(fileSize)));
  355. };
  356. /**
  357. * @swagger
  358. *
  359. * /attachments.add:
  360. * post:
  361. * tags: [Attachments, CrowiCompatibles]
  362. * operationId: addAttachment
  363. * summary: /attachments.add
  364. * description: Add attachment to the page
  365. * requestBody:
  366. * content:
  367. * "multipart/form-data":
  368. * schema:
  369. * properties:
  370. * page_id:
  371. * nullable: true
  372. * type: string
  373. * path:
  374. * nullable: true
  375. * type: string
  376. * file:
  377. * type: string
  378. * format: binary
  379. * description: attachment data
  380. * encoding:
  381. * path:
  382. * contentType: application/x-www-form-urlencoded
  383. * "*\/*":
  384. * schema:
  385. * properties:
  386. * page_id:
  387. * nullable: true
  388. * type: string
  389. * path:
  390. * nullable: true
  391. * type: string
  392. * file:
  393. * type: string
  394. * format: binary
  395. * description: attachment data
  396. * encoding:
  397. * path:
  398. * contentType: application/x-www-form-urlencoded
  399. * responses:
  400. * 200:
  401. * description: Succeeded to add attachment.
  402. * content:
  403. * application/json:
  404. * schema:
  405. * properties:
  406. * ok:
  407. * $ref: '#/components/schemas/V1Response/properties/ok'
  408. * page:
  409. * $ref: '#/components/schemas/Page'
  410. * attachment:
  411. * $ref: '#/components/schemas/Attachment'
  412. * url:
  413. * $ref: '#/components/schemas/Attachment/properties/url'
  414. * pageCreated:
  415. * type: boolean
  416. * description: whether the page was created
  417. * example: false
  418. * 403:
  419. * $ref: '#/components/responses/403'
  420. * 500:
  421. * $ref: '#/components/responses/500'
  422. */
  423. /**
  424. * @api {post} /attachments.add Add attachment to the page
  425. * @apiName AddAttachments
  426. * @apiGroup Attachment
  427. *
  428. * @apiParam {String} page_id
  429. * @apiParam {File} file
  430. */
  431. api.add = async function(req, res) {
  432. let pageId = req.body.page_id || null;
  433. const pagePath = req.body.path || null;
  434. let pageCreated = false;
  435. // check params
  436. if (pageId == null && pagePath == null) {
  437. return res.json(ApiResponse.error('Either page_id or path is required.'));
  438. }
  439. if (!req.file) {
  440. return res.json(ApiResponse.error('File error.'));
  441. }
  442. const file = req.file;
  443. let page;
  444. if (pageId == null) {
  445. logger.debug('Create page before file upload');
  446. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  447. pageCreated = true;
  448. pageId = page._id;
  449. }
  450. else {
  451. page = await Page.findById(pageId);
  452. // check the user is accessible
  453. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  454. if (!isAccessible) {
  455. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  456. }
  457. }
  458. let attachment;
  459. try {
  460. attachment = await attachmentService.createAttachment(file, req.user, pageId);
  461. }
  462. catch (err) {
  463. logger.error(err);
  464. return res.json(ApiResponse.error(err.message));
  465. }
  466. const result = {
  467. page: page.toObject(),
  468. attachment: attachment.toObject({ virtuals: true }),
  469. pageCreated,
  470. };
  471. return res.json(ApiResponse.success(result));
  472. };
  473. /**
  474. * @swagger
  475. *
  476. * /attachments.uploadProfileImage:
  477. * post:
  478. * tags: [Attachments]
  479. * operationId: uploadProfileImage
  480. * summary: /attachments.uploadProfileImage
  481. * description: Upload profile image
  482. * requestBody:
  483. * content:
  484. * "multipart/form-data":
  485. * schema:
  486. * properties:
  487. * file:
  488. * type: string
  489. * format: binary
  490. * description: attachment data
  491. * user:
  492. * type: string
  493. * description: user to set profile image
  494. * encoding:
  495. * path:
  496. * contentType: application/x-www-form-urlencoded
  497. * "*\/*":
  498. * schema:
  499. * properties:
  500. * file:
  501. * type: string
  502. * format: binary
  503. * description: attachment data
  504. * user:
  505. * type: string
  506. * description: user to set profile
  507. * encoding:
  508. * path:
  509. * contentType: application/x-www-form-urlencoded
  510. * responses:
  511. * 200:
  512. * description: Succeeded to add attachment.
  513. * content:
  514. * application/json:
  515. * schema:
  516. * properties:
  517. * ok:
  518. * $ref: '#/components/schemas/V1Response/properties/ok'
  519. * attachment:
  520. * $ref: '#/components/schemas/AttachmentProfile'
  521. * 403:
  522. * $ref: '#/components/responses/403'
  523. * 500:
  524. * $ref: '#/components/responses/500'
  525. */
  526. /**
  527. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  528. * @apiName UploadProfileImage
  529. * @apiGroup Attachment
  530. *
  531. * @apiParam {File} file
  532. */
  533. api.uploadProfileImage = async function(req, res) {
  534. // check params
  535. if (!req.file) {
  536. return res.json(ApiResponse.error('File error.'));
  537. }
  538. if (!req.user) {
  539. return res.json(ApiResponse.error('param "user" must be set.'));
  540. }
  541. const file = req.file;
  542. // check type
  543. const acceptableFileType = /image\/.+/;
  544. if (!file.mimetype.match(acceptableFileType)) {
  545. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  546. }
  547. let attachment;
  548. try {
  549. req.user.deleteImage();
  550. attachment = await attachmentService.createAttachment(file, req.user);
  551. await req.user.updateImage(attachment);
  552. }
  553. catch (err) {
  554. logger.error(err);
  555. return res.json(ApiResponse.error(err.message));
  556. }
  557. const result = {
  558. attachment: attachment.toObject({ virtuals: true }),
  559. };
  560. return res.json(ApiResponse.success(result));
  561. };
  562. /**
  563. * @swagger
  564. *
  565. * /attachments.remove:
  566. * post:
  567. * tags: [Attachments, CrowiCompatibles]
  568. * operationId: removeAttachment
  569. * summary: /attachments.remove
  570. * description: Remove attachment
  571. * requestBody:
  572. * content:
  573. * application/json:
  574. * schema:
  575. * properties:
  576. * attachment_id:
  577. * $ref: '#/components/schemas/Attachment/properties/_id'
  578. * required:
  579. * - attachment_id
  580. * responses:
  581. * 200:
  582. * description: Succeeded to remove attachment.
  583. * content:
  584. * application/json:
  585. * schema:
  586. * properties:
  587. * ok:
  588. * $ref: '#/components/schemas/V1Response/properties/ok'
  589. * 403:
  590. * $ref: '#/components/responses/403'
  591. * 500:
  592. * $ref: '#/components/responses/500'
  593. */
  594. /**
  595. * @api {post} /attachments.remove Remove attachments
  596. * @apiName RemoveAttachments
  597. * @apiGroup Attachment
  598. *
  599. * @apiParam {String} attachment_id
  600. */
  601. api.remove = async function(req, res) {
  602. const id = req.body.attachment_id;
  603. const attachment = await Attachment.findById(id);
  604. if (attachment == null) {
  605. return res.json(ApiResponse.error('attachment not found'));
  606. }
  607. const isDeletable = await isDeletableByUser(req.user, attachment);
  608. if (!isDeletable) {
  609. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  610. }
  611. try {
  612. await removeAttachment(attachment);
  613. }
  614. catch (err) {
  615. logger.error(err);
  616. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  617. }
  618. return res.json(ApiResponse.success({}));
  619. };
  620. /**
  621. * @swagger
  622. *
  623. * /attachments.removeProfileImage:
  624. * post:
  625. * tags: [Attachments]
  626. * operationId: removeProfileImage
  627. * summary: /attachments.removeProfileImage
  628. * description: Remove profile image
  629. * requestBody:
  630. * content:
  631. * application/json:
  632. * schema:
  633. * properties:
  634. * user:
  635. * type: string
  636. * description: user to remove profile image
  637. * responses:
  638. * 200:
  639. * description: Succeeded to add attachment.
  640. * content:
  641. * application/json:
  642. * schema:
  643. * properties:
  644. * ok:
  645. * $ref: '#/components/schemas/V1Response/properties/ok'
  646. * 403:
  647. * $ref: '#/components/responses/403'
  648. * 500:
  649. * $ref: '#/components/responses/500'
  650. */
  651. /**
  652. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  653. * @apiGroup Attachment
  654. * @apiParam {String} attachment_id
  655. */
  656. api.removeProfileImage = async function(req, res) {
  657. const user = req.user;
  658. const attachment = await Attachment.findById(user.imageAttachment);
  659. if (attachment == null) {
  660. return res.json(ApiResponse.error('attachment not found'));
  661. }
  662. const isDeletable = await isDeletableByUser(user, attachment);
  663. if (!isDeletable) {
  664. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  665. }
  666. try {
  667. await user.deleteImage();
  668. }
  669. catch (err) {
  670. logger.error(err);
  671. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  672. }
  673. return res.json(ApiResponse.success({}));
  674. };
  675. return actions;
  676. };