From beb3de8eae4a32175ec655b70b2180bc1940b0ad Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sun, 22 Apr 2018 19:17:18 +0100 Subject: Edit file uploads to use raw data instead of forms --- src/FileRouter.ts | 369 ++++++++++++++++++++++++++------------------------- src/db/model/File.ts | 2 +- src/files.ts | 126 +++++++++--------- src/index.ts | 4 +- 4 files changed, 253 insertions(+), 248 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ecd5185..dd5e74b 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,11 +8,14 @@ import { default as UserGroup } from './db/model/UserGroup'; import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; import { View, addSubFileToFolder, copyFile, createProjectFolder, deleteFile, - rootPathId, saveFile, upload, views } from './files'; + rootPathId, saveFile, views } from './files'; import { logger } from './logger'; +import { mimetype } from './mimetype'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; +import * as bodyParser from 'body-parser'; + /** * The type of an Express middleware callback. */ @@ -492,6 +495,9 @@ const postProjectName: Middleware = async( res.locals.modified = true; let promise: PromiseLike | null = null; if (project == null) { + if (req.query.action !== 'create') { + return next(new RequestError(404, 'project-not-found')); + } logger.debug('Adding new project'); const file: File = new File({ uuid: uuid.generate(), @@ -509,6 +515,9 @@ const postProjectName: Middleware = async( }); project.rootFolderId = file.uuid; } else { + if (req.query.action === 'create') { + return next(new RequestError(400, 'project_already_exists')); + } logger.debug('Updating project properties'); } @@ -678,200 +687,200 @@ const qH: { !qH.truncates(req) && !qH.isFinal(req) }; +const makeFile = async(req: Request, res: Response): Promise => { + // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found + let remainingPath: string = (res.locals.deepestFolderName == '') ? '/' + res.locals.path + : res.locals.path.split(res.locals.deepestFolderName)[1]; + + let curPath: string = res.locals.deepestFolderName; + // Loop the part of the path that doesn't exist yet and create all the folders + while ((remainingPath.match(/\//g) || []).length > 1) { + // If there are more subfolders that dont exist, then create them + const subFolder: string = remainingPath.split('/')[1]; + curPath += subFolder; + logger.debug(`Adding subfolder '${subFolder}'`); + const dir: File = new File({ + uuid: uuid.generate(), + type: 'directory', + status: 'ready', + fullPathInternal: curPath, + nameInternal: subFolder + }); + await dir.save(); + curPath += '/'; + // update parent directory of new directory + await addSubFileToFolder(res.locals.deepestFolderId, dir); + // update vars + remainingPath = remainingPath.split(subFolder)[1]; + res.locals.deepestFolderName = subFolder; + res.locals.deepestFolderId = dir.uuid; + } + + logger.debug(`Writing file '${res.locals.filename}' to folder '${res.locals.deepestFolderName}'`); + res.locals.file = new File({ + uuid: uuid.generate(), + nameInternal: res.locals.filename, + fullPathInternal: res.locals.path, + status: req.query.final + ? 'ready' + : 'uploading' + }); + res.locals.file.mimetype = mimetype( + req.header('Content-Type'), req.body, res.locals.filename); + + // update parent directory of new directory + await addSubFileToFolder(res.locals.deepestFolderId, res.locals.file); + return res.locals.file; +}; + /** * Post a File. / delete / move / etc */ -/* tslint:disable */ -const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { +const postFilePath: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { try { await getFileFromPath(req, res); logger.debug(`Receiving file ${res.locals.path}`); - // req.query.action: set_metadata, mkdir, delete, move, copy - // req.query.overwrite (bool) - // req.query.offset (int) - // req.query.truncate (bool) - // req.query.final (bool) - - // Return 404 when one of these actions is attempted on non-existing file - if (res.locals.file == null && (qH.setsMetadata(req) || qH.deletes(req) || qH.moves(req) || qH.copys(req))){ - logger.debug(`Action \'${req.query.action}\' not valid if file does not exist`); - next(new RequestError(404, 'file_not_found')); - return; - } - - // Return 400 when one of these actions is attempted on existing file - if (res.locals.file != null && (qH.nothingSet(req) || qH.mksDir(req))) { - logger.debug(`Action \'${req.query.action}\' not valid if file exists`); - next(new RequestError(400, 'file_exists')); - return; - } - - // Sets final if requested - if (res.locals.file && qH.isFinal(req)) { - res.locals.file.status = 'preprocessing'; - // start file conversion - } - - // Sets Metadata if requested - if(qH.setsMetadata(req)){ - res.locals.file.metadata = req.body; - await res.locals.file.save(); - next(); - return; - } - - // Deletes File if requested - if(qH.deletes(req)){ - logger.info(`File ${res.locals.file.name} will be deleted`) - deleteFile(res.locals.file.uuid, res.locals.project.name); - await res.locals.file.destroy(); - next(); - return; - } - - // Moves File if requested - if(qH.moves(req)){ - if(!req.body.path){ - logger.debug(`copying by uuid not implimented`); - next(new RequestError(500, "copy_to_path_only")); - return; - } - logger.info(`Copying file \'${res.locals.file.fullPath}\' to new path \'${req.body.path}\'`); - // new File object - let promise: PromiseLike | null = null; - - const newFile: File = new File({ - uuid: uuid.generate(), - type: res.locals.file.type, - status: res.locals.file.status, - creatorName: res.locals.file.creatorName, - createdAt: res.locals.file.createdAt, - modifyDate: res.locals.file.modifyDate - }); - newFile.setMetadataInternal(res.locals.file.metadata); - newFile.fullPath = req.body.path; - newFile.parentFolderId = res.locals.parentFolderId; - await newFile.save(); - const oldUUID: string = res.locals.file.uuid; - await res.locals.file.destroy(); - copyFile(res.locals.project.name, res.locals.file.uuid, oldUUID, true); - next(); - return; - } - - // Copies File if requested - if(qH.copys(req)){ - if(!req.body.path){ - logger.debug(`copying by uuid not implimented`); - next(new RequestError(500, "copy_to_path_only")); - return; - } - logger.info(`Copying file \'${res.locals.file.fullPath}\' to new path \'${req.body.path}\'`); - // new File object - let promise: PromiseLike | null = null; - - const newFile: File = new File({ - uuid: uuid.generate(), - type: res.locals.file.type, - status: res.locals.file.status, - creatorName: res.locals.file.creatorName, - createdAt: res.locals.file.createdAt, - modifyDate: res.locals.file.modifyDate - }); - newFile.setMetadataInternal(res.locals.file.metadata); - newFile.fullPath = req.body.path; - newFile.parentFolderId = res.locals.parentFolderId; - await newFile.save(); - copyFile(res.locals.project.name, res.locals.file.uuid, newFile.uuid); - next(); - return; - } - - // Overwrite data but not truncate - // eg. OOOONNNNNNOOOO (O = old data, N = new data) - if(qH.overwrites(req) && !qH.truncates(req)){ - logger.info(`overwriting without truncating not supported`); - next(new RequestError(500, 'not_implemented', 'please specify truncate parameter')); - return; - } - - // Create File or Folder if file doesn't exist - if (res.locals.file == null){ - // Guarding against stupid Postman - if(!qH.mksDir(req) && !req.file){ - logger.debug("No file attached. Sending 400"); - next(new RequestError(400, 'no_file_attached')); + // / req.query.action: set_metadata, mkdir, delete, move, copy + // / req.query.overwrite (bool) + // / req.query.offset (int) + // / req.query.truncate (bool) + // / req.query.final (bool) + + if (res.locals.file) { + /* tslint:disable-next-line:curly */ + if (req.query.action) switch (req.query.action) { + case 'set_metadata': { + res.locals.file.metadata = JSON.parse(req.body.toString()); + await res.locals.file.save(); + break; + } case 'delete': { + logger.info(`File ${res.locals.file.name} will be deleted`); + deleteFile(res.locals.file.uuid, res.locals.project.name); + await res.locals.file.destroy(); + break; + } case 'move': { + if (!req.body.path) { + logger.warn('copying by uuid not implimented'); + return next(new RequestError(500, 'copy_to_path_only')); + } + logger.info(`Copying file '${ + res.locals.file.fullPath}' to new path '${req.body.path}'`); + // New File object + const promise: PromiseLike | null = null; + const newFile: File = new File({ + uuid: uuid.generate(), + type: res.locals.file.type, + status: res.locals.file.status, + creatorName: res.locals.file.creatorName, + createdAt: res.locals.file.createdAt, + modifyDate: res.locals.file.modifyDate + }); + newFile.setMetadataInternal(res.locals.file.metadata); + newFile.fullPath = req.body.path; + newFile.parentFolderId = res.locals.parentFolderId; + await newFile.save(); + const oldUUID: string = res.locals.file.uuid; + await res.locals.file.destroy(); + copyFile(res.locals.project.name, res.locals.file.uuid, oldUUID, true); + break; + } case 'copy': { + if (!req.body.path) { + logger.debug('copying by uuid not implimented'); + return next(new RequestError(500, 'copy_to_path_only')); + } + logger.info(`Copying file '${ + res.locals.file.fullPath}' to new path '${req.body.path}'`); + const promise: PromiseLike | null = null; + const newFile: File = new File({ + uuid: uuid.generate(), + type: res.locals.file.type, + status: res.locals.file.status, + creatorName: res.locals.file.creatorName, + createdAt: res.locals.file.createdAt, + modifyDate: res.locals.file.modifyDate + }); + newFile.setMetadataInternal(res.locals.file.metadata); + newFile.fullPath = req.body.path; + newFile.parentFolderId = res.locals.parentFolderId; + await newFile.save(); + copyFile(res.locals.project.name, res.locals.file.uuid, newFile.uuid); + break; + } case 'mkdir': { + logger.debug(`Action '${req.query.action}' not valid if file exists`); + return next(new RequestError(400, 'file_exists')); + } default: { + logger.warn(`Unknown file edit action '${req.query.action}'`); + return next(new RequestError(400, 'unknown_action')); + } + } else { + if (req.query.overwrite) { + if (req.query.truncate) { + await saveFile( + req.body, + res.locals.project.name, + res.locals.file.uuid, + req.query + ); + if (req.query.final) { + res.locals.file.status = 'preprocessing'; + await res.locals.file.save(); + // Start file preprocesssing + } + } else { + logger.warn('overwriting without truncating not supported'); + return next(new RequestError( + 500, + 'not_implemented', + 'please specify truncate parameter' + )); + } + } else { + return next(new RequestError(400, 'file_already_exists')); + } } - - // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found - let remainingPath: string = (res.locals.deepestFolderName == '') ? '/' + res.locals.path - : res.locals.path.split(res.locals.deepestFolderName)[1]; - - let curPath: string = res.locals.deepestFolderName; - // Loop the part of the path that doesn't exist yet and create all the folders - while((remainingPath.match(/\//g) || []).length > 1){ - // If there are more subfolders that dont exist, then create them - const subFolder: string = remainingPath.split("/")[1] - curPath += subFolder; - logger.debug(`Adding subfolder \'${subFolder}\'`); - const dir: File = new File({ - uuid: uuid.generate(), - type: 'directory', - status: 'ready', - fullPathInternal: curPath, - nameInternal: subFolder - }); - await dir.save(); - curPath += '/'; - // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, dir.uuid)){ - logger.debug("adding file to folder failed!") - next(new RequestError(500, 'Adding file to folder failed')) + } else { + /* tslint:disable-next-line:curly */ + if (req.query.action) switch (req.query.action) { + case 'mkdir': { + await makeFile(req, res); + res.locals.file.status = 'final'; + break; + } + case 'set_metadata': + case 'delete': + case 'move': + case 'copy': + logger.debug(`Action '${req.query.action + }' not valid if file does not exist`); + return next(new RequestError(404, 'file_not_found')); + } else { + if (!req.body) { + logger.debug('No file attached. Sending 400'); + next(new RequestError(400, 'no_file_attached')); + } + await makeFile(req, res); + await saveFile( + req.body, + res.locals.project.name, + res.locals.file.uuid, + req.query + ); + // Sets final if requested + if (qH.isFinal(req)) { + res.locals.file.status = 'preprocessing'; + // TODO Start file preprocessing } - // update vars - remainingPath = remainingPath.split(subFolder)[1] - res.locals.deepestFolderName = subFolder; - res.locals.deepestFolderId = dir.uuid; } - - logger.debug(`Writing file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) - res.locals.file = new File({ - uuid: uuid.generate(), - nameInternal: res.locals.filename, - fullPathInternal: res.locals.path, - status: req.query.final - ? 'ready' - : 'uploading' - }); - res.locals.file.mimetype = qH.mksDir(req) ? 'inode/directory' : req.file.mimetype; - await res.locals.file.save(); - - // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, res.locals.file.uuid)){ - logger.debug("adding file to folder failed!") - next(new RequestError(500, 'Adding file to folder failed')) - return; - } - } - - // Move temp file to proper location (if not directory) - if(!qH.mksDir(req)){ - saveFile(req.file.originalname, res.locals.project.name, res.locals.file.uuid, qH.offset(req)); } - - // Sets final if requested - if (qH.isFinal(req)) { - res.locals.file.status = 'final'; - } - - next(); + return next(); } catch (e) { next(e); } }; -/* tslint:enable */ export class FileRouter { public router: Router; @@ -915,7 +924,7 @@ export class FileRouter { this.router.get ('/projects/:project_name/files/*', getFilePath); this.router.post( '/projects/:project_name/files/*', - upload.single('userfile'), postFilePath); + bodyParser.raw({ type: '*/*' }), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 89415b7..5bae182 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -116,7 +116,7 @@ export default class File extends Model { } public get metadata(): Metadata { - return !!(this.metadataInternal) ? JSON.parse(this.metadataInternal) + return !!(this.metadataInternal) ? JSON.parse(this.metadataInternal) : INITIAL_METADATA; } diff --git a/src/files.ts b/src/files.ts index aa4e24f..b5495d8 100644 --- a/src/files.ts +++ b/src/files.ts @@ -2,11 +2,16 @@ import { Request, Response } from 'express'; import * as fs from 'fs-extra'; import { logger } from './logger'; import * as Multer from 'multer'; +import * as stream from 'stream'; import * as parse from 'csv-parse'; import * as stringify from 'csv-stringify'; + import { default as File } from './db/model/File'; import { default as Project } from './db/model/Project'; +import { uuid } from './uuid'; + +import { RequestError } from './errors'; const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; @@ -42,7 +47,21 @@ interface TabularParameters { cols: string[]; } -interface Query extends Partial, Partial { +interface FileUploadParameters { + truncate: boolean; + overwrite: boolean; + offset: number; + action: 'set_metadata' + | 'delete' + | 'move' + | 'copy' + | 'mkdir'; +} + +interface Query extends + Partial, + Partial, + Partial { children?: boolean; } @@ -67,15 +86,6 @@ export const logPath: (type: string, projectName?: string) => string = ( : `${LOG_BASE_DIRECTORY}/general/${type}`; }; -let storage = Multer.diskStorage({ - destination: function (req, file, cb) { - cb(null, CONTENT_BASE_DIRECTORY) - }, - filename: function (req, file, cb) { - cb(null, `temp-${file.originalname}`) - } -}); - export const path: (file: string, project: string, view?: ViewName) => string = (file: string, project: string, view: ViewName = 'raw'): string => `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`; @@ -87,41 +97,39 @@ export const pathNoView: (file: string, project: string) => string = export const tempPath: (file: string, project: string) => string = ( file: string ): string => - `${TEMP_BASE_DIRECTORY}/${file}` + `${TEMP_BASE_DIRECTORY}/${uuid.generate()}`; -export const upload: Multer.Instance = Multer({ storage: storage }); - -export const saveFile: (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean) => Promise = - async(filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean): Promise => { +export const saveFile: (data: Buffer, projectName: string, fileId: string, query: Query) => Promise = + async(data: Buffer, projectName: string, fileId: string, query: Query): Promise => { // TODO only overwrite beginning of file and keep rest of data - // ensure file exists - await fs.ensureFile(path(fileId, projectname)); - // truncate to offset - await truncateFile(fileId, projectname, offset); - // open streams to append to file - let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); - let wStream = fs.createWriteStream(path(fileId, projectname), {'flags':'a'}); - rStream.pipe(wStream).on('finish', async() => { - fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); - }).on('error', (err: any) => { - logger.error(`Error while saving file to proper location: ${err}`); + // Ensure file exists + await fs.ensureFile(path(fileId, projectName)); + // Truncate to offset + await truncateFile(fileId, projectName, query.offset || 0); + // Open streams to append to file + const rStream: stream.PassThrough = new stream.PassThrough(); + rStream.end(data); + const wStream: fs.WriteStream = + fs.createWriteStream(path(fileId, projectName), { flags: 'a' }); + rStream.pipe(wStream).on('error', (err: Error) => { + throw new RequestError(500, `Error while saving file to proper location: ${err}`); }); -} +}; export const deleteFile: (fileId: string, projectName: string) => void = async( fileId: string, projectName: string ): Promise => { await fs.remove(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`); -} +}; export const truncateFile: (fileId: string, projectName: string, newLength: number) => Promise = async(fileId: string, projectName: string, newLength: number): Promise => { // get the file descriptor of the file to be truncated const fd: number = await fs.open(path(fileId, projectName), 'r+'); await fs.ftruncate(fd, newLength); -} +}; -export const copyFile: (projName: string, fromId: string, toId: string, move?: boolean) +export const copyFile: (projName: string, fromId: string, toId: string, move?: boolean) => Promise = async(projName: string, fromId: string, toId: string, move?: boolean): Promise => { // ensure to path exists fs.ensureDirSync(pathNoView(toId, projName)); @@ -129,29 +137,29 @@ export const copyFile: (projName: string, fromId: string, toId: string, move?: b const toDir: string = pathNoView(toId, projName); // loop all views in file fs.readdir(fromDir, (err: any, files: string[]) => { - if(err){ + if (err) { logger.error(`Error while copying file: ${err}`); } else { files.forEach((file: string, index: number) => { - const fromPathFull = fromDir + "/" + file; - const toPathFull = toDir + "/" + file; + const fromPathFull = fromDir + '/' + file; + const toPathFull = toDir + '/' + file; fs.ensureFileSync(toPathFull); // open streams to transfer data - let rStream = fs.createReadStream(fromPathFull); - let wStream = fs.createWriteStream(toPathFull); + const rStream = fs.createReadStream(fromPathFull); + const wStream = fs.createWriteStream(toPathFull); rStream.pipe(wStream).on('finish', async() => { - if(!!move){ + if (!!move) { await fs.remove(fromPathFull); } - console.log(`copy success of file from \'${fromPathFull}\' to \'${toPathFull}\'`) + console.log(`copy success of file from \'${fromPathFull}\' to \'${toPathFull}\'`); }).on('error', (err: any) => { logger.error(`Error while copying file: ${err}`); }); - }) + }); } }); - -} + +}; export const files: { path: (f: string, p: string) => string; @@ -341,38 +349,26 @@ export const rootPathFile: File | null = null; export const createRootFolder: () => Promise = async( ): Promise => { - if (!(await fs.exists(CONTENT_BASE_DIRECTORY))){ + if (!(await fs.access(CONTENT_BASE_DIRECTORY))) { await fs.mkdir(CONTENT_BASE_DIRECTORY); } -} +}; export const createProjectFolder: (name: string) => Promise = async( projName: string ): Promise => { - if (!(await fs.exists(CONTENT_BASE_DIRECTORY + '/' + projName))){ + if (!(await fs.access(CONTENT_BASE_DIRECTORY + '/' + projName))) { await fs.mkdir(CONTENT_BASE_DIRECTORY + '/' + projName); } -} +}; -export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise = async(parentId: string, subFileId: string): Promise => { - logger.debug(`adding file ${subFileId} to directory ${parentId}`) +export const addSubFileToFolder: ( + parentId: string, subFile: File +) => Promise = async( + parentId: string, subFile: File +): Promise => { + logger.debug(`adding file ${subFile.uuid} to directory ${parentId}`); // Fetch parent and subFile object from database - const parent: File | null = await File.findOne({ - include: [{all: true}], - where: { - uuid: parentId - } - }); - const file: File | null = await File.findOne({ - include: [{all: true}], - where: { - uuid: subFileId - } - }); - if(!parent || !file){ - return false; - } - parent.$add('containedFilesInternal', file); - - return true; -} + subFile.parentFolderId = parentId; + await subFile.save(); +}; diff --git a/src/index.ts b/src/index.ts index 4dc83ad..d5708d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,7 +18,7 @@ const DEFAULT_PORT: number = 3000; // Use default port 3000 or port supplied by OS const port: number = process.env.PORT - ? process.env.PORT + ? Number(process.env.PORT) : DEFAULT_PORT; logger.info(`Port ${port} chosen`); @@ -93,7 +93,7 @@ async function reset(): Promise { process.exit(1); } - await reset(); + // /await reset(); logger.info('Booting ExpressJS server'); app.listen(port, (err: Error) => { -- cgit v1.2.1