attachment.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. async function responseForAttachment(res, attachment, forceDownload) {
  12. let fileStream;
  13. try {
  14. fileStream = await fileUploader.findDeliveryFile(attachment);
  15. }
  16. catch (e) {
  17. logger.error(e);
  18. return res.json(ApiResponse.error(e.message));
  19. }
  20. setHeaderToRes(res, attachment, forceDownload);
  21. return fileStream.pipe(res);
  22. }
  23. function setHeaderToRes(res, attachment, forceDownload) {
  24. // download
  25. if (forceDownload) {
  26. const headers = {
  27. 'Content-Type': 'application/force-download',
  28. 'Content-Disposition': `inline;filename*=UTF-8''${encodeURIComponent(attachment.originalName)}`,
  29. };
  30. res.writeHead(200, headers);
  31. }
  32. // reference
  33. else {
  34. res.set('Content-Type', attachment.fileFormat);
  35. }
  36. }
  37. const actions = {};
  38. const api = {};
  39. actions.api = api;
  40. api.download = async function(req, res) {
  41. const id = req.params.id;
  42. const attachment = await Attachment.findById(id);
  43. if (attachment == null) {
  44. return res.json(ApiResponse.error('attachment not found'));
  45. }
  46. // TODO consider page restriction
  47. return responseForAttachment(res, attachment, true);
  48. };
  49. /**
  50. * @api {get} /attachments.get get attachments
  51. * @apiName get
  52. * @apiGroup Attachment
  53. *
  54. * @apiParam {String} id
  55. */
  56. api.get = async function(req, res) {
  57. const id = req.params.id;
  58. const attachment = await Attachment.findById(id);
  59. if (attachment == null) {
  60. return res.json(ApiResponse.error('attachment not found'));
  61. }
  62. // TODO consider page restriction
  63. return responseForAttachment(res, attachment);
  64. };
  65. /**
  66. * @api {get} /attachments.obsoletedGetForMongoDB get attachments from mongoDB
  67. * @apiName get
  68. * @apiGroup Attachment
  69. *
  70. * @apiParam {String} pageId, fileName
  71. */
  72. api.obsoletedGetForMongoDB = async function(req, res) {
  73. if (process.env.FILE_UPLOAD !== 'mongodb') {
  74. return res.status(400);
  75. }
  76. const pageId = req.params.pageId;
  77. const fileName = req.params.fileName;
  78. const filePath = `attachment/${pageId}/${fileName}`;
  79. const attachment = await Attachment.findOne({ filePath });
  80. if (attachment == null) {
  81. return res.json(ApiResponse.error('attachment not found'));
  82. }
  83. return responseForAttachment(res, attachment);
  84. };
  85. /**
  86. * @api {get} /attachments.list Get attachments of the page
  87. * @apiName ListAttachments
  88. * @apiGroup Attachment
  89. *
  90. * @apiParam {String} page_id
  91. */
  92. api.list = async function(req, res) {
  93. const id = req.query.page_id || null;
  94. if (!id) {
  95. return res.json(ApiResponse.error('Parameters page_id is required.'));
  96. }
  97. let attachments = await Attachment.find({page: id})
  98. .sort({'updatedAt': 1})
  99. .populate('creator', User.USER_PUBLIC_FIELDS);
  100. // toJSON
  101. attachments = attachments.map(attachment => {
  102. const json = attachment.toJSON({ virtuals: true});
  103. // omit unnecessary property
  104. json.filePathOnStorage = undefined;
  105. return json;
  106. });
  107. return res.json(ApiResponse.success({ attachments }));
  108. };
  109. /**
  110. * @api {get} /attachments.limit get available capacity of uploaded file with GridFS
  111. * @apiName AddAttachments
  112. * @apiGroup Attachment
  113. */
  114. api.limit = async function(req, res) {
  115. const isUploadable = await fileUploader.checkCapacity(req.query.fileSize);
  116. return res.json(ApiResponse.success({isUploadable: isUploadable}));
  117. };
  118. /**
  119. * @api {post} /attachments.add Add attachment to the page
  120. * @apiName AddAttachments
  121. * @apiGroup Attachment
  122. *
  123. * @apiParam {String} page_id
  124. * @apiParam {File} file
  125. */
  126. api.add = async function(req, res) {
  127. var id = req.body.page_id || 0,
  128. path = decodeURIComponent(req.body.path) || null,
  129. pageCreated = false,
  130. page = {};
  131. debug('id and path are: ', id, path);
  132. var tmpFile = req.file || null;
  133. const isUploadable = await fileUploader.checkCapacity(tmpFile.size);
  134. if (!isUploadable) {
  135. return res.json(ApiResponse.error('MongoDB for uploading files reaches limit'));
  136. }
  137. debug('Uploaded tmpFile: ', tmpFile);
  138. if (!tmpFile) {
  139. return res.json(ApiResponse.error('File error.'));
  140. }
  141. new Promise(function(resolve, reject) {
  142. if (id == 0) {
  143. if (path === null) {
  144. throw new Error('path required if page_id is not specified.');
  145. }
  146. debug('Create page before file upload');
  147. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  148. .then(function(page) {
  149. pageCreated = true;
  150. resolve(page);
  151. })
  152. .catch(reject);
  153. }
  154. else {
  155. Page.findById(id).then(resolve).catch(reject);
  156. }
  157. }).then(function(pageData) {
  158. page = pageData;
  159. id = pageData._id;
  160. var tmpPath = tmpFile.path,
  161. originalName = tmpFile.originalname,
  162. fileName = tmpFile.filename + tmpFile.originalname,
  163. fileType = tmpFile.mimetype,
  164. fileSize = tmpFile.size,
  165. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
  166. tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  167. return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
  168. .then(function(data) {
  169. debug('Uploaded data is: ', data);
  170. // TODO size
  171. return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
  172. }).then(function(data) {
  173. var fileUrl = data.fileUrl;
  174. var result = {
  175. page: page.toObject(),
  176. attachment: data.toObject(),
  177. url: fileUrl,
  178. pageCreated: pageCreated,
  179. };
  180. result.page.creator = User.filterToPublicFields(result.page.creator);
  181. result.attachment.creator = User.filterToPublicFields(result.attachment.creator);
  182. // delete anyway
  183. fs.unlink(tmpPath, function(err) { if (err) { debug('Error while deleting tmp file.') } });
  184. return res.json(ApiResponse.success(result));
  185. }).catch(function(err) {
  186. logger.error('Error on saving attachment data', err);
  187. // @TODO
  188. // Remove from S3
  189. // delete anyway
  190. fs.unlink(tmpPath, function(err) { if (err) { logger.error('Error while deleting tmp file.') } });
  191. return res.json(ApiResponse.error('Error while uploading.'));
  192. });
  193. }).catch(function(err) {
  194. logger.error('Attachement upload error', err);
  195. return res.json(ApiResponse.error('Error.'));
  196. });
  197. };
  198. /**
  199. * @api {post} /attachments.remove Remove attachments
  200. * @apiName RemoveAttachments
  201. * @apiGroup Attachment
  202. *
  203. * @apiParam {String} attachment_id
  204. */
  205. api.remove = function(req, res) {
  206. const id = req.body.attachment_id;
  207. Attachment.findById(id)
  208. .then(function(data) {
  209. const attachment = data;
  210. Attachment.removeAttachment(attachment)
  211. .then(data => {
  212. debug('removeAttachment', data);
  213. return res.json(ApiResponse.success({}));
  214. }).catch(err => {
  215. logger.error('Error', err);
  216. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  217. });
  218. }).catch(err => {
  219. logger.error('Error', err);
  220. return res.status(404);
  221. });
  222. };
  223. return actions;
  224. };