aboutsummaryrefslogtreecommitdiff
path: root/src/FileRouter.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/FileRouter.ts')
-rw-r--r--src/FileRouter.ts675
1 files changed, 437 insertions, 238 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 9059e88..c8884f7 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -5,12 +5,18 @@ import { ProjectFullInfo, default as Project } from './db/model/Project';
import { UserFullInfo, default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';
+import * as bodyParser from 'body-parser';
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,
+ saveFile, views, preprocess } from './files';
+import { appendFileSync } from 'fs';
import { logger } from './logger';
+import { mimetype } from './mimetype';
+import { Contains } from 'sequelize-typescript';
import { Property, default as serverConfig } from './serverConfig';
+import UserHasPrivilege from './db/model/UserHasPrivilege';
+import UserJoinsProject from './db/model/UserJoinsProject';
import { uuid } from './uuid';
/**
@@ -245,14 +251,14 @@ const getUsers: Middleware = async(
Project
]
});
- res.locals.data = users.map((u: User): UserFullInfo => {
- const info: UserFullInfo = u.fullInfo;
- if (!req.user.hasPrivilege('admin')) {
- delete info.private_user_metadata;
- delete info.private_admin_metadata;
- }
+ res.locals.data = Promise.all(users.map((u: User): Promise<UserFullInfo> => {
+ const info: Promise<UserFullInfo> = u.getFullInfo();
return info;
- });
+ }));
+ if (!req.user.hasPrivilege('admin')) {
+ delete res.locals.data.private_user_metadata;
+ delete res.locals.data.private_admin_metadata;
+ }
next();
};
@@ -292,24 +298,24 @@ const getUserProperties: Middleware = (
* "private_admin_metadata": metadata
* }
*/
-const getUsername: Middleware = (
+const getUsername: Middleware = async(
req: Request, res: Response, next: NextFunction
-): void => {
+): Promise<void> => {
logger.debug(`Listing user ${res.locals.user}`);
res.locals.modified = true;
if (res.locals.user == null) {
next(new RequestError(404, 'user_not_found'));
return;
}
- res.locals.data = res.locals.user.fullInfo;
+ res.locals.data = await res.locals.user.getFullInfo();
next();
};
-const getCurUser: Middleware = (
+const getCurUser: Middleware = async(
req: Request, res: Response, next: NextFunction
-): void => {
+): Promise<void> => {
logger.debug('Listing current user');
- res.locals.data = req.user.fullInfo;
+ res.locals.data = await req.user.getFullInfo();
next();
};
@@ -367,19 +373,65 @@ const postUsername: Middleware = async(
): Promise<void> => {
let user: User | null | undefined = res.locals.user;
res.locals.modified = true;
- if (user == null) {
- logger.debug('Adding new user');
- user = new User({
- username: req.params.username,
- password: req.params.password
- });
- } else {
- logger.debug('Editing user');
- user.password = req.params.password;
+
+ if( req.query.action === 'update'){
+ if (user!= null){
+ logger.debug('Editing user');
+
+ if(req.body.password != null){
+ user.password = req.body.password;
+ }
+ if (req.body) {
+ user.metadata = req.body;
+ }
+ await user.save();
+ if(req.body.privileges != null){
+ const priv: UserGroup[] | null = await UserGroup.findAll({
+ include: [{all: true}],
+ where: {
+ name: req.body.privileges
+ }
+ })
+ await user.$set('userGroups', priv);
+ }
+ }
+ else{
+ next(new RequestError(404, 'user_not_found'));
+ return;
+ }
}
- if (req.body) {
- user.metadata = req.body;
+ else if( req.query.action === 'delete'){
+ logger.debug('Deleting a user');
+ if (user!= null){
+ await user.destroy();
+ }
+ else{
+ next(new RequestError(404, 'user_not_found'));
+ return;
+ }
}
+ else{
+ if (user == null) {
+ logger.debug('Adding new user');
+ const priv: UserGroup[] | null = await UserGroup.findAll({
+ include: [{all: true}],
+ where: {
+ name: req.body.privileges
+ }
+ })
+ user = new User({
+ username: req.params.username,
+ password: req.params.password,
+ });
+ await user.save();
+ await user.$set('userGroups', priv);
+ }
+ else{
+ next(new RequestError(400, 'user_already_exists'));
+ return;
+ }
+ }
+ await user.save();
next();
};
@@ -435,9 +487,9 @@ const getProjects: Middleware = async(
User
]
});
- res.locals.data = projects.map(
- (p: Project): ProjectFullInfo => p.fullInfo
- );
+ res.locals.data = Promise.all(projects.map(
+ (p: Project): Promise<ProjectFullInfo> => p.getFullInfo()
+ ));
next();
};
@@ -467,7 +519,7 @@ const getProjectName: Middleware = async(
if (project == null) {
return next(new RequestError(404, 'project_not_found'));
} else {
- res.locals.data = project.fullInfo;
+ res.locals.data = await project.getFullInfo();
next();
}
};
@@ -491,31 +543,81 @@ const postProjectName: Middleware = async(
let project: Project | null = res.locals.project;
res.locals.modified = true;
let promise: PromiseLike<File> | null = null;
- if (project == null) {
- logger.debug('Adding new project');
- const file: File = new File({
- uuid: uuid.generate(),
- mimetype: 'inode/directory',
- 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;
+ if (req.query.action === 'update') {
+ logger.debug('Adding new project');
+ if (project != null) {
+ project.metadata = req.body;
+ await project.save();
+ } else {
+ next(new RequestError(400, 'project_not_found'));
+ }
+ } else if (req.query.action === 'delete') {
+ if (project != null) {
+ project.destroy();
+ } else {
+ next(new RequestError(400, 'project_not_found'));
+ }
+ } else if (req.query.action === 'update_grant') {
+ if (project == null) {
+ next(new RequestError(400, 'project_not_found'));
+ } else {
+ const ujp: UserJoinsProject | null = await UserJoinsProject.findOne({
+ include: [{all: true}],
+ where: {
+ username: req.body.username,
+ projectName: project.name
+ }
+ });
+ if (ujp != null) {
+ await ujp.destroy();
+ }
+ if (req.body.access_level !== 'none') {
+ try {
+ let ujp: UserJoinsProject = new UserJoinsProject({
+ username: req.body.username,
+ projectName: project.name,
+ contributorGroupName: req.body.access_level
+ });
+ await ujp.save();
+ } catch (err) {
+ next(new RequestError(400, 'invalid_access_level'));
+ }
+ }
+ }
} else {
- logger.debug('Updating project properties');
+ if (project == null) {
+ logger.debug('Adding new project');
+ const file: File = new File({
+ uuid: uuid.generate(),
+ });
+ file.mimetype = 'inode/directory';
+ file.name = '';
+ promise = file.save();
+ project = new Project({
+ name: req.params.project_name,
+ rootFolderId: file.uuid
+ });
+
+ createProjectFolder(req.params.project_name);
+
+ project.metadata = req.body;
+ // tslint:disable-next-line:await-promise
+ await promise;
+ await project.save()
+ const contribute: UserJoinsProject = new UserJoinsProject({
+ username: req.user.username,
+ projectName: req.params.project_name,
+ contributorGroupName: 'projectOwner'
+
+ })
+ contribute.save()
+ } else {
+ next(new RequestError(400, 'project_already_exists'));
+ }
}
- project.metadata = req.body;
- // tslint:disable-next-line:await-promise
- await promise;
- await project.save();
- next();
+ next()
};
/**
@@ -534,6 +636,90 @@ const getProjectProperties: Middleware = (
}
};
+// Fetch a file from its path:
+const getFileFromPath: (req: Request, res: Response) => Promise<void> = async(
+ req: Request, res: Response
+): Promise<void> => {
+ // 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
+
+ const nth: (str: string, pat: string, n: number) => number = (
+ str: string, pat: string, num: number
+ ): number => {
+ const l: number = str.length;
+ let j: number = -1;
+ let n: number = num;
+ while (n-- && j++ < l) {
+ j = str.indexOf(pat, j);
+ if (j < 0) {
+ break;
+ }
+ }
+ return j;
+ };
+
+ const path: string = req.path.substring(nth(req.path, '/', 4) + 1);
+
+ res.locals.path = path;
+ logger.debug(`Searching for path '${res.locals.path}'`);
+ // Split path into parts
+ const fileNames: string[] = res.locals.path.split('/')
+ .filter((s: string): boolean => s !== '');
+ res.locals.filename = fileNames.length > 0
+ ? fileNames[fileNames.length - 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');
+ throw new RequestError(404, 'project_not_found');
+ }
+ let curDir: File | null = project.rootFolder;
+ if (!curDir) {
+ throw new Error(`Project ${project.name} has been left with no root folder`);
+ }
+ res.locals.deepestFolderId = curDir.uuid;
+ res.locals.deepestFolderName = curDir.name;
+ if (fileNames.length === 0) {
+ res.locals.file = curDir;
+ }
+ 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) {
+ logger.debug(`Searching for '${fileNames[i]}'`);
+ const fileOrNull: File | null = await File.findOne({
+ include: [{all: true}],
+ where: {
+ nameInternal: fileNames[i],
+ parentFolderId: curDir.uuid
+ }
+ });
+ if (fileOrNull == null) {
+ logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`);
+ return;
+ }
+
+ if (i < fileNames.length - 1) {
+ // Found next subdirectory
+ logger.debug(`Found Sub-folder \'${fileOrNull.name}\'`);
+ res.locals.deepestFolderId = fileOrNull.uuid;
+ res.locals.deepestFolderName = fileOrNull.name;
+ } else {
+ // Found actual file
+ logger.debug(`Found file \'${fileOrNull.name}\'`);
+ res.locals.file = fileOrNull;
+ }
+ curDir = fileOrNull;
+ i++;
+ }
+};
+
/**
* GET a File.
*/
@@ -547,7 +733,7 @@ const getFile: Middleware = async(
}
const project: Project = res.locals.project;
const view: View = views[req.query.view || 'meta'];
- // TODO return 400 for unsuported views
+ // TODO return 400 for unsupported 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);
@@ -557,7 +743,16 @@ const getFile: Middleware = async(
/**
* GET a File.
*/
-const getFilePath: Middleware = getFile;
+const getFilePath: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ try {
+ await getFileFromPath(req, res);
+ await getFile(req, res, next);
+ } catch (e) {
+ next(e);
+ }
+};
/**
* GET a File.
@@ -587,130 +782,200 @@ const qH: {
!qH.truncates(req) && !qH.isFinal(req)
};
-/**
- * Post a File. / delete / move / etc
- */
-/* tslint:disable */
-const postFilePath: Middleware = async(req: Request, res: Response, next: NextFunction): Promise<void> => {
- logger.debug(`Receiving file ${res.locals.path}`);
- console.log(req.file);
- // 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'));
- }
-
- // 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'));
- }
-
- // Sets final if requested
- if (res.locals.file && qH.isFinal(req)) {
- res.locals.file.status = 'preprocessing';
- // start file conversion
- }
-
- // 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)){
- logger.info(`File ${res.locals.file.name} will be deleted`)
- deleteFile(res.locals.file.uuid, res.locals.project.name);
- await res.locals.file.destroy();
- next();
- }
+const makeFile = async(req: Request, res: Response): Promise<File> => {
+ // 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];
- // Moves File if requested
- if(qH.moves(req)){
- // TODO
- next(new RequestError(500, 'not_implemented'));
+ let curPath: string = res.locals.deepestFolderName;
+ // 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];
+ curPath += subFolder;
+ logger.debug(`Adding subfolder '${subFolder}'`);
+ const dir: File = new File({
+ uuid: uuid.generate(),
+ type: 'directory',
+ status: 'ready',
+ fullPathInternal: curPath,
+ nameInternal: subFolder
+ });
+ await dir.save();
+ curPath += '/';
+ // update parent directory of new directory
+ await addSubFileToFolder(res.locals.deepestFolderId, dir);
+ // update vars
+ remainingPath = remainingPath.split(subFolder)[1];
+ res.locals.deepestFolderName = subFolder;
+ res.locals.deepestFolderId = dir.uuid;
}
- // Copies File if requested
- if(qH.copys(req)){
- // TODO
- next(new RequestError(500, 'not_implemented'));
- }
+ logger.debug(`Writing file '${res.locals.filename}' to folder '${res.locals.deepestFolderName}'`);
+ res.locals.file = new File({
+ uuid: uuid.generate(),
+ nameInternal: res.locals.filename,
+ fullPathInternal: res.locals.path,
+ status: req.query.final
+ ? 'ready'
+ : 'uploading'
+ });
+ res.locals.file.mimetype = mimetype(
+ req.header('Content-Type'), req.body, res.locals.filename);
- // 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'));
- }
+ // update parent directory of new directory
+ await addSubFileToFolder(res.locals.deepestFolderId, res.locals.file);
+ return res.locals.file;
+};
- // 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();
+/**
+ * Post a File. / delete / move / etc
+ */
+const postFilePath: Middleware = async(
+ req: Request, res: Response, next: NextFunction
+): Promise<void> => {
+ try {
+ await getFileFromPath(req, res);
+ logger.debug(`Receiving file ${res.locals.path}`);
+ // / 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)
- // 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'))
+ if (res.locals.file) {
+ /* tslint:disable-next-line:curly */
+ if (req.query.action) switch (req.query.action) {
+ case 'set_metadata': {
+ res.locals.file.metadata = JSON.parse(req.body.toString());
+ await res.locals.file.save();
+ break;
+ } case 'delete': {
+ logger.info(`File ${res.locals.file.name} will be deleted`);
+ deleteFile(res.locals.file.uuid, res.locals.project.name);
+ await res.locals.file.destroy();
+ break;
+ } case 'move': {
+ if (!req.body.path) {
+ logger.warn('copying by uuid not implimented');
+ return next(new RequestError(500, 'copy_to_path_only'));
+ }
+ logger.info(`Copying file '${
+ res.locals.file.fullPath}' to new path '${req.body.path}'`);
+ // New File object
+ const 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);
+ break;
+ } case 'copy': {
+ if (!req.body.path) {
+ logger.debug('copying by uuid not implimented');
+ return next(new RequestError(500, 'copy_to_path_only'));
+ }
+ logger.info(`Copying file '${
+ res.locals.file.fullPath}' to new path '${req.body.path}'`);
+ const 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);
+ break;
+ } case 'mkdir': {
+ logger.debug(`Action '${req.query.action}' not valid if file exists`);
+ return next(new RequestError(400, 'file_exists'));
+ } default: {
+ logger.warn(`Unknown file edit action '${req.query.action}'`);
+ return next(new RequestError(400, 'unknown_action'));
+ }
+ } else {
+ if (req.query.overwrite) {
+ if (req.query.truncate) {
+ await saveFile(
+ req.body,
+ res.locals.project.name,
+ res.locals.file.uuid,
+ req.query
+ );
+ if (req.query.final) {
+ res.locals.file.status = 'preprocessing';
+ await res.locals.file.save();
+ preprocess(res.locals.file, res.locals.project);
+ }
+ } else {
+ logger.warn('overwriting without truncating not supported');
+ return next(new RequestError(
+ 500,
+ 'not_implemented',
+ 'please specify truncate parameter'
+ ));
+ }
+ } else {
+ return next(new RequestError(400, 'file_already_exists'));
+ }
}
- // 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(),
- nameInternal: res.locals.filename
- });
- 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, res.locals.file.uuid)){
- logger.debug("adding file to folder failed!")
- next(new RequestError(500, 'Adding file to folder failed'))
+ } else {
+ /* tslint:disable-next-line:curly */
+ if (req.query.action) switch (req.query.action) {
+ case 'mkdir': {
+ await makeFile(req, res);
+ res.locals.file.status = 'final';
+ break;
+ }
+ case 'set_metadata':
+ case 'delete':
+ case 'move':
+ case 'copy':
+ logger.debug(`Action '${req.query.action
+ }' not valid if file does not exist`);
+ return next(new RequestError(404, 'file_not_found'));
+ } else {
+ if (!req.body) {
+ logger.debug('No file attached. Sending 400');
+ next(new RequestError(400, 'no_file_attached'));
+ }
+ await makeFile(req, res);
+ await saveFile(
+ req.body,
+ res.locals.project.name,
+ res.locals.file.uuid,
+ req.query
+ );
+ // Sets final if requested
+ if (qH.isFinal(req)) {
+ res.locals.file.status = 'preprocessing';
+ preprocess(res.locals.file, res.locals.project);
+ }
+ }
+ await res.locals.file.save();
}
- }
+ return next();
- // 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));
+ } catch (e) {
+ next(e);
}
-
- // Sets final if requested
- if (qH.isFinal(req)) {
- res.locals.file.status = 'final';
- }
-
- next();
-
};
-/* tslint:enable */
export class FileRouter {
public router: Router;
@@ -751,10 +1016,10 @@ export class FileRouter {
this.router.post('/projects/:project_name', postProjectName);
this.router.get ('/projects/:project_name/properties', getProjectProperties);
// File access
- this.router.get ('/projects/:project_name/files/:path', getFilePath);
+ this.router.get ('/projects/:project_name/files/*', getFilePath);
this.router.post(
- '/projects/:project_name/files/:path',
- upload.single('userfile'), postFilePath);
+ '/projects/:project_name/files/*',
+ bodyParser.raw({ type: '*/*', limit: '20GB' }), postFilePath);
this.router.get ('/projects/:project_name/files_by_id/:id', getFileId);
}
@@ -783,7 +1048,7 @@ export class FileRouter {
}
});
if (user == null) {
- return next(new RequestError(404, 'user_not_found'));
+ //return next(new RequestError(404, 'user_not_found'));
} else {
res.locals.user = user;
}
@@ -800,7 +1065,8 @@ export class FileRouter {
): Promise<void> => {
res.locals.project = await Project.findOne({
include: [
- User
+ User,
+ File
],
where: {
name: projectName
@@ -810,73 +1076,6 @@ export class FileRouter {
}
);
- // Fetch a file from its path:
- this.router.param(
- 'path',
- async(
- req: Request, res: Response, next: NextFunction,
- filename: string
- ): Promise<void> => {
- // 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 /
- 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'));
- }
- let curDir: File | null = project.rootFolder;
- 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.
- while (curDir && i < fileNames.length) {
- logger.debug(`Searching for \'${fileNames[i]}\'`);
- const fileOrNull: File | null = await File.findOne({
- include: [{all: true}],
- where: {
- nameInternal: fileNames[i],
- parentFolderId: curDir.uuid
- }
- });
- if (fileOrNull == null) {
- logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`);
- return next();
- }
-
- if (i < fileNames.length - 1) {
- // Found next subdirectory
- logger.debug(`Found Sub-folder \'${fileOrNull.name}\'`);
- res.locals.deepestFolderId = fileOrNull.uuid;
- res.locals.deepestFolderName = fileOrNull.name;
- } else {
- // Found actual file
- logger.debug(`Found file \'${fileOrNull.name}\'`);
- res.locals.file = fileOrNull;
- }
- curDir = fileOrNull;
- i++;
- }
-
- next();
- }
- );
-
// Fetch a file from its UUID:
this.router.param(
'id',