attachment.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. module.exports = function(crowi, app) {
  6. const Attachment = crowi.model('Attachment');
  7. const User = crowi.model('User');
  8. const Page = crowi.model('Page');
  9. const fileUploader = require('../service/file-uploader')(crowi, app);
  10. /**
  11. * Check the user is accessible to the related page
  12. *
  13. * @param {User} user
  14. * @param {Attachment} attachment
  15. */
  16. async function isAccessibleByViewer(user, attachment) {
  17. if (attachment.page != null) {
  18. // eslint-disable-next-line no-return-await
  19. return await Page.isAccessiblePageByViewer(attachment.page, user);
  20. }
  21. return true;
  22. }
  23. /**
  24. * Check the user is accessible to the related page
  25. *
  26. * @param {User} user
  27. * @param {Attachment} attachment
  28. */
  29. async function isDeletableByUser(user, attachment) {
  30. const ownerId = attachment.creator._id || attachment.creator;
  31. if (attachment.page == null) { // when profile image
  32. return user.id === ownerId.toString();
  33. }
  34. // eslint-disable-next-line no-return-await
  35. return await Page.isAccessiblePageByViewer(attachment.page, user);
  36. }
  37. /**
  38. * Common method to response
  39. *
  40. * @param {Response} res
  41. * @param {User} user
  42. * @param {Attachment} attachment
  43. * @param {boolean} forceDownload
  44. */
  45. async function responseForAttachment(res, user, attachment, forceDownload) {
  46. if (attachment == null) {
  47. return res.json(ApiResponse.error('attachment not found'));
  48. }
  49. const isAccessible = await isAccessibleByViewer(user, attachment);
  50. if (!isAccessible) {
  51. return res.json(ApiResponse.error(`Forbidden to access to the attachment '${attachment.id}'`));
  52. }
  53. let fileStream;
  54. try {
  55. fileStream = await fileUploader.findDeliveryFile(attachment);
  56. }
  57. catch (e) {
  58. logger.error(e);
  59. return res.json(ApiResponse.error(e.message));
  60. }
  61. setHeaderToRes(res, attachment, forceDownload);
  62. return fileStream.pipe(res);
  63. }
  64. /**
  65. * set http response header
  66. *
  67. * @param {Response} res
  68. * @param {Attachment} attachment
  69. * @param {boolean} forceDownload
  70. */
  71. function setHeaderToRes(res, attachment, forceDownload) {
  72. // download
  73. if (forceDownload) {
  74. const headers = {
  75. 'Content-Type': 'application/force-download',
  76. 'Content-Disposition': `inline;filename*=UTF-8''${encodeURIComponent(attachment.originalName)}`,
  77. };
  78. res.writeHead(200, headers);
  79. }
  80. // reference
  81. else {
  82. res.set('Content-Type', attachment.fileFormat);
  83. }
  84. }
  85. async function createAttachment(file, user, pageId = null) {
  86. // check limit
  87. const res = await fileUploader.checkLimit(file.size);
  88. if (!res.isUploadable) {
  89. throw new Error(res.errorMessage);
  90. }
  91. const fileStream = fs.createReadStream(file.path, {
  92. flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true,
  93. });
  94. // create an Attachment document and upload file
  95. let attachment;
  96. try {
  97. attachment = await Attachment.create(pageId, user, fileStream, file.originalname, file.mimetype, file.size);
  98. }
  99. catch (err) {
  100. // delete temporary file
  101. fs.unlink(file.path, (err) => { if (err) { logger.error('Error while deleting tmp file.') } });
  102. throw err;
  103. }
  104. return attachment;
  105. }
  106. const actions = {};
  107. const api = {};
  108. actions.api = api;
  109. api.download = async function(req, res) {
  110. const id = req.params.id;
  111. const attachment = await Attachment.findById(id);
  112. return responseForAttachment(res, req.user, attachment, true);
  113. };
  114. /**
  115. * @api {get} /attachments.get get attachments
  116. * @apiName get
  117. * @apiGroup Attachment
  118. *
  119. * @apiParam {String} id
  120. */
  121. api.get = async function(req, res) {
  122. const id = req.params.id;
  123. const attachment = await Attachment.findById(id);
  124. return responseForAttachment(res, req.user, attachment);
  125. };
  126. /**
  127. * @api {get} /attachments.obsoletedGetForMongoDB get attachments from mongoDB
  128. * @apiName get
  129. * @apiGroup Attachment
  130. *
  131. * @apiParam {String} pageId, fileName
  132. */
  133. api.obsoletedGetForMongoDB = async function(req, res) {
  134. if (process.env.FILE_UPLOAD !== 'mongodb') {
  135. return res.status(400);
  136. }
  137. const pageId = req.params.pageId;
  138. const fileName = req.params.fileName;
  139. const filePath = `attachment/${pageId}/${fileName}`;
  140. const attachment = await Attachment.findOne({ filePath });
  141. return responseForAttachment(res, req.user, attachment);
  142. };
  143. /**
  144. * @api {get} /attachments.list Get attachments of the page
  145. * @apiName ListAttachments
  146. * @apiGroup Attachment
  147. *
  148. * @apiParam {String} page_id
  149. */
  150. api.list = async function(req, res) {
  151. const id = req.query.page_id || null;
  152. if (!id) {
  153. return res.json(ApiResponse.error('Parameters page_id is required.'));
  154. }
  155. let attachments = await Attachment.find({ page: id })
  156. .sort({ updatedAt: 1 })
  157. .populate({ path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION });
  158. attachments = attachments.map((attachment) => {
  159. return attachment.toObject({ virtuals: true });
  160. });
  161. return res.json(ApiResponse.success({ attachments }));
  162. };
  163. /**
  164. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  165. * @apiName AddAttachments
  166. * @apiGroup Attachment
  167. */
  168. api.limit = async function(req, res) {
  169. const fileSize = Number(req.query.fileSize);
  170. return res.json(ApiResponse.success(await fileUploader.checkLimit(fileSize)));
  171. };
  172. /**
  173. * @api {post} /attachments.add Add attachment to the page
  174. * @apiName AddAttachments
  175. * @apiGroup Attachment
  176. *
  177. * @apiParam {String} page_id
  178. * @apiParam {File} file
  179. */
  180. api.add = async function(req, res) {
  181. let pageId = req.body.page_id || null;
  182. const pagePath = decodeURIComponent(req.body.path) || null;
  183. let pageCreated = false;
  184. // check params
  185. if (pageId == null && pagePath == null) {
  186. return res.json(ApiResponse.error('Either page_id or path is required.'));
  187. }
  188. if (!req.file) {
  189. return res.json(ApiResponse.error('File error.'));
  190. }
  191. const file = req.file;
  192. let page;
  193. if (pageId == null) {
  194. logger.debug('Create page before file upload');
  195. page = await Page.create(pagePath, `# ${pagePath}`, req.user, { grant: Page.GRANT_OWNER });
  196. pageCreated = true;
  197. pageId = page._id;
  198. }
  199. else {
  200. page = await Page.findById(pageId);
  201. // check the user is accessible
  202. const isAccessible = await Page.isAccessiblePageByViewer(page.id, req.user);
  203. if (!isAccessible) {
  204. return res.json(ApiResponse.error(`Forbidden to access to the page '${page.id}'`));
  205. }
  206. }
  207. let attachment;
  208. try {
  209. attachment = await createAttachment(file, req.user, pageId);
  210. }
  211. catch (err) {
  212. logger.error(err);
  213. return res.json(ApiResponse.error(err.message));
  214. }
  215. const result = {
  216. page: page.toObject(),
  217. attachment: attachment.toObject({ virtuals: true }),
  218. pageCreated,
  219. };
  220. return res.json(ApiResponse.success(result));
  221. };
  222. /**
  223. * @api {post} /attachments.uploadProfileImage Add attachment for profile image
  224. * @apiName UploadProfileImage
  225. * @apiGroup Attachment
  226. *
  227. * @apiParam {File} file
  228. */
  229. api.uploadProfileImage = async function(req, res) {
  230. // check params
  231. if (!req.file) {
  232. return res.json(ApiResponse.error('File error.'));
  233. }
  234. if (!req.user) {
  235. return res.json(ApiResponse.error('param "user" must be set.'));
  236. }
  237. const file = req.file;
  238. // check type
  239. const acceptableFileType = /image\/.+/;
  240. if (!file.mimetype.match(acceptableFileType)) {
  241. return res.json(ApiResponse.error('File type error. Only image files is allowed to set as user picture.'));
  242. }
  243. let attachment;
  244. try {
  245. req.user.deleteImage();
  246. attachment = await createAttachment(file, req.user);
  247. await req.user.updateImage(attachment);
  248. }
  249. catch (err) {
  250. logger.error(err);
  251. return res.json(ApiResponse.error(err.message));
  252. }
  253. const result = {
  254. attachment: attachment.toObject({ virtuals: true }),
  255. };
  256. return res.json(ApiResponse.success(result));
  257. };
  258. /**
  259. * @api {post} /attachments.remove Remove attachments
  260. * @apiName RemoveAttachments
  261. * @apiGroup Attachment
  262. *
  263. * @apiParam {String} attachment_id
  264. */
  265. api.remove = async function(req, res) {
  266. const id = req.body.attachment_id;
  267. const attachment = await Attachment.findById(id);
  268. if (attachment == null) {
  269. return res.json(ApiResponse.error('attachment not found'));
  270. }
  271. const isDeletable = await isDeletableByUser(req.user, attachment);
  272. if (!isDeletable) {
  273. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  274. }
  275. try {
  276. await Attachment.removeWithSubstanceById(id);
  277. }
  278. catch (err) {
  279. logger.error(err);
  280. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  281. }
  282. return res.json(ApiResponse.success({}));
  283. };
  284. /**
  285. * @api {post} /attachments.removeProfileImage Remove profile image attachments
  286. * @apiGroup Attachment
  287. * @apiParam {String} attachment_id
  288. */
  289. api.removeProfileImage = async function(req, res) {
  290. const user = req.user;
  291. const attachment = await Attachment.findById(user.imageAttachment);
  292. if (attachment == null) {
  293. return res.json(ApiResponse.error('attachment not found'));
  294. }
  295. const isDeletable = await isDeletableByUser(user, attachment);
  296. if (!isDeletable) {
  297. return res.json(ApiResponse.error(`Forbidden to remove the attachment '${attachment.id}'`));
  298. }
  299. try {
  300. await user.deleteImage();
  301. }
  302. catch (err) {
  303. logger.error(err);
  304. return res.status(500).json(ApiResponse.error('Error while deleting image'));
  305. }
  306. return res.json(ApiResponse.success({}));
  307. };
  308. return actions;
  309. };