attachment.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. var config = crowi.getConfig();
  59. var baseUrl = (config.crowi['app:url'] || '');
  60. return res.json(ApiResponse.success({
  61. attachments: attachments.map(at => {
  62. var fileUrl = at.fileUrl;
  63. at = at.toObject();
  64. at.url = baseUrl + fileUrl;
  65. return at;
  66. })
  67. }));
  68. });
  69. };
  70. /**
  71. * @api {post} /attachments.add Add attachment to the page
  72. * @apiName AddAttachments
  73. * @apiGroup Attachment
  74. *
  75. * @apiParam {String} page_id
  76. * @apiParam {File} file
  77. */
  78. api.add = function(req, res){
  79. var id = req.body.page_id || 0,
  80. path = decodeURIComponent(req.body.path) || null,
  81. pageCreated = false,
  82. page = {};
  83. debug('id and path are: ', id, path);
  84. var tmpFile = req.file || null;
  85. debug('Uploaded tmpFile: ', tmpFile);
  86. if (!tmpFile) {
  87. return res.json(ApiResponse.error('File error.'));
  88. }
  89. new Promise(function(resolve, reject) {
  90. if (id == 0) {
  91. if (path === null) {
  92. throw new Error('path required if page_id is not specified.');
  93. }
  94. debug('Create page before file upload');
  95. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  96. .then(function(page) {
  97. pageCreated = true;
  98. resolve(page);
  99. })
  100. .catch(reject);
  101. } else {
  102. Page.findPageById(id).then(resolve).catch(reject);
  103. }
  104. }).then(function(pageData) {
  105. page = pageData;
  106. id = pageData._id;
  107. var tmpPath = tmpFile.path,
  108. originalName = tmpFile.originalname,
  109. fileName = tmpFile.filename + tmpFile.originalname,
  110. fileType = tmpFile.mimetype,
  111. fileSize = tmpFile.size,
  112. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
  113. tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  114. return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
  115. .then(function(data) {
  116. debug('Uploaded data is: ', data);
  117. // TODO size
  118. return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
  119. }).then(function(data) {
  120. var fileUrl = data.fileUrl;
  121. var config = crowi.getConfig();
  122. // isLocalUrl??
  123. if (!fileUrl.match(/^https?/)) {
  124. fileUrl = (config.crowi['app:url'] || '') + fileUrl;
  125. }
  126. var result = {
  127. page: page.toObject(),
  128. attachment: data.toObject(),
  129. url: fileUrl,
  130. filename: fileUrl, // this is for inline-attachemnets plugin http://inlineattachment.readthedocs.io/en/latest/pages/configuration.html
  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. ;
  147. }).catch(function(err) {
  148. debug('Attachement upload error', err);
  149. return res.json(ApiResponse.error('Error.'));
  150. });
  151. };
  152. /**
  153. * @api {post} /attachments.remove Remove attachments
  154. * @apiName RemoveAttachments
  155. * @apiGroup Attachment
  156. *
  157. * @apiParam {String} attachment_id
  158. */
  159. api.remove = function(req, res){
  160. const id = req.body.attachment_id;
  161. Attachment.findById(id)
  162. .then(function(data) {
  163. const attachment = data;
  164. Attachment.removeAttachment(attachment)
  165. .then(data => {
  166. debug('removeAttachment', data);
  167. return res.json(ApiResponse.success({}));
  168. }).catch(err => {
  169. return res.status(500).json(ApiResponse.error('Error while deleting file'));
  170. });
  171. }).catch(err => {
  172. debug('Error', err);
  173. return res.status(404);
  174. });
  175. };
  176. return actions;
  177. };