backend/app/controllers/api/v1/File.controller.js

84 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-02-09 10:37:21 +00:00
const Controller = require('libflitter/controller/Controller')
const Page = require('../../../models/api/Page.model')
const Node = require('../../../models/api/Node.model')
const FileGroup = require('../../../models/api/FileGroup.model')
const { ObjectId } = require('mongodb')
/*
* File Controller
* -------------------------------------------------------------
* Put some description here!
*/
class File extends Controller {
static get services() {
return [...super.services, 'models']
}
async create_config(req, res) {
const { page, node } = req.form
2020-02-09 10:37:21 +00:00
const group = new FileGroup({
NodeId: node.UUID,
PageId: page.UUID,
FileIds: [],
})
2020-10-31 02:59:42 +00:00
if ( req.body.UUID ) {
const existingUUID = await FileGroup.findOne({ UUID: req.body.UUID })
if ( !existingUUID ) {
group.UUID = req.body.UUID
}
}
await group.version_save(`Added to page "${page.Name}"`, req.user.id)
2020-02-09 10:37:21 +00:00
req.user.allow(`files:${group.UUID}`)
await req.user.save()
return res.api(group)
}
async get_config(req, res) {
const { page, node, file_group } = req.form
2020-02-09 10:37:21 +00:00
const File = this.models.get('upload::File')
file_group.files = await File.find({_id: {$in: file_group.FileIds.map(x => ObjectId(x))}})
2020-02-09 10:37:21 +00:00
return res.api(file_group)
2020-02-09 10:37:21 +00:00
}
async save_upload(req, res) {
const { page, node, file_group } = req.form
2020-02-09 10:37:21 +00:00
let file_name = ''
2020-02-09 10:37:21 +00:00
if ( req.uploads.uploaded_file ) {
file_group.FileIds.push(req.uploads.uploaded_file.id)
2020-02-09 10:37:21 +00:00
}
await file_group.version_save(`Added file${file_name ? ' "'+file_name+'"' : ''}`, req.user.id)
return res.redirect(req.body.redirectTo ? req.body.redirectTo : '/')
2020-02-09 10:37:21 +00:00
}
async download(req, res) {
const { page, node, file_group } = req.form
2020-02-09 10:37:21 +00:00
if ( !file_group.FileIds.includes(req.params.FileId) ) {
2020-02-09 10:37:21 +00:00
return req.security.deny()
}
const File = this.models.get('upload::File')
const file = await File.findOne({_id: ObjectId(req.params.FileId)})
if ( !file ) return res.status(404).api({})
return file.send(res)
}
async delete_group(req, res) {
const { page, node, file_group } = req.form
2020-02-09 10:37:21 +00:00
await file_group.delete()
2020-02-09 10:37:21 +00:00
return res.api({})
}
}
module.exports = exports = File