attachment.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. return res.redirect(deliveryFile.fileName);
  31. } else {
  32. return res.sendFile(deliveryFile.fileName, deliveryFile.options);
  33. }
  34. });
  35. }).catch((err) => {
  36. debug('err', err);
  37. // not found
  38. return res.status(404).sendFile(crowi.publicDir + '/images/file-not-found.png');
  39. });
  40. };
  41. /**
  42. * @api {get} /attachments.list Get attachments of the page
  43. * @apiName ListAttachments
  44. * @apiGroup Attachment
  45. *
  46. * @apiParam {String} page_id
  47. */
  48. api.list = function(req, res){
  49. var id = req.query.page_id || null;
  50. if (!id) {
  51. return res.json(ApiResponse.error('Parameters page_id is required.'));
  52. }
  53. Attachment.getListByPageId(id)
  54. .then(function(attachments) {
  55. return res.json(ApiResponse.success({
  56. attachments: attachments
  57. }));
  58. });
  59. };
  60. /**
  61. * @api {post} /attachments.add Add attachment to the page
  62. * @apiName AddAttachments
  63. * @apiGroup Attachment
  64. *
  65. * @apiParam {String} page_id
  66. * @apiParam {File} file
  67. */
  68. api.add = function(req, res){
  69. var id = req.body.page_id || 0,
  70. path = decodeURIComponent(req.body.path) || null,
  71. pageCreated = false,
  72. page = {};
  73. debug('id and path are: ', id, path);
  74. var tmpFile = req.file || null;
  75. debug('Uploaded tmpFile: ', tmpFile);
  76. if (!tmpFile) {
  77. return res.json(ApiResponse.error('File error.'));
  78. }
  79. new Promise(function(resolve, reject) {
  80. if (id == 0) {
  81. if (path === null) {
  82. throw new Error('path required if page_id is not specified.');
  83. }
  84. debug('Create page before file upload');
  85. Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
  86. .then(function(page) {
  87. pageCreated = true;
  88. resolve(page);
  89. })
  90. .catch(reject);
  91. } else {
  92. Page.findPageById(id).then(resolve).catch(reject);
  93. }
  94. }).then(function(pageData) {
  95. page = pageData;
  96. id = pageData._id;
  97. var tmpPath = tmpFile.path,
  98. originalName = tmpFile.originalname,
  99. fileName = tmpFile.filename + tmpFile.originalname,
  100. fileType = tmpFile.mimetype,
  101. fileSize = tmpFile.size,
  102. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
  103. tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  104. return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
  105. .then(function(data) {
  106. debug('Uploaded data is: ', data);
  107. // TODO size
  108. return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
  109. }).then(function(data) {
  110. var imageUrl = fileUploader.generateUrl(data.filePath);
  111. var result = {
  112. page: page.toObject(),
  113. attachment: data.toObject(),
  114. filename: imageUrl,
  115. pageCreated: pageCreated,
  116. };
  117. result.page.creator = User.filterToPublicFields(result.page.creator);
  118. result.attachment.creator = User.filterToPublicFields(result.attachment.creator);
  119. // delete anyway
  120. fs.unlink(tmpPath, function (err) { if (err) { debug('Error while deleting tmp file.'); } });
  121. return res.json(ApiResponse.success(result));
  122. }).catch(function (err) {
  123. debug('Error on saving attachment data', err);
  124. // @TODO
  125. // Remove from S3
  126. // delete anyway
  127. fs.unlink(tmpPath, function (err) { if (err) { debug('Error while deleting tmp file.'); } });
  128. return res.json(ApiResponse.error('Error while uploading.'));
  129. });
  130. ;
  131. }).catch(function(err) {
  132. debug('Attachement upload error', err);
  133. return res.json(ApiResponse.error('Error.'));
  134. });
  135. };
  136. api.remove = function(req, res){
  137. var id = req.params.id;
  138. };
  139. return actions;
  140. };