attachment.js 4.4 KB

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