attachment.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. var deliveryFile = {
  22. fileName: fileName,
  23. options: {
  24. headers: {
  25. 'Content-Type': data.fileFormat,
  26. },
  27. },
  28. };
  29. if (deliveryFile.fileName.match(/^\/uploads/)) {
  30. debug('Using loacal file module, just redirecting.')
  31. return res.redirect(deliveryFile.fileName);
  32. } else {
  33. return res.sendFile(deliveryFile.fileName, deliveryFile.options);
  34. }
  35. }).catch(err => {
  36. //debug('error', err);
  37. });
  38. }).catch((err) => {
  39. //debug('err', err);
  40. // not found
  41. return res.status(404).sendFile(crowi.publicDir + '/images/file-not-found.png');
  42. });
  43. };
  44. /**
  45. * @api {get} /attachments.list Get attachments of the page
  46. * @apiName ListAttachments
  47. * @apiGroup Attachment
  48. *
  49. * @apiParam {String} page_id
  50. */
  51. api.list = function(req, res){
  52. var id = req.query.page_id || null;
  53. if (!id) {
  54. return res.json(ApiResponse.error('Parameters page_id is required.'));
  55. }
  56. Attachment.getListByPageId(id)
  57. .then(function(attachments) {
  58. // NOTE: use original fileUrl directly (not proxy) -- 2017.05.08 Yuki Takei
  59. // reason:
  60. // 1. this is buggy (doesn't work on Win)
  61. // 2. ensure backward compatibility of data
  62. // var config = crowi.getConfig();
  63. // var baseUrl = (config.crowi['app:url'] || '');
  64. return res.json(ApiResponse.success({
  65. attachments: attachments.map(at => {
  66. var fileUrl = at.fileUrl;
  67. at = at.toObject();
  68. // at.url = baseUrl + fileUrl;
  69. at.url = fileUrl;
  70. return at;
  71. })
  72. }));
  73. });
  74. };
  75. /**
  76. * @api {post} /attachments.add Add attachment to the page
  77. * @apiName AddAttachments
  78. * @apiGroup Attachment
  79. *
  80. * @apiParam {String} page_id
  81. * @apiParam {File} file
  82. */
  83. api.add = function(req, res){
  84. var id = req.body.page_id || 0,
  85. path = decodeURIComponent(req.body.path) || null,
  86. pageCreated = false,
  87. page = {};
  88. debug('id and path are: ', id, path);
  89. var tmpFile = req.file || null;
  90. debug('Uploaded tmpFile: ', tmpFile);
  91. if (!tmpFile) {
  92. return res.json(ApiResponse.error('File error.'));
  93. }
  94. new Promise(function(resolve, reject) {
  95. if (id == 0) {
  96. if (path === null) {
  97. throw new Error('path required if page_id is not specified.');
  98. }
  99. debug('Create page before file upload');
  100. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  101. .then(function(page) {
  102. pageCreated = true;
  103. resolve(page);
  104. })
  105. .catch(reject);
  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. // isLocalUrl??
  128. if (!fileUrl.match(/^https?/)) {
  129. fileUrl = (config.crowi['app:url'] || '') + fileUrl;
  130. }
  131. var result = {
  132. page: page.toObject(),
  133. attachment: data.toObject(),
  134. url: fileUrl,
  135. pageCreated: pageCreated,
  136. };
  137. result.page.creator = User.filterToPublicFields(result.page.creator);
  138. result.attachment.creator = User.filterToPublicFields(result.attachment.creator);
  139. // delete anyway
  140. fs.unlink(tmpPath, function (err) { if (err) { debug('Error while deleting tmp file.'); } });
  141. return res.json(ApiResponse.success(result));
  142. }).catch(function (err) {
  143. debug('Error on saving attachment data', err);
  144. // @TODO
  145. // Remove from S3
  146. // delete anyway
  147. fs.unlink(tmpPath, function (err) { if (err) { debug('Error while deleting tmp file.'); } });
  148. return res.json(ApiResponse.error('Error while uploading.'));
  149. });
  150. ;
  151. }).catch(function(err) {
  152. debug('Attachement upload error', err);
  153. return res.json(ApiResponse.error('Error.'));
  154. });
  155. };
  156. /**
  157. * @api {post} /attachments.remove Remove attachments
  158. * @apiName RemoveAttachments
  159. * @apiGroup Attachment
  160. *
  161. * @apiParam {String} attachment_id
  162. */
  163. api.remove = function(req, res){
  164. const id = req.body.attachment_id;
  165. Attachment.findById(id)
  166. .then(function(data) {
  167. const attachment = data;
  168. Attachment.removeAttachment(attachment)
  169. .then(data => {
  170. debug('removeAttachment', data);
  171. return res.json(ApiResponse.success({}));
  172. }).catch(err => {
  173. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  174. });
  175. }).catch(err => {
  176. debug('Error', err);
  177. return res.status(404);
  178. });
  179. };
  180. return actions;
  181. };