aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorjw2552018-04-21 23:01:58 +0100
committerjw2552018-04-21 23:01:58 +0100
commit7bfdc2cc7c5aa1aaed655c7ddd3a7c3cf38430e5 (patch)
tree15ac9f791daa89e88d8adde6e7775c205229602a
parentMerge branch 'trh/files' into trh/gets (diff)
downloadmedicine-7bfdc2cc7c5aa1aaed655c7ddd3a7c3cf38430e5.tar.gz
medicine-7bfdc2cc7c5aa1aaed655c7ddd3a7c3cf38430e5.zip

implimented moving and copying of files

-rw-r--r--src/FileRouter.ts76
-rw-r--r--src/db/model/File.ts7
-rw-r--r--src/files.ts38
-rw-r--r--src/index.ts2
4 files changed, 111 insertions, 12 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 6b03453..ecd5185 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -7,8 +7,8 @@ import { default as UserGroup } from './db/model/UserGroup';
import { RequestError } from './errors/errorware';
import { NextFunction, Request, Response, Router } from 'express';
-import { View, addSubFileToFolder, createProjectFolder, deleteFile, rootPathId,
- saveFile, upload, views } from './files';
+import { View, addSubFileToFolder, copyFile, createProjectFolder, deleteFile,
+ rootPathId, saveFile, upload, views } from './files';
import { logger } from './logger';
import { Property, default as serverConfig } from './serverConfig';
import { uuid } from './uuid';
@@ -572,7 +572,6 @@ const getFileFromPath: (req: Request, res: Response) => Promise<void> = async(
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
@@ -682,6 +681,7 @@ const qH: {
/**
* Post a File. / delete / move / etc
*/
+/* tslint:disable */
const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise<void> => {
try {
await getFileFromPath(req, res);
@@ -696,12 +696,14 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu
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'));
+ return;
}
// 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'));
+ return;
}
// Sets final if requested
@@ -715,6 +717,7 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu
res.locals.file.metadata = req.body;
await res.locals.file.save();
next();
+ return;
}
// Deletes File if requested
@@ -723,29 +726,83 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu
deleteFile(res.locals.file.uuid, res.locals.project.name);
await res.locals.file.destroy();
next();
+ return;
}
// Moves File if requested
if(qH.moves(req)){
- // TODO
- next(new RequestError(500, 'not_implemented'));
+ if(!req.body.path){
+ logger.debug(`copying by uuid not implimented`);
+ next(new RequestError(500, "copy_to_path_only"));
+ return;
+ }
+ logger.info(`Copying file \'${res.locals.file.fullPath}\' to new path \'${req.body.path}\'`);
+ // new File object
+ let promise: PromiseLike<File> | null = null;
+
+ const newFile: File = new File({
+ uuid: uuid.generate(),
+ type: res.locals.file.type,
+ status: res.locals.file.status,
+ creatorName: res.locals.file.creatorName,
+ createdAt: res.locals.file.createdAt,
+ modifyDate: res.locals.file.modifyDate
+ });
+ newFile.setMetadataInternal(res.locals.file.metadata);
+ newFile.fullPath = req.body.path;
+ newFile.parentFolderId = res.locals.parentFolderId;
+ await newFile.save();
+ const oldUUID: string = res.locals.file.uuid;
+ await res.locals.file.destroy();
+ copyFile(res.locals.project.name, res.locals.file.uuid, oldUUID, true);
+ next();
+ return;
}
// Copies File if requested
if(qH.copys(req)){
- // TODO
- next(new RequestError(500, 'not_implemented'));
+ if(!req.body.path){
+ logger.debug(`copying by uuid not implimented`);
+ next(new RequestError(500, "copy_to_path_only"));
+ return;
+ }
+ logger.info(`Copying file \'${res.locals.file.fullPath}\' to new path \'${req.body.path}\'`);
+ // new File object
+ let promise: PromiseLike<File> | null = null;
+
+ const newFile: File = new File({
+ uuid: uuid.generate(),
+ type: res.locals.file.type,
+ status: res.locals.file.status,
+ creatorName: res.locals.file.creatorName,
+ createdAt: res.locals.file.createdAt,
+ modifyDate: res.locals.file.modifyDate
+ });
+ newFile.setMetadataInternal(res.locals.file.metadata);
+ newFile.fullPath = req.body.path;
+ newFile.parentFolderId = res.locals.parentFolderId;
+ await newFile.save();
+ copyFile(res.locals.project.name, res.locals.file.uuid, newFile.uuid);
+ next();
+ return;
}
// Overwrite data but not truncate
// eg. OOOONNNNNNOOOO (O = old data, N = new data)
if(qH.overwrites(req) && !qH.truncates(req)){
- // TODO
+ logger.info(`overwriting without truncating not supported`);
next(new RequestError(500, 'not_implemented', 'please specify truncate parameter'));
+ return;
}
// Create File or Folder if file doesn't exist
if (res.locals.file == null){
+ // Guarding against stupid Postman
+ if(!qH.mksDir(req) && !req.file){
+ logger.debug("No file attached. Sending 400");
+ next(new RequestError(400, 'no_file_attached'));
+ }
+
// 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];
@@ -787,7 +844,6 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu
: 'uploading'
});
res.locals.file.mimetype = qH.mksDir(req) ? 'inode/directory' : req.file.mimetype;
- console.log(req.file.mimetype);
await res.locals.file.save();
@@ -795,6 +851,7 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu
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'))
+ return;
}
}
@@ -814,6 +871,7 @@ const postFilePath: Middleware = async(req: Request, res: Response, next: NextFu
next(e);
}
};
+/* tslint:enable */
export class FileRouter {
public router: Router;
diff --git a/src/db/model/File.ts b/src/db/model/File.ts
index 6b71f3d..89415b7 100644
--- a/src/db/model/File.ts
+++ b/src/db/model/File.ts
@@ -116,7 +116,8 @@ export default class File extends Model<File> {
}
public get metadata(): Metadata {
- return JSON.parse(this.metadataInternal) || INITIAL_METADATA;
+ return !!(this.metadataInternal) ? JSON.parse(this.metadataInternal)
+ : INITIAL_METADATA;
}
public set metadata(md: Metadata) {
@@ -128,6 +129,10 @@ export default class File extends Model<File> {
if (newMD.version !== oldMD.version + 1) {
throw new RequestError(400, 'invalid_request');
}
+ this.metadataInternal = JSON.stringify(newMD);
+ }
+ public setMetadataInternal(md: Metadata): void {
+ this.metadataInternal = JSON.stringify(md);
}
public set mimetype(mime: string) {
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<void> = async(projName: string, fromId: string, toId: string, move?: boolean): Promise<void> => {
+ // 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;
diff --git a/src/index.ts b/src/index.ts
index 0074d7b..4dc83ad 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -93,7 +93,7 @@ async function reset(): Promise<void> {
process.exit(1);
}
- //await reset();
+ await reset();
logger.info('Booting ExpressJS server');
app.listen(port, (err: Error) => {