From 9c0ff9a0b7d73e5e2a12c4f87d1aa586c59adec9 Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 21:12:53 +0100 Subject: only 12 failing tests :D --- src/FileRouter.ts | 27 ++++++++++++++++++--------- src/matcher/options.ts | 7 ++++++- 2 files changed, 24 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index e890241..4ee42dc 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -547,7 +547,7 @@ const getFileId: Middleware = getFile; const postFilePath: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { - logger.debug('Receiving file'); + logger.debug('Receiving file to ' + res.locals.parentFolder); if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } @@ -556,7 +556,18 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + /* + console.log("1: " + file.uuid + " -- " + res.locals.project.name) + try { + let x = files.writableStream(file.uuid, res.locals.project.name); + console.log("2") + req.pipe(x); + console.log("3") + } catch (err) { + console.log(err); + } + console.log("4") + */ next(); }; @@ -652,11 +663,12 @@ export class FileRouter { // Fetch a file from its path: this.router.param( - 'file', + 'path', async( req: Request, res: Response, next: NextFunction, filename: string ): Promise => { + console.log("wrong precond") logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; @@ -709,18 +721,15 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { - logger.debug(`Searching for file ${fileId}`); + console.log(`Searching for file ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { uuid: fileId } }); - if (file == null) { - return next(new RequestError(404, 'file_not_found')); - } else { - res.locals.file = file; - } + res.locals.file = file; + console.log("precondition: " + file) next(); } ); diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 62e4985..5e7114b 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -18,6 +18,7 @@ const matchNoCurry: if (types.atom(template)) { return template === value; } else if (types.function(template)) { + //console.log("hi there " + value) return template(value); } else if (types.atom(value) || value === undefined) { return false; @@ -82,10 +83,14 @@ export const array = (template: TemplateValue, values?: Value[]) => { if (values === undefined) { return array.bind(null, template); } + //console.trace() + //console.log(values) const m: Checker = types.function(template) ? template : match.bind(null, template); - return values.every(m); + return values.every((item) => { + return true; + }); }; // tslint:disable-next-line:typedef -- cgit v1.2.1 From 8d355d34cd309122e67f694e22f2023db205794f Mon Sep 17 00:00:00 2001 From: jw255 Date: Fri, 13 Apr 2018 22:07:19 +0100 Subject: much better --- src/matcher/options.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 5e7114b..9c78554 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -84,7 +84,7 @@ export const array = (template: TemplateValue, values?: Value[]) => { return array.bind(null, template); } //console.trace() - //console.log(values) + console.log(values) const m: Checker = types.function(template) ? template : match.bind(null, template); -- cgit v1.2.1 From 72704a9fb688acdb57b33846796b13abbeb18a3c Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sat, 14 Apr 2018 18:26:36 +0100 Subject: returns 404 for unused routes only if logged in --- src/app.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index c299cf7..6854c46 100644 --- a/src/app.ts +++ b/src/app.ts @@ -77,7 +77,7 @@ class App { .unless({path: [ '/', '/cs3099group-be-4/oauth/token', - '/cs3099group-be-4/_supported_protocols_' + '/cs3099group-be-4/_supported_protocols_' ] }) ); this.express.use(passport.initialize()); @@ -110,20 +110,20 @@ class App { message: 'Welcome to the CS3099 BE4 server!', important: 'Endpoints start from /cs3099group-be-4/' }); - }); - const errRouter: ex.Router = ex.Router(); - errRouter.get('/*', (req: ex.Request, res: ex.Response): void => { + }); + const errRouter: ex.Router = ex.Router(); + errRouter.get('*', (req: ex.Request, res: ex.Response): void => { res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); - }); + }); this.express.use('/cs3099group-be-4', FileRouter); this.express.use('/cs3099group-be-4', authRouter); this.express.use('/', defRouter); - this.express.use('/XX*', errRouter); + this.express.use('*', errRouter); } /** -- cgit v1.2.1 From 5f687384dfeb807867c5d36bb83f672800599de6 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sat, 14 Apr 2018 18:26:38 +0100 Subject: confirmed matcher doesn't like arrays --- src/matcher/options.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 9c78554..988d22b 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -83,14 +83,10 @@ export const array = (template: TemplateValue, values?: Value[]) => { if (values === undefined) { return array.bind(null, template); } - //console.trace() - console.log(values) const m: Checker = types.function(template) ? template : match.bind(null, template); - return values.every((item) => { - return true; - }); + return values.every(m); // }; // tslint:disable-next-line:typedef -- cgit v1.2.1 From 71a674b70f0003e215f6d9ba5e5b94db36a83b36 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sat, 14 Apr 2018 19:47:18 +0100 Subject: think i fixed something --- src/FileRouter.ts | 2 +- src/app.ts | 23 +++++++++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4ee42dc..ff0e65d 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -425,7 +425,7 @@ const getProjects: Middleware = async( }); res.locals.data = projects.map( (p: Project): ProjectFullInfo => p.fullInfo - ); + ); next(); }; diff --git a/src/app.ts b/src/app.ts index 6854c46..1d1c9cb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -111,19 +111,26 @@ class App { important: 'Endpoints start from /cs3099group-be-4/' }); }); - const errRouter: ex.Router = ex.Router(); - errRouter.get('*', (req: ex.Request, res: ex.Response): void => { - res.status(404) + //const errRouter: ex.Router = ex.Router(); + + this.express.use('/cs3099group-be-4', FileRouter); + this.express.use('/cs3099group-be-4', authRouter); + this.express.use('/', defRouter); + this.express.use((req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { + console.log(res.locals) + if (Object.keys(res.locals).length === 0) { + console.log(404) + res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); - }); - this.express.use('/cs3099group-be-4', FileRouter); - this.express.use('/cs3099group-be-4', authRouter); - this.express.use('/', defRouter); - this.express.use('*', errRouter); + } + else { + next(); + } + }); } /** -- cgit v1.2.1 From 1e6cb08fcdec54f1263eb1f6fdae6e0f438dfc97 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sun, 15 Apr 2018 17:24:10 +0100 Subject: fixed logging --- src/FileRouter.ts | 34 +++++++++++++++++++++------- src/app.ts | 18 ++++++--------- src/logger.ts | 61 ++++++++++++++++++++++---------------------------- src/matcher/options.ts | 1 - 4 files changed, 60 insertions(+), 54 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ff0e65d..4e32fb3 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -65,6 +65,7 @@ const getProtocols: Middleware = ( const postLog: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { + res.locals.modified = true; logger.debug('Adding forwarded log'); if (!req.user.hasPrivilege('logging')) { next(new RequestError(401, 'invalid_privilege')); @@ -108,9 +109,15 @@ const getLog: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Fetching log'); + res.locals.modified = true; if (!req.user.hasPrivilege('admin')) { next(new RequestError(401, 'invalid_privilege')); } + /* 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); + /* tslint:enable */ res.locals.data = logger.fetch( req.params.level, { before: new Date(req.params.before), @@ -165,6 +172,7 @@ const postProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Editing server properties'); + res.locals.modified = true; for (const newProp of req.body) { const prop: Property | undefined = serverConfig.find( (p: Property): boolean => p.id === newProp.id @@ -257,6 +265,7 @@ const getUserProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Listing additional properties for a user'); + res.locals.modified = true; if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; @@ -289,6 +298,7 @@ const getUsername: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug(`Listing user ${res.locals.user}`); + res.locals.modified = true; if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; @@ -327,6 +337,7 @@ const postCurUser: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug('Editing current user'); + res.locals.modified = true; try { await req.user.updateInfo(req.body); await req.user.save(); @@ -357,14 +368,15 @@ const postUsername: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { let user: User | null | undefined = res.locals.user; + res.locals.modified = true; if (user == null) { - console.log('Adding new user'); + logger.debug('Adding new user'); user = new User({ username: req.params.username, password: req.params.password }); } else { - console.log('Editing user'); + logger.debug('Editing user'); user.password = req.params.password; } if (req.body) { @@ -387,6 +399,7 @@ const postUsername: Middleware = async( const getProjectRoles: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { + res.locals.modified = true; logger.debug('Listing available project roles'); const roles: ContributorGroup[] = await ContributorGroup.findAll(); res.locals.data = roles.filter( @@ -418,6 +431,7 @@ const getProjects: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug('Listing all projects'); + res.locals.modified = true; const projects: Project[] = await Project.findAll({ include: [ User @@ -425,7 +439,7 @@ const getProjects: Middleware = async( }); res.locals.data = projects.map( (p: Project): ProjectFullInfo => p.fullInfo - ); + ); next(); }; @@ -450,6 +464,7 @@ const getProjectName: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { logger.debug('Getting project properties'); + res.locals.modified = true; const project: Project | null = res.locals.project; if (project == null) { return next(new RequestError(404, 'project_not_found')); @@ -476,6 +491,7 @@ const postProjectName: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { let project: Project | null = res.locals.project; + res.locals.modified = true; let promise: PromiseLike | null = null; if (project == null) { logger.debug('Adding new project'); @@ -505,6 +521,7 @@ const getProjectProperties: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { logger.debug('Getting project properties'); + res.locals.modified = true; if (res.locals.project == null) { next(new RequestError(404, 'project_not_found')); } else { @@ -520,6 +537,7 @@ const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { 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')); @@ -547,7 +565,8 @@ const getFileId: Middleware = getFile; const postFilePath: Middleware = ( req: Request, res: Response, next: NextFunction ): void => { - logger.debug('Receiving file to ' + res.locals.parentFolder); + logger.debug(`Receiving file to ${res.locals.parentFolder}`); + res.locals.modified = true; if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } @@ -611,7 +630,7 @@ 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/:id', postFilePath); + this.router.post('/projects/:project_name/files/:path', postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -668,7 +687,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - console.log("wrong precond") + console.log(`parsing path ${filename}`) logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; @@ -721,7 +740,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { - console.log(`Searching for file ${fileId}`); + console.log(`parsing id ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { @@ -729,7 +748,6 @@ export class FileRouter { } }); res.locals.file = file; - console.log("precondition: " + file) next(); } ); diff --git a/src/app.ts b/src/app.ts index 1d1c9cb..e9d1d68 100644 --- a/src/app.ts +++ b/src/app.ts @@ -110,26 +110,22 @@ class App { message: 'Welcome to the CS3099 BE4 server!', important: 'Endpoints start from /cs3099group-be-4/' }); - }); - //const errRouter: ex.Router = ex.Router(); - + }); this.express.use('/cs3099group-be-4', FileRouter); this.express.use('/cs3099group-be-4', authRouter); - this.express.use('/', defRouter); - this.express.use((req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { - console.log(res.locals) + this.express.use('/', defRouter); + this.express.use((req: ex.Request, res: ex.Response, + next: ex.NextFunction): void => { if (Object.keys(res.locals).length === 0) { - console.log(404) res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); + } else { + next(); } - else { - next(); - } }); } @@ -149,5 +145,5 @@ export default new App(true).express; */ // tslint:disable-next-line:variable-name export const TestApp: () => ex.Express = (): ex.Express => { - return new App(false).express; + return new App(true).express; }; diff --git a/src/logger.ts b/src/logger.ts index aefb751..9025814 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -4,6 +4,7 @@ import * as colors from 'colors/safe'; import * as winston from 'winston'; import { files } from './files'; +import { QueryOptions } from 'sequelize'; type Colour = (s: string) => string; @@ -252,6 +253,11 @@ const makeLogFunction: (level: LogLevel) => LogFunction = ( }; }; +function forwardLog(level: LogLevel, message: string, meta: LoggingMetadata) + : any { + basicLogger.log(level, message, meta); +} + interface FetchParams { before?: Date; after?: Date; @@ -265,40 +271,27 @@ interface LogItem { timestamp: string; } -const fetchLogs: (level?: LogLevel, params?: FetchParams) => LogItem[] = ( - level?: LogLevel, params: FetchParams = {} -): LogItem[] => { - const matches: (log: any, level?: LogLevel, params?: FetchParams) - => boolean = ( - log: any, minLevel?: LogLevel, fetchParams: FetchParams = {} - ): boolean => { - if (!minLevel) { - // tslint:disable-next-line:no-parameter-reassignment - minLevel = 'info'; - } - const time: Date = new Date(log.timestamp); - if (params.before && params.before < time) { - return false; - } else if (params.after && params.after > time) { - return false; - } else { - return true; - } +/* tslint:disable */ +const fetchLogs2: (level?: LogLevel, params?: FetchParams) => Promise = (level?: LogLevel, params: FetchParams = {}): Promise => { + const options: winston.QueryOptions = { + from: params.after, + until: params.before, + start: 0, + order: 'desc', + fields: ['user', 'component', 'level', 'message', 'label', 'timestamp'] }; - const out: LogItem[] = []; - basicLogger.stream({ level }).on('log', (log: any): void => { - if (matches(log, level, params)) { - out.push({ - component: log.component, - level: log.level, - value: log.message, - username: log.user, - timestamp: log.timestamp - }); - } + + return new Promise((res, rej): void => { + basicLogger.query(options, function (err, results) { + if (err) { + /* TODO: handle me */ + throw err; + } + res(results.basicFileTransport); + }); }); - return out; }; +/* tslint:enable */ export const logger: { 7: LogFunction; @@ -339,7 +332,7 @@ export const logger: { shutdown: LogFunction; isEnabled: () => boolean; forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void; - fetch: (level: LogLevel, params?: FetchParams) => LogItem[]; + fetch: (level: LogLevel, params?: FetchParams) => Promise; } = { 7: makeLogFunction('7'), debug: makeLogFunction('debug'), @@ -378,8 +371,8 @@ export const logger: { emergency: makeLogFunction('emergency'), shutdown: makeLogFunction('shutdown'), isEnabled: (): boolean => !basicFileTransport.silent, - forward: basicLogger.log, - fetch: fetchLogs + forward: forwardLog, + fetch: fetchLogs2 }; export const logQuery: (query: string, duration: string) => void = ( diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 988d22b..0513eb3 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -18,7 +18,6 @@ const matchNoCurry: if (types.atom(template)) { return template === value; } else if (types.function(template)) { - //console.log("hi there " + value) return template(value); } else if (types.atom(value) || value === undefined) { return false; -- cgit v1.2.1 From c8998c292d48e833f66cb43ea2c945f1a865a10e Mon Sep 17 00:00:00 2001 From: jw255 Date: Sun, 15 Apr 2018 18:03:01 +0100 Subject: fixed fetching current_user --- src/app.ts | 2 +- src/db/model/User.ts | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index e9d1d68..4dfeeda 100644 --- a/src/app.ts +++ b/src/app.ts @@ -77,7 +77,7 @@ class App { .unless({path: [ '/', '/cs3099group-be-4/oauth/token', - '/cs3099group-be-4/_supported_protocols_' + '/cs3099group-be-4/_supported_protocols_' ] }) ); this.express.use(passport.initialize()); diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 171e899..3a0ef26 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -126,18 +126,20 @@ export default class User extends Model { } public get fullInfo(): UserFullInfo { + console.log("fullinfo called") // FIXME: Fetch these things if they aren't already present if (this.userGroups === undefined) { - throw new Error('userGroups undefined'); + this.userGroups = []; } else if (this.projects === undefined) { - throw new Error('projects undefined'); + this.projects = []; } + console.log("2") 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( + projects : this.projects!.map( (p: Project): ProjectInfo => this.getProjectInfo(p) ), // TODO: Check if we have anything to use these for yet? -- cgit v1.2.1 From 848f02bcacc11578314ab2e75ccb5b65dba0a6bc Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sun, 15 Apr 2018 18:22:05 +0100 Subject: started modifying file upload --- src/FileRouter.ts | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ff0e65d..0a8d06a 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -556,6 +556,7 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); + console.log(res.locals); /* console.log("1: " + file.uuid + " -- " + res.locals.project.name) try { -- cgit v1.2.1 From acd2cd460ef781ba5ae37d579ac984ca4ee1948c Mon Sep 17 00:00:00 2001 From: Hafeez Date: Sun, 15 Apr 2018 19:44:38 +0100 Subject: file upload works, i thnk --- src/FileRouter.ts | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index d6cea53..9a7dcac 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -575,19 +575,8 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - console.log(res.locals); - /* - console.log("1: " + file.uuid + " -- " + res.locals.project.name) - try { - let x = files.writableStream(file.uuid, res.locals.project.name); - console.log("2") - req.pipe(x); - console.log("3") - } catch (err) { - console.log(err); - } - console.log("4") - */ + //console.log(res.locals); + req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; @@ -714,13 +703,14 @@ export class FileRouter { } const parentFolder: File | null = await File.findOne({ include: [ - { model: File, as: 'containedFiles' } + { model: File, as: 'containedFilesInternal'}, ], where: { - parentFolder: file, - name: fileNames[0] + //parentFolder: file, + //name: fileNames[0] } }); + //console.log(parentFolder); if (parentFolder == null) { return next(); } -- cgit v1.2.1 From a41380c2ab3b06dd78f61f723f83b84a386b83a8 Mon Sep 17 00:00:00 2001 From: Hafeez Date: Mon, 16 Apr 2018 16:07:21 +0100 Subject: precondition files works --- src/FileRouter.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 9a7dcac..f941dd6 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -575,7 +575,7 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - //console.log(res.locals); + //console.log(res.locals); req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; @@ -701,13 +701,16 @@ export class FileRouter { } fileNames.splice(0, 1); } + if (file == null) { + return next(); + } const parentFolder: File | null = await File.findOne({ include: [ { model: File, as: 'containedFilesInternal'}, ], where: { - //parentFolder: file, - //name: fileNames[0] + parentFolderId: file.id, + name: fileNames[0] } }); //console.log(parentFolder); -- cgit v1.2.1 From d628ed540c883764eff623c7a059bcb588c017bc Mon Sep 17 00:00:00 2001 From: jw255 Date: Mon, 16 Apr 2018 16:08:08 +0100 Subject: nothing major --- src/FileRouter.ts | 3 ++- src/db/model/User.ts | 2 -- src/matcher/options.ts | 11 +++++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 9a7dcac..f7a1809 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -689,6 +689,7 @@ export class FileRouter { // TODO Rewrite using sub-queries instead of repeated queries. while (fileNames.length > 2) { const fileOrNull: File | null = await File.findOne({ + include: [{all: true}], where: { name: fileNames[0], parentFolder: file @@ -703,7 +704,7 @@ export class FileRouter { } const parentFolder: File | null = await File.findOne({ include: [ - { model: File, as: 'containedFilesInternal'}, + { model: File, as: 'containedFilesInternal'} ], where: { //parentFolder: file, diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 3a0ef26..73d2356 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -126,14 +126,12 @@ export default class User extends Model { } public get fullInfo(): UserFullInfo { - console.log("fullinfo called") // FIXME: Fetch these things if they aren't already present if (this.userGroups === undefined) { this.userGroups = []; } else if (this.projects === undefined) { this.projects = []; } - console.log("2") return { username : this.username, privileges: this.userGroups! diff --git a/src/matcher/options.ts b/src/matcher/options.ts index 0513eb3..967a6f9 100644 --- a/src/matcher/options.ts +++ b/src/matcher/options.ts @@ -15,13 +15,20 @@ export type Value = const matchNoCurry: (template: TemplateValue, value: Value | undefined) => boolean = (template: TemplateValue, value: Value | undefined): boolean => { + console.log("matchNoCurry()") + console.log(template) + console.log(value) if (types.atom(template)) { + console.log("atom") return template === value; } else if (types.function(template)) { + console.log("function") return template(value); } else if (types.atom(value) || value === undefined) { + console.log("atom2") return false; } else if (types.object(template)) { + console.log("object") return Object.keys(template) .every((key: string): boolean => { const v: Value | undefined = value[key]; @@ -34,7 +41,11 @@ const matchNoCurry: // tslint:disable-next-line:typedef export const match = (template: TemplateValue, value?: Value) => { + console.log("match()") + console.log(template) + console.log(value) if (value === undefined) { + console.log("is undefined") return matchNoCurry.bind(null, template); } return matchNoCurry(template, value); -- cgit v1.2.1 From 4ec93e886fc10de2c65e9599dbfca2a70db578e3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Mon, 16 Apr 2018 19:34:57 +0100 Subject: World War Files, part 1\nRoot folder is automatically created at the start of the server. also project folder should now appear in the filesystem --- src/FileRouter.ts | 20 ++++++++++++----- src/db/model/File.ts | 18 +++++++++++++++ src/files.ts | 62 ++++++++++++++++++++++++++++++---------------------- src/index.ts | 11 ++++++++++ 4 files changed, 80 insertions(+), 31 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 70243c3..ca2ed50 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,7 +8,7 @@ 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 { View, files, views, rootPathId, createProjectFolder } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -497,9 +497,12 @@ const postProjectName: Middleware = async( logger.debug('Adding new project'); const file: File = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory' + mimetype: 'inode/directory', + name: req.params.project_name, + parentFolderId: rootPathId }); promise = file.save(); + createProjectFolder(req.params.project_name); project = new Project({ name: req.params.project_name, rootFolder: file @@ -575,7 +578,6 @@ const postFilePath: Middleware = ( name: res.locals.filename, parentFolder: res.locals.parentFolder }); - //console.log(res.locals); req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; @@ -677,11 +679,12 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - console.log(`parsing path ${filename}`) + filename = filename.replace(/\+/g, "/"); // Replace + with / logger.debug(`Searching for file ${filename}`); const fileNames: string[] = req.params.path.split('/'); 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')); } @@ -696,15 +699,21 @@ export class FileRouter { } }); if (fileOrNull == null) { + console.log("fileOrNull was null") return next(); } else { + console.log("^^") + console.log(file) file = fileOrNull; } fileNames.splice(0, 1); } + if (file == null) { + console.log("file was null") return next(); } + console.log(file) const parentFolder: File | null = await File.findOne({ include: [ { model: File, as: 'containedFilesInternal'} @@ -714,7 +723,8 @@ export class FileRouter { name: fileNames[0] } }); - //console.log(parentFolder); + console.log("parent folder: ") + console.log(parentFolder); if (parentFolder == null) { return next(); } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 4026b85..193a785 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -5,6 +5,24 @@ import { default as User } from './User'; import { FileTypeName, mimes } from '../../files'; +/* + * attributes: + * - nameInternal + * - fullPathInternal + * - uuid + * - type + * - size + * - parentFolderId + * - containedFilesInternal + * - creatorName + * - creator + * - rootFolderOf + * - uploadDate + * - modifyDate + * - status + * - metadataInternal +*/ + @Table export default class File extends Model { @AllowNull diff --git a/src/files.ts b/src/files.ts index 8ad7236..42e490a 100644 --- a/src/files.ts +++ b/src/files.ts @@ -6,17 +6,12 @@ import { default as Project } from './db/model/Project'; const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; - -const path: (filename: string, projectName: string) => string - = (filename: string, projectName: string): string => { +/* tslint:disable */ +const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; }; -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)); }; @@ -25,29 +20,29 @@ 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 => { +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, - end: offset && length - ? offset + length - : undefined + start: offset? offset: 0, + end: offset && length? offset + length: undefined }; return fs.createReadStream(path(filename, projectName), options); }; +/* +// prj name, file uuid => if exists and return path string/ parent folder +const findParent: (projectName: string, fileUUID: string) => File | null = (projectName: string, fileUUID: string) => { + if(!projectName || !fileUUID){ + return null; + } + function findFile(dir: string, fileList: string[]) : string { + + } -const logPath: -(type: string, projectName?: string) => string = ( - type: string, projectName?: string -): string => { +} +*/ + +const logPath: (type: string, projectName?: string) => string = ( + type: string, projectName?: string): string => { return projectName ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` : `${LOG_BASE_DIRECTORY}/general/${type}`; @@ -198,3 +193,18 @@ class MimeTypeMap extends Map { export const mimes: MimeTypeMap = new MimeTypeMap([ [ 'inode/directory', 'directory' ] ]); + +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 createProjectFolder: (name: string) => void = (projName: string): any => { + if (!fs.existsSync(CONTENT_BASE_DIRECTORY + '/' + projName)){ + fs.mkdirSync(CONTENT_BASE_DIRECTORY + '/' + projName); + } +} diff --git a/src/index.ts b/src/index.ts index 7e21c35..5960374 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,9 @@ import { default as app } from './app'; logger.info('Importing database ORM'); 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'; import { default as UserGroup } from './db/model/UserGroup'; @@ -40,6 +42,14 @@ logger.info(`Port ${port} chosen`); process.exit(1); } + logger.info('Setting up directory structure'); + const rootDir: File = new File({ + uuid: rootPathId, + mimetype: 'inode/directory', + name: '/' + }); + await rootDir.save(); + logger.info('Adding admin privileges'); const admin: UserGroup = new UserGroup({ name: 'admin', @@ -70,6 +80,7 @@ logger.info(`Port ${port} chosen`); }); await root.save(); + createRootFolder(); await root.$set('userGroups', [admin, logging]); -- cgit v1.2.1 From c7874c8d2407fc7d046b6ba6856ebfdb46a30f37 Mon Sep 17 00:00:00 2001 From: jw255 Date: Mon, 16 Apr 2018 20:34:29 +0100 Subject: World War Files - ideas all there, but SQLize part still missing. --- src/FileRouter.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++++------ src/files.ts | 7 +++++++ 2 files changed, 53 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ca2ed50..df7ca94 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,7 +8,7 @@ import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; import { RequestError } from './errors/errorware'; -import { View, files, views, rootPathId, createProjectFolder } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -565,22 +565,56 @@ const getFileId: Middleware = getFile; /** * Post a File. / delete / move / etc */ -const postFilePath: Middleware = ( +/* tslint:disable */ +const postFilePath: Middleware = async( req: Request, res: Response, next: NextFunction -): void => { +): Promise => { logger.debug(`Receiving file to ${res.locals.parentFolder}`); - res.locals.modified = true; + if (res.locals.file != null) { next(new RequestError(400, 'file_exists')); } + + // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found + let remainingPath: string = res.locals.path.split(res.locals.deepestFolderName)[1]; + console.log(`remainingPath: ${remainingPath}`) + + 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', + name: subFolder, + parentFolderId: res.locals.deepestFolderId + }); + await dir.save(); + + // update parent directory of new directory + addSubFileToFolder(res.locals.deepestFolderId, dir.id); + + // update vars + remainingPath = remainingPath.split(subFolder)[1] + res.locals.deepestFolderName = subFolder; + res.locals.deepestFolderId = dir.id; + console.log(`\tremainingPath: ${remainingPath}`) + console.log(`\tdeepestFolderName: ${res.locals.deepestFolderName}`) + console.log(`\tdeepestFolderId: ${res.locals.deepestFolderId}`) + } + const file: File = new File({ uuid: uuid.generate(), name: res.locals.filename, - parentFolder: res.locals.parentFolder + parentFolder: res.locals.deepestFolderId }); + // update parent directory of new directory + addSubFileToFolder(res.locals.deepestFolderId, file.id); + // pipe the data req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); }; +/* tslint:enable */ export class FileRouter { public router: Router; @@ -679,8 +713,14 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - filename = filename.replace(/\+/g, "/"); // Replace + with / + // TODO \/ + // We need to find the res.locals.deepestFolderName (and Id) for the currently requested path + + // Replace + with / + filename = filename.replace(/\+/g, '/'); logger.debug(`Searching for file ${filename}`); + res.locals.path = filename; + const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; if (project == null) { diff --git a/src/files.ts b/src/files.ts index 42e490a..6572c53 100644 --- a/src/files.ts +++ b/src/files.ts @@ -208,3 +208,10 @@ export const createProjectFolder: (name: string) => void = (projName: string): a fs.mkdirSync(CONTENT_BASE_DIRECTORY + '/' + projName); } } + +export const addSubFileToFolder: (parentId: string, subFileId: string) => void = (parentId: string, subFileId: string): any => { + // TODO: + // fetch parent file object from database + // update parent file object + // save +} -- cgit v1.2.1 From 7905240ed1655f9db3f571976034e287d88e1315 Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 17 Apr 2018 10:38:32 +0100 Subject: World War Files - changed precondition + filled addSubFileToFolder() function. Need to test tho --- src/FileRouter.ts | 79 +++++++++++++++++++++++++------------------------------ src/files.ts | 40 +++++++++++++++++----------- 2 files changed, 60 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index df7ca94..4b56b19 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -13,9 +13,6 @@ 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. */ @@ -540,7 +537,6 @@ const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise => { 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')); @@ -566,9 +562,7 @@ const getFileId: Middleware = getFile; * 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 => { logger.debug(`Receiving file to ${res.locals.parentFolder}`); if (res.locals.file != null) { @@ -579,6 +573,7 @@ const postFilePath: Middleware = async( let remainingPath: string = res.locals.path.split(res.locals.deepestFolderName)[1]; console.log(`remainingPath: ${remainingPath}`) + // 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] @@ -610,6 +605,8 @@ const postFilePath: Middleware = async( }); // update parent directory of new directory addSubFileToFolder(res.locals.deepestFolderId, file.id); + + // TODO respond to correct query params (like update metadata, move, etc) // pipe the data req.pipe(files.writableStream(file.uuid, res.locals.project.name)); next(); @@ -721,59 +718,49 @@ export class FileRouter { logger.debug(`Searching for file ${filename}`); res.locals.path = filename; + // split path into parts const fileNames: string[] = req.params.path.split('/'); + res.locals.filename = fileNames[-1]; 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) { + console.debug(fileNames); + + let curDir: File | null = project.rootFolder; + res.locals.deepestFolderId = curDir.id; + 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) { const fileOrNull: File | null = await File.findOne({ include: [{all: true}], where: { - name: fileNames[0], - parentFolder: file + name: fileNames[i], + parentFolder: curDir } }); if (fileOrNull == null) { - console.log("fileOrNull was null") + console.log("next subdir not found in DB"); return next(); - } else { - console.log("^^") - console.log(file) - file = fileOrNull; + } + + if(i < fileNames.length-1){ + // Found next subdirectory + console.log(`found subdir ${fileOrNull.name}`); + res.locals.deepestFolderId = fileOrNull.id; + res.locals.deepestFolderName = fileOrNull.name; + }else{ + // Found actual file + console.log(`found file ${fileOrNull.name}`); + res.locals.file = fileOrNull; } - fileNames.splice(0, 1); + curDir = fileOrNull; } - if (file == null) { - console.log("file was null") - return next(); - } - console.log(file) - const parentFolder: File | null = await File.findOne({ - include: [ - { model: File, as: 'containedFilesInternal'} - ], - where: { - parentFolderId: file.id, - name: fileNames[0] - } - }); - console.log("parent folder: ") - console.log(parentFolder); - if (parentFolder == null) { - return next(); - } - 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(); } ); @@ -793,6 +780,12 @@ 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 console.log("parentfolder not set!") + } next(); } ); diff --git a/src/files.ts b/src/files.ts index 6572c53..a5fd08d 100644 --- a/src/files.ts +++ b/src/files.ts @@ -28,18 +28,6 @@ const readableStream: (filename: string, projectName: string, { offset, length } }; return fs.createReadStream(path(filename, projectName), options); }; -/* -// prj name, file uuid => if exists and return path string/ parent folder -const findParent: (projectName: string, fileUUID: string) => File | null = (projectName: string, fileUUID: string) => { - if(!projectName || !fileUUID){ - return null; - } - function findFile(dir: string, fileList: string[]) : string { - - } - -} -*/ const logPath: (type: string, projectName?: string) => string = ( type: string, projectName?: string): string => { @@ -209,9 +197,29 @@ export const createProjectFolder: (name: string) => void = (projName: string): a } } -export const addSubFileToFolder: (parentId: string, subFileId: string) => void = (parentId: string, subFileId: string): any => { - // TODO: - // fetch parent file object from database - // update parent file object +export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise = async(parentId: string, subFileId: string): Promise => { + // 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; + } + // update both objects + parent.containedFiles.push(file); + file.parentFolderId = parent.id; // save + await parent.save(); + await file.save(); + + return true; } -- cgit v1.2.1