attachment.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('growi:routs:attachment')
  4. , Attachment = crowi.model('Attachment')
  5. , User = crowi.model('User')
  6. , Page = crowi.model('Page')
  7. , config = crowi.getConfig()
  8. , path = require('path')
  9. , fs = require('fs')
  10. , fileUploader = require('../util/fileUploader')(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
  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. debug('download err', err);
  40. return res.status(404).sendFile(crowi.publicDir + '/images/file-not-found.png');
  41. });
  42. };
  43. /**
  44. * @api {get} /attachments.list Get attachments of the page
  45. * @apiName ListAttachments
  46. * @apiGroup Attachment
  47. *
  48. * @apiParam {String} page_id
  49. */
  50. api.list = function(req, res) {
  51. var id = req.query.page_id || null;
  52. if (!id) {
  53. return res.json(ApiResponse.error('Parameters page_id is required.'));
  54. }
  55. Attachment.getListByPageId(id)
  56. .then(function(attachments) {
  57. // NOTE: use original fileUrl directly (not proxy) -- 2017.05.08 Yuki Takei
  58. // reason:
  59. // 1. this is buggy (doesn't work on Win)
  60. // 2. ensure backward compatibility of data
  61. // var config = crowi.getConfig();
  62. // var baseUrl = (config.crowi['app:url'] || '');
  63. return res.json(ApiResponse.success({
  64. attachments: attachments.map(at => {
  65. var fileUrl = at.fileUrl;
  66. at = at.toObject();
  67. // at.url = baseUrl + fileUrl;
  68. at.url = fileUrl;
  69. return at;
  70. })
  71. }));
  72. });
  73. };
  74. /**
  75. * @api {post} /attachments.add Add attachment to the page
  76. * @apiName AddAttachments
  77. * @apiGroup Attachment
  78. *
  79. * @apiParam {String} page_id
  80. * @apiParam {File} file
  81. */
  82. api.add = function(req, res) {
  83. var id = req.body.page_id || 0,
  84. path = decodeURIComponent(req.body.path) || null,
  85. pageCreated = false,
  86. page = {};
  87. debug('id and path are: ', id, path);
  88. var tmpFile = req.file || null;
  89. debug('Uploaded tmpFile: ', tmpFile);
  90. if (!tmpFile) {
  91. return res.json(ApiResponse.error('File error.'));
  92. }
  93. new Promise(function(resolve, reject) {
  94. if (id == 0) {
  95. if (path === null) {
  96. throw new Error('path required if page_id is not specified.');
  97. }
  98. debug('Create page before file upload');
  99. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  100. .then(function(page) {
  101. pageCreated = true;
  102. resolve(page);
  103. })
  104. .catch(reject);
  105. }
  106. else {
  107. Page.findPageById(id).then(resolve).catch(reject);
  108. }
  109. }).then(function(pageData) {
  110. page = pageData;
  111. id = pageData._id;
  112. var tmpPath = tmpFile.path,
  113. originalName = tmpFile.originalname,
  114. fileName = tmpFile.filename + tmpFile.originalname,
  115. fileType = tmpFile.mimetype,
  116. fileSize = tmpFile.size,
  117. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
  118. tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  119. return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
  120. .then(function(data) {
  121. debug('Uploaded data is: ', data);
  122. // TODO size
  123. return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
  124. }).then(function(data) {
  125. var fileUrl = data.fileUrl;
  126. var config = crowi.getConfig();
  127. var result = {
  128. page: page.toObject(),
  129. attachment: data.toObject(),
  130. url: fileUrl,
  131. pageCreated: pageCreated,
  132. };
  133. result.page.creator = User.filterToPublicFields(result.page.creator);
  134. result.attachment.creator = User.filterToPublicFields(result.attachment.creator);
  135. // delete anyway
  136. fs.unlink(tmpPath, function(err) { if (err) { debug('Error while deleting tmp file.') } });
  137. return res.json(ApiResponse.success(result));
  138. }).catch(function(err) {
  139. debug('Error on saving attachment data', err);
  140. // @TODO
  141. // Remove from S3
  142. // delete anyway
  143. fs.unlink(tmpPath, function(err) { if (err) { debug('Error while deleting tmp file.') } });
  144. return res.json(ApiResponse.error('Error while uploading.'));
  145. });
  146. }).catch(function(err) {
  147. debug('Attachement upload error', err);
  148. return res.json(ApiResponse.error('Error.'));
  149. });
  150. };
  151. /**
  152. * @api {post} /attachments.remove Remove attachments
  153. * @apiName RemoveAttachments
  154. * @apiGroup Attachment
  155. *
  156. * @apiParam {String} attachment_id
  157. */
  158. api.remove = function(req, res) {
  159. const id = req.body.attachment_id;
  160. Attachment.findById(id)
  161. .then(function(data) {
  162. const attachment = data;
  163. Attachment.removeAttachment(attachment)
  164. .then(data => {
  165. debug('removeAttachment', data);
  166. return res.json(ApiResponse.success({}));
  167. }).catch(err => {
  168. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  169. });
  170. }).catch(err => {
  171. debug('Error', err);
  172. return res.status(404);
  173. });
  174. };
  175. return actions;
  176. };