attachment.js 4.3 KB

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