From 09155e88a34c211dd9429a70fde432c062af77e0 Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 21 Apr 2018 03:06:02 +0100 Subject: Fix many small file-handling problems --- src/files.ts | 118 +++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 70 insertions(+), 48 deletions(-) (limited to 'src/files.ts') diff --git a/src/files.ts b/src/files.ts index e87d8da..53360a4 100644 --- a/src/files.ts +++ b/src/files.ts @@ -8,12 +8,20 @@ import { default as Project } from './db/model/Project'; const CONTENT_BASE_DIRECTORY: string = './files'; const LOG_BASE_DIRECTORY: string = './logs'; +const TEMP_BASE_DIRECTORY: string = './files-temp'; -/* tslint:disable */ -const path: (filename: string, projectName: string) => string = (filename: string, projectName: string): string => { - return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; +export interface Metadata { + version: number; + namespaces: object; + [index: string]: any; +} + +export const INITIAL_METADATA: Metadata = { + version: 1, + namespaces: {} }; +/* tslint:disable */ const writableStream: (filename: string, projectName: string) => fs.WriteStream = (filename: string, projectName: string): fs.WriteStream => { return fs.createWriteStream(path(filename, projectName)); }; @@ -23,7 +31,7 @@ interface RawSize { length: number; } -const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream +const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream = (filename: string, projectName: string, { offset, length }: Partial = { offset: undefined, length: undefined }): fs.ReadStream => { const options: object = { start: offset? offset: 0, @@ -50,42 +58,51 @@ export const logPath: (type: string, projectName?: string) => string = ( let storage = Multer.diskStorage({ destination: function (req, file, cb) { cb(null, CONTENT_BASE_DIRECTORY) - }, - filename: function (req, file, cb) { + }, + filename: function (req, file, cb) { cb(null, `temp-${file.originalname}`) - } + } }); +export const path: (file: string, project: string, view?: ViewName) => string = + (file: string, project: string, view: ViewName = 'raw'): string => + `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`; + +export const tempPath: (file: string, project: string) => string = ( + file: string +): string => + `${TEMP_BASE_DIRECTORY}/${file}` + export const upload: Multer.Instance = Multer({ storage: storage }); -export const saveFile: (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean) => void = - (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean): void => { +export const saveFile: (filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean) => Promise = + async(filename: string, projectname: string, fileId: string, offset: number, truncate?: boolean): Promise => { // TODO only overwrite beginning of file and keep rest of data // ensure file exists - fs.ensureFileSync(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`); + await fs.ensureFile(path(fileId, projectname)); // truncate to offset - truncateFile(fileId, projectname, offset); + await truncateFile(fileId, projectname, offset); // open streams to append to file let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); - let wStream = fs.createWriteStream(`${CONTENT_BASE_DIRECTORY}/${projectname}/${fileId}`, {'flags':'a'}); - rStream.pipe(wStream).on('finish', () => { - fs.removeSync(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + let wStream = fs.createWriteStream(path(fileId, projectname), {'flags':'a'}); + rStream.pipe(wStream).on('finish', async() => { + await fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); }).on('error', (err: any) => { - logger.debug(`Error while saving file to proper location: ${err}`); + logger.error(`Error while saving file to proper location: ${err}`); }); } -export const deleteFile: (fileId: string, projectName: string) => void = - (fileId: string, projectName: string): void => { - - fs.removeSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`); +export const deleteFile: (fileId: string, projectName: string) => void = async( + fileId: string, projectName: string +): Promise => { + await fs.remove(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`); } -export const truncateFile: (fileId: string, projectName: string, newLength: number) => void = - (fileId: string, projectName: string, newLength: number): void => { +export const truncateFile: (fileId: string, projectName: string, newLength: number) => Promise = + async(fileId: string, projectName: string, newLength: number): Promise => { // get the file descriptor of the file to be truncated - const fd: number = fs.openSync(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`, 'r+'); - fs.ftruncateSync(fd, newLength); + const fd: number = await fs.open(path(fileId, projectName), 'r+'); + await fs.ftruncate(fd, newLength); } export const files: { @@ -101,11 +118,11 @@ export const files: { export type ViewName = 'raw' | 'meta'; interface Query extends Partial { - children?: boolean; + include_children?: boolean; } export interface View { - getContents: (file: File) => object; + getContents: (file: File, project: Project) => object | Promise; getResponseData: (file: File, project: Project, query: Query) => Promise; getResponseFunction: (req: Request, res: Response) => Function | null; @@ -132,7 +149,7 @@ const metaGetResponseData: ( const data: MetaResponseData = { file_path: file.fullPath, file_name: file.name, - id: file.id, + id: file.uuid, type: file.type, metadata: file.metadata, status: file.status, @@ -140,23 +157,23 @@ const metaGetResponseData: ( }; for (const view of fileTypes[file.type].supportedViews) { data.supported_views[view] = - views[view].getContents(file); + await views[view].getContents(file, project); } - if (query.children) { + if (query.include_children) { data.children = []; const children: File[] | null = await File.findAll({ where: { - parentFolder: file + parentFolderId: file.uuid } }); if (children != null) { for (const child of children) { data.children.push(await metaGetResponseData( - file, + child, project, { ...query, - children: undefined + include_children: undefined } )); } @@ -165,13 +182,20 @@ const metaGetResponseData: ( return data; }; +export const getSize: (file: File, project: Project) => Promise = async( + file: File, project: Project +): Promise => { + const stat: fs.Stats = await fs.stat(path(file.uuid, project.name)); + return stat.size; +}; + export const views: { [view: string]: View; } = { raw: { - getContents: (file: File): object => { + getContents: async(file: File, project: Project): Promise => { return { - size: file.size + size: await getSize(file, project) }; }, getResponseData: async( @@ -180,7 +204,7 @@ export const views: { return readableStream(file.uuid, project.name, query); }, getResponseFunction: (req: Request, res: Response): Function | null => { - return res.send; + return (stream: fs.ReadStream) => stream.pipe(res); } }, meta: { @@ -237,29 +261,30 @@ export const mimes: MimeTypeMap = new MimeTypeMap([ export const rootPathId: string = '0'; export const rootPathFile: File | null = null; -export const createRootFolder: () => void = (): any => { - if (!fs.existsSync(CONTENT_BASE_DIRECTORY)){ - fs.mkdirSync(CONTENT_BASE_DIRECTORY); +export const createRootFolder: () => Promise = async( +): Promise => { + if (!(await fs.exists(CONTENT_BASE_DIRECTORY))){ + await fs.mkdir(CONTENT_BASE_DIRECTORY); } } -export const createProjectFolder: (name: string) => void = (projName: string): any => { - if (!fs.existsSync(CONTENT_BASE_DIRECTORY + '/' + projName)){ - fs.mkdirSync(CONTENT_BASE_DIRECTORY + '/' + projName); +export const createProjectFolder: (name: string) => Promise = async( + projName: string +): Promise => { + if (!(await fs.exists(CONTENT_BASE_DIRECTORY + '/' + projName))){ + await fs.mkdir(CONTENT_BASE_DIRECTORY + '/' + projName); } } export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise = async(parentId: string, subFileId: string): Promise => { - logger.debug(`adding file ${subFileId}) to directory ${parentId}`) + logger.debug(`adding file ${subFileId} to directory ${parentId}`) // Fetch parent and subFile object from database const parent: File | null = await File.findOne({ - include: [{all: true}], where: { uuid: parentId } }); const file: File | null = await File.findOne({ - include: [{all: true}], where: { uuid: subFileId } @@ -268,11 +293,8 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis return false; } // update both objects - parent.containedFiles.push(file); - file.parentFolderId = parent.uuid; - // save - await file.save(); - await parent.save(); + // parent.containedFiles.push(file); + parent.$add('containedFilesInternal', file); return true; } -- cgit v1.2.1 From b81e9555f07adfa5b9fb749a539c49810acdc67a Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Sat, 21 Apr 2018 23:01:54 +0100 Subject: Add support for tabular files --- src/files.ts | 82 +++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 62 insertions(+), 20 deletions(-) (limited to 'src/files.ts') diff --git a/src/files.ts b/src/files.ts index 53360a4..af01798 100644 --- a/src/files.ts +++ b/src/files.ts @@ -3,6 +3,8 @@ import * as fs from 'fs-extra'; import { logger } from './logger'; import * as Multer from 'multer'; +import * as parse from 'csv-parse'; +import * as stringify from 'csv-stringify'; import { default as File } from './db/model/File'; import { default as Project } from './db/model/Project'; @@ -21,8 +23,11 @@ export const INITIAL_METADATA: Metadata = { namespaces: {} }; -/* tslint:disable */ -const writableStream: (filename: string, projectName: string) => fs.WriteStream = (filename: string, projectName: string): fs.WriteStream => { +const writableStream: ( + filename: string, projectName: string +) => fs.WriteStream = ( + filename: string, projectName: string +): fs.WriteStream => { return fs.createWriteStream(path(filename, projectName)); }; @@ -31,29 +36,36 @@ interface RawSize { length: number; } -const readableStream: (filename: string, projectName: string, { offset, length }?: Partial) => fs.ReadStream - = (filename: string, projectName: string, { offset, length }: Partial = { offset: undefined, length: undefined }): fs.ReadStream => { +interface TabularParameters { + rowstart: number; + rowcount: number; + cols: string[]; +} + +interface Query extends Partial, Partial { + children?: boolean; +} + +const readableStream: ( + filename: string, projectName: string, { offset, length }?: Query +) => fs.ReadStream = ( + filename: string, projectName: string, { offset, length }: Query = + { offset: undefined, length: undefined } +): fs.ReadStream => { const options: object = { - start: offset? offset: 0, - end: offset && length? offset + length: undefined + start: offset ? offset : 0, + end: offset && length ? offset + length : undefined }; return fs.createReadStream(path(filename, projectName), options); }; -export function logPath (type: string, projectName?: string){ - return projectName - ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` - : `${LOG_BASE_DIRECTORY}/general/${type}`; -} - -/* export const logPath: (type: string, projectName?: string) => string = ( - type: string, projectName?: string): string => { + type: string, projectName?: string +): string => { return projectName ? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}` : `${LOG_BASE_DIRECTORY}/general/${type}`; }; -*/ let storage = Multer.diskStorage({ destination: function (req, file, cb) { @@ -115,7 +127,7 @@ export const files: { logPath }; -export type ViewName = 'raw' | 'meta'; +export type ViewName = 'raw' | 'meta' | 'tabular'; interface Query extends Partial { include_children?: boolean; @@ -215,10 +227,34 @@ export const views: { getResponseFunction: (req: Request, res: Response): Function | null => { return null; } + }, + tabular: { + getContents: (file: File): object => { + return { + // columns: + // rows: + }; + }, + getResponseData: async( + file: File, project: Project, query: Query + ): Promise => { + return readableStream(file.name, project.name, query) + .pipe(parse({ + columns: true, + from: query.rowstart, + to: (query.rowstart && query.rowcount) + ? query.rowstart + query.rowcount + : undefined + })).pipe(stringify({ + })); + }, + getResponseFunction: (req: Request, res: Response): Function | null => { + return (stream: fs.ReadStream) => stream.pipe(res); + } } }; -export type FileTypeName = 'generic' | 'directory'; +export type FileTypeName = 'generic' | 'directory' | 'tabular'; export interface FileType { supportedViews: ViewName[]; @@ -236,6 +272,11 @@ const fileTypes: { supportedViews: [ 'meta' ] + }, + tabular: { + supportedViews: [ + 'raw', 'meta', 'tabular' + ] } }; @@ -255,7 +296,8 @@ class MimeTypeMap extends Map { } export const mimes: MimeTypeMap = new MimeTypeMap([ - [ 'inode/directory', 'directory' ] + [ 'inode/directory', 'directory' ], + [ 'text/csv', 'tabular' ] ]); export const rootPathId: string = '0'; @@ -280,11 +322,13 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis logger.debug(`adding file ${subFileId} to directory ${parentId}`) // Fetch parent and subFile object from database const parent: File | null = await File.findOne({ + include: [{all: true}], where: { uuid: parentId } }); const file: File | null = await File.findOne({ + include: [{all: true}], where: { uuid: subFileId } @@ -292,8 +336,6 @@ export const addSubFileToFolder: (parentId: string, subFileId: string) => Promis if(!parent || !file){ return false; } - // update both objects - // parent.containedFiles.push(file); parent.$add('containedFilesInternal', file); return true; -- cgit v1.2.1 From 7bfdc2cc7c5aa1aaed655c7ddd3a7c3cf38430e5 Mon Sep 17 00:00:00 2001 From: jw255 Date: Sat, 21 Apr 2018 23:01:58 +0100 Subject: implimented moving and copying of files --- src/files.ts | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'src/files.ts') diff --git a/src/files.ts b/src/files.ts index 53360a4..d80f09f 100644 --- a/src/files.ts +++ b/src/files.ts @@ -68,6 +68,10 @@ export const path: (file: string, project: string, view?: ViewName) => string = (file: string, project: string, view: ViewName = 'raw'): string => `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`; +export const pathNoView: (file: string, project: string) => string = + (file: string, project: string): string => + `${CONTENT_BASE_DIRECTORY}/${project}/${file}`; + export const tempPath: (file: string, project: string) => string = ( file: string ): string => @@ -86,7 +90,7 @@ export const saveFile: (filename: string, projectname: string, fileId: string, o let rStream = fs.createReadStream(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); let wStream = fs.createWriteStream(path(fileId, projectname), {'flags':'a'}); rStream.pipe(wStream).on('finish', async() => { - await fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); + fs.remove(`${CONTENT_BASE_DIRECTORY}/temp-${filename}`); }).on('error', (err: any) => { logger.error(`Error while saving file to proper location: ${err}`); }); @@ -105,6 +109,38 @@ export const truncateFile: (fileId: string, projectName: string, newLength: numb await fs.ftruncate(fd, newLength); } +export const copyFile: (projName: string, fromId: string, toId: string, move?: boolean) + => Promise = async(projName: string, fromId: string, toId: string, move?: boolean): Promise => { + // ensure to path exists + fs.ensureDirSync(pathNoView(toId, projName)); + const fromDir: string = pathNoView(fromId, projName); + const toDir: string = pathNoView(toId, projName); + // loop all views in file + fs.readdir(fromDir, (err: any, files: string[]) => { + if(err){ + logger.error(`Error while copying file: ${err}`); + } else { + files.forEach((file: string, index: number) => { + const fromPathFull = fromDir + "/" + file; + const toPathFull = toDir + "/" + file; + fs.ensureFileSync(toPathFull); + // open streams to transfer data + let rStream = fs.createReadStream(fromPathFull); + let wStream = fs.createWriteStream(toPathFull); + rStream.pipe(wStream).on('finish', async() => { + if(!!move){ + await fs.remove(fromPathFull); + } + console.log(`copy success of file from \'${fromPathFull}\' to \'${toPathFull}\'`) + }).on('error', (err: any) => { + logger.error(`Error while copying file: ${err}`); + }); + }) + } + }); + +} + export const files: { path: (f: string, p: string) => string; writableStream: (f: string, p: string) => fs.WriteStream; -- cgit v1.2.1