attachment.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. debug(deliveryFile.fileName);
  30. if (deliveryFile.fileName.match(/^\/uploads/)) {
  31. debug('Using loacal file module, just redirecting.')
  32. return res.redirect(deliveryFile.fileName);
  33. } else {
  34. return res.sendFile(deliveryFile.fileName, deliveryFile.options);
  35. }
  36. });
  37. }).catch((err) => {
  38. debug('err', err);
  39. // not found
  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. return res.json(ApiResponse.success({
  58. attachments: attachments
  59. }));
  60. });
  61. };
  62. /**
  63. * @api {post} /attachments.add Add attachment to the page
  64. * @apiName AddAttachments
  65. * @apiGroup Attachment
  66. *
  67. * @apiParam {String} page_id
  68. * @apiParam {File} file
  69. */
  70. api.add = function(req, res){
  71. var id = req.body.page_id || 0,
  72. path = decodeURIComponent(req.body.path) || null,
  73. pageCreated = false,
  74. page = {};
  75. debug('id and path are: ', id, path);
  76. var tmpFile = req.file || null;
  77. debug('Uploaded tmpFile: ', tmpFile);
  78. if (!tmpFile) {
  79. return res.json(ApiResponse.error('File error.'));
  80. }
  81. new Promise(function(resolve, reject) {
  82. if (id == 0) {
  83. if (path === null) {
  84. throw new Error('path required if page_id is not specified.');
  85. }
  86. debug('Create page before file upload');
  87. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  88. .then(function(page) {
  89. pageCreated = true;
  90. resolve(page);
  91. })
  92. .catch(reject);
  93. } else {
  94. Page.findPageById(id).then(resolve).catch(reject);
  95. }
  96. }).then(function(pageData) {
  97. page = pageData;
  98. id = pageData._id;
  99. var tmpPath = tmpFile.path,
  100. originalName = tmpFile.originalname,
  101. fileName = tmpFile.filename + tmpFile.originalname,
  102. fileType = tmpFile.mimetype,
  103. fileSize = tmpFile.size,
  104. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
  105. tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  106. return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
  107. .then(function(data) {
  108. debug('Uploaded data is: ', data);
  109. // TODO size
  110. return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
  111. }).then(function(data) {
  112. var fileUrl = data.fileUrl;
  113. var config = crowi.getConfig();
  114. // isLocalUrl??
  115. if (!fileUrl.match(/^https?/)) {
  116. fileUrl = (config.crowi['app:url'] || '') + fileUrl;
  117. }
  118. var result = {
  119. page: page.toObject(),
  120. attachment: data.toObject(),
  121. url: fileUrl,
  122. filename: fileUrl, // this is for inline-attachemnets plugin http://inlineattachment.readthedocs.io/en/latest/pages/configuration.html
  123. pageCreated: pageCreated,
  124. };
  125. result.page.creator = User.filterToPublicFields(result.page.creator);
  126. result.attachment.creator = User.filterToPublicFields(result.attachment.creator);
  127. // delete anyway
  128. fs.unlink(tmpPath, function (err) { if (err) { debug('Error while deleting tmp file.'); } });
  129. return res.json(ApiResponse.success(result));
  130. }).catch(function (err) {
  131. debug('Error on saving attachment data', err);
  132. // @TODO
  133. // Remove from S3
  134. // delete anyway
  135. fs.unlink(tmpPath, function (err) { if (err) { debug('Error while deleting tmp file.'); } });
  136. return res.json(ApiResponse.error('Error while uploading.'));
  137. });
  138. ;
  139. }).catch(function(err) {
  140. debug('Attachement upload error', err);
  141. return res.json(ApiResponse.error('Error.'));
  142. });
  143. };
  144. api.remove = function(req, res){
  145. var id = req.params.id;
  146. };
  147. return actions;
  148. };