diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/FileRouter.ts | 33 | ||||
| -rw-r--r-- | src/app.ts | 37 | ||||
| -rw-r--r-- | src/db/model/File.ts | 54 | ||||
| -rw-r--r-- | src/files.ts | 172 | ||||
| -rw-r--r-- | src/logger.ts | 167 |
5 files changed, 407 insertions, 56 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4d6eb16..ee10662 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 { files } from './files'; +import { View, files, views } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -268,7 +268,7 @@ const getUserProperties: Middleware = */ const getUsername: Middleware = (req: Request, res: Response, next: NextFunction): void => { - if (res.locals.user === null) { + if (res.locals.user == null) { next(new RequestError(404, 'user_not_found')); return; } @@ -473,36 +473,29 @@ const getProjectProperties: Middleware = /** * GET a File. */ -const getFilePath: Middleware = async( +const getFile: Middleware = async( req: Request, res: Response, next: NextFunction ): Promise<void> => { const file: File | null = res.locals.file; - const project: Project | null = res.locals.project; if (file == null) { return next(new RequestError(404, 'file_not_found')); - } else if (project == null) { - return next(new RequestError(404, 'project_not_found')); } - res.locals.function = res.sendFile; - res.locals.data = - `${BASE_FILE_STORAGE}/${res.locals.project.name}/${file.uuid}`; + const project: Project = res.locals.project; + const view: View = views[req.query.view || 'meta']; + res.locals.function = view.getResponseFunction(req, res); + res.locals.data = view.getResponseData(file, project, req.query); next(); }; /** * GET a File. */ -const getFileId: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - const file: File | null = res.locals.file; - if (file === null) { - next(new RequestError(404, 'file_not_found')); - return; - } - res.locals.function = res.sendFile; - res.locals.data = files.path(req.params.id, res.locals.project.name); - next(); -}; +const getFilePath: Middleware = getFile; + +/** + * GET a File. + */ +const getFileId: Middleware = getFile; /** * Post a File. / delete / move / etc @@ -1,7 +1,6 @@ import * as bodyParser from 'body-parser'; import * as ex from 'express'; import * as expressJwt from 'express-jwt'; -import * as logger from 'morgan'; import * as passport from 'passport'; import { default as authRouter, unauthorisedErr } from './auth'; @@ -24,7 +23,7 @@ import { default as UserGroup } from './db/model/UserGroup'; */ class App { /** - * The Express app used throught the server. + * The Express app used throughout the server. */ public express: ex.Express; @@ -42,16 +41,23 @@ class App { public constructor(enableLog: boolean) { this.logEnabled = enableLog; this.express = ex(); + this.express.use(( + req: ex.Request, res: ex.Response, next: ex.NextFunction + ): void => { console.log(req.url); next(); }); this.precondition(); this.middleware(); this.mountRoutes(); this.express.use( async(req: ex.Request, res: ex.Response, next: ex.NextFunction): Promise<void> => { - res.json({ - status: 'success', - data: await res.locals.data - }); + if (res.locals.function) { + res.locals.function.bind(res)(res.locals.data); + } else { + res.json({ + status: 'success', + data: await res.locals.data + }); + } } ); this.errorware(); @@ -83,9 +89,6 @@ class App { } next(); }); - if (this.logEnabled) { - this.express.use(logger('combined')); - } this.express.use(bodyParser.json()); this.express.use(bodyParser.urlencoded({ extended: false })); } @@ -143,7 +146,7 @@ class App { username: name } }); - if (user === null) { + if (user == null) { return next(new RequestError(404, 'user_not_found')); } else { res.locals.user = user; @@ -177,9 +180,8 @@ class App { ): Promise<void> => { const fileNames: string[] = req.params.path.split('/'); const project: Project | null = res.locals.project; - if (project === null) { - next(new RequestError(404, 'project_not_found')); - return; + if (project == null) { + return next(new RequestError(404, 'project_not_found')); } let file: File = project.rootFolder; // TODO Rewrite using sub-queries instead of repeated queries. @@ -190,7 +192,7 @@ class App { parentFolder: file } }); - if (fileOrNull === null) { + if (fileOrNull == null) { return next(); } else { file = fileOrNull; @@ -206,7 +208,7 @@ class App { name: fileNames[0] } }); - if (parentFolder === null) { + if (parentFolder == null) { return next(); } res.locals.parentFolder = parentFolder; @@ -231,9 +233,8 @@ class App { uuid: fileId } }); - if (file === null) { - next(new RequestError(404, 'file_not_found')); - return; + if (file == null) { + return next(new RequestError(404, 'file_not_found')); } else { res.locals.file = file; } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 33043f0..4026b85 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -3,18 +3,27 @@ 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'; + @Table export default class File extends Model<File> { @AllowNull @Column - public name!: string; + private nameInternal!: string; + + @AllowNull + @Column + private fullPathInternal!: string; @PrimaryKey @Column public uuid!: string; + @Column(DataType.TEXT) + public type!: FileTypeName; + @Column - public mimetype!: string; + public size!: number; @ForeignKey(() => File) @AllowNull @@ -46,6 +55,35 @@ export default class File extends Model<File> { @Column(DataType.DATE) public modifyDate!: Date; + @Column + public status!: string; + + @Column + private metadataInternal!: string; + + public get name(): string { + return this.nameInternal; + } + + public set name(name: string) { + this.nameInternal = name; + this.fullPathInternal = this.fullPathInternal.substring( + 0, + this.fullPathInternal.lastIndexOf('/') + 1 + ) + this.name; + } + + public get fullPath(): string { + return this.fullPathInternal; + } + + public set fullPath(path: string) { + this.fullPathInternal = path; + this.nameInternal = this.fullPath.substring( + this.fullPathInternal.lastIndexOf('/') + 1 + ); + } + public get containedFiles(): File[] { if (this.containedFilesInternal === undefined) { throw new Error('containedFiles is undefined'); @@ -56,4 +94,16 @@ export default class File extends Model<File> { public set containedFiles(files: File[]) { this.containedFilesInternal = files; } + + public get metadata(): object { + return JSON.parse(this.metadataInternal); + } + + public set metadata(metadata: object) { + this.metadataInternal = JSON.stringify(metadata); + } + + public set mimetype(mime: string) { + this.type = mimes.get(mime) || 'generic'; + } } diff --git a/src/files.ts b/src/files.ts index 644d24e..8ad7236 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,5 +1,9 @@ +import { Request, Response } from 'express'; import * as fs from 'fs'; +import { default as File } from './db/model/File'; +import { default as Project } from './db/model/Project'; + const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; @@ -8,12 +12,38 @@ const path: (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)); }; +interface RawSize { + offset: number; + 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 options: object = { + 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 @@ -32,3 +62,139 @@ export const files: { writableStream, logPath }; + +export type ViewName = 'raw' | 'meta'; + +interface Query extends Partial<RawSize> { + children?: boolean; +} + +export interface View { + getContents: (file: File) => object; + getResponseData: (file: File, project: Project, query: Query) => + Promise<object>; + getResponseFunction: (req: Request, res: Response) => Function | null; +} + +interface MetaResponseData { + file_path: string; + file_name: string; + id: string; + type: FileTypeName; + metadata: object; + status: string; + supported_views: { + [key: string]: object | undefined; + }; + children?: MetaResponseData[]; +} + +const metaGetResponseData: ( + file: File, project: Project, query: Query +) => Promise<MetaResponseData> = async( + file: File, project: Project, query: Query +): Promise<MetaResponseData> => { + const data: MetaResponseData = { + file_path: file.fullPath, + file_name: file.name, + id: file.id, + type: file.type, + metadata: file.metadata, + status: file.status, + supported_views: {} + }; + for (const view of fileTypes[file.type].supportedViews) { + data.supported_views[view] = + views[view].getContents(file); + } + if (query.children) { + data.children = []; + const children: File[] | null = await File.findAll({ + where: { + parentFolder: file + } + }); + if (children != null) { + for (const child of children) { + data.children.push(await metaGetResponseData( + file, + project, + { + ...query, + children: undefined + } + )); + } + } + } + return data; +}; + +export const views: { + [view: string]: View; +} = { + raw: { + getContents: (file: File): object => { + return { + size: file.size + }; + }, + getResponseData: async( + file: File, project: Project, query: Query + ): Promise<object> => { + return readableStream(file.name, project.name, query); + }, + getResponseFunction: (req: Request, res: Response): Function | null => { + return res.send; + } + }, + meta: { + getContents: (file: File): object => { + return {}; + }, + getResponseData: metaGetResponseData, + getResponseFunction: (req: Request, res: Response): Function | null => { + return null; + } + } +}; + +export type FileTypeName = 'generic' | 'directory'; + +export interface FileType { + supportedViews: ViewName[]; +} + +const fileTypes: { + [type: string]: FileType; +} = { + generic: { + supportedViews: [ + 'raw', 'meta' + ] + }, + directory: { + supportedViews: [ + 'meta' + ] + } +}; + +class MimeTypeMap extends Map<string, string> { + public constructor(pairs: [string, FileTypeName][]) { + super(pairs); + } + + public get(mime: string): FileTypeName { + const ret: string | undefined = super.get(mime); + if (ret) { + return ret as FileTypeName; + } else { + return 'generic'; + } + } +} + +export const mimes: MimeTypeMap = new MimeTypeMap([ + [ 'inode/directory', 'directory' ] +]); diff --git a/src/logger.ts b/src/logger.ts index bbb0a73..069cdf5 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -5,26 +5,105 @@ import * as winston from 'winston'; import { files } from './files'; -type LogLevel = 'critical' | 'error' | 'warning' | 'security' | 'info'; +type Colour = (s: string) => string; + +type LogLevel = + | '7' + | 'debug' + | 'minor' + | 'silly' + | 'testing' + | 'verbose' + | '6' + | 'information' + | 'inform' + | 'info' + | '5' + | 'note' + | 'notice' + | 'notify' + | 'success' + | 'security' + | '4' + | 'warn' + | 'warning' + | '3' + | 'err' + | 'failure' + | 'fail' + | 'error' + | '2' + | 'crit' + | 'severe' + | 'critical' + | '1' + | 'alert' + | 'breach' + | '0' + | 'fatal' + | 'emerg' + | 'emergency' + | 'shutdown'; const LOG_LEVELS: winston.LoggerOptions = { - info: 4, - security: 3, - warning: 2, - error: 1, - critical: 0 + 7: 7, + debug: 7, + minor: 7, + silly: 7, + testing: 7, + verbose: 7, + 6: 6, + information: 6, + inform: 6, + info: 6, + 5: 5, + note: 5, + notice: 5, + notify: 5, + success: 5, + security: 5, + 4: 4, + warn: 4, + warning: 4, + 3: 3, + err: 3, + failure: 3, + fail: 3, + error: 3, + 2: 2, + crit: 2, + severe: 2, + critical: 2, + 1: 1, + alert: 1, + breach: 1, + 0: 0, + fatal: 0, + emerg: 0, + emergency: 0, + shutdown: 0 }; -const LOG_LEVEL_COLOURS: { - [key: string]: (s: string) => string; +const LEVEL_COLOURS: { + [key: number]: Colour; } = { - info: colors.cyan, - security: colors.blue, - warning: colors.yellow, - error: colors.red, - critical: colors.red + 7: colors.cyan, + 6: colors.blue, + 5: colors.green, + 4: colors.yellow, + 3: colors.red, + 2: colors.magenta, + 1: colors.black, + 0: colors.white }; +const LOG_LEVEL_COLOURS: { + [key: string]: Colour; +} = {}; +Object.keys(LOG_LEVELS).forEach((k: string): void => { + LOG_LEVEL_COLOURS[k] = LEVEL_COLOURS[LOG_LEVELS[k]]; +}); + interface LoggingMetadata { component?: string; user?: string; @@ -217,20 +296,82 @@ const fetchLogs: (level: LogLevel, params?: FetchParams) => LogItem[] = ( }; export const logger: { + 7: LogFunction; + debug: LogFunction; + minor: LogFunction; + silly: LogFunction; + testing: LogFunction; + verbose: LogFunction; + 6: LogFunction; + information: LogFunction; + inform: LogFunction; info: LogFunction; + 5: LogFunction; + note: LogFunction; + notice: LogFunction; + notify: LogFunction; + success: LogFunction; security: LogFunction; + 4: LogFunction; + warn: LogFunction; warning: LogFunction; + 3: LogFunction; + err: LogFunction; + failure: LogFunction; + fail: LogFunction; error: LogFunction; + 2: LogFunction; + crit: LogFunction; + severe: LogFunction; critical: LogFunction; + 1: LogFunction; + alert: LogFunction; + breach: LogFunction; + 0: LogFunction; + fatal: LogFunction; + emerg: LogFunction; + emergency: LogFunction; + shutdown: LogFunction; isEnabled: () => boolean; forward: (level: LogLevel, message: string, meta: LoggingMetadata) => void; fetch: (level: LogLevel, params?: FetchParams) => LogItem[]; } = { + 7: makeLogFunction('7'), + debug: makeLogFunction('debug'), + minor: makeLogFunction('minor'), + silly: makeLogFunction('silly'), + testing: makeLogFunction('testing'), + verbose: makeLogFunction('verbose'), + 6: makeLogFunction('6'), + information: makeLogFunction('information'), + inform: makeLogFunction('inform'), info: makeLogFunction('info'), + 5: makeLogFunction('5'), + note: makeLogFunction('note'), + notice: makeLogFunction('notice'), + notify: makeLogFunction('notify'), + success: makeLogFunction('success'), security: makeLogFunction('security'), + 4: makeLogFunction('4'), + warn: makeLogFunction('warn'), warning: makeLogFunction('warning'), + 3: makeLogFunction('3'), + err: makeLogFunction('err'), + failure: makeLogFunction('failure'), + fail: makeLogFunction('fail'), error: makeLogFunction('error'), + 2: makeLogFunction('2'), + crit: makeLogFunction('crit'), + severe: makeLogFunction('severe'), critical: makeLogFunction('critical'), + 1: makeLogFunction('1'), + alert: makeLogFunction('alert'), + breach: makeLogFunction('breach'), + 0: makeLogFunction('0'), + fatal: makeLogFunction('fatal'), + emerg: makeLogFunction('emerg'), + emergency: makeLogFunction('emergency'), + shutdown: makeLogFunction('shutdown'), isEnabled: (): boolean => !basicFileTransport.silent, forward: basicLogger.log, fetch: fetchLogs |
