attachment.js 9.1 KB

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