attachment.js 6.3 KB

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