attachment.js 22 KB

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