From f2f471e9c081d94622de02a22ca2faeaf8f6647b Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 13 Apr 2018 16:45:31 +0100 Subject: Fix some tests by including users in projects --- src/FileRouter.ts | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index b750094..48ec9c7 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -639,6 +639,9 @@ export class FileRouter { projectName: string ): Promise => { res.locals.project = await Project.findOne({ + include: [ + User + ], where: { name: projectName } -- cgit v1.2.1 From de1be5ca1789dbd8e8a88ebe042cb767793ef333 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Fri, 13 Apr 2018 16:54:22 +0100 Subject: Fix some tests by adding properties in projects --- src/db/model/Project.ts | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts index d57eaaa..6cda34e 100644 --- a/src/db/model/Project.ts +++ b/src/db/model/Project.ts @@ -36,6 +36,10 @@ export default class Project extends Model { return this.rootFolderInternal; } + public get properties(): object { + return this; + } + public get metadata(): { public_metadata?: Metadata; private_metadata?: Metadata; -- 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 From fb54545484732f149223a63d06eff4c7d98b8410 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Tue, 17 Apr 2018 17:39:56 +0100 Subject: Fix tests for matcher, and minor import edits --- src/matcher/index.ts | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/matcher/index.ts b/src/matcher/index.ts index 99cc18c..0806907 100644 --- a/src/matcher/index.ts +++ b/src/matcher/index.ts @@ -10,6 +10,7 @@ export { export { Atom, + isPresent as anything, isNumber as number, isString as string, isBoolean as boolean, -- cgit v1.2.1 From 8f1837af9400ef0ef5c1cab1e853b46e11b1b76b Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 17 Apr 2018 18:43:06 +0100 Subject: Files - now actually works --- src/FileRouter.ts | 108 ++++++++++++++++++++++++++++++--------------------- src/db/model/File.ts | 14 ++++--- src/files.ts | 7 +++- 3 files changed, 78 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 4b56b19..ed6567c 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -495,18 +495,21 @@ const postProjectName: Middleware = async( const file: File = new File({ uuid: uuid.generate(), mimetype: 'inode/directory', - name: req.params.project_name, parentFolderId: rootPathId }); + file.name = ''; // Leave blank as discussed promise = file.save(); createProjectFolder(req.params.project_name); + project = new Project({ name: req.params.project_name, rootFolder: file }); + project.rootFolderId = file.uuid; } else { logger.debug('Updating project properties'); } + project.metadata = req.body; // tslint:disable-next-line:await-promise await promise; @@ -563,48 +566,57 @@ const getFileId: Middleware = getFile; */ /* tslint:disable */ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise => { - logger.debug(`Receiving file to ${res.locals.parentFolder}`); + logger.debug(`Receiving file ${res.locals.path}`); if (res.locals.file != null) { + // TODO update metadata or append to file 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}`) + 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}`); + logger.debug(`Adding subfolder \'${subFolder}\'`); const dir: File = new File({ uuid: uuid.generate(), mimetype: 'inode/directory', - name: subFolder, - parentFolderId: res.locals.deepestFolderId + nameInternal: subFolder//, + //parentFolderId: res.locals.deepestFolderId }); await dir.save(); // update parent directory of new directory - addSubFileToFolder(res.locals.deepestFolderId, dir.id); - + 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.id; - console.log(`\tremainingPath: ${remainingPath}`) - console.log(`\tdeepestFolderName: ${res.locals.deepestFolderName}`) - console.log(`\tdeepestFolderId: ${res.locals.deepestFolderId}`) + res.locals.deepestFolderId = dir.uuid; } + logger.debug(`now adding the actual file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) + const file: File = new File({ uuid: uuid.generate(), - name: res.locals.filename, - parentFolder: res.locals.deepestFolderId + nameInternal: res.locals.filename//, + //parentFolder: res.locals.deepestFolderId }); + file.mimetype = req.headers['content-type']!; + + await file.save(); + // update parent directory of new directory - addSubFileToFolder(res.locals.deepestFolderId, file.id); + if(!await addSubFileToFolder(res.locals.deepestFolderId, file.uuid)){ + logger.debug("adding file to folder failed!") + next(new RequestError(500, 'Adding file to folder failed')) + } // TODO respond to correct query params (like update metadata, move, etc) // pipe the data @@ -710,55 +722,60 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, filename: string ): Promise => { - // TODO \/ - // We need to find the res.locals.deepestFolderName (and Id) for the currently requested path + // 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 / - 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]; + 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')); } - console.debug(fileNames); - let curDir: File | null = project.rootFolder; - res.locals.deepestFolderId = curDir.id; + 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. + // Loop through the path and find the deepest folder that exists. + // Also find the file if possible. while (curDir && i < fileNames.length) { + logger.debug(`Searching for \'${fileNames[i]}\'`); const fileOrNull: File | null = await File.findOne({ include: [{all: true}], where: { - name: fileNames[i], - parentFolder: curDir + nameInternal: fileNames[i], + parentFolderId: curDir.uuid } }); if (fileOrNull == null) { - console.log("next subdir not found in DB"); + logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`); return next(); - } - - if(i < fileNames.length-1){ + } + + 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{ + logger.debug(`Found Sub-folder \'${fileOrNull.name}\'`); + res.locals.deepestFolderId = fileOrNull.uuid; + res.locals.deepestFolderName = fileOrNull.name; + } else { // Found actual file - console.log(`found file ${fileOrNull.name}`); + logger.debug(`Found file \'${fileOrNull.name}\'`); res.locals.file = fileOrNull; } curDir = fileOrNull; + i++; } next(); @@ -772,7 +789,7 @@ export class FileRouter { req: Request, res: Response, next: NextFunction, fileId: string ): Promise => { - console.log(`parsing id ${fileId}`); + logger.info(`parsing id ${fileId}`); const file: File | null = await File.findOne({ include: [{all: true}], where: { @@ -783,8 +800,11 @@ export class FileRouter { 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!") + if (file.parentFolder) { + res.locals.deepestFolderName = file.parentFolder.name; + } else { + logger.debug('parentfolder not set!') + } } next(); } diff --git a/src/db/model/File.ts b/src/db/model/File.ts index 193a785..8a12431 100644 --- a/src/db/model/File.ts +++ b/src/db/model/File.ts @@ -27,7 +27,7 @@ import { FileTypeName, mimes } from '../../files'; export default class File extends Model { @AllowNull @Column - private nameInternal!: string; + public nameInternal!: string; @AllowNull @Column @@ -85,10 +85,14 @@ export default class File extends Model { public set name(name: string) { this.nameInternal = name; - this.fullPathInternal = this.fullPathInternal.substring( - 0, - this.fullPathInternal.lastIndexOf('/') + 1 - ) + this.name; + if (this.fullPathInternal) { + this.fullPathInternal = this.fullPathInternal.substring( + 0, + this.fullPathInternal.lastIndexOf('/') + 1 + ) + this.name; + } else { + this.fullPathInternal = this.name; + } } public get fullPath(): string { diff --git a/src/files.ts b/src/files.ts index a5fd08d..9be0381 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,11 +1,13 @@ import { Request, Response } from 'express'; import * as fs from 'fs'; +import { logger } from './logger'; 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'; + /* tslint:disable */ const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; @@ -198,6 +200,7 @@ export const createProjectFolder: (name: string) => void = (projName: string): a } export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise = async(parentId: string, subFileId: string): Promise => { + 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}], @@ -216,10 +219,10 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis } // update both objects parent.containedFiles.push(file); - file.parentFolderId = parent.id; + file.parentFolderId = parent.uuid; // save - await parent.save(); await file.save(); + await parent.save(); return true; } -- cgit v1.2.1 From 505ae2d6af5ce31360f0f0b018a75cfee59cf3ac Mon Sep 17 00:00:00 2001 From: jw255 Date: Tue, 17 Apr 2018 22:58:03 +0100 Subject: using multer for files now --- src/FileRouter.ts | 28 ++++++++++++++++------------ src/files.ts | 20 +++++++++++++++++++- 2 files changed, 35 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index ed6567c..8dc8468 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -6,13 +6,13 @@ 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 } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, moveFile } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; + /** * The type of an Express middleware callback. */ @@ -567,6 +567,8 @@ const getFileId: Middleware = getFile; /* 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 if (res.locals.file != null) { // TODO update metadata or append to file @@ -605,10 +607,9 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu const file: File = new File({ uuid: uuid.generate(), - nameInternal: res.locals.filename//, - //parentFolder: res.locals.deepestFolderId + nameInternal: res.locals.filename }); - file.mimetype = req.headers['content-type']!; + file.mimetype = req.file.mimetype; await file.save(); @@ -618,9 +619,8 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu next(new RequestError(500, 'Adding file to folder failed')) } - // TODO respond to correct query params (like update metadata, move, etc) - // pipe the data - req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + // Move temp file to proper location + moveFile(req.file.originalname, res.locals.project.name, file.uuid); next(); }; /* tslint:enable */ @@ -665,7 +665,8 @@ export class FileRouter { this.router.get ('/projects/:project_name/properties', getProjectProperties); // File access this.router.get ('/projects/:project_name/files/:path', getFilePath); - this.router.post('/projects/:project_name/files/:path', postFilePath); + this.router.post('/projects/:project_name/files/:path', + upload.single('userfile'), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -730,6 +731,9 @@ export class FileRouter { // Vars arleady assigned: // - res.locals.project: requested project object + //console.log(`req.file.filename: ${req.file}`) + console.log(req.file) + // Replace + with / res.locals.path = filename.replace(/\+/g, '/'); logger.debug(`Searching for path \'${res.locals.path}\'`); @@ -748,7 +752,7 @@ export class FileRouter { 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. + // 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]}\'`); @@ -797,13 +801,13 @@ export class FileRouter { } }); res.locals.file = file; - if(file) { + if (file) { res.locals.filename = file.name; res.locals.deepestFolderId = file.parentFolderId; if (file.parentFolder) { res.locals.deepestFolderName = file.parentFolder.name; } else { - logger.debug('parentfolder not set!') + logger.debug('parentfolder not set!'); } } next(); diff --git a/src/files.ts b/src/files.ts index 9be0381..b0e63aa 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,6 +1,7 @@ import { Request, Response } from 'express'; -import * as fs from 'fs'; +import * as fs from 'fs-extra'; import { logger } from './logger'; +import * as Multer from 'multer'; import { default as File } from './db/model/File'; import { default as Project } from './db/model/Project'; @@ -38,6 +39,23 @@ const logPath: (type: string, projectName?: string) => string = ( : `${LOG_BASE_DIRECTORY}/general/${type}`; }; +let storage = Multer.diskStorage({ + destination: function (req, file, cb) { + cb(null, CONTENT_BASE_DIRECTORY) + }, + filename: function (req, file, cb) { + cb(null, `temp-${file.originalname}`) + } +}); + +export const upload: Multer.Instance = Multer({ storage: storage }); + +export const moveFile: (filename: string, projectname: string, fileId: string) => void = + (filename: string, projectname: string, fileId: string): void => { + + fs.moveSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`, `${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); +} + export const files: { path: (f: string, p: string) => string; writableStream: (f: string, p: string) => fs.WriteStream; -- cgit v1.2.1 From f37c8433ea3bca786898c46c03b86557fa0b6bb3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Wed, 18 Apr 2018 16:50:30 +0100 Subject: POST file parameters maybe working --- src/FileRouter.ts | 177 ++++++++++++++++++++++++++++++++++++++++++------------ src/files.ts | 26 +++++++- 2 files changed, 160 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 8dc8468..3796544 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -7,7 +7,7 @@ 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, moveFile } from './files'; +import { addSubFileToFolder, View, files, views, rootPathId, createProjectFolder, upload, deleteFile, truncateFile, saveFile } from './files'; import { logger } from './logger'; import { Property, default as serverConfig } from './serverConfig'; import { uuid } from './uuid'; @@ -546,7 +546,9 @@ const getFile: Middleware = async( } const project: Project = res.locals.project; const view: View = views[req.query.view || 'meta']; - res.locals.function = view.getResponseFunction(req, res); + // TODO return 400 for unsuported views + // TODO raw view accepts extra query params offset and length + res.locals.function = view.getResponseFunction(req, res); res.locals.data = view.getResponseData(file, project, req.query); next(); }; @@ -561,6 +563,42 @@ const getFilePath: Middleware = getFile; */ const getFileId: Middleware = getFile; +namespace qH { + export const hasAction: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action ? true : false); + } + export const setsMetadata: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'set_metadata' ? true : false); + } + export const mksDir: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'mkdir' ? true : false); + } + export const deletes: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'delete' ? true : false); + } + export const moves: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'move' ? true : false); + } + export const copys: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.action && req.query.action == 'copy' ? true : false); + } + export const overwrites: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.overwrite ? req.query.overwrite : false); + } + export const offset: ((req: Request) => number) = (req: Request): number => { + return (req.query.offset ? req.query.offset : 0); + } + export const truncates: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.truncate ? req.query.truncate : false); + } + export const isFinal: ((req: Request) => boolean) = (req: Request): boolean => { + return (req.query.final ? req.query.final : false); + } + export const nothingSet: ((req: Request) => boolean) = (req: Request): boolean => { + return (!hasAction(req) && !overwrites(req) && !truncates(req) && !isFinal(req)); + } +} + /** * Post a File. / delete / move / etc */ @@ -568,60 +606,119 @@ const getFileId: Middleware = getFile; 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 + // 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')); + } - if (res.locals.file != null) { - // TODO update metadata or append to file + // 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')); } - // 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({ + // Sets final if requested + if (res.locals.file && qH.isFinal(req)) { + res.locals.file.status = 'final'; + } + + // 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)){ + deleteFile(res.locals.file.uuid, res.locals.project.name); + await res.locals.file.delete(); + next(); + } + + // Moves File if requested + if(qH.moves(req)){ + // TODO + next(new RequestError(500, 'not_implemented')); + } + + // Copies File if requested + if(qH.copys(req)){ + // TODO + next(new RequestError(500, 'not_implemented')); + } + + // Overwrite data but not truncate + // eg. OOOONNNNNNOOOO (O = old data, N = new data) + if(qH.overwrites(req) && !qH.truncates(req)){ + // TODO + next(new RequestError(500, 'not_implemented', 'please specify truncate parameter')); + } + + // Create File or Folder if file doesn't exist + if (res.locals.file == null){ + // lets have a res.locals.deepestFolderName (and Id) which is a string of the deepest parent folder found + let remainingPath: string = (res.locals.deepestFolderName == '') ? '/' + res.locals.path + : res.locals.path.split(res.locals.deepestFolderName)[1]; + + // Loop the part of the path that doesn't exist yet and create all the folders + while((remainingPath.match(/\//g) || []).length > 1){ + // If there are more subfolders that dont exist, then create them + const subFolder: string = remainingPath.split("/")[1] + logger.debug(`Adding subfolder \'${subFolder}\'`); + const dir: File = new File({ + uuid: uuid.generate(), + mimetype: 'inode/directory', + nameInternal: subFolder + }); + await dir.save(); + + // update parent directory of new directory + if(!await addSubFileToFolder(res.locals.deepestFolderId, dir.uuid)){ + logger.debug("adding file to folder failed!") + next(new RequestError(500, 'Adding file to folder failed')) + } + // update vars + remainingPath = remainingPath.split(subFolder)[1] + res.locals.deepestFolderName = subFolder; + res.locals.deepestFolderId = dir.uuid; + } + + logger.debug(`Writing file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) + res.locals.file = new File({ uuid: uuid.generate(), - mimetype: 'inode/directory', - nameInternal: subFolder//, - //parentFolderId: res.locals.deepestFolderId + nameInternal: res.locals.filename }); - await dir.save(); + res.locals.file.mimetype = qH.mksDir(req) ? 'inode/directory' : req.file.mimetype; + + await res.locals.file.save(); // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, 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(`now adding the actual file \'${res.locals.filename}\' to folder \'${res.locals.deepestFolderName}\'`) - - const file: File = new File({ - uuid: uuid.generate(), - nameInternal: res.locals.filename - }); - file.mimetype = req.file.mimetype; - - await file.save(); - - // update parent directory of new directory - if(!await addSubFileToFolder(res.locals.deepestFolderId, file.uuid)){ - logger.debug("adding file to folder failed!") - next(new RequestError(500, 'Adding file to folder failed')) + // Move temp file to proper location (if not directory) + if(!qH.mksDir(req)){ + saveFile(req.file.originalname, res.locals.project.name, res.locals.file.uuid, qH.offset(req)); } - // Move temp file to proper location - moveFile(req.file.originalname, res.locals.project.name, file.uuid); + // Sets final if requested + if (qH.isFinal(req)) { + res.locals.file.status = 'final'; + } + next(); + }; /* tslint:enable */ diff --git a/src/files.ts b/src/files.ts index b0e63aa..92ed165 100644 --- a/src/files.ts +++ b/src/files.ts @@ -50,10 +50,30 @@ let storage = Multer.diskStorage({ export const upload: Multer.Instance = Multer({ storage: storage }); -export const moveFile: (filename: string, projectname: string, fileId: string) => void = - (filename: string, projectname: string, fileId: string): void => { +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 => { + // TODO only overwrite beginning of file and keep rest of data + // ensure file exists + fs.ensureFileSync(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); + // truncate to offset + 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); +} + +export const deleteFile: (fileId: string, projectName: string) => void = + (fileId: string, projectName: string): void => { - fs.moveSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`, `${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); + fs.removeSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`); +} + +export const truncateFile: (fileId: string, projectName: string, newLength: number) => void = + (fileId: string, projectName: string, newLength: number): void => { + // 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); } export const files: { -- cgit v1.2.1 From b9cb14f9368e281ab01d92cc8864cdcb4a0cb386 Mon Sep 17 00:00:00 2001 From: jw255 Date: Thu, 19 Apr 2018 11:08:40 +0100 Subject: minor fixes --- src/FileRouter.ts | 6 +++++- src/files.ts | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 3796544..70d3d51 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -563,6 +563,9 @@ const getFilePath: Middleware = getFile; */ const getFileId: Middleware = getFile; +/** + * Checks the parameters for file posting + */ namespace qH { export const hasAction: ((req: Request) => boolean) = (req: Request): boolean => { return (req.query.action ? true : false); @@ -638,8 +641,9 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu // 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.delete(); + await res.locals.file.destroy(); next(); } diff --git a/src/files.ts b/src/files.ts index 92ed165..1b8a652 100644 --- a/src/files.ts +++ b/src/files.ts @@ -60,7 +60,11 @@ export const saveFile: (filename: string, projectname: string, fileId: string, o // 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); + rStream.pipe(wStream).on('finish', () => { + fs.removeSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + }).on('error', (err: any) => { + logger.debug(`Error while saving file to proper location: ${err}`); + }); } export const deleteFile: (fileId: string, projectName: string) => void = -- cgit v1.2.1 From 8af06a4e7ea7ebaa29559a345d28791079b77dd3 Mon Sep 17 00:00:00 2001 From: jw255 Date: Thu, 19 Apr 2018 14:21:38 +0100 Subject: no reset --- src/FileRouter.ts | 5 +---- src/files.ts | 2 +- src/index.ts | 25 +++++++++++++++---------- 3 files changed, 17 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 70d3d51..0798ce8 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -548,7 +548,7 @@ const getFile: Middleware = async( const view: View = views[req.query.view || 'meta']; // TODO return 400 for unsuported views // TODO raw view accepts extra query params offset and length - res.locals.function = view.getResponseFunction(req, res); + res.locals.function = view.getResponseFunction(req, res); res.locals.data = view.getResponseData(file, project, req.query); next(); }; @@ -832,9 +832,6 @@ export class FileRouter { // Vars arleady assigned: // - res.locals.project: requested project object - //console.log(`req.file.filename: ${req.file}`) - console.log(req.file) - // Replace + with / res.locals.path = filename.replace(/\+/g, '/'); logger.debug(`Searching for path \'${res.locals.path}\'`); diff --git a/src/files.ts b/src/files.ts index 1b8a652..5b15a10 100644 --- a/src/files.ts +++ b/src/files.ts @@ -169,7 +169,7 @@ export const views: { getResponseData: async( file: File, project: Project, query: Query ): Promise => { - return readableStream(file.name, project.name, query); + return readableStream(file.uuid, project.name, query); }, getResponseFunction: (req: Request, res: Response): Function | null => { return res.send; diff --git a/src/index.ts b/src/index.ts index 5960374..1ce284d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,16 +22,7 @@ const port: number = process.env.PORT : DEFAULT_PORT; logger.info(`Port ${port} chosen`); -// tslint:disable:no-floating-promises -(async(): Promise => { - try { - logger.info('Authenticating with database'); - await seq.authenticate(); - } catch (err) { - logger.error(`Cannot authenticate with database: ${err}`); - process.exit(1); - } - +async function reset(): Promise { try { logger.info('Resetting Database'); await seq.sync({ @@ -91,6 +82,20 @@ logger.info(`Port ${port} chosen`); } }); +} + +// tslint:disable:no-floating-promises +(async(): Promise => { + try { + logger.info('Authenticating with database'); + await seq.authenticate(); + } catch (err) { + logger.error(`Cannot authenticate with database: ${err}`); + process.exit(1); + } + + //await reset(); + logger.info('Booting ExpressJS server'); app.listen(port, (err: Error) => { if (err) { -- cgit v1.2.1 From 2c7cebcd140cc5413118d8246aa9f51b756c512d Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 19 Apr 2018 15:24:55 +0100 Subject: Change minimum recording level for logs --- src/logger.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/logger.ts b/src/logger.ts index 9025814..74ae1f7 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -138,7 +138,7 @@ const consoleTransport: winston.TransportInstance = const basicFileTransport: winston.TransportInstance = new winston.transports.File({ name: 'basicFileTransport', - level: 'info', + level: 'debug', label: 'Basic File Transport', silent: false, colorize: false, @@ -193,7 +193,7 @@ const criticalFileTransport: winston.TransportInstance = const queryFileTransport: winston.TransportInstance = new winston.transports.File({ name: 'queryFileTransport', - level: 'info', + level: 'debug', label: 'Query Logs', silent: false, colorize: false, @@ -271,7 +271,7 @@ interface LogItem { timestamp: string; } -/* tslint:disable */ +/* tslint:disable */ const fetchLogs2: (level?: LogLevel, params?: FetchParams) => Promise = (level?: LogLevel, params: FetchParams = {}): Promise => { const options: winston.QueryOptions = { from: params.after, -- cgit v1.2.1 From ec1162de99e1744b52fcce0c5341649a7e9a2955 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Thu, 19 Apr 2018 16:19:46 +0100 Subject: Add CORS support --- src/app.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index 4dfeeda..09b9e6a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,6 +43,7 @@ class App { logger.debug('Constructing router'); this.logEnabled = enableLog; this.express = ex(); + this.cors(); this.express.use( (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { logger.info(`Connection from ${req.ip} requesting ${req.url}`); @@ -68,6 +69,22 @@ 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' + ); + next(); + }); + } + /** * Configures regular Express middleware. */ @@ -114,8 +131,8 @@ class App { 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 => { + this.express.use( + (req: ex.Request, res: ex.Response, next: ex.NextFunction): void => { if (Object.keys(res.locals).length === 0) { res.status(404) .json({ -- cgit v1.2.1