attachment.js 21 KB

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