diff options
| author | josh97josh | 2018-04-20 11:53:37 +0100 |
|---|---|---|
| committer | josh97josh | 2018-04-20 11:53:37 +0100 |
| commit | af7934c3852bbde45210dd0c475817b8f20ddefc (patch) | |
| tree | 39ae972ea75cfc0033161b54eb26192bec14d353 /src/FileRouter.ts | |
| parent | small fixes (diff) | |
| parent | reduced # of failing tests (diff) | |
| download | medicine-af7934c3852bbde45210dd0c475817b8f20ddefc.tar.gz medicine-af7934c3852bbde45210dd0c475817b8f20ddefc.zip | |
Merge branch ‘trh/gets’ of ssh://localhost:2222/cs3099group-be-4/project-code into trh/gets
Diffstat (limited to 'src/FileRouter.ts')
| -rw-r--r-- | src/FileRouter.ts | 286 |
1 files changed, 230 insertions, 56 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4f59586..bd376b0 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -6,15 +6,12 @@ import { UserFullInfo, default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; - import { RequestError } from './errors/errorware'; -import { View, files, views } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, deleteFile, truncateFile, saveFile } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; -// TODO: figure this out -const BASE_FILE_STORAGE: string = 'TODO: figure this out'; /** * The type of an Express middleware callback. @@ -171,7 +168,7 @@ const getProperties: Middleware = ( const postProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { - logger.debug('Editing server properties'); + console.log('Editing server properties'); res.locals.modified = true; for (const newProp of req.body) { const prop: Property | undefined = serverConfig.find( @@ -192,6 +189,7 @@ const postProperties: Middleware = ( return; } } + console.log("Posted Properties successfully"); next(); }; @@ -498,16 +496,22 @@ const postProjectName: Middleware = async( logger.debug('Adding new project'); const file: File = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory' + mimetype: 'inode/directory', + parentFolderId: rootPathId }); + file.name = ''; // Leave blank as discussed promise = file.save(); + createProjectFolder(req.params.project_name); + project = new Project({ name: req.params.project_name, rootFolder: file }); + project.rootFolderId = file.uuid; } else { logger.debug('Updating project properties'); } + project.metadata = req.body; // tslint:disable-next-line:await-promise await promise; @@ -538,13 +542,14 @@ const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { logger.debug(`Getting file in ${req.query.view} view`); - res.locals.modified = true; const file: File | null = res.locals.file; if (file == null) { return next(new RequestError(404, 'file_not_found')); } const project: Project = res.locals.project; const view: View = views[req.query.view || 'meta']; + // TODO return 400 for unsuported views + // TODO raw view accepts extra query params offset and length res.locals.function = view.getResponseFunction(req, res); res.locals.data = view.getResponseData(file, project, req.query); next(); @@ -561,25 +566,168 @@ const getFilePath: Middleware = getFile; const getFileId: Middleware = getFile; /** + * Checks the parameters for file posting + */ +namespace qH { + export const hasAction: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action ? true : false); + } + export const setsMetadata: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'set_metadata' ? true : false); + } + export const mksDir: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'mkdir' ? true : false); + } + export const deletes: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'delete' ? true : false); + } + export const moves: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'move' ? true : false); + } + export const copys: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'copy' ? true : false); + } + export const overwrites: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.overwrite ? req.query.overwrite : false); + } + export const offset: ((req: Request) => number) = (req: Request): number => { + return (req.query.offset ? req.query.offset : 0); + } + export const truncates: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.truncate ? req.query.truncate : false); + } + export const isFinal: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.final ? req.query.final : false); + } + export const nothingSet: ((req: Request) => boolean) = (req: Request): boolean => { + return (!hasAction(req) && !overwrites(req) && !truncates(req) && !isFinal(req)); + } +} + +/** * Post a File. / delete / move / etc */ -const postFilePath: Middleware = ( - req: Request, res: Response, next: NextFunction -): void => { - logger.debug(`Receiving file to ${res.locals.parentFolder}`); - res.locals.modified = true; - if (res.locals.file != null) { +/* tslint:disable */ +const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise<void> => { + logger.debug(`Receiving file ${res.locals.path}`); + console.log(req.file); + // 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 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')); } - const file: File = new File({ - uuid: uuid.generate(), - name: res.locals.filename, - parentFolder: res.locals.parentFolder - }); - //console.log(res.locals); - req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + + // 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(); + } + + // 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(); + } + + // Moves File if requested + if(qH.moves(req)){ + // TODO + next(new RequestError(500, 'not_implemented')); + } + + // Copies File if requested + if(qH.copys(req)){ + // TODO + next(new RequestError(500, 'not_implemented')); + } + + // Overwrite data but not truncate + // eg. OOOONNNNNNOOOO (O = old data, N = new data) + if(qH.overwrites(req) && !qH.truncates(req)){ + // TODO + next(new RequestError(500, 'not_implemented', 'please specify truncate parameter')); + } + + // Create File or Folder if file doesn't exist + if (res.locals.file == null){ + // 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]; + + // 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] + logger.debug(`Adding subfolder \'${subFolder}\'`); + const dir: File = new File({ + uuid: uuid.generate(), + mimetype: 'inode/directory', + nameInternal: subFolder + }); + await dir.save(); + + // 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')) + } + // 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 + }); + 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')) + } + } + + // 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(); + }; +/* tslint:enable */ export class FileRouter { public router: Router; @@ -621,7 +769,8 @@ export class FileRouter { this.router.get ('/projects/:project_name/properties', getProjectProperties); // File access this.router.get ('/projects/:project_name/files/:path', getFilePath); - this.router.post('/projects/:project_name/files/:path', postFilePath); + this.router.post('/projects/:project_name/files/:path', + upload.single('userfile'), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -649,7 +798,11 @@ export class FileRouter { username: name } }); - res.locals.user = user; + if (user == null) { + return next(new RequestError(404, 'user_not_found')); + } else { + res.locals.user = user; + } next(); } ); @@ -662,7 +815,9 @@ export class FileRouter { projectName: string ): Promise<void> => { res.locals.project = await Project.findOne({ - include: [{all: true}], + include: [ + User + ], where: { name: projectName } @@ -678,52 +833,62 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise<void> => { - console.log(`parsing path ${filename}`) - logger.debug(`Searching for file ${filename}`); - const fileNames: string[] = req.params.path.split('/'); + // Vars we assign here: + // - res.locals.deepestFolderName (...Id): deepest existing folder in path + // - res.locals.path: requested path (using "/") + // - res.locals.filename: requested file name (may be '') + // - res.locals.file: actual file object if it exists + // Vars arleady assigned: + // - res.locals.project: requested project object + + // Replace + with / + res.locals.path = filename.replace(/\+/g, '/'); + logger.debug(`Searching for path \'${res.locals.path}\'`); + // Split path into parts + const fileNames: string[] = res.locals.path.split('/'); + res.locals.filename = (fileNames.length > 0) ? + fileNames[fileNames.length - 1] : ''; + logger.debug(`Searching for file \'${res.locals.filename}\'`); const project: Project | null = res.locals.project; if (project == null) { + // Project should have been found by previous precondition logger.debug('Project was not found: skipping finding file'); return next(new RequestError(404, 'project_not_found')); } - let file: File = project.rootFolder; - // TODO Rewrite using sub-queries instead of repeated queries. - while (fileNames.length > 2) { + let curDir: File | null = project.rootFolder; + res.locals.deepestFolderId = curDir.uuid; + res.locals.deepestFolderName = curDir.name; + let i: number = 0; + // Loop through the path and find the deepest folder that exists. + // Also find the file if possible. + while (curDir && i < fileNames.length) { + logger.debug(`Searching for \'${fileNames[i]}\'`); const fileOrNull: File | null = await File.findOne({ + include: [{all: true}], where: { - name: fileNames[0], - parentFolder: file + nameInternal: fileNames[i], + parentFolderId: curDir.uuid } }); if (fileOrNull == null) { + logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`); return next(); - } else { - file = fileOrNull; } - fileNames.splice(0, 1); - } - if (file == null) { - return next(); - } - const parentFolder: File | null = await File.findOne({ - include: [ - { model: File, as: 'containedFilesInternal'}, - ], - where: { - parentFolderId: file.id, - name: fileNames[0] + + if (i < fileNames.length - 1) { + // Found next subdirectory + logger.debug(`Found Sub-folder \'${fileOrNull.name}\'`); + res.locals.deepestFolderId = fileOrNull.uuid; + res.locals.deepestFolderName = fileOrNull.name; + } else { + // Found actual file + logger.debug(`Found file \'${fileOrNull.name}\'`); + res.locals.file = fileOrNull; } - }); - //console.log(parentFolder); - if (parentFolder == null) { - return next(); + curDir = fileOrNull; + i++; } - res.locals.parentFolder = parentFolder; - const tFile: File | undefined = parentFolder.containedFiles.find( - (f: File): boolean => f.name === fileNames[1] - ); - res.locals.file = tFile; - res.locals.filename = fileNames[1]; + next(); } ); @@ -735,7 +900,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise<void> => { - console.log(`parsing id ${fileId}`); + logger.info(`parsing id ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { @@ -743,6 +908,15 @@ export class FileRouter { } }); res.locals.file = file; + if (file) { + res.locals.filename = file.name; + res.locals.deepestFolderId = file.parentFolderId; + if (file.parentFolder) { + res.locals.deepestFolderName = file.parentFolder.name; + } else { + logger.debug('parentfolder not set!'); + } + } next(); } ); |
