attachment.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. * /_api/attachments.list:
  274. * get:
  275. * tags: [Attachments, CrowiCompatibles]
  276. * operationId: listAttachments
  277. * summary: /_api/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, populate: User.IMAGE_POPULATION });
  319. attachments = attachments.map((attachment) => {
  320. return attachment.toObject({ virtuals: true });
  321. });
  322. return res.json(ApiResponse.success({ attachments }));
  323. };
  324. /**
  325. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  326. * @apiName AddAttachments
  327. * @apiGroup Attachment
  328. */
  329. api.limit = async function(req, res) {
  330. const fileSize = Number(req.query.fileSize);
  331. return res.json(ApiResponse.success(await fileUploader.checkLimit(fileSize)));
  332. };
  333. /**
  334. * @swagger
  335. *
  336. * /_api/attachments.add:
  337. * post:
  338. * tags: [Attachments, CrowiCompatibles]
  339. * operationId: addAttachment
  340. * summary: /_api/attachments.add
  341. * description: Add attachment to the page
  342. * requestBody:
  343. * content:
  344. * "multipart/form-data":
  345. * schema:
  346. * properties:
  347. * page_id:
  348. * nullable: true
  349. * type: string
  350. * path:
  351. * nullable: true
  352. * type: string
  353. * file:
  354. * type: string
  355. * format: binary
  356. * description: attachment data
  357. * encoding:
  358. * path:
  359. * contentType: application/x-www-form-urlencoded
  360. * "*\/*":
  361. * schema:
  362. * properties:
  363. * page_id:
  364. * nullable: true
  365. * type: string
  366. * path:
  367. * nullable: true
  368. * type: string
  369. * file:
  370. * type: string
  371. * format: binary
  372. * description: attachment data
  373. * encoding:
  374. * path:
  375. * contentType: application/x-www-form-urlencoded
  376. * responses:
  377. * 200:
  378. * description: Succeeded to add attachment.
  379. * content:
  380. * application/json:
  381. * schema:
  382. * properties:
  383. * ok:
  384. * $ref: '#/components/schemas/V1Response/properties/ok'
  385. * page:
  386. * $ref: '#/components/schemas/Page'
  387. * attachment:
  388. * $ref: '#/components/schemas/Attachment'
  389. * url:
  390. * $ref: '#/components/schemas/Attachment/properties/url'
  391. * pageCreated:
  392. * type: boolean
  393. * description: whether the page was created
  394. * example: false
  395. * 403:
  396. * $ref: '#/components/responses/403'
  397. * 500:
  398. * $ref: '#/components/responses/500'
  399. */
  400. /**
  401. * @api {post} /attachments.add Add attachment to the page
  402. * @apiName AddAttachments
  403. * @apiGroup Attachment
  404. *
  405. * @apiParam {String} page_id
  406. * @apiParam {File} file
  407. */
  408. api.add = async function(req, res) {
  409. let pageId = req.body.page_id || null;
  410. const pagePath = decodeURIComponent(req.body.path) || null;
  411. let pageCreated = false;
  412. // check params
  413. if (pageId == null && pagePath == null) {
  414. return res.json(ApiResponse.error('Either page_id or path is required.'));
  415. }
  416. if (!req.file) {
  417. return res.json(ApiResponse.error('File error.'));
  418. }
  419. const file = req.file;
  420. let page;
  421. if (pageId == null) {
  422. logger.debug('Create page before file upload');
  423. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  424. pageCreated = true;
  425. pageId = page._id;
  426. }
  427. else {
  428. page = await Page.findById(pageId);
  429. // check the user is accessible
  430. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  431. if (!isAccessible) {
  432. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  433. }
  434. }
  435. let attachment;
  436. try {
  437. attachment = await createAttachment(file, req.user, pageId);
  438. }
  439. catch (err) {
  440. logger.error(err);
  441. return res.json(ApiResponse.error(err.message));
  442. }
  443. const result = {
  444. page: page.toObject(),
  445. attachment: attachment.toObject({ virtuals: true }),
  446. pageCreated,
  447. };
  448. return res.json(ApiResponse.success(result));
  449. };
  450. /**
  451. * @swagger
  452. *
  453. * /_api/attachments.uploadProfileImage:
  454. * post:
  455. * tags: [Attachments]
  456. * operationId: uploadProfileImage
  457. * summary: /_api/attachments.uploadProfileImage
  458. * description: Upload profile image
  459. * requestBody:
  460. * content:
  461. * "multipart/form-data":
  462. * schema:
  463. * properties:
  464. * file:
  465. * type: string
  466. * format: binary
  467. * description: attachment data
  468. * user:
  469. * type: string
  470. * description: user to set profile image
  471. * encoding:
  472. * path:
  473. * contentType: application/x-www-form-urlencoded
  474. * "*\/*":
  475. * schema:
  476. * properties:
  477. * file:
  478. * type: string
  479. * format: binary
  480. * description: attachment data
  481. * user:
  482. * type: string
  483. * description: user to set profile
  484. * encoding:
  485. * path:
  486. * contentType: application/x-www-form-urlencoded
  487. * responses:
  488. * 200:
  489. * description: Succeeded to add attachment.
  490. * content:
  491. * application/json:
  492. * schema:
  493. * properties:
  494. * ok:
  495. * $ref: '#/components/schemas/V1Response/properties/ok'
  496. * attachment:
  497. * $ref: '#/components/schemas/AttachmentProfile'
  498. * 403:
  499. * $ref: '#/components/responses/403'
  500. * 500:
  501. * $ref: '#/components/responses/500'
  502. */
  503. /**
  504. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  505. * @apiName UploadProfileImage
  506. * @apiGroup Attachment
  507. *
  508. * @apiParam {File} file
  509. */
  510. api.uploadProfileImage = async function(req, res) {
  511. // check params
  512. if (!req.file) {
  513. return res.json(ApiResponse.error('File error.'));
  514. }
  515. if (!req.user) {
  516. return res.json(ApiResponse.error('param "user" must be set.'));
  517. }
  518. const file = req.file;
  519. // check type
  520. const acceptableFileType = /image\/.+/;
  521. if (!file.mimetype.match(acceptableFileType)) {
  522. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  523. }
  524. let attachment;
  525. try {
  526. req.user.deleteImage();
  527. attachment = await createAttachment(file, req.user);
  528. await req.user.updateImage(attachment);
  529. }
  530. catch (err) {
  531. logger.error(err);
  532. return res.json(ApiResponse.error(err.message));
  533. }
  534. const result = {
  535. attachment: attachment.toObject({ virtuals: true }),
  536. };
  537. return res.json(ApiResponse.success(result));
  538. };
  539. /**
  540. * @swagger
  541. *
  542. * /_api/attachments.remove:
  543. * post:
  544. * tags: [Attachments, CrowiCompatibles]
  545. * operationId: removeAttachment
  546. * summary: /_api/attachments.remove
  547. * description: Remove attachment
  548. * requestBody:
  549. * content:
  550. * application/json:
  551. * schema:
  552. * properties:
  553. * attachment_id:
  554. * $ref: '#/components/schemas/Attachment/properties/_id'
  555. * required:
  556. * - attachment_id
  557. * responses:
  558. * 200:
  559. * description: Succeeded to remove attachment.
  560. * content:
  561. * application/json:
  562. * schema:
  563. * properties:
  564. * ok:
  565. * $ref: '#/components/schemas/V1Response/properties/ok'
  566. * 403:
  567. * $ref: '#/components/responses/403'
  568. * 500:
  569. * $ref: '#/components/responses/500'
  570. */
  571. /**
  572. * @api {post} /attachments.remove Remove attachments
  573. * @apiName RemoveAttachments
  574. * @apiGroup Attachment
  575. *
  576. * @apiParam {String} attachment_id
  577. */
  578. api.remove = async function(req, res) {
  579. const id = req.body.attachment_id;
  580. const attachment = await Attachment.findById(id);
  581. if (attachment == null) {
  582. return res.json(ApiResponse.error('attachment not found'));
  583. }
  584. const isDeletable = await isDeletableByUser(req.user, attachment);
  585. if (!isDeletable) {
  586. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  587. }
  588. try {
  589. await Attachment.removeWithSubstanceById(id);
  590. }
  591. catch (err) {
  592. logger.error(err);
  593. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  594. }
  595. return res.json(ApiResponse.success({}));
  596. };
  597. /**
  598. * @swagger
  599. *
  600. * /_api/attachments.removeProfileImage:
  601. * post:
  602. * tags: [Attachments]
  603. * operationId: removeProfileImage
  604. * summary: /_api/attachments.removeProfileImage
  605. * description: Remove profile image
  606. * requestBody:
  607. * content:
  608. * application/json:
  609. * schema:
  610. * properties:
  611. * user:
  612. * type: string
  613. * description: user to remove profile image
  614. * responses:
  615. * 200:
  616. * description: Succeeded to add attachment.
  617. * content:
  618. * application/json:
  619. * schema:
  620. * properties:
  621. * ok:
  622. * $ref: '#/components/schemas/V1Response/properties/ok'
  623. * 403:
  624. * $ref: '#/components/responses/403'
  625. * 500:
  626. * $ref: '#/components/responses/500'
  627. */
  628. /**
  629. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  630. * @apiGroup Attachment
  631. * @apiParam {String} attachment_id
  632. */
  633. api.removeProfileImage = async function(req, res) {
  634. const user = req.user;
  635. const attachment = await Attachment.findById(user.imageAttachment);
  636. if (attachment == null) {
  637. return res.json(ApiResponse.error('attachment not found'));
  638. }
  639. const isDeletable = await isDeletableByUser(user, attachment);
  640. if (!isDeletable) {
  641. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  642. }
  643. try {
  644. await user.deleteImage();
  645. }
  646. catch (err) {
  647. logger.error(err);
  648. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  649. }
  650. return res.json(ApiResponse.success({}));
  651. };
  652. return actions;
  653. };