| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- module.exports = function(crowi, app) {
- 'use strict';
- var debug = require('debug')('crowi:routs:attachment')
- , Attachment = crowi.model('Attachment')
- , User = crowi.model('User')
- , Page = crowi.model('Page')
- , Promise = require('bluebird')
- , config = crowi.getConfig()
- , fs = require('fs')
- , fileUploader = require('../util/fileUploader')(crowi, app)
- , actions = {}
- , api = {};
- actions.api = api;
- api.list = function(req, res){
- var id = req.params.pageId;
- Attachment.getListByPageId(id)
- .then(function(attachments) {
- res.json({
- status: true,
- data: {
- attachments: attachments
- }
- });
- });
- };
- /**
- *
- */
- api.add = function(req, res){
- var id = req.params.pageId,
- path = decodeURIComponent(req.body.path),
- pageCreated = false,
- page = {};
- debug('id and path are: ', id, path);
- var tmpFile = req.files.file || null;
- debug('Uploaded tmpFile: ', tmpFile);
- if (!tmpFile) {
- return res.json({
- status: false,
- message: 'File error.'
- });
- }
- new Promise(function(resolve, reject) {
- if (id == 0) {
- debug('Create page before file upload');
- Page.create(path, '# ' + path, req.user, {grant: Page.GRANT_OWNER})
- .then(function(page) {
- pageCreated = true;
- resolve(page);
- })
- .catch(reject);
- } else {
- Page.findPageById(id).then(resolve).catch(reject);
- }
- }).then(function(pageData) {
- page = pageData;
- id = pageData._id;
- var tmpPath = tmpFile.path,
- originalName = tmpFile.originalname,
- fileName = tmpFile.name,
- fileType = tmpFile.mimetype,
- fileSize = tmpFile.size,
- filePath = Attachment.createAttachmentFilePath(id, fileName, fileType),
- tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
- return fileUploader.uploadFile(filePath, fileType, tmpFileStream, {})
- .then(function(data) {
- debug('Uploaded data is: ', data);
- // TODO size
- return Attachment.create(id, req.user, filePath, originalName, fileName, fileType, fileSize);
- }).then(function(data) {
- var imageUrl = fileUploader.generateUrl(data.filePath);
- return res.json({
- status: true,
- filename: imageUrl,
- attachment: data,
- page: page,
- pageCreated: pageCreated,
- message: 'Successfully uploaded.',
- });
- }).catch(function (err) {
- debug('Error on saving attachment data', err);
- // @TODO
- // Remove from S3
- return res.json({
- status: false,
- message: 'Error while uploading.',
- });
- }).finally(function() {
- fs.unlink(tmpPath, function (err) {
- if (err) {
- debug('Error while deleting tmp file.');
- }
- });
- })
- ;
- });
- };
- api.remove = function(req, res){
- var id = req.params.id;
- };
- return actions;
- };
|