diff options
| author | Tom Harley | 2018-04-17 17:03:14 +0100 |
|---|---|---|
| committer | Tom Harley | 2018-04-17 17:03:14 +0100 |
| commit | 44c14c13bdd7ad91a119564622b811cc70147de8 (patch) | |
| tree | 318420a6bc570bcd3c990d387411e7a205a4e677 /src | |
| parent | Merge branch 'trh/gets' of gitlab.cs.st-andrews.ac.uk:cs3099group-be-4/projec... (diff) | |
| parent | World War Files - changed precondition + filled addSubFileToFolder() function... (diff) | |
| download | medicine-44c14c13bdd7ad91a119564622b811cc70147de8.tar.gz medicine-44c14c13bdd7ad91a119564622b811cc70147de8.zip | |
Merge branch ‘trh/gets’ of gitlab.cs.st-andrews.ac.uk:cs3099group-be-4/project-code into trh/gets
Diffstat (limited to 'src')
| -rw-r--r-- | src/FileRouter.ts | 151 | ||||
| -rw-r--r-- | src/app.ts | 19 | ||||
| -rw-r--r-- | src/db/model/File.ts | 18 | ||||
| -rw-r--r-- | src/db/model/User.ts | 8 | ||||
| -rw-r--r-- | src/files.ts | 77 | ||||
| -rw-r--r-- | src/index.ts | 11 | ||||
| -rw-r--r-- | src/logger.ts | 61 | ||||
| -rw-r--r-- | src/matcher/options.ts | 13 |
8 files changed, 242 insertions, 116 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts index b662a9c..3f22b34 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -8,14 +8,11 @@ import { default as UserGroup } from './db/model/UserGroup'; import { NextFunction, Request, Response, Router } from 'express'; import { RequestError } from './errors/errorware'; -import { View, files, views } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; -// TODO: figure this out -const BASE_FILE_STORAGE: string = 'TODO: figure this out'; - /** * The type of an Express middleware callback. */ @@ -65,6 +62,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 +106,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 +169,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 +262,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 +295,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 +334,7 @@ const postCurUser: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { logger.debug('Editing current user'); + res.locals.modified = true; try { await req.user.updateInfo(req.body); await req.user.save(); @@ -357,6 +365,7 @@ const postUsername: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { let user: User | null | undefined = res.locals.user; + res.locals.modified = true; if (user == null) { logger.debug('Adding new user'); user = new User({ @@ -387,6 +396,7 @@ const postUsername: Middleware = async( const getProjectRoles: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { + res.locals.modified = true; logger.debug('Listing available project roles'); const roles: ContributorGroup[] = await ContributorGroup.findAll(); res.locals.data = roles.filter( @@ -418,6 +428,7 @@ const getProjects: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { logger.debug('Listing all projects'); + res.locals.modified = true; const projects: Project[] = await Project.findAll({ include: [ User @@ -450,6 +461,7 @@ const getProjectName: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { 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,14 +488,18 @@ const postProjectName: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { let project: Project | null = res.locals.project; + res.locals.modified = true; let promise: PromiseLike<File> | null = null; if (project == null) { 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 @@ -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 { @@ -544,21 +561,57 @@ const getFileId: Middleware = getFile; /** * Post a File. / delete / move / etc */ -const postFilePath: Middleware = ( - req: Request, res: Response, next: NextFunction -): void => { - logger.debug('Receiving file'); +/* tslint:disable */ +const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise<void> => { + logger.debug(`Receiving file to ${res.locals.parentFolder}`); + 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}`) + + // Loop the part of the path that doesn't exist yet and create all the folders + while((remainingPath.match(/\//g) || []).length > 1){ + // If there are more subfolders that dont exist, then create them + const subFolder: string = remainingPath.split("/")[1] + logger.debug(`Adding subfolder \'${subFolder}`); + const dir: File = new File({ + uuid: uuid.generate(), + mimetype: 'inode/directory', + 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); + + // 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(); }; +/* tslint:enable */ export class FileRouter { public router: Router; @@ -600,7 +653,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); } @@ -658,52 +711,62 @@ export class FileRouter { // Fetch a file from its path: this.router.param( - 'file', + 'path', async( req: Request, res: Response, next: NextFunction, filename: string ): Promise<void> => { + // 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; + + // 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("next subdir not found in DB"); return next(); - } else { - 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; } - const parentFolder: File | null = await File.findOne({ - include: [ - { model: File, as: 'containedFiles' } - ], - where: { - parentFolder: file, - name: fileNames[0] - } - }); - 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(); } ); @@ -715,17 +778,19 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise<void> => { - logger.debug(`Searching for file ${fileId}`); + console.log(`parsing id ${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; + 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(); } @@ -111,19 +111,22 @@ 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) + 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 => { + if (Object.keys(res.locals).length === 0) { + res.status(404) .json({ status: 'error', error : 'invalid_route', error_description: 'Endpoints start from /cs3099group-be-4/' }); + } else { + next(); + } }); - this.express.use('/cs3099group-be-4', FileRouter); - this.express.use('/cs3099group-be-4', authRouter); - this.express.use('/', defRouter); - this.express.use('/XX*', errRouter); } /** @@ -142,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/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<File> { @AllowNull diff --git a/src/db/model/User.ts b/src/db/model/User.ts index 171e899..73d2356 100644 --- a/src/db/model/User.ts +++ b/src/db/model/User.ts @@ -128,16 +128,16 @@ export default class User extends Model<User> { public get fullInfo(): UserFullInfo { // 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 = []; } 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? diff --git a/src/files.ts b/src/files.ts index 8ad7236..a5fd08d 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,17 @@ interface RawSize { length: number; } -const readableStream: ( - filename: string, projectName: string, - { offset, length }?: Partial<RawSize> -) => fs.ReadStream = ( - filename: string, projectName: string, - { offset, length }: Partial<RawSize> = - { offset: undefined, length: undefined } -): fs.ReadStream => { +const readableStream: (filename: string, projectName: string, { offset, length }?: Partial<RawSize>) => fs.ReadStream + = (filename: string, projectName: string, { offset, length }: Partial<RawSize> = { 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); }; -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 +181,45 @@ class MimeTypeMap extends Map<string, string> { 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); + } +} + +export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise<boolean> = async(parentId: string, subFileId: string): Promise<boolean> => { + // 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; +} 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]); 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<LogItem[]> = (level?: LogLevel, params: FetchParams = {}): Promise<LogItem[]> => { + 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<LogItem[]>; } = { 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 62e4985..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); @@ -85,7 +96,7 @@ export const array = (template: TemplateValue, values?: Value[]) => { const m: Checker = types.function(template) ? template : match.bind(null, template); - return values.every(m); + return values.every(m); // }; // tslint:disable-next-line:typedef |
