attachment.js 22 KB

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