attachment.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('growi:routss:attachment')
  4. , logger = require('@alias/logger')('growi:routes:attachment')
  5. , Attachment = crowi.model('Attachment')
  6. , User = crowi.model('User')
  7. , Page = crowi.model('Page')
  8. , path = require('path')
  9. , fs = require('fs')
  10. , fileUploader = require('../service/file-uploader')(crowi, app)
  11. , ApiResponse = require('../util/apiResponse')
  12. , actions = {}
  13. , api = {};
  14. actions.api = api;
  15. api.download = function(req, res) {
  16. const id = req.params.id;
  17. Attachment.findById(id)
  18. .then(function(data) {
  19. Attachment.findDeliveryFile(data)
  20. .then(fileName => {
  21. // local
  22. if (fileName.match(/^\/uploads/)) {
  23. return res.download(path.join(crowi.publicDir, fileName), data.originalName);
  24. }
  25. // aws or gridfs
  26. else {
  27. const options = {
  28. headers: {
  29. 'Content-Type': 'application/force-download',
  30. 'Content-Disposition': `inline;filename*=UTF-8''${encodeURIComponent(data.originalName)}`,
  31. }
  32. };
  33. return res.sendFile(fileName, options);
  34. }
  35. });
  36. })
  37. // not found
  38. .catch((err) => {
  39. logger.error('download err', err);
  40. return res.status(404).sendFile(crowi.publicDir + '/images/file-not-found.png');
  41. });
  42. };
  43. /**
  44. * @api {get} /attachments.get get attachments from mongoDB
  45. * @apiName get
  46. * @apiGroup Attachment
  47. *
  48. * @apiParam {String} pageId, fileName
  49. */
  50. api.get = async function(req, res) {
  51. if (process.env.FILE_UPLOAD != 'gridfs') {
  52. return res.status(400);
  53. }
  54. const pageId = req.params.pageId;
  55. const fileName = req.params.fileName;
  56. const filePath = `attachment/${pageId}/${fileName}`;
  57. try {
  58. const fileData = await fileUploader.getFileData(filePath);
  59. res.set('Content-Type', fileData.contentType);
  60. return res.send(ApiResponse.success(fileData.data));
  61. }
  62. catch (e) {
  63. return res.json(ApiResponse.error('attachment not found'));
  64. }
  65. };
  66. /**
  67. * @api {get} /attachments.list Get attachments of the page
  68. * @apiName ListAttachments
  69. * @apiGroup Attachment
  70. *
  71. * @apiParam {String} page_id
  72. */
  73. api.list = function(req, res) {
  74. const id = req.query.page_id || null;
  75. if (!id) {
  76. return res.json(ApiResponse.error('Parameters page_id is required.'));
  77. }
  78. Attachment.getListByPageId(id)
  79. .then(function(attachments) {
  80. // NOTE: use original fileUrl directly (not proxy) -- 2017.05.08 Yuki Takei
  81. // reason:
  82. // 1. this is buggy (doesn't work on Win)
  83. // 2. ensure backward compatibility of data
  84. // var config = crowi.getConfig();
  85. // var baseUrl = (config.crowi['app:siteUrl:fixed'] || '');
  86. return res.json(ApiResponse.success({
  87. attachments: attachments.map(at => {
  88. const fileUrl = at.fileUrl;
  89. at = at.toObject();
  90. // at.url = baseUrl + fileUrl;
  91. at.url = fileUrl;
  92. return at;
  93. })
  94. }));
  95. });
  96. };
  97. /**
  98. * @api {post} /attachments.add Add attachment to the page
  99. * @apiName AddAttachments
  100. * @apiGroup Attachment
  101. *
  102. * @apiParam {String} page_id
  103. * @apiParam {File} file
  104. */
  105. api.add = function(req, res) {
  106. var id = req.body.page_id || 0,
  107. path = decodeURIComponent(req.body.path) || null,
  108. pageCreated = false,
  109. page = {};
  110. debug('id and path are: ', id, path);
  111. var tmpFile = req.file || null;
  112. debug('Uploaded tmpFile: ', tmpFile);
  113. if (!tmpFile) {
  114. return res.json(ApiResponse.error('File error.'));
  115. }
  116. new Promise(function(resolve, reject) {
  117. if (id == 0) {
  118. if (path === null) {
  119. throw new Error('path required if page_id is not specified.');
  120. }
  121. debug('Create page before file upload');
  122. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  123. .then(function(page) {
  124. pageCreated = true;
  125. resolve(page);
  126. })
  127. .catch(reject);
  128. }
  129. else {
  130. Page.findPageById(id).then(resolve).catch(reject);
  131. }
  132. }).then(function(pageData) {
  133. page = pageData;
  134. id = pageData._id;
  135. var tmpPath = tmpFile.path,
  136. originalName = tmpFile.originalname,
  137. fileName = tmpFile.filename + tmpFile.originalname,
  138. fileType = tmpFile.mimetype,
  139. fileSize = tmpFile.size,
  140. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
  141. tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  142. return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
  143. .then(function(data) {
  144. debug('Uploaded data is: ', data);
  145. // TODO size
  146. return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
  147. }).then(function(data) {
  148. var fileUrl = data.fileUrl;
  149. var result = {
  150. page: page.toObject(),
  151. attachment: data.toObject(),
  152. url: fileUrl,
  153. pageCreated: pageCreated,
  154. };
  155. result.page.creator = User.filterToPublicFields(result.page.creator);
  156. result.attachment.creator = User.filterToPublicFields(result.attachment.creator);
  157. // delete anyway
  158. fs.unlink(tmpPath, function(err) { if (err) { debug('Error while deleting tmp file.') } });
  159. return res.json(ApiResponse.success(result));
  160. }).catch(function(err) {
  161. logger.error('Error on saving attachment data', err);
  162. // @TODO
  163. // Remove from S3
  164. // delete anyway
  165. fs.unlink(tmpPath, function(err) { if (err) { logger.error('Error while deleting tmp file.') } });
  166. return res.json(ApiResponse.error('Error while uploading.'));
  167. });
  168. }).catch(function(err) {
  169. logger.error('Attachement upload error', err);
  170. return res.json(ApiResponse.error('Error.'));
  171. });
  172. };
  173. /**
  174. * @api {post} /attachments.remove Remove attachments
  175. * @apiName RemoveAttachments
  176. * @apiGroup Attachment
  177. *
  178. * @apiParam {String} attachment_id
  179. */
  180. api.remove = function(req, res) {
  181. const id = req.body.attachment_id;
  182. Attachment.findById(id)
  183. .then(function(data) {
  184. const attachment = data;
  185. Attachment.removeAttachment(attachment)
  186. .then(data => {
  187. debug('removeAttachment', data);
  188. return res.json(ApiResponse.success({}));
  189. }).catch(err => {
  190. logger.error('Error', err);
  191. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  192. });
  193. }).catch(err => {
  194. logger.error('Error', err);
  195. return res.status(404);
  196. });
  197. };
  198. return actions;
  199. };