aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorjw2552018-04-19 16:26:46 +0100
committerjw2552018-04-19 16:26:46 +0100
commitb56d886000a70898dcc54c06bd265fa379f44ac4 (patch)
tree7de1d7dd6479b979e0c6d33edf91fa5ae7b67cc5 /src
parentProject Owners added (diff)
parentAdd CORS support (diff)
downloadmedicine-b56d886000a70898dcc54c06bd265fa379f44ac4.tar.gz
medicine-b56d886000a70898dcc54c06bd265fa379f44ac4.zip

Merge branch ‘trh/gets’ into ‘jl247/permissions’

Conflicts:

src/FileRouter.ts

Diffstat (limited to 'src')
-rw-r--r--src/FileRouter.ts271
-rw-r--r--src/app.ts21
-rw-r--r--src/db/model/File.ts32
-rw-r--r--src/db/model/Project.ts4
-rw-r--r--src/db/model/User.ts1
-rw-r--r--src/files.ts124
-rw-r--r--src/index.ts36
-rw-r--r--src/logger.ts6
-rw-r--r--src/matcher/index.ts1
-rw-r--r--src/matcher/options.ts11
10 files changed, 408 insertions, 99 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts
index 61f8262..0882272 100644
--- a/src/FileRouter.ts
+++ b/src/FileRouter.ts
@@ -6,9 +6,8 @@ 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 { View, files, views } 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';
@@ -16,8 +15,6 @@ import UserHasPrivilege from './db/model/UserHasPrivilege';
import { Contains } from 'sequelize-typescript';
import UserJoinsProject from './db/model/UserJoinsProject';
-// TODO: figure this out
-const BASE_FILE_STORAGE: string = 'TODO: figure this out';
/**
* The type of an Express middleware callback.
@@ -632,13 +629,14 @@ const getFile: Middleware = async(
req: Request, res: Response, next: NextFunction
): Promise<void> => {
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'));
}
const project: Project = res.locals.project;
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.data = view.getResponseData(file, project, req.query);
next();
@@ -655,25 +653,167 @@ 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);
+ }
+ 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
*/
-const postFilePath: Middleware = (
- req: Request, res: Response, next: NextFunction
-): void => {
- logger.debug(`Receiving file to ${res.locals.parentFolder}`);
- res.locals.modified = true;
- if (res.locals.file != null) {
+/* 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'));
}
- const file: File = new File({
- uuid: uuid.generate(),
- name: res.locals.filename,
- parentFolder: res.locals.parentFolder
- });
- //console.log(res.locals);
- req.pipe(files.writableStream(file.uuid, res.locals.project.name));
+
+ // 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)){
+ 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();
+ }
+
+ // 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(),
+ 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'))
+ }
+ }
+
+ // 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));
+ }
+
+ // Sets final if requested
+ if (qH.isFinal(req)) {
+ res.locals.file.status = 'final';
+ }
+
next();
+
};
+/* tslint:enable */
export class FileRouter {
public router: Router;
@@ -718,7 +858,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);
}
@@ -746,7 +887,11 @@ export class FileRouter {
username: name
}
});
- res.locals.user = user;
+ if (user == null) {
+ return next(new RequestError(404, 'user_not_found'));
+ } else {
+ res.locals.user = user;
+ }
next();
}
);
@@ -759,7 +904,9 @@ export class FileRouter {
projectName: string
): Promise<void> => {
res.locals.project = await Project.findOne({
- include: [{all: true}],
+ include: [
+ User
+ ],
where: {
name: projectName
}
@@ -775,49 +922,62 @@ export class FileRouter {
req: Request, res: Response, next: NextFunction,
filename: string
): Promise<void> => {
- console.log(`parsing path ${filename}`)
- logger.debug(`Searching for file ${filename}`);
- const fileNames: string[] = req.params.path.split('/');
+ // 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 file: File = project.rootFolder;
- // TODO Rewrite using sub-queries instead of repeated queries.
- while (fileNames.length > 2) {
+ 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: {
- name: fileNames[0],
- parentFolder: file
+ nameInternal: fileNames[i],
+ parentFolderId: curDir.uuid
}
});
if (fileOrNull == null) {
+ logger.debug(`Sub-file \'${fileNames[i]}\' not found in DB`);
return next();
- } else {
- file = fileOrNull;
}
- fileNames.splice(0, 1);
- }
- const parentFolder: File | null = await File.findOne({
- include: [
- { model: File, as: 'containedFilesInternal'},
- ],
- where: {
- //parentFolder: file,
- //name: fileNames[0]
+
+ 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;
}
- });
- //console.log(parentFolder);
- if (parentFolder == null) {
- return next();
+ curDir = fileOrNull;
+ i++;
}
- 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();
}
);
@@ -829,7 +989,7 @@ export class FileRouter {
req: Request, res: Response, next: NextFunction,
fileId: string
): Promise<void> => {
- console.log(`parsing id ${fileId}`);
+ logger.info(`parsing id ${fileId}`);
const file: File | null = await File.findOne({
include: [{all: true}],
where: {
@@ -837,6 +997,15 @@ 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 {
+ logger.debug('parentfolder not set!');
+ }
+ }
next();
}
);
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}`);
@@ -69,6 +70,22 @@ class App {
}
/**
+ * 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.
*/
private middleware(): void {
@@ -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({
diff --git a/src/db/model/File.ts b/src/db/model/File.ts
index 4026b85..8a12431 100644
--- a/src/db/model/File.ts
+++ b/src/db/model/File.ts
@@ -5,11 +5,29 @@ 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<File> {
@AllowNull
@Column
- private nameInternal!: string;
+ public nameInternal!: string;
@AllowNull
@Column
@@ -67,10 +85,14 @@ export default class File extends Model<File> {
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/db/model/Project.ts b/src/db/model/Project.ts
index 41a70c9..a7f1199 100644
--- a/src/db/model/Project.ts
+++ b/src/db/model/Project.ts
@@ -36,6 +36,10 @@ export default class Project extends Model<Project> {
return this.rootFolderInternal;
}
+ public get properties(): object {
+ return this;
+ }
+
public get metadata(): {
public_metadata?: Metadata;
private_metadata?: Metadata;
diff --git a/src/db/model/User.ts b/src/db/model/User.ts
index 506614c..8c27012 100644
--- a/src/db/model/User.ts
+++ b/src/db/model/User.ts
@@ -126,7 +126,6 @@ export default class User extends Model<User> {
}
public get fullInfo(): UserFullInfo {
- console.log("fullinfo called")
// FIXME: Fetch these things if they aren't already present
if (this.userGroups === undefined) {
this.userGroups = [];
diff --git a/src/files.ts b/src/files.ts
index 8ad7236..5b15a10 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -1,5 +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';
@@ -7,16 +9,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,34 +23,63 @@ interface RawSize {
length: number;
}
-const readableStream: (
- filename: string, projectName: string,
- { offset, length }?: Partial<RawSize>
-) => fs.ReadStream = (
- filename: string, projectName: string,
- { offset, length }: Partial<RawSize> =
- { offset: undefined, length: undefined }
-): fs.ReadStream => {
+const readableStream: (filename: string, projectName: string, { offset, length }?: Partial<RawSize>) => fs.ReadStream
+ = (filename: string, projectName: string, { offset, length }: Partial<RawSize> = { offset: undefined, length: undefined }): fs.ReadStream => {
const options: object = {
- start: offset
- ? offset
- : 0,
- end: offset && length
- ? offset + length
- : undefined
+ start: offset? offset: 0,
+ end: offset && length? offset + length: undefined
};
return fs.createReadStream(path(filename, projectName), options);
};
-const logPath:
-(type: string, projectName?: string) => string = (
- type: string, projectName?: string
-): 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}`;
};
+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 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).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 =
+ (fileId: string, projectName: string): void => {
+
+ 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: {
path: (f: string, p: string) => string;
writableStream: (f: string, p: string) => fs.WriteStream;
@@ -142,7 +169,7 @@ export const views: {
getResponseData: async(
file: File, project: Project, query: Query
): Promise<object> => {
- return readableStream(file.name, project.name, query);
+ return readableStream(file.uuid, project.name, query);
},
getResponseFunction: (req: Request, res: Response): Function | null => {
return res.send;
@@ -198,3 +225,46 @@ class MimeTypeMap extends Map<string, string> {
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);
+ }
+}
+
+export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise<boolean> = async(parentId: string, subFileId: string): Promise<boolean> => {
+ 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
+ }
+ });
+ if(!parent || !file){
+ return false;
+ }
+ // update both objects
+ parent.containedFiles.push(file);
+ file.parentFolderId = parent.uuid;
+ // save
+ await file.save();
+ await parent.save();
+
+ return true;
+}
diff --git a/src/index.ts b/src/index.ts
index 0b2cec9..b323895 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';
import { default as ContributorGroup } from './db/model/ContributorGroup';
@@ -21,16 +23,7 @@ const port: number = process.env.PORT
: DEFAULT_PORT;
logger.info(`Port ${port} chosen`);
-// tslint:disable:no-floating-promises
-(async(): Promise<void> => {
- 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<void> {
try {
logger.info('Resetting Database');
await seq.sync({
@@ -41,6 +34,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',
@@ -141,6 +142,7 @@ logger.info(`Port ${port} chosen`);
});
await root.save();
+ createRootFolder();
await root.$set('userGroups', [admin, logging]);
@@ -151,6 +153,20 @@ logger.info(`Port ${port} chosen`);
}
});
+}
+
+// tslint:disable:no-floating-promises
+(async(): Promise<void> => {
+ 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) {
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<LogItem[]> = (level?: LogLevel, params: FetchParams = {}): Promise<LogItem[]> => {
const options: winston.QueryOptions = {
from: params.after,
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,
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);