From 8d0293af5592402448769451f85ce666ed407cb4 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 20 Apr 2018 15:15:46 +0100 Subject: Finalise CORS support with package corser --- src/FileRouter.ts | 75 +++++++++++++++++++---------------------------- src/app.ts | 22 ++------------ src/auth.ts | 2 +- src/conversion/czi/czi.ts | 51 +++++++++++++++----------------- src/cors/index.d.ts | 3 ++ src/cors/index.js | 2 ++ src/db/model/User.ts | 2 +- src/index.ts | 3 +- 8 files changed, 64 insertions(+), 96 deletions(-) create mode 100644 src/cors/index.d.ts create mode 100644 src/cors/index.js (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 3f966c2..9059e88 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -5,14 +5,14 @@ import { ProjectFullInfo, default as Project } from './db/model/Project'; 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 { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, deleteFile, truncateFile, saveFile } from './files'; +import { NextFunction, Request, Response, Router } from 'express'; +import { View, addSubFileToFolder, createProjectFolder, deleteFile, rootPathId, + saveFile, upload, views } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; - /** * The type of an Express middleware callback. */ @@ -110,7 +110,7 @@ const getLog: Middleware = ( if (!req.user.hasPrivilege('admin')) { next(new RequestError(401, 'invalid_privilege')); } - /* tslint:disable */ + /* tslint:disable */ if(!req.params.level) req.params.level = 'info'; if(!req.params.before) req.params.before = new Date(); if(!req.params.after) req.params.after = new Date(0); @@ -168,7 +168,7 @@ const getProperties: Middleware = ( const postProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { - console.log('Editing server properties'); + logger.debug('Editing server properties'); res.locals.modified = true; for (const newProp of req.body) { const prop: Property | undefined = serverConfig.find( @@ -189,7 +189,7 @@ const postProperties: Middleware = ( return; } } - console.log("Posted Properties successfully"); + logger.debug('Posted Properties successfully'); next(); }; @@ -567,41 +567,25 @@ 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)); - } -} +const qH: { + [key: string]: Function; +} = { + hasAction: (req: Request): boolean => !!req.query.action, + setsMetadata: (req: Request): boolean => + req.query.action === 'set_metadata', + mksDir: (req: Request): boolean => req.query.action === 'mkdir', + deletes: (req: Request): boolean => req.query.action === 'delete', + moves: (req: Request): boolean => req.query.action === 'move', + copys: (req: Request): boolean => req.query.action === 'copy', + overwrites: (req: Request): boolean => !!req.query.overwrite, + offset: (req: Request): number => + req.query.offset ? req.query.offset : 0, + truncates: (req: Request): boolean => !!req.query.truncate, + isFinal: (req: Request): boolean => !!req.query.final, + nothingSet: (req: Request): boolean => + !qH.hasAction(req) && !qH.overwrites(req) && + !qH.truncates(req) && !qH.isFinal(req) +}; /** * Post a File. / delete / move / etc @@ -722,9 +706,9 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu if (qH.isFinal(req)) { res.locals.file.status = 'final'; } - + next(); - + }; /* tslint:enable */ @@ -768,8 +752,9 @@ 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', - upload.single('userfile'), postFilePath); + this.router.post( + '/projects/:project_name/files/:path', + upload.single('userfile'), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } diff --git a/src/app.ts b/src/app.ts index d94011a..6a595f6 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,4 +1,5 @@ import * as bodyParser from 'body-parser'; +import { cors } from './cors'; import * as ex from 'express'; import * as expressJwt from 'express-jwt'; import * as passport from 'passport'; @@ -6,7 +7,7 @@ import * as passport from 'passport'; import { default as authRouter, unauthorisedErr } from './auth'; import { logger } from './logger'; -import { RequestError, errorHandler } from './errors/errorware'; +import { errorHandler } from './errors/errorware'; import FileRouter from './FileRouter'; import { default as File } from './db/model/File'; @@ -43,7 +44,7 @@ class App { logger.debug('Constructing router'); this.logEnabled = enableLog; this.express = ex(); - this.cors(); + this.express.use(cors()); this.express.use( (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { logger.info(`Connection from ${req.ip} requesting ${req.url}`); @@ -69,23 +70,6 @@ class App { this.errorware(); } - /** - * Enables Cross-Origin for the server. - */ - public cors(): void { - this.express.use(( - req: ex.Request, res: ex.Response, next: ex.NextFunction - ): void => { - res.header('Access-Control-Allow-Origin', '*'); - res.header( - 'Access-Control-Allow-Headers', - 'Origin, X-Requested-With, Content-Type, Accept' - ); - res.header('Access-Control-Allow-Methods', '*'); - next(); - }); - } - /** * Configures regular Express middleware. */ diff --git a/src/auth.ts b/src/auth.ts index 14e1170..490ae35 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -211,7 +211,7 @@ export const unauthorisedErr: Errorware = export const isAdmin: Middleware = (req: Request, res: Response, next: NextFunction): void => { // tslint:disable-next-line:no-non-null-assertion - const admin: boolean = req!.user!.object!.userGroups! + const admin: boolean = req.user.object.userGroups .some((x: UserGroup): boolean => x.name === 'admin'); if (!admin) { diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index addf43e..127fce6 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -2,11 +2,11 @@ import * as fs from 'fs'; import { logger } from '../../logger'; import * as sharp from 'sharp'; -import * as parsexml from 'xml-parser'; import { SharpInstance } from 'sharp'; +import * as parsexml from 'xml-parser'; const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/'; -const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/' +const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/'; const tileOverlap: number = 0; const tileSize: number = 1024; const maxZoom: number = 64; @@ -61,7 +61,7 @@ interface SupportedViews { units: string; }; metadata?: {}; - } + }; } interface CZITile { x_offset: number; @@ -71,7 +71,7 @@ interface CZITile { file: string; } interface CZIHeightMap { - zoom_level: number, + zoom_level: number; plane: CZITile[][]; } interface WholeCZIHierarchy { @@ -217,7 +217,7 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] { const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds { const baseBounds: TileBounds = getOriginalTileBounds(segment); - let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); + const chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); if (desired.left <= baseBounds.left) { chunkToExtract.left = 0; @@ -248,14 +248,14 @@ const findRegionToExtract: Function = function(segment: Segment, desired: TileBo const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise { - let tileVerticalBuffer: Buffer[] = []; + const tileVerticalBuffer: Buffer[] = []; for (const segRow of segments) { - let tileRow: Buffer[] = []; + const tileRow: Buffer[] = []; let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1); for (const segCol of segRow) { chunkToExtract = findRegionToExtract(segCol, desiredRegion); - let data: Promise = + const data: Promise = sharp(`${extractionDirectory}${segCol.Data.Data}`) .extract({ left: chunkToExtract.left, @@ -269,38 +269,35 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d } let imageVerticalSlice: SharpInstance = sharp(tileRow[0]); - let bufferBound = findRegionToExtract(segRow[0], desiredRegion); + const bufferBound = findRegionToExtract(segRow[0], desiredRegion); if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) { imageVerticalSlice = await imageVerticalSlice.extend( - {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))}); + {top: 0, left: 0, bottom: 0, right: (tileSize - (bufferBound.right - bufferBound.left))}); } for (let index = 1; index < segRow.length; index++) { imageVerticalSlice = await imageVerticalSlice .overlayWith(tileRow[index], - {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)}); + {top: 0, left: (bufferBound.right - bufferBound.left) + ((index - 1) * tileSize)}); } tileVerticalBuffer.push(await imageVerticalSlice.toBuffer()); } let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]); - let bufferBound = findRegionToExtract(segments[0][0], desiredRegion); + const bufferBound = findRegionToExtract(segments[0][0], desiredRegion); if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) { finalImage = await finalImage.extend( - {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); + {top: 0, left: 0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0}); } for (let index = 1; index < segments.length; index++) { finalImage = finalImage.overlayWith( tileVerticalBuffer[index], - {top: getDimension(segments[index -1][0], 'Y').Size, left: 0}); + {top: getDimension(segments[index - 1][0], 'Y').Size, left: 0}); } return finalImage; }; - - - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter( @@ -308,7 +305,7 @@ const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).c const inspect = require('util').inspect; const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8')); -let supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}}; +const supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}}; supportedViews.scalable_image.channels.pop(); let totalSizeX: number = -1; @@ -330,13 +327,13 @@ for (const child of metaXML.root.children) { totalSizeY = Number.parseInt(property.content, 10); supportedViews.scalable_image.height = totalSizeY; continue; - } else if(property.name === 'Dimensions') { + } else if (property.name === 'Dimensions') { for (const chan of property.children) { if (chan.name === 'Channels') { for (const channel of chan.children) { supportedViews.scalable_image.channels.push( { - channel_id: channel.attributes.Id.split(":")[1], + channel_id: channel.attributes.Id.split(':')[1], channel_name: channel.attributes.Name, metadata: channel.children } @@ -383,16 +380,15 @@ const filterC: Function = function(to: number): void { ); }; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin work on getting the new tiles all nice // Print out all of the related tiles to every new tile to be created. let filecoutner: number = 0; async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise { - console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY/tileSize)}): 0% complete.`) + console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY / tileSize)}): 0% complete.`); for (let ys: number = 0; ys < totalSizeY;) { - var timing = process.hrtime(); + let timing = process.hrtime(); for (let xs: number = 0; xs < totalSizeX; xs += tileSize) { const desired = new TileBounds ( xs - tileOverlap, @@ -408,20 +404,19 @@ async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: } ys += tileSize; timing = process.hrtime(timing); - console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys/tileSize}/${Math.ceil(totalSizeY/tileSize)}): ${Math.ceil(((ys/totalSizeY)*100) *100)/100}% complete. (${timing[0]} sec/iter)`); + console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. (${timing[0]} sec/iter)`); } return []; } -let finalCZIJson: WholeCZIHierarchy = {} as any; +const finalCZIJson: WholeCZIHierarchy = {} as any; async function main(): Promise { for (const cval of supportedViews.scalable_image.channels) { - await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then(v => - { + await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then((v) => { finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v}); console.log(`Completed Tier: ${cval.channel_id}`); return; - }, err => { + }, (err) => { console.error(err); } ); diff --git a/src/cors/index.d.ts b/src/cors/index.d.ts new file mode 100644 index 0000000..81da9d4 --- /dev/null +++ b/src/cors/index.d.ts @@ -0,0 +1,3 @@ +import { NextFunction, Request, Response } from 'express'; +export const cors: () => (req: Request, res: Response, next: NextFunction) => + void; diff --git a/src/cors/index.js b/src/cors/index.js new file mode 100644 index 0000000..96ffa61 --- /dev/null +++ b/src/cors/index.js @@ -0,0 +1,2 @@ +const cors = require('corser').create; +module.exports = { cors: cors }; diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 73d2356..76e055d 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -134,7 +134,7 @@ export default class User extends Model { } return { username : this.username, - privileges: this.userGroups! + privileges: this.userGroups .filter((ug: UserGroup): boolean => ug.name !== null) .map((ug: UserGroup): string => ug.name as string), projects : this.projects!.map( diff --git a/src/index.ts b/src/index.ts index 1ce284d..0074d7b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,8 +7,8 @@ logger.info('Importing server logic'); import { default as app } from './app'; logger.info('Importing database ORM'); +import { createRootFolder, rootPathId } from './files'; import { default as seq } from './db/orm'; -import { View, files, views, rootPathId, createRootFolder } from './files'; import { default as File } from './db/model/File'; import { default as User } from './db/model/User'; @@ -63,7 +63,6 @@ async function reset(): Promise { await logging.save(); await admin.save(); - logger.info('Adding admin user'); const root: User = new User({ username: 'hafeez', -- cgit v1.2.1 From 67afa3e0e9ca77d32bcc44faafecc8b716bc439d Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 20 Apr 2018 17:32:26 +0100 Subject: Include authoris/zation headers in CORS --- src/cors/index.d.ts | 16 ++++++++++++++-- src/cors/index.js | 8 +++++++- 2 files changed, 21 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/cors/index.d.ts b/src/cors/index.d.ts index 81da9d4..d6e651a 100644 --- a/src/cors/index.d.ts +++ b/src/cors/index.d.ts @@ -1,3 +1,15 @@ import { NextFunction, Request, Response } from 'express'; -export const cors: () => (req: Request, res: Response, next: NextFunction) => - void; + +export interface CORSOptions { + origins?: string[] | Function; + methods?: string[]; + requestHeaders?: string[]; + responseHeaders?: string[]; + supportsCredentials?: boolean; + maxAge?: number; + endPreflightRequests?: boolean; +} + +export const cors: () => + (req: Request, res: Response, next: NextFunction) => + void; diff --git a/src/cors/index.js b/src/cors/index.js index 96ffa61..7e21093 100644 --- a/src/cors/index.js +++ b/src/cors/index.js @@ -1,2 +1,8 @@ -const cors = require('corser').create; +const corser = require('corser'); +const cors = corser.create.bind(null, { + requestHeaders: corser.simpleRequestHeaders.concat([ + 'Authorisation', + 'Authorization' + ]) +}); module.exports = { cors: cors }; -- cgit v1.2.1 From 09155e88a34c211dd9429a70fde432c062af77e0 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 21 Apr 2018 03:06:02 +0100 Subject: Fix many small file-handling problems --- src/FileRouter.ts | 377 ++++++++++++++++++++++++++---------------------- src/app.ts | 2 +- src/db/model/File.ts | 25 ++-- src/errors/errorware.ts | 5 +- src/files.ts | 118 +++++++++------ src/matcher/index.ts | 4 +- src/matcher/options.ts | 6 + 7 files changed, 306 insertions(+), 231 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 9059e88..6b03453 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -495,7 +495,8 @@ const postProjectName: Middleware = async( logger.debug('Adding new project'); const file: File = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory', + type: 'directory', + status: 'ready', parentFolderId: rootPathId }); file.name = ''; // Leave blank as discussed @@ -534,6 +535,88 @@ const getProjectProperties: Middleware = ( } }; +// Fetch a file from its path: +const getFileFromPath: (req: Request, res: Response) => Promise = async( + req: Request, res: Response +): Promise => { + // 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 + + const nth: (str: string, pat: string, n: number) => number = ( + str: string, pat: string, num: number + ): number => { + const l: number = str.length; + let j: number = -1; + let n: number = num; + while (n-- && j++ < l) { + j = str.indexOf(pat, j); + if (j < 0) { + break; + } + } + return j; + }; + + const path: string = req.path.substring(nth(req.path, '/', 4) + 1); + + res.locals.path = path; + logger.debug(`Searching for path '${res.locals.path}'`); + // Split path into parts + const fileNames: string[] = res.locals.path.split('/') + .filter((s: string): boolean => s !== ''); + 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'); + throw new RequestError(404, 'project_not_found'); + } + let curDir: File | null = project.rootFolder; + res.locals.deepestFolderId = curDir.uuid; + res.locals.deepestFolderName = curDir.name; + if (fileNames.length === 0) { + res.locals.file = curDir; + } + 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: { + nameInternal: fileNames[i], + parentFolderId: curDir.uuid + } + }); + if (fileOrNull == null) { + logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`); + return; + } + + 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; + } + curDir = fileOrNull; + i++; + } +}; + /** * GET a File. */ @@ -547,7 +630,7 @@ const getFile: Middleware = async( } const project: Project = res.locals.project; const view: View = views[req.query.view || 'meta']; - // TODO return 400 for unsuported views + // TODO return 400 for unsupported 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); @@ -557,7 +640,16 @@ const getFile: Middleware = async( /** * GET a File. */ -const getFilePath: Middleware = getFile; +const getFilePath: Middleware = async( + req: Request, res: Response, next: NextFunction +): Promise => { + try { + await getFileFromPath(req, res); + await getFile(req, res, next); + } catch (e) { + next(e); + } +}; /** * GET a File. @@ -590,127 +682,138 @@ const qH: { /** * Post a File. / delete / move / etc */ -/* tslint:disable */ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { - 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')); - } + 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 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 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')); + } - // Sets final if requested - if (res.locals.file && qH.isFinal(req)) { - res.locals.file.status = 'preprocessing'; - // start file conversion - } + // 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(); - } + // 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(); - } + // 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')); - } + // 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')); - } + // 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')); - } + // 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]; + + 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')) + } + // update vars + remainingPath = remainingPath.split(subFolder)[1] + res.locals.deepestFolderName = subFolder; + res.locals.deepestFolderId = dir.uuid; + } - // 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({ + logger.debug(`Writing file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) + res.locals.file = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory', - nameInternal: subFolder + nameInternal: res.locals.filename, + fullPathInternal: res.locals.path, + status: req.query.final + ? 'ready' + : 'uploading' }); - await dir.save(); + res.locals.file.mimetype = qH.mksDir(req) ? 'inode/directory' : req.file.mimetype; + console.log(req.file.mimetype); + + await res.locals.file.save(); // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, dir.uuid)){ + 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')) } - // 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(); + // 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)); + } - // 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')) + // Sets final if requested + if (qH.isFinal(req)) { + res.locals.file.status = 'final'; } - } - // 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)); - } + next(); - // Sets final if requested - if (qH.isFinal(req)) { - res.locals.file.status = 'final'; + } catch (e) { + next(e); } - - next(); - }; -/* tslint:enable */ export class FileRouter { public router: Router; @@ -751,9 +854,9 @@ export class FileRouter { this.router.post('/projects/:project_name', postProjectName); this.router.get ('/projects/:project_name/properties', getProjectProperties); // File access - this.router.get ('/projects/:project_name/files/:path', getFilePath); + this.router.get ('/projects/:project_name/files/*', getFilePath); this.router.post( - '/projects/:project_name/files/:path', + '/projects/:project_name/files/*', upload.single('userfile'), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -800,7 +903,8 @@ export class FileRouter { ): Promise => { res.locals.project = await Project.findOne({ include: [ - User + User, + File ], where: { name: projectName @@ -810,73 +914,6 @@ export class FileRouter { } ); - // Fetch a file from its path: - this.router.param( - 'path', - async( - req: Request, res: Response, next: NextFunction, - filename: string - ): Promise => { - // 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 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: { - nameInternal: fileNames[i], - parentFolderId: curDir.uuid - } - }); - if (fileOrNull == null) { - logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`); - return next(); - } - - 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; - } - curDir = fileOrNull; - i++; - } - - next(); - } - ); - // Fetch a file from its UUID: this.router.param( 'id', diff --git a/src/app.ts b/src/app.ts index 6a595f6..a6e0d27 100644 --- a/src/app.ts +++ b/src/app.ts @@ -57,7 +57,7 @@ class App { async(req: ex.Request, res: ex.Response, next: ex.NextFunction): Promise => { if (res.locals.function) { - res.locals.function.bind(res)(res.locals.data); + res.locals.function.bind(res)(await res.locals.data); } else { res.json({ status: 'success', diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 8a12431..6b71f3d 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -3,7 +3,9 @@ import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, HasMany, HasOne, Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; import { default as User } from './User'; -import { FileTypeName, mimes } from '../../files'; +import { RequestError } from '../../errors'; +import { FileTypeName, INITIAL_METADATA, Metadata, mimes } from '../../files'; +import { match, metadata } from '../../matcher'; /* * attributes: @@ -11,7 +13,6 @@ import { FileTypeName, mimes } from '../../files'; * - fullPathInternal * - uuid * - type - * - size * - parentFolderId * - containedFilesInternal * - creatorName @@ -31,7 +32,7 @@ export default class File extends Model { @AllowNull @Column - private fullPathInternal!: string; + public fullPathInternal!: string; @PrimaryKey @Column @@ -40,9 +41,6 @@ export default class File extends Model { @Column(DataType.TEXT) public type!: FileTypeName; - @Column - public size!: number; - @ForeignKey(() => File) @AllowNull @Column(DataType.TEXT) @@ -117,12 +115,19 @@ export default class File extends Model { this.containedFilesInternal = files; } - public get metadata(): object { - return JSON.parse(this.metadataInternal); + public get metadata(): Metadata { + return JSON.parse(this.metadataInternal) || INITIAL_METADATA; } - public set metadata(metadata: object) { - this.metadataInternal = JSON.stringify(metadata); + public set metadata(md: Metadata) { + const oldMD: Metadata = this.metadata; + const newMD: Metadata = md; + if (!match(metadata, newMD)) { + throw new RequestError(400, 'invalid_request'); + } + if (newMD.version !== oldMD.version + 1) { + throw new RequestError(400, 'invalid_request'); + } } public set mimetype(mime: string) { diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts index 6d87bcb..e2b5610 100644 --- a/src/errors/errorware.ts +++ b/src/errors/errorware.ts @@ -1,5 +1,7 @@ import { NextFunction, Request, Response } from 'express'; +import { logger } from '../logger'; + /** * General error and error-handling logic for the middleware stack. */ @@ -115,10 +117,11 @@ export type Errorware = export const errorHandler: Errorware = ( err: Error, req: Request, res: Response, next: NextFunction ): void => { + logger.failure(`Responded to ${req.ip}`); if (RequestError.is(err)) { res.status(err.code) .json(err.responseBlock()); } else { - res.send(err); + res.status(500).send(err.stack); } }; diff --git a/src/files.ts b/src/files.ts index e87d8da..53360a4 100644 --- a/src/files.ts +++ b/src/files.ts @@ -8,12 +8,20 @@ import { default as Project } from './db/model/Project'; const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; +const TEMP_BASE_DIRECTORY: string = './files-temp'; -/* tslint:disable */ -const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { - return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; +export interface Metadata { + version: number; + namespaces: object; + [index: string]: any; +} + +export const INITIAL_METADATA: Metadata = { + version: 1, + namespaces: {} }; +/* tslint:disable */ const writableStream: (filename: string, projectName: string) => fs.WriteStream = (filename: string, projectName: string): fs.WriteStream => { return fs.createWriteStream(path(filename, projectName)); }; @@ -23,7 +31,7 @@ interface RawSize { length: number; } -const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream +const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream = (filename: string, projectName: string, { offset, length }: Partial = { offset: undefined, length: undefined }): fs.ReadStream => { const options: object = { start: offset? offset: 0, @@ -50,42 +58,51 @@ export const logPath: (type: string, projectName?: string) => string = ( let storage = Multer.diskStorage({ destination: function (req, file, cb) { cb(null, CONTENT_BASE_DIRECTORY) - }, - filename: function (req, file, cb) { + }, + 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}`; + +export const tempPath: (file: string, project: string) => string = ( + file: string +): string => + `${TEMP_BASE_DIRECTORY}/${file}` + export const upload: Multer.Instance = Multer({ storage: storage }); -export const saveFile: (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean) => void = - (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean): void => { +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 => { // TODO only overwrite beginning of file and keep rest of data // ensure file exists - fs.ensureFileSync(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); + await fs.ensureFile(path(fileId, projectname)); // truncate to offset - truncateFile(fileId, projectname, 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(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`, {'flags':'a'}); - rStream.pipe(wStream).on('finish', () => { - fs.removeSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + let wStream = fs.createWriteStream(path(fileId, projectname), {'flags':'a'}); + rStream.pipe(wStream).on('finish', async() => { + await fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); }).on('error', (err: any) => { - logger.debug(`Error while saving file to proper location: ${err}`); + logger.error(`Error while saving file to proper location: ${err}`); }); } -export const deleteFile: (fileId: string, projectName: string) => void = - (fileId: string, projectName: string): void => { - - fs.removeSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`); +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) => void = - (fileId: string, projectName: string, newLength: number): void => { +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 = fs.openSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`, 'r+'); - fs.ftruncateSync(fd, newLength); + const fd: number = await fs.open(path(fileId, projectName), 'r+'); + await fs.ftruncate(fd, newLength); } export const files: { @@ -101,11 +118,11 @@ export const files: { export type ViewName = 'raw' | 'meta'; interface Query extends Partial { - children?: boolean; + include_children?: boolean; } export interface View { - getContents: (file: File) => object; + getContents: (file: File, project: Project) => object | Promise; getResponseData: (file: File, project: Project, query: Query) => Promise; getResponseFunction: (req: Request, res: Response) => Function | null; @@ -132,7 +149,7 @@ const metaGetResponseData: ( const data: MetaResponseData = { file_path: file.fullPath, file_name: file.name, - id: file.id, + id: file.uuid, type: file.type, metadata: file.metadata, status: file.status, @@ -140,23 +157,23 @@ const metaGetResponseData: ( }; for (const view of fileTypes[file.type].supportedViews) { data.supported_views[view] = - views[view].getContents(file); + await views[view].getContents(file, project); } - if (query.children) { + if (query.include_children) { data.children = []; const children: File[] | null = await File.findAll({ where: { - parentFolder: file + parentFolderId: file.uuid } }); if (children != null) { for (const child of children) { data.children.push(await metaGetResponseData( - file, + child, project, { ...query, - children: undefined + include_children: undefined } )); } @@ -165,13 +182,20 @@ const metaGetResponseData: ( return data; }; +export const getSize: (file: File, project: Project) => Promise = async( + file: File, project: Project +): Promise => { + const stat: fs.Stats = await fs.stat(path(file.uuid, project.name)); + return stat.size; +}; + export const views: { [view: string]: View; } = { raw: { - getContents: (file: File): object => { + getContents: async(file: File, project: Project): Promise => { return { - size: file.size + size: await getSize(file, project) }; }, getResponseData: async( @@ -180,7 +204,7 @@ export const views: { return readableStream(file.uuid, project.name, query); }, getResponseFunction: (req: Request, res: Response): Function | null => { - return res.send; + return (stream: fs.ReadStream) => stream.pipe(res); } }, meta: { @@ -237,29 +261,30 @@ export const mimes: MimeTypeMap = new MimeTypeMap([ export const rootPathId: string = '0'; export const rootPathFile: File | null = null; -export const createRootFolder: () => void = (): any => { - if (!fs.existsSync(CONTENT_BASE_DIRECTORY)){ - fs.mkdirSync(CONTENT_BASE_DIRECTORY); +export const createRootFolder: () => Promise = async( +): Promise => { + if (!(await fs.exists(CONTENT_BASE_DIRECTORY))){ + await fs.mkdir(CONTENT_BASE_DIRECTORY); } } -export const createProjectFolder: (name: string) => void = (projName: string): any => { - if (!fs.existsSync(CONTENT_BASE_DIRECTORY + '/' + projName)){ - fs.mkdirSync(CONTENT_BASE_DIRECTORY + '/' + projName); +export const createProjectFolder: (name: string) => Promise = async( + projName: string +): Promise => { + if (!(await fs.exists(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}`) + logger.debug(`adding file ${subFileId} 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 } @@ -268,11 +293,8 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis return false; } // update both objects - parent.containedFiles.push(file); - file.parentFolderId = parent.uuid; - // save - await file.save(); - await parent.save(); + // parent.containedFiles.push(file); + parent.$add('containedFilesInternal', file); return true; } diff --git a/src/matcher/index.ts b/src/matcher/index.ts index 0806907..e7c2f88 100644 --- a/src/matcher/index.ts +++ b/src/matcher/index.ts @@ -5,7 +5,9 @@ export { exact, optional, alternative, - array + array, + match, + metadata } from './options'; export { diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 62e4985..0bad627 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -88,6 +88,12 @@ export const array = (template: TemplateValue, values?: Value[]) => { return values.every(m); }; +// tslint:disable-next-line:typedef +export const metadata = exact({ + version: types.integer, + namespaces: {} +}); + // tslint:disable-next-line:typedef const options = { match, -- cgit v1.2.1 From b81e9555f07adfa5b9fb749a539c49810acdc67a Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 21 Apr 2018 23:01:54 +0100 Subject: Add support for tabular files --- src/files.ts | 82 +++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 62 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/files.ts b/src/files.ts index 53360a4..af01798 100644 --- a/src/files.ts +++ b/src/files.ts @@ -3,6 +3,8 @@ import * as fs from 'fs-extra'; import { logger } from './logger'; import * as Multer from 'multer'; +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'; @@ -21,8 +23,11 @@ export const INITIAL_METADATA: Metadata = { namespaces: {} }; -/* tslint:disable */ -const writableStream: (filename: string, projectName: string) => fs.WriteStream = (filename: string, projectName: string): fs.WriteStream => { +const writableStream: ( + filename: string, projectName: string +) => fs.WriteStream = ( + filename: string, projectName: string +): fs.WriteStream => { return fs.createWriteStream(path(filename, projectName)); }; @@ -31,29 +36,36 @@ interface RawSize { length: number; } -const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream - = (filename: string, projectName: string, { offset, length }: Partial = { offset: undefined, length: undefined }): fs.ReadStream => { +interface TabularParameters { + rowstart: number; + rowcount: number; + cols: string[]; +} + +interface Query extends Partial, Partial { + children?: boolean; +} + +const readableStream: ( + filename: string, projectName: string, { offset, length }?: Query +) => fs.ReadStream = ( + filename: string, projectName: string, { offset, length }: Query = + { offset: undefined, length: undefined } +): fs.ReadStream => { const options: object = { - start: offset? offset: 0, - end: offset && length? offset + length: undefined + start: offset ? offset : 0, + end: offset && length ? offset + length : undefined }; return fs.createReadStream(path(filename, projectName), options); }; -export function logPath (type: string, projectName?: string){ - return projectName - ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` - : `${LOG_BASE_DIRECTORY}/general/${type}`; -} - -/* export const logPath: (type: string, projectName?: string) => string = ( - type: string, projectName?: string): string => { + type: string, projectName?: string +): string => { return projectName ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` : `${LOG_BASE_DIRECTORY}/general/${type}`; }; -*/ let storage = Multer.diskStorage({ destination: function (req, file, cb) { @@ -115,7 +127,7 @@ export const files: { logPath }; -export type ViewName = 'raw' | 'meta'; +export type ViewName = 'raw' | 'meta' | 'tabular'; interface Query extends Partial { include_children?: boolean; @@ -215,10 +227,34 @@ export const views: { getResponseFunction: (req: Request, res: Response): Function | null => { return null; } + }, + tabular: { + getContents: (file: File): object => { + return { + // columns: + // rows: + }; + }, + getResponseData: async( + file: File, project: Project, query: Query + ): Promise => { + return readableStream(file.name, project.name, query) + .pipe(parse({ + columns: true, + from: query.rowstart, + to: (query.rowstart && query.rowcount) + ? query.rowstart + query.rowcount + : undefined + })).pipe(stringify({ + })); + }, + getResponseFunction: (req: Request, res: Response): Function | null => { + return (stream: fs.ReadStream) => stream.pipe(res); + } } }; -export type FileTypeName = 'generic' | 'directory'; +export type FileTypeName = 'generic' | 'directory' | 'tabular'; export interface FileType { supportedViews: ViewName[]; @@ -236,6 +272,11 @@ const fileTypes: { supportedViews: [ 'meta' ] + }, + tabular: { + supportedViews: [ + 'raw', 'meta', 'tabular' + ] } }; @@ -255,7 +296,8 @@ class MimeTypeMap extends Map { } export const mimes: MimeTypeMap = new MimeTypeMap([ - [ 'inode/directory', 'directory' ] + [ 'inode/directory', 'directory' ], + [ 'text/csv', 'tabular' ] ]); export const rootPathId: string = '0'; @@ -280,11 +322,13 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis logger.debug(`adding file ${subFileId} 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 } @@ -292,8 +336,6 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis if(!parent || !file){ return false; } - // update both objects - // parent.containedFiles.push(file); parent.$add('containedFilesInternal', file); return true; -- cgit v1.2.1 From 7bfdc2cc7c5aa1aaed655c7ddd3a7c3cf38430e5 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sat, 21 Apr 2018 23:01:58 +0100 Subject: implimented moving and copying of files --- src/FileRouter.ts | 76 +++++++++++++++++++++++++++++++++++++++++++++------- src/db/model/File.ts | 7 ++++- src/files.ts | 38 +++++++++++++++++++++++++- src/index.ts | 2 +- 4 files changed, 111 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 6b03453..ecd5185 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -7,8 +7,8 @@ import { default as UserGroup } from './db/model/UserGroup'; import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; -import { View, addSubFileToFolder, createProjectFolder, deleteFile, rootPathId, - saveFile, upload, views } from './files'; +import { View, addSubFileToFolder, copyFile, createProjectFolder, deleteFile, + rootPathId, saveFile, upload, views } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -572,7 +572,6 @@ const getFileFromPath: (req: Request, res: Response) => Promise = async( 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 @@ -682,6 +681,7 @@ const qH: { /** * Post a File. / delete / move / etc */ +/* tslint:disable */ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { try { await getFileFromPath(req, res); @@ -696,12 +696,14 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu 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 @@ -715,6 +717,7 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu res.locals.file.metadata = req.body; await res.locals.file.save(); next(); + return; } // Deletes File if requested @@ -723,29 +726,83 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu deleteFile(res.locals.file.uuid, res.locals.project.name); await res.locals.file.destroy(); next(); + return; } // Moves File if requested if(qH.moves(req)){ - // TODO - next(new RequestError(500, 'not_implemented')); + 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)){ - // TODO - next(new RequestError(500, 'not_implemented')); + 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)){ - // TODO + 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')); + } + // 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]; @@ -787,7 +844,6 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu : 'uploading' }); res.locals.file.mimetype = qH.mksDir(req) ? 'inode/directory' : req.file.mimetype; - console.log(req.file.mimetype); await res.locals.file.save(); @@ -795,6 +851,7 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu 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; } } @@ -814,6 +871,7 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu next(e); } }; +/* tslint:enable */ export class FileRouter { public router: Router; diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 6b71f3d..89415b7 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -116,7 +116,8 @@ export default class File extends Model { } public get metadata(): Metadata { - return JSON.parse(this.metadataInternal) || INITIAL_METADATA; + return !!(this.metadataInternal) ? JSON.parse(this.metadataInternal) + : INITIAL_METADATA; } public set metadata(md: Metadata) { @@ -128,6 +129,10 @@ export default class File extends Model { if (newMD.version !== oldMD.version + 1) { throw new RequestError(400, 'invalid_request'); } + this.metadataInternal = JSON.stringify(newMD); + } + public setMetadataInternal(md: Metadata): void { + this.metadataInternal = JSON.stringify(md); } public set mimetype(mime: string) { diff --git a/src/files.ts b/src/files.ts index 53360a4..d80f09f 100644 --- a/src/files.ts +++ b/src/files.ts @@ -68,6 +68,10 @@ export const path: (file: string, project: string, view?: ViewName) => string = (file: string, project: string, view: ViewName = 'raw'): string => `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`; +export const pathNoView: (file: string, project: string) => string = + (file: string, project: string): string => + `${CONTENT_BASE_DIRECTORY}/${project}/${file}`; + export const tempPath: (file: string, project: string) => string = ( file: string ): string => @@ -86,7 +90,7 @@ export const saveFile: (filename: string, projectname: string, fileId: string, o let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); let wStream = fs.createWriteStream(path(fileId, projectname), {'flags':'a'}); rStream.pipe(wStream).on('finish', async() => { - await fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); }).on('error', (err: any) => { logger.error(`Error while saving file to proper location: ${err}`); }); @@ -105,6 +109,38 @@ export const truncateFile: (fileId: string, projectName: string, newLength: numb await fs.ftruncate(fd, newLength); } +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)); + const fromDir: string = pathNoView(fromId, projName); + const toDir: string = pathNoView(toId, projName); + // loop all views in file + fs.readdir(fromDir, (err: any, files: string[]) => { + if(err){ + logger.error(`Error while copying file: ${err}`); + } else { + files.forEach((file: string, index: number) => { + 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); + rStream.pipe(wStream).on('finish', async() => { + if(!!move){ + await fs.remove(fromPathFull); + } + 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; writableStream: (f: string, p: string) => fs.WriteStream; diff --git a/src/index.ts b/src/index.ts index 0074d7b..4dc83ad 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 From bd75d9ebc4f7c22b2c36d68bdead9021042504c9 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sun, 22 Apr 2018 15:59:16 +0100 Subject: autocreating logs folder on startup --- src/index.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/index.ts b/src/index.ts index 4dc83ad..5e35014 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,11 @@ import { logger } from './logger'; +import * as fs from 'fs-extra'; logger.info('Starting up server'); +logger.info('Creating necessary directories'); +fs.ensureDirSync('logs/general'); +fs.ensureDirSync('files'); logger.info('Importing server logic'); import { default as app } from './app'; @@ -9,7 +13,6 @@ import { default as app } from './app'; logger.info('Importing database ORM'); import { createRootFolder, rootPathId } from './files'; import { default as seq } from './db/orm'; - import { default as File } from './db/model/File'; import { default as User } from './db/model/User'; import { default as UserGroup } from './db/model/UserGroup'; @@ -93,7 +96,8 @@ 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