aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/.DS_Storebin0 -> 8196 bytes
-rw-r--r--src/FileRouter.ts675
-rw-r--r--src/app.ts12
-rw-r--r--src/conversion/csv/excel.ts126
-rwxr-xr-xsrc/conversion/czi/JxrDecAppbin0 -> 296464 bytes
-rw-r--r--src/conversion/czi/convertJxrs.py47
-rw-r--r--src/conversion/czi/czi.ts1001
-rwxr-xr-xsrc/conversion/czi/cziConvert.sh7
-rw-r--r--src/conversion/czi/cziconvert.c14
-rw-r--r--src/conversion/czi/pyramidWorker.ts93
-rw-r--r--src/conversion/czi/tileDims.pngbin0 -> 292647 bytes
-rw-r--r--src/conversion/czi/tileExtraction.ts122
-rw-r--r--src/conversion/leica/requestconvertor.ts1
-rw-r--r--src/conversion/leica/scn.ts95
-rw-r--r--src/conversion/types/customPyramidIndex.ts37
-rw-r--r--src/conversion/types/cziBinaryTypings.ts23
-rw-r--r--src/conversion/types/helpers.ts106
-rw-r--r--src/cors/index.d.ts16
-rw-r--r--src/cors/index.js8
-rw-r--r--src/db/.DS_Storebin0 -> 6148 bytes
-rw-r--r--src/db/model/ContributorGroup.ts13
-rw-r--r--src/db/model/File.ts34
-rw-r--r--src/db/model/Project.ts88
-rw-r--r--src/db/model/User.ts73
-rw-r--r--src/db/model/UserJoinsProject.ts10
-rw-r--r--src/errors/errorware.ts5
-rw-r--r--src/files.ts436
-rw-r--r--src/index.ts80
-rw-r--r--src/matcher/index.ts4
-rw-r--r--src/matcher/options.ts6
-rw-r--r--src/mimetype.ts29
-rw-r--r--src/serverConfig.ts2
32 files changed, 2468 insertions, 695 deletions
diff --git a/src/.DS_Store b/src/.DS_Store
new file mode 100644
index 0000000..2d5870d
--- /dev/null
+++ b/src/.DS_Store
Binary files differ
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',
diff --git a/src/app.ts b/src/app.ts
index 6a595f6..7b398fd 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -57,7 +57,7 @@ class App {
async(req: ex.Request, res: ex.Response, next: ex.NextFunction):
Promise<void> => {
if (res.locals.function) {
- res.locals.function.bind(res)(res.locals.data);
+ res.locals.function.bind(res)(await res.locals.data);
} else {
res.json({
status: 'success',
@@ -82,6 +82,12 @@ class App {
'/cs3099group-be-4/_supported_protocols_'
] })
);
+ this.express.use((req, res, next) => {
+ if (req.headers.authorisation) {
+ (req.headers.authorization as any) = req.headers.authorisation;
+ }
+ next();
+ })
this.express.use(passport.initialize());
this.express.use(async(
req: ex.Request, res: ex.Response, next: ex.NextFunction
@@ -110,7 +116,7 @@ class App {
defRouter.get('/', (req: ex.Request, res: ex.Response): void => {
res.json({
message: 'Welcome to the CS3099 BE4 server!',
- important: 'Endpoints start from /cs3099group-be-4/'
+ important: 'Endpoints start from /cs3099group-be-4'
});
});
this.express.use('/cs3099group-be-4', FileRouter);
@@ -123,7 +129,7 @@ class App {
.json({
status: 'error',
error : 'invalid_route',
- error_description: 'Endpoints start from /cs3099group-be-4/'
+ error_description: 'Endpoints start from /cs3099group-be-4'
});
} else {
next();
diff --git a/src/conversion/csv/excel.ts b/src/conversion/csv/excel.ts
new file mode 100644
index 0000000..3f5d30b
--- /dev/null
+++ b/src/conversion/csv/excel.ts
@@ -0,0 +1,126 @@
+import { logger } from '../../logger';
+import * as xlsx from 'xlsx';
+import * as fs from 'fs';
+import { SupportedViews, writeJSONToFile } from '../types/helpers';
+import * as csv from 'csv-parse';
+import { extension } from '../../mimetype'
+
+const writeFile = require('util').promisify(fs.writeFile);
+const readFile = require('util').promisify(fs.readFile);
+const createFolder = require('util').promisify(fs.mkdir);
+const readDir = require('util').promisify(fs.readdir);
+const rename = require('util').promisify(fs.rename);
+const copy = require('util').promisify(fs.copyFile);
+
+const supportedViewsFromMem: (content: string) => Promise<SupportedViews> = (content: string): Promise<SupportedViews> => {
+ return new Promise((res, rej) => {
+ csv(content, {}, function(err: any, output: any) {
+ res({
+ tabular: {
+ columns: output[0],
+ rows: output.length - 1
+ }
+ });
+ });
+ });
+}
+
+const supportedViewsFromDsk: (path: string) => Promise<SupportedViews> = async(path: string): Promise<SupportedViews> => {
+ return supportedViewsFromMem((await readFile(path)).toString());
+}
+
+export const toCSV: (file: string, output: string, mimetype: string) => Promise<number> = async (file: string, output: string, mimetype: string): Promise<number> => {
+ logger.info(`xls convertor received new file to convert to csv: ${file}`);
+
+ await copy(file, `${file}.${extension(mimetype)}`);
+ let book: xlsx.WorkBook = xlsx.readFile(file);
+ fs.unlink(`${file}.${extension(mimetype)}`, (err) => {
+ if (err) {
+ logger.warn(err.toString());
+ }
+ });;
+
+ try {
+ await createFolder(output);
+ let noSheets: number = 0;
+
+ for (let name of book.SheetNames) {
+ await writeFile(`${output}/-${name}`, xlsx.utils.sheet_to_csv(book.Sheets[name]));
+ noSheets++;
+ }
+
+ rename(`${output}/-${book.SheetNames[0]}`, `${output}/_${book.SheetNames[0]}`)
+
+ return noSheets;
+ } catch (err) {
+ logger.failure(err);
+ return 0;
+ }
+}
+
+
+const buildSupportedView: (file: string ) => Promise<object> = async (file: string): Promise<object> => {
+ let shortFile:string = file.split('/')[file.split('/').length - 1]
+ let index: string = shortFile.substring(1, shortFile.length);
+ return {
+ firstSheet: shortFile.startsWith('_'),
+ name: index,
+ tabular: (await supportedViewsFromDsk(file)).tabular
+ }
+}
+
+export const buildSupportedViews: (inputFolder: string ) => Promise<SupportedViews> = async (inputFolder: string): Promise<SupportedViews> => {
+ let allSheets: string[] = await readDir(inputFolder);
+
+ let views: any = {}; views.items = [];
+
+ for (let file of allSheets) {
+ let view: any = await buildSupportedView(`${inputFolder}/${file}`);
+ views.items.push(view.name);
+ views[view.name] = view.tabular;
+ if (view.firstSheet) {
+ views.columns = view.tabular.columns;
+ views.rows = view.tabular.rows;
+ }
+ }
+ return views;
+}
+
+
+// const toAll: (file: string) =>
+// Promise<{csv: string, json: string, html: string}> =
+// async (file: string):
+// Promise<{csv: string, json: string, html: string}> => {
+// return {
+// csv: await toCSV(file).then(),
+// html: await toCSV(file).then()
+// }
+// }
+//
+
+
+
+// const main: () => Promise<void> = async (): Promise<void> => {
+// console.log(await toCSV('/cs/scratch/cjd24/t.xlsx'));
+// }
+// // try {
+// // let file: xlsx.WorkBook = xlsx.readFile(`${testDir}${testFile}`);
+// //
+// // for (let name of file.SheetNames) {
+// // fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.csv`, xlsx.utils.sheet_to_csv(file.Sheets[name]));
+// // logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as CSV.`);
+// // fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.json`, xlsx.utils.sheet_to_json(file.Sheets[name]));
+// // logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as json.`);
+// // fs.writeFileSync(`${testDir}${testFile.split('.')[0]}-${name}.html`, xlsx.utils.sheet_to_html(file.Sheets[name]));
+// // logger.info(`Wrote ${testFile.split('.')[1]} subsheet {${testFile} : ${name}} as HTML.`);
+// // }
+// //
+// // logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as CSV.`);
+// // logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as JSON.`);
+// // logger.success(`Wrote ${testFile.split('.')[1]} {${testFile}} as HTML.`);
+// // } catch (err) {
+// // // console.log(err);
+// // logger.error(err);
+// // }
+// // };
+// main().then();
diff --git a/src/conversion/czi/JxrDecApp b/src/conversion/czi/JxrDecApp
new file mode 100755
index 0000000..bc35f65
--- /dev/null
+++ b/src/conversion/czi/JxrDecApp
Binary files differ
diff --git a/src/conversion/czi/convertJxrs.py b/src/conversion/czi/convertJxrs.py
index d19a59a..f4b897f 100644
--- a/src/conversion/czi/convertJxrs.py
+++ b/src/conversion/czi/convertJxrs.py
@@ -8,14 +8,21 @@ coutner = 0
def convertjxrs(filename):
- global counter
- global totalFiles
- asTif = filename.rsplit('.',1)[0] + ".tif"
- check_call(['./JxrDecApp', "-i", filename, "-o", asTif])
- check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"])
- check_call(['rm', filename, asTif])
- counter += 1
- print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png")
+ global counter
+ global totalFiles
+ try:
+ asTif = filename.rsplit('.',1)[0] + ".tif"
+ check_call(['JxrDecApp', "-i", filename, "-o", asTif])
+ check_call(['convert', asTif, filename.rsplit('.',1)[0] + ".png"])
+ check_call(['rm', filename, asTif])
+ counter += 1
+ except Exception as help:
+ print ("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging.");
+ print ("Actual error was:");
+ print (help);
+ exit(0);
+
+ print (f"> Processed File: {counter}/{totalFiles} : {filename} --> {filename.rsplit('.',1)[0]}.png")
if __name__ == "__main__":
@@ -24,15 +31,15 @@ if __name__ == "__main__":
print("\nMissing Argument!\n\nUsage:\npython3 convertJxrs.py <DirectoryContainingJxrs>")
exit(0)
else:
- print("=========== BEGIN JXR CONVERSION ===========")
- print ('Files Dir: ' + argv[1] + '\n')
-
- filenames = glob(argv[1] + 'data-*.jxr')
- counter = 0
- totalFiles = len(filenames)
-
- pool = ThreadPoolExecutor(5)
- for f in pool.map(convertjxrs, filenames):
- pass
- pool.shutdown(True)
- print("=========== FINISH JXR CONVERSION ===========")
+ print("=========== BEGIN JXR CONVERSION ===========")
+ print ('Files Dir: ' + argv[1] + '\n')
+
+ filenames = glob(argv[1] + 'data-*.jxr')
+ counter = 0
+ totalFiles = len(filenames)
+
+ pool = ThreadPoolExecutor(5)
+ for f in pool.map(convertjxrs, filenames):
+ pass
+ pool.shutdown(True)
+ print("=========== FINISH JXR CONVERSION ===========")
diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts
index 127fce6..33bc738 100644
--- a/src/conversion/czi/czi.ts
+++ b/src/conversion/czi/czi.ts
@@ -1,95 +1,55 @@
-
+import { CZIHeightMap, CZITile,
+ WholeCZIHierarchy } from '../types/customPyramidIndex';
+import { Dimension, Segment } from '../types/cziBinaryTypings';
import * as fs from 'fs';
-import { logger } from '../../logger';
+import { SupportedViews, TileBounds, checkForOutputDirectories, writeJSONToFile, execpaths } from '../types/helpers';
+// import { logger } from '../../logger';
import * as sharp from 'sharp';
+// tslint:disable-next-line:no-duplicate-imports
import { SharpInstance } from 'sharp';
+import { isTileRelated, regionToExtract } from './tileExtraction';
import * as parsexml from 'xml-parser';
+import { uuid } from '../../uuid'
+
+const readFile = require('util').promisify(fs.readFile);
+const readdir = require('util').promisify(fs.readdir);
+const exists = require('util').promisify(fs.exists);
-const extractionDirectory: string = '/cs/scratch/cjd24/0701-extraction/';
-const outputImageDirectory: string = '/cs/scratch/cjd24/0701-extraction-processed2/';
-const tileOverlap: number = 0;
+// Various constants for placing files and defining tiles
+let extractDirectory: string = "";
+let outputImageData: string = "";
+let outputImageDirectory: string = "";
+const tileOverlap: number = 0; // Overlap is only half implemented
const tileSize: number = 1024;
const maxZoom: number = 64;
-
-interface Dimension {
- Dimension: string;
- Start: number;
- Size: number;
-}
-interface DirectoryEntry {
- DimensionCount: number;
- DimensionEntries: Dimension[];
-}
-interface SubBlock {
- DirectoryEntry: DirectoryEntry;
- Data: string;
-}
-interface Segment {
- Id: string;
- UsedSize: number;
- Data: SubBlock;
-}
-class TileBounds {
- public left!: number;
- public right!: number;
- public top!: number;
- public bottom!: number;
- public constructor(leftBound: number, rightBound: number, topBound: number, bottomBound: number) {
- this.left = leftBound;
- this.right = rightBound;
- this.top = topBound;
- this.bottom = bottomBound;
- }
-}
-interface SupportedViews {
- scalable_image: {
- width: number;
- height: number;
- channels: [
- {
- channel_id: string;
- channel_name: string;
- metadata?: {};
- }
- ];
- real_width?: {
- value: number;
- units: string;
- };
- real_height?: {
- value: number;
- units: string;
- };
- metadata?: {};
- };
-}
-interface CZITile {
- x_offset: number;
- y_offset: number;
- width: number;
- height: number;
- file: string;
-}
-interface CZIHeightMap {
- zoom_level: number;
- plane: CZITile[][];
-}
-interface WholeCZIHierarchy {
- c_values: [{
- channel_id: string,
- height_map: CZIHeightMap[];
- }];
-}
-
-const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBounds | null) {
+const shell = require('shelljs');
+const finalCZIJson: WholeCZIHierarchy = {
+ c_value_count: 0,
+ total_files: 0,
+ complete: false,
+ c_values: [],
+ zoom_level_count: 0
+};
+let dataBlocks: Segment[] = [];
+
+/**
+ * Simple function to find the tile bounds version of an original tile
+ * in the base image
+ */
+const getOriginalTileBounds: (originalTile: Segment) => TileBounds = (
+ originalTile: Segment
+): TileBounds => {
const bounds: TileBounds = new TileBounds(-1, -1, -1, -1);
+ // Loop over all dimensions to get the x and y
for (const dimension of originalTile.Data.DirectoryEntry.DimensionEntries) {
switch (dimension.Dimension) {
+ // If we have found x, then match the start and width
case 'X':
bounds.left = dimension.Start;
bounds.right = bounds.left + dimension.Size;
continue;
+ // If we have found y, then match the top and bottom
case 'Y':
bounds.top = dimension.Start;
bounds.bottom = bounds.top + dimension.Size;
@@ -99,87 +59,92 @@ const getOriginalTileBounds: Function = function(originalTile: Segment): (TileBo
}
}
- if (bounds.left < 0 || bounds.right < 0 || bounds.top < 0 || bounds.bottom < 0) {
- return null;
+ // If one of the bounds was not created, then there must have been an error
+ if (bounds.left < 0
+ || bounds.right < 0
+ || bounds.top < 0
+ || bounds.bottom < 0
+ ) {
+ throw new Error(
+ `One of the bounds had a dimension less than zero: ${originalTile.Data.Data}`
+ );
}
-
+ // Successful return
return bounds;
};
-const findRelatedTiles: Function = function(activeSegments: Segment[], desired: TileBounds): Segment[] {
+/**
+ * Function used to find which of the original base tiles are
+ * overlapping with the area of the to-be-created tile
+ */
+const findRelatedTiles: (activeSegments: Segment[], desired: TileBounds) =>
+ Segment[] = (
+ activeSegments: Segment[], desired: TileBounds
+): Segment[] => {
const relatedTiles: Segment[] = [];
+ // For all tiles within the region being checked
for (const baseTile of activeSegments) {
-
- let origCoords: TileBounds | null;
-
- if ((origCoords = getOriginalTileBounds(baseTile)) === null) {
- throw new Error('There was a Sad Boi error');
- }
-
- // Desired X on left is within current tile
- if (((desired.left >= origCoords.left) &&
- (desired.left < origCoords.right)) ||
-
- // Desired X on right is within the current tile
- ((desired.right > origCoords.left) &&
- (desired.right <= origCoords.right)) ||
-
- // Desired tile X overlaps base tile
- ((desired.left < origCoords.left) &&
- (desired.right > origCoords.right))) {
-
- // Desired Y on top is within current tile
- if (((desired.top >= origCoords.top) &&
- (desired.top < origCoords.bottom)) ||
-
- // Desired Y on right is within the current tile
- ((desired.bottom > origCoords.top) &&
- (desired.bottom <= origCoords.bottom)) ||
-
- // Desired tile Y overlaps whole base tile
- ((desired.top < origCoords.top) &&
- (desired.bottom > origCoords.bottom))) {
-
- relatedTiles.push(baseTile);
- }
+ if (isTileRelated(getOriginalTileBounds(baseTile), desired)) {
+ relatedTiles.push(baseTile);
}
}
return relatedTiles;
};
-const getDimension: Function = function(segment: Segment, name: string): Dimension {
+/**
+ * This gets the particular dimension from a segment given a segment
+ * and dimension ID
+ */
+const getDimension: (segment: Segment, name: string) => Dimension = (
+ segment: Segment, name: string
+): Dimension => {
for (const dimension of segment.Data.DirectoryEntry.DimensionEntries) {
+ // If the current dimension is the one we are looking for then return it.
if (dimension.Dimension === name) {
return dimension;
}
}
- throw new Error('Dimension: ' + name + " doesn't exist for segment: " + segment);
+ // If we have gotten to here, then the dimension doesnt exist, so throw error.
+ throw new Error(`Dimension: ${name} doesn't exist for segment: ${segment}`);
};
-const orderSegments: Function = function(segments: Segment[]): Segment[][] {
-
+/**
+ * This takes a selection of segments and ensures that they are ordered
+ * left to right, and top to bottom like the words in a book, so that the
+ * stiching process will take the correct slice from them all.
+ * (this is based on the pixel x-y coords of the segment.)
+ */
+const orderSegments: (segments: Segment[]) => Segment[][] = (
+ segments: Segment[]
+): Segment[][] => {
const output: Segment[][] = [];
+ // So long as there is at least 2 segments to order
if (segments.length > 1) {
let xCoords: number[] = [];
let yCoords: number[] = [];
// Get all x/y's;
+ // However also ensure that all of the segments to be ordered, all come
+ // From the same value of 'C' dimension, otherwise there could be overlaps.
const initC: number = getDimension(segments[0], 'C').Start;
for (const seg of segments) {
if (getDimension(seg, 'C').Start !== initC) {
- throw new Error('Segment array contains multiple values of C - this overlay is currently unsupported within this method');
+ throw new Error(`Segment array contains multiple values of C -\
+ this overlay is currently unsupported within this method`);
}
xCoords.push(getDimension(seg, 'X').Start);
yCoords.push(getDimension(seg, 'Y').Start);
}
- // Filter to get Uniaue Values
- xCoords = xCoords.filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
- yCoords = yCoords.filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
+
+ // Filter to get Unique Values
+ const filter: (item: number, index: number, array: number[]) => boolean = (
+ item: number, index: number, array: number[]
+ ): boolean => array.indexOf(item) === index;
+ xCoords = xCoords.filter(filter);
+ yCoords = yCoords.filter(filter);
// Use the filtered list to order the segments into rows
for (const yVal of yCoords) {
@@ -209,54 +174,52 @@ const orderSegments: Function = function(segments: Segment[]): Segment[][] {
// Return the result
return output;
- } else {
- output.push(segments);
- return output;
- }
-};
-
-const findRegionToExtract: Function = function(segment: Segment, desired: TileBounds): TileBounds {
- const baseBounds: TileBounds = getOriginalTileBounds(segment);
- const chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
-
- if (desired.left <= baseBounds.left) {
- chunkToExtract.left = 0;
- } else {
- chunkToExtract.left = desired.left - baseBounds.left;
- }
-
- if (desired.right >= baseBounds.right) {
- chunkToExtract.right = baseBounds.right - baseBounds.left;
- } else {
- chunkToExtract.right = desired.right - baseBounds.left;
}
- if (desired.top <= baseBounds.top) {
- chunkToExtract.top = 0;
- } else {
- chunkToExtract.top = desired.top - baseBounds.top;
- }
-
- if (desired.bottom >= baseBounds.bottom) {
- chunkToExtract.bottom = baseBounds.bottom - baseBounds.top;
- } else {
- chunkToExtract.bottom = desired.bottom - baseBounds.top;
- }
-
- return chunkToExtract;
+ // There is only one segment, so no need to re-order.
+ return [segments];
};
-const extractAndStitchChunks: Function = async function(segments: Segment[][], desiredRegion: TileBounds): Promise<SharpInstance> {
+/**
+ * Takes a base tile, and the whole bounds of a new tile, and uses this
+ * to calculate the region within the base tile that is overlapping the new tile
+ * to be extracted.
+ */
+const findRegionToExtract: (
+ segmanet: Segment, desired: TileBounds
+) => TileBounds = (
+ segment: Segment, desired: TileBounds
+): TileBounds => {
+ // Return the slice within the base tile for extraction
+ return regionToExtract(getOriginalTileBounds(segment), desired, 1);
+};
+/*
+ * Take an ordered selection of segments and cookie cutter out a tile from this
+ * into a new image
+ */
+ const extractAndStitchChunks: (
+ segments: Segment[][], desiredRegion: TileBounds
+ ) => Promise<SharpInstance> = async(
+ segments: Segment[][], desiredRegion: TileBounds
+ ): Promise<SharpInstance> => {
+
+ // Create a buffer for the rows part of raw image data
const tileVerticalBuffer: Buffer[] = [];
+ // For all ros (y coords) in the image
for (const segRow of segments) {
+ // Create a buffer for this row
const tileRow: Buffer[] = [];
let chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
+
+ // For all of the columns within this row
for (const segCol of segRow) {
+ // Find out the region of the base tile to be added to the new image
chunkToExtract = findRegionToExtract(segCol, desiredRegion);
- const data: Promise<Buffer> =
- sharp(`${extractionDirectory}${segCol.Data.Data}`)
+ // Extract this section of image data into a sharp buffer
+ let data: Promise<Buffer> =
+ sharp(`${extractDirectory}${segCol.Data.Data}`)
.extract({
left: chunkToExtract.left,
top: chunkToExtract.top,
@@ -265,162 +228,674 @@ const extractAndStitchChunks: Function = async function(segments: Segment[][], d
})
.toBuffer();
+ // Push this data into the row buffer
tileRow.push(await data);
}
+ // Prepare variables to squash all of the column data into one, for this row
let imageVerticalSlice: SharpInstance = sharp(tileRow[0]);
- const bufferBound = findRegionToExtract(segRow[0], desiredRegion);
+ const bufferBound: TileBounds = findRegionToExtract(segRow[0], desiredRegion);
+ // Check if the inital chunk needs to be extended to support the other columns
if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) {
- imageVerticalSlice = await imageVerticalSlice.extend(
- {top: 0, left: 0, bottom: 0, right: (tileSize - (bufferBound.right - bufferBound.left))});
+ imageVerticalSlice = await imageVerticalSlice.extend({
+ top: 0,
+ left: 0,
+ bottom: 0,
+ right: (tileSize - (bufferBound.right - bufferBound.left))
+ });
}
- for (let index = 1; index < segRow.length; index++) {
+ // For every column along this row, join it to the previous column data
+ for (let index: number = 1; index < segRow.length; index++) {
imageVerticalSlice = await imageVerticalSlice
- .overlayWith(tileRow[index],
- {top: 0, left: (bufferBound.right - bufferBound.left) + ((index - 1) * tileSize)});
+ .overlayWith(tileRow[index], {
+ top: 0,
+ left: (bufferBound.right - bufferBound.left)
+ + ((index - 1) * tileSize)
+ });
}
+ // Add this horizontal data buffer to the vertical buffer
tileVerticalBuffer.push(await imageVerticalSlice.toBuffer());
}
+ // Prepare variables used to combine all rows into one image
let finalImage: SharpInstance = sharp(tileVerticalBuffer[0]);
- const bufferBound = findRegionToExtract(segments[0][0], desiredRegion);
+ const bufferBound: TileBounds =
+ findRegionToExtract(segments[0][0], desiredRegion);
+ // Check if the inital row needs to be extended to support further rows
if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) {
- finalImage = await finalImage.extend(
- {top: 0, left: 0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0});
+ finalImage = await finalImage
+ .background({
+ r: 0,
+ g: 0,
+ b: 0,
+ alpha: 1
+ }).extend({
+ top: 0,
+ left: 0,
+ bottom: (tileSize - (bufferBound.bottom - bufferBound.top)),
+ right: 0
+ });
}
- for (let index = 1; index < segments.length; index++) {
+ // For all further rows in the image, combine it with the previous rows' data
+ for (let index: number = 1; index < segments.length; index++) {
finalImage = finalImage.overlayWith(
tileVerticalBuffer[index],
{top: getDimension(segments[index - 1][0], 'Y').Size, left: 0});
}
- return finalImage;
-};
+ // Return the finalised image.
+ if ((await finalImage.metadata()).channels != 4) {
+ return sharp(Buffer.alloc(tileSize, tileSize), {
+ create: {
+ width: tileSize,
+ height: tileSize,
+ channels: 4,
+ background: { r: 0, g: 0, b: 0, alpha: 1 }
+ }
+ }).overlayWith(await finalImage.toBuffer())
+ } else {
+ return finalImage;
+ }
+ // .toFile("/cs/home/cjd24/Documents/current/groupPractical/project-code/src/conversion/czi/test1.png");
+}
-//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Used to remove obtuse JSON data,
+ * where it is not needed in the SupportedView object
+ */
+const cleanSupportedViewObject: (obj: parsexml.Node[]) => object = (
+ obj: parsexml.Node[]
+): object => {
+ const newChild: any = {};
+ let hasAttr: boolean = false;
+ let hasChildren: boolean = false;
+ let hasContent: boolean = false;
+
+ // For all nodes in the json object
+ for (const node of obj) {
+
+ // Check if this node has attributes
+ hasAttr = (node.attributes !== undefined
+ && node.attributes !== null
+ && Object.keys(node.attributes).length !== 0
+ );
+ // Check for further children
+ hasChildren = (node.children !== undefined && node.children.length > 0);
+ // Check for simple content object
+ hasContent = (node.content !== undefined
+ && node.content !== null
+ && node.content !== '');
+
+ // If the Node has further children, then deal with this
+ if (hasChildren) {
+ let soloChildren: boolean = true;
+
+ // Check if this node just contains children, or its own data too
+ newChild[node.name] = {};
+ if (hasAttr) {
+ // If there are also attributes, then set this in the output
+ newChild[node.name].attributes = node.attributes;
+ soloChildren = false;
+ }
+ if (hasContent) {
+ // If there is also a 'content' then set this in the output
+ newChild[node.name].content = node.content;
+ soloChildren = false;
+ }
+ // If there are only chilren, then set this as this objects data
+ if (soloChildren) {
+ // Recursively call this function to clean up sub-children too.
+ newChild[node.name] = cleanSupportedViewObject(node.children);
+ } else {
+ // Otherwise, if there is also data, then add a children object
+ newChild[node.name].children = cleanSupportedViewObject(node.children);
+ }
+ } else if (hasAttr) {
+ newChild[node.name] = {};
-const dataBlocks: Segment[] = require(`${extractionDirectory}outputjson.json`).czi.filter(
- (s: Segment) => s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty');
-const inspect = require('util').inspect;
-const metaXML: parsexml.Document = parsexml(fs.readFileSync(`${extractionDirectory}FILE-META-1.xml`, 'utf8'));
+ // Check for content too, if so, add a discrete child for this.
+ if (hasContent) {
+ newChild[node.name].content = node.content;
+ }
+ /*
+ * Add the attributes as a sub child regardless,
+ * since it exists on this key.
+ */
+ newChild[node.name].attributes = node.attributes;
+ } else if (hasContent) {
+ newChild[node.name] = node.content;
+ }
+ }
-const supportedViews: SupportedViews = {scalable_image: {width: -1, height: -1, channels: [{channel_id: '-1', channel_name: ''}], metadata: metaXML}};
-supportedViews.scalable_image.channels.pop();
+ return newChild;
+};
+
+/**
+ * Clean up all vales of C within the JSON for supported views
+ */
+const cleanSupportedViews: (view: SupportedViews) => void = (
+ view: SupportedViews
+): void => {
+ if (!view.scalable_image) {
+ throw new Error("SupportedView.scalable_image does not exist where it should.");
+ }
+ for (const channel of view.scalable_image.channels) {
+ channel.metadata = cleanSupportedViewObject(
+ channel.metadata as parsexml.Node[]
+ );
+ }
+};
let totalSizeX: number = -1;
let totalSizeY: number = -1;
+const supportedViews: SupportedViews = {
+ scalable_image: {
+ width: -1,
+ height: -1,
+ channels: [{
+ channel_id: '-1',
+ channel_name: ''
+ }],
+ metadata: {}
+ }
+};
+if (!supportedViews.scalable_image) {
+ throw new Error("SupportedView.scalable_image does not exist where it should.");
+}
+supportedViews.scalable_image.channels.pop();
-// THE FOLLOWING FOR LOOP IS DISGUSTING AND I HATE IT, AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'(
-for (const child of metaXML.root.children) {
- if (child.name === 'Metadata') {
- for (const entry of child.children) {
- if (entry.name === 'Information') {
- for (const properties of entry.children) {
- if (properties.name === 'Image') {
- for (const property of properties.children) {
- if (property.name === 'SizeX' && property.content) {
- totalSizeX = Number.parseInt(property.content, 10);
- supportedViews.scalable_image.width = totalSizeX;
- continue;
- } else if (property.name === 'SizeY' && property.content) {
- totalSizeY = Number.parseInt(property.content, 10);
- supportedViews.scalable_image.height = totalSizeY;
- continue;
- } else if (property.name === 'Dimensions') {
- for (const chan of property.children) {
- if (chan.name === 'Channels') {
- for (const channel of chan.children) {
- supportedViews.scalable_image.channels.push(
- {
- channel_id: channel.attributes.Id.split(':')[1],
- channel_name: channel.attributes.Name,
- metadata: channel.children
- }
- );
- }
- }
+/* tslint:disable:curly cyclomatic-complexity */
+/*
+ * Function to parse the xml file from the original extraction from CZI,
+ * its nasty!
+ */
+const parseExtractedXML: (xmlFile: string) => void = async(
+ xmlFile: string
+): Promise<void> => {
+ const metaXML: parsexml.Document = parsexml(await readFile(xmlFile, 'utf8'));
+ // Parse the XML :(
+ // THE FOLLOWING 2 FOR LOOPS ARE DISGUSTING AND I HATE IT,
+ // AND I WISH I DIDNT WRITE IT BUT DON'T SEE ANY OTHER WAY TO DO IT LOL :'(
+ if (!supportedViews.scalable_image) {
+ throw new Error("SupportedView.scalable_image does not exist where it should.");
+ }
+ for (const child of metaXML.root.children) if (child.name === 'Metadata') {
+ for (const entry of child.children) if (entry.name === 'Information') {
+ for (const properties of entry.children) if (properties.name === 'Image') {
+ for (const property of properties.children) if (
+ property.name === 'SizeX' && property.content
+ ) {
+ totalSizeX = Number.parseInt(property.content, 10);
+ supportedViews.scalable_image.width = totalSizeX;
+ continue;
+ } else if (property.name === 'SizeY' && property.content) {
+ totalSizeY = Number.parseInt(property.content, 10);
+ supportedViews.scalable_image.height = totalSizeY;
+ continue;
+ } else if (property.name === 'Dimensions') {
+ for (const chan of property.children) if (chan.name === 'Channels') {
+ for (const channel of chan.children) {
+ supportedViews.scalable_image.channels.push({
+ channel_id: channel.attributes.Id.split(':')[1],
+ channel_name: channel.attributes.Name,
+ metadata: channel.children
+ });
+ }
+ }
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ }
+ for (const child of metaXML.root.children) if (child.name === 'Metadata') {
+ for (const entry of child.children) if (entry.name === 'Scaling') {
+ for (const properties of entry.children) if (properties.name === 'Items') {
+ for (const dist of properties.children) if (dist.name === 'Distance') {
+ switch (dist.attributes.Id) {
+ case 'X': {
+ supportedViews.scalable_image.real_width = {};
+ for (const attr of dist.children) {
+ if (attr.name === 'Value' && attr.content !== undefined) {
+ supportedViews.scalable_image.real_width.value =
+ Number.parseFloat(attr.content) * 1000000 * totalSizeX;
+ } else if (attr.name === 'DefaultUnitFormat') {
+ supportedViews.scalable_image.real_width.units = attr.content;
+ }
+ }
+ break;
+ }
+ case 'Y': {
+ supportedViews.scalable_image.real_height = {};
+ for (const attr of dist.children) {
+ if (attr.name === 'Value' && attr.content !== undefined) {
+ supportedViews.scalable_image.real_height.value =
+ Number.parseFloat(attr.content) * 1000000 * totalSizeY;
+ } else if (attr.name === 'DefaultUnitFormat') {
+ supportedViews.scalable_image.real_height.units = attr.content;
}
}
+ break;
}
}
}
+ break;
}
+ break;
}
+ break;
}
-}
+ supportedViews.scalable_image.metadata = metaXML;
+};
+/* tslint:enable:curly cyclomatic-complexity */
-// Get all values of X and Y respectively.
-const uniqueX: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'X').Start).filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
-const uniqueY: number[] = dataBlocks.map((x: Segment) => getDimension(x, 'Y').Start).filter(
- (item: number, index: number, array: number[]) => array.indexOf(item) === index);
-
-const uniqueTileSizes: number[][] = [];
-for (const seg of dataBlocks) {
-
- const x: number = getDimension(seg, 'X').Size;
- const y: number = getDimension(seg, 'Y').Size;
- let found: boolean = false;
- for (const dimPair of uniqueTileSizes) {
- if (x === dimPair[0] && y === dimPair[1]) {
- found = true;
- break;
+////////////////////////////////////////////////////////////////////////////////
+// Begin work on getting the new tiles all nice
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * This is used to create the next zoomed out tier of the given height map
+ */
+const zoomTier: (
+ previousHeightMap: CZIHeightMap, p: number, c: number
+) => Promise<CZIHeightMap> = async(
+ previousHeightMap: CZIHeightMap, p: number, c: number
+): Promise<CZIHeightMap> => {
+
+ const squashRow = async (previousPlane: CZITile[][], ys: number, p: number): Promise<CZITile[]> => {
+
+ const squashQuad = async (previousPlane: CZITile[][], ys: number, xs: number, p: number): Promise<CZITile> => {
+ if (await exists(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`) && (ys < previousPlane.length)) {
+ finalCZIJson.total_files++;
+ return {
+ x_offset: xs * tileSize,
+ y_offset: ys * tileSize,
+ width: tileSize,
+ height: tileSize,
+ file: `img-c${c}-p${p}-y${ys}-x${xs}.png`
+ };
+ }
+
+ // Combine 4 tiles into a new tile and scale down for this tier
+ // Top left
+ let quadrents:string = `${outputImageDirectory}${previousPlane[ys][xs].file} `;
+ let across:number = 1;
+ let quadrentCount: number = 1;
+
+ // Combine top right
+ const moreToRight: boolean = (xs + 1) < previousPlane[0].length;
+ if (moreToRight) {
+ quadrents += `${outputImageDirectory}${previousPlane[ys][xs + 1].file} `;
+ across++; quadrentCount++;
+ }
+ // Combine bottom left
+ const moreToBottom: boolean = (ys + 1) < previousPlane.length;
+ if (moreToBottom) {
+ quadrents += `${outputImageDirectory}${previousPlane[ys + 1][xs].file} `;
+ quadrentCount++;
+ }
+ // Combine bottom right
+ if (moreToBottom && moreToRight) {
+ quadrents += `${outputImageDirectory}${previousPlane[ys + 1][xs + 1].file} `;
+ }
+
+ let outputFileName: string =`${outputImageData}/tmp/${uuid.generate()}.png`;
+ shell.exec(`${execpaths} vips arrayjoin "${quadrents}" ${outputFileName} --across ${across}`, {silent: true});
+
+ // Rescale and push to file
+ if (quadrentCount !== 3) {
+
+ let extRight: number = 0, extBottom: number = 0;
+ if (moreToRight) {
+ extBottom = tileSize;
+ } else if (moreToBottom){
+ extRight = tileSize;
+ }
+
+ sharp(await sharp(outputFileName)
+ .background({r: 0, g: 0, b: 0, alpha: 1})
+ .extend({
+ top: 0, left: 0,
+ bottom: extBottom, right: extRight
+ }).toBuffer())
+ .resize(tileSize, tileSize)
+ .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
+ } else {
+ await sharp(outputFileName)
+ .resize(tileSize, tileSize)
+ .toFile(`${outputImageDirectory}img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`);
+ }
+ shell.exec(`rm ${outputFileName}`, {silent: true});
+
+ finalCZIJson.total_files++;
+ return {
+ x_offset: previousPlane[ys][xs].x_offset,
+ y_offset: previousPlane[ys][xs].y_offset,
+ width: previousPlane[ys][xs].width * 2,
+ height: previousPlane[ys][xs].height * 2,
+ file: `img-c${c}-p${p}-y${ys * tileSize}-x${xs * tileSize}.png`
+ };
}
+
+ const cziRow: Promise<CZITile>[] = [];
+ // For all columns within the previous plane
+ for (let xs: number = 0; xs < previousPlane[0].length; xs += 2) {
+ cziRow.push(squashQuad(previousPlane, ys, xs, p));
+ }
+
+ return await Promise.all(cziRow);
}
- if (!found) {
- uniqueTileSizes.push([x, y]);
+
+ const newZoomTier: CZIHeightMap = {
+ zoom_level: previousHeightMap.zoom_level * 2, plane: []
+ };
+
+ // Check the condition where another zoom level does not make sense
+ if (previousHeightMap.plane.length === 1
+ && previousHeightMap.plane[0].length === 1) {
+ console.log(
+ ' Task(1/1): ' +
+ 'Stage 100% complete. ' +
+ 'Stage was skipped as maximum sensible zoom level was reached.'
+ );
+ return previousHeightMap;
}
-}
-let filteredDataBlocks: Segment[] = [];
-const filterC: Function = function(to: number): void {
- filteredDataBlocks = dataBlocks.filter(
- (item: Segment, index: number, array: Segment[]) => getDimension(item, 'C').Start === to
- );
-};
+ const newplane: CZITile[][] = [];
+ // For all rows within the previous plane
+ for (let ys: number = 0; ys < previousHeightMap.plane.length; ys += 2) {
+ newplane.push(await squashRow(previousHeightMap.plane, ys, p));
+
+ console.log(
+ ` Task(${ys / 2 + 1}/${
+ Math.floor(previousHeightMap.plane.length / 2) + 1}): ` +
+ `Stage ${Math.ceil(((ys / previousHeightMap.plane.length)
+ * 100) * 100) / 100}% complete. `
+ );
+ }
-////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ newZoomTier.plane = newplane;
+ newZoomTier.tile_height_count = newZoomTier.plane.length;
+ newZoomTier.tile_width_count = newZoomTier.plane[0].length;
-// Begin work on getting the new tiles all nice
-// Print out all of the related tiles to every new tile to be created.
-let filecoutner: number = 0;
-async function extrapolateDimension(cVal: number, totalCs: number, maxZoomLevel: number): Promise<CZIHeightMap[]> {
- console.log(`Stage (${cVal + 1}/${totalCs}): Task(0/${Math.ceil(totalSizeY / tileSize)}): 0% complete.`);
- for (let ys: number = 0; ys < totalSizeY;) {
- let timing = process.hrtime();
- for (let xs: number = 0; xs < totalSizeX; xs += tileSize) {
- const desired = new TileBounds (
+ return newZoomTier;
+};
+
+/**
+ * Big boi function to build up the base tier of each value of c, then builds
+ * Our pre-computed pyramid of the rest of the zoom levels.
+ */
+const extrapolateDimension: (
+ cVal: number, totalCs: number, maxZoom: number
+) => Promise<CZIHeightMap[]> = async(
+ cVal: number, totalCs: number, maxZoom: number
+): Promise<CZIHeightMap[]> => {
+
+ const doOneRow = (ys: number, filteredDataBlocks: Segment[]): Promise<CZITile[]> => {
+
+ const doOneBaseTile = async(xs: number, ys: number, filteredDataBlocks: Segment[]): Promise<CZITile> => {
+ if (await exists(`${outputImageDirectory}img-c${cVal}-p0-y${ys}-x${xs}.png`) && (ys + tileSize < totalSizeY)) {
+ ///////////////////////////////////////////////////////////////////////////////////This if statement should be temporary??????????????????????????????????/
+ finalCZIJson.total_files++;
+ return {
+ x_offset: xs,
+ y_offset: ys,
+ width: tileSize,
+ height: tileSize,
+ file: `img-c${cVal}-p0-y${ys}-x${xs}.png`
+ };
+ }
+ const desired: TileBounds = new TileBounds(
xs - tileOverlap,
xs + tileSize + tileOverlap,
ys - tileOverlap,
ys + tileSize + tileOverlap
);
- filterC(cVal);
- // console.log(filteredDataBlocks.map((x: any) => x.Data.DirectoryEntry.DimensionEntries[2]));
- const sortedSegments: Segment[][] = orderSegments(findRelatedTiles(filteredDataBlocks, desired));
- (await extractAndStitchChunks(sortedSegments, desired)).toFile(`${outputImageDirectory}img-${filecoutner++}`);
+ const sortedSegments: Segment[][] =
+ orderSegments(findRelatedTiles(filteredDataBlocks, desired));
+
+ (await extractAndStitchChunks(sortedSegments, desired))
+ .toFile(`${outputImageDirectory}img-c${cVal}-p0-y${ys}-x${xs}.png`);
+
+ return {
+ x_offset: xs,
+ y_offset: ys,
+ width: tileSize,
+ height: tileSize,
+ file: `img-c${cVal}-p0-y${ys}-x${xs}.png`
+ };
}
- ys += tileSize;
- timing = process.hrtime(timing);
- console.log(`Stage (${cVal + 1}/${totalCs}): Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. (${timing[0]} sec/iter)`);
+
+ const rowPromises: Promise<CZITile>[] = [];
+
+ for (let xs: number = 0; xs < totalSizeX; xs += tileSize) {
+ rowPromises.push(doOneBaseTile(xs, ys, filteredDataBlocks));
+ finalCZIJson.total_files++;
+ }
+
+ return Promise.all(rowPromises);
}
- return [];
-}
-const finalCZIJson: WholeCZIHierarchy = {} as any;
-async function main(): Promise<void> {
- for (const cval of supportedViews.scalable_image.channels) {
- await extrapolateDimension(Number.parseInt(cval.channel_id, 10), supportedViews.scalable_image.channels.length, maxZoom).then((v) => {
- finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v});
- console.log(`Completed Tier: ${cval.channel_id}`);
+ const filteredDataBlocks: Segment[] = dataBlocks.filter(
+ (item: Segment, index: number, array: Segment[]) =>
+ getDimension(item, 'C').Start === cVal
+ );
+ // Begin output for the base tier
+ console.log('=========================================================');
+ console.log(`>> Beginning Dimension Extrapolation for \'C\' : ${cVal}`);
+ console.log('=========================================================');
+ console.log('>> Computing base tier, this will take a while...\n');
+ const baseCZIHeightMap: CZIHeightMap = {zoom_level: 1, plane: []};
+
+ console.log(`Stage (${cVal * Math.log2(maxZoom) + 1}/${totalCs}):`);
+ // For all rows within the total base pixel height
+ const plane: CZITile[][] = [];
+ for (let ys: number = 0; ys < totalSizeY; ys += tileSize) {
+ plane.push(await doOneRow(ys, filteredDataBlocks));
+
+ process.stdout.write("\r");
+ console.log(
+ ` Task(${ys / tileSize}/${Math.ceil(totalSizeY / tileSize)}): ` +
+ `Stage ${Math.ceil(((ys / totalSizeY) * 100) * 100) / 100}% complete. `
+ );
+ }
+ baseCZIHeightMap.plane = plane;
+ baseCZIHeightMap.tile_height_count = baseCZIHeightMap.plane.length;
+ baseCZIHeightMap.tile_width_count = baseCZIHeightMap.plane[0].length;
+
+ // BUILD UP THE HIGHER ZOOM LAYERS.
+ console.log(`>> Base tier complete for \'C\': ${cVal
+ }; Begin computing zoom tiers...\n`);
+
+ const retHeightMap: CZIHeightMap[] = [baseCZIHeightMap];
+ writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap);
+ for (let stage: number = 1; stage <= Math.log2(maxZoom); stage++) {
+ console.log(`Stage (${cVal * Math.log2(maxZoom) + 1 + stage}/${totalCs}):`);
+ await zoomTier(retHeightMap[stage - 1], stage, cVal)
+ .then((v: CZIHeightMap) => {
+ retHeightMap.push(v);
return;
- }, (err) => {
- console.error(err);
}
);
+ writeJSONToFile(`${outputImageData}/intermediate-stage-map.json`, retHeightMap);
+ }
+
+ console.log(`>> Completed Extrapolation for dimension, \'C\': ${cVal}\n\n`);
+ return retHeightMap;
+};
+
+
+/**
+ * used to write the supported views object to file both in total and "cleaned"
+ */
+const createSupportedViewsObject: () => void = async(): Promise<void> => {
+ dataBlocks = require(`${extractDirectory}outputjson.json`)
+ .czi.filter((s: Segment) =>
+ s.Id === 'ZISRAWSUBBLOCK' && s.Data.Data !== 'empty'
+ );
+ // Parse the xml
+ await parseExtractedXML(`${extractDirectory}FILE-META-1.xml`);
+
+ // Create the total supported Views object
+ // !!!!! This line was removed in order to reduce the output file size and
+ // !!!!! increase the usability by only giving the striped down version
+ // writeJSONToFile(`${outputImageData}/supported_views.json`, supportedViews);
+
+ // Cleanup and create "smart" supported views object without whole metadata
+ cleanSupportedViews(supportedViews);
+ if (!supportedViews.scalable_image) {
+ throw new Error("SupportedView.scalable_image does not exist where it should.");
+ }
+ supportedViews.scalable_image.metadata = {
+ tile_size: tileSize,
+ max_zoom: maxZoom,
+ tile_overlap: tileOverlap
+ };
+ writeJSONToFile(
+ `${outputImageData}/supported_views.json`, supportedViews);
+};
+
+/**
+ * Used to build up a pyramid for each value of c from the base images
+ */
+const buildCustomPyramids: () => Promise<boolean> = async(): Promise<boolean> => {
+ // Set some variables for errors and and percent counts
+ let errorOccurred: boolean = false;
+ finalCZIJson.zoom_level_count = Math.log2(maxZoom) + 1;
+
+ // For all channels in the base image
+ if (!supportedViews.scalable_image) {
+ throw new Error("SupportedView.scalable_image does not exist where it should.");
}
- fs.writeFile(`${outputImageDirectory}layout.json`, JSON.stringify(finalCZIJson), (err) => console.error(err));
+ for (const cval of supportedViews.scalable_image.channels) {
+
+ errorOccurred = false;
+ if (!errorOccurred) {
+ // Extract the base tiles and build up custom pyramid data
+ await extrapolateDimension(
+ Number.parseInt(cval.channel_id, 10),
+ supportedViews.scalable_image.channels.length * Math.log2(maxZoom * 2),
+ maxZoom
+ ).then((v: CZIHeightMap[]) => {
+ // On success, add the new heightmap to the final json data block
+ finalCZIJson.c_values.push({channel_id: cval.channel_id, height_map: v});
+ finalCZIJson.c_value_count++;
+ return;
+ }).catch((err: Error) => {
+ // On error, write the error to console and set an error true.
+ if (err) {
+ console.error(err.message);
+ }
+ errorOccurred = true;
+ }
+ );
+ } else {
+ console.error(`\nAn error occurred while extracting dimension: ${cval}`);
+ console.error('Skipping futher elements and moving to next dimension.\n\n');
+ }
+ // Write the final json data to file with most recent changes
+ writeJSONToFile(`${outputImageData}/layout.json`, finalCZIJson);
+ }
+ finalCZIJson.complete = true;
+ return errorOccurred;
+};
+
+const initialExtractAndConvert: (absFilePath: string, space: string) => Promise<void> = async (absFilePath: string, space: string): Promise<void> => {
+
+ outputImageData = space;
+ extractDirectory = outputImageData + "/extract/";
+ outputImageDirectory = outputImageData + "/data/";
+
+ checkForOutputDirectories([outputImageData, extractDirectory]);
+ console.log(">> This will complete at roughly 2GB/min");
+ shell.exec(`${execpaths} CZICrunch ${absFilePath} ${extractDirectory}`);
+
+ shell.exec(`${execpaths} python3 convertJxrs.py ${extractDirectory}`);
+
+ // let totalFiles: number = 0, counter: number = 0;
+ // console.log("=========== BEGIN JXR CONVERSION ===========")
+ //
+ // let filenames: string[] = (await readdir(extractDirectory)).filter((x: string) => x.endsWith(".jxr"));
+ // counter = 0
+ // totalFiles = filenames.length;
+ //
+ // const doOne: (n: number, file: string, asTif: string) => Promise<void> = async(n: number, file: string, asTif: string): Promise<void> => {
+ // shell.exec(`${execpaths} JxrDecApp -i ${file} -o ${asTif}`);
+ // shell.exec(`convert ${asTif} ${file.substring(0, file.lastIndexOf('.'))}.png`);
+ // shell.exec(`rm ${file} ${asTif}`);
+ // console.log (`> Processed File: ${n}/${totalFiles} : ${file} --> ${file.substring(0, file.lastIndexOf('.'))}.png`);
+ // }
+ //
+ // try {
+ // let promises: Promise<void>[] = [];
+ // for (let index: number = 0; index < filenames.length; index++) {
+ //
+ // if (promises.length < 30) {
+ // let file = extractDirectory + filenames[index];
+ // promises.push(doOne(counter++, file, file.substring(0, file.lastIndexOf('.')) + ".tif"));
+ // } else {
+ // index--;
+ // await Promise.all(promises);
+ // promises.length = 0;
+ // }
+ // }
+ // await Promise.all(promises);
+ // } catch (err) {
+ // console.log("Processing Failed. Probably couldn't find decoder due to invalid system environment path, check this before debugging. Actual Err:");
+ // console.error(err);
+ // }
+ // console.log("=========== FINISH JXR CONVERSION ===========")
}
-main();
+
+process.on("warning", (err: any) => console.warn(err))
+/**
+ * Main function used to call the rest of the relevant code to crunch a CZI
+ * extraction.
+ */
+export const main: (original: string, space:string) => Promise<void> = async (original: string, space:string): Promise<void> => {
+ console.log('\n');
+
+ try {
+ console.log('>> Extracting from CZI and Converting to PNG');
+ await initialExtractAndConvert(original, space);
+
+ console.log('\n>> Checking/Creating output directories...');
+ checkForOutputDirectories([outputImageDirectory, `${outputImageData}/tmp/`]);
+
+ console.log('\n>> Creating Supported Views and writing files...');
+ await createSupportedViewsObject();
+
+ console.log('\n');
+ if (await buildCustomPyramids()) {
+ console.log('>> Removing the initial extraction bloat');
+ shell.exec(`rm -rf ${outputImageData}/extract/`, { async: true })
+ };
+
+ console.log("\n>> Done");
+ } catch (Err) {
+ console.error("This was a really big boi error, and something is sad: ");
+ console.error(Err);
+ }
+};
+// main();
+
+// /* tslint:disable */
+// async function main2() {
+//
+// let layout: WholeCZIHierarchy = require(`${outputImageData}layout.json`);
+//
+// for (let stage:number = 1; stage < Math.sqrt(maxZoom); stage++) {
+// await zoomTier(layout.c_values[0].height_map[stage - 1])
+// .then((v: CZIHeightMap) =>
+// {
+// writeJSONToFile(`${outputImageData}stageMap-${stage}.json`, v);
+// return;
+// }
+// );
+// }
+// }
+//
+// main2().then().catch(e => console.log(e));
diff --git a/src/conversion/czi/cziConvert.sh b/src/conversion/czi/cziConvert.sh
index 639251c..dd664d5 100755
--- a/src/conversion/czi/cziConvert.sh
+++ b/src/conversion/czi/cziConvert.sh
@@ -1,8 +1,11 @@
#!/bin/sh
+FILENAME='2016_12_17__0701'
CZI_WORKING_DIR=${1:-"/cs/scratch"}
-CZI_EXTRACTION_DIR=${2:-"0701-extraction"}
-CZI_FILE=${3:-"2016_12_17__0701.czi"}
+CZI_EXTRACTION_DIR=${2:-${FILENAME}}
+CZI_FILE=${3:-${FILENAME}".czi"}
+
+echo "about to try to convert: " + ${CZI_WORKING_DIR}/${USER}/${CZI_FILE}
gcc -Wall -Wextra --pedantic -std=c99 cziconvert.c
mkdir -p ${CZI_WORKING_DIR}/${USER}/${CZI_EXTRACTION_DIR}
diff --git a/src/conversion/czi/cziconvert.c b/src/conversion/czi/cziconvert.c
index 85b925c..3024e7c 100644
--- a/src/conversion/czi/cziconvert.c
+++ b/src/conversion/czi/cziconvert.c
@@ -284,8 +284,8 @@ int functionRouter(FILE* imageFile, FILE* jsonOutput, long* fileOffset) {
int main(int argc, char* argv[]) {
//Check program input arguments.
- if (argc < 2 || argc > 4) {
- printf("Invalid number of arguments passed in.\nUsage:\n\n./prog <input file> <outputjson> <pythonJxrConvertor>\n\n");
+ if (argc < 2 || argc > 3) {
+ printf("Invalid number of arguments passed in.\nUsage:\n\n./prog <input file> <outputjson>\n\n");
exit(1);
}
@@ -340,15 +340,5 @@ int main(int argc, char* argv[]) {
fclose(jsonOutput);
printf("\n=========== FINISH CZI EXTRACTION ===========\n\n\n\n");
-
- //convert all the data's to jxr;
- char jxrLoc[200];
- sprintf(jxrLoc, "%s %s %s", "python3", argv[3], argv[2]);
- system(jxrLoc);
-
-
- //begin work on re-factoring the image structure into a "smooth" grid
-
-
return 0;
}
diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts
new file mode 100644
index 0000000..6b12409
--- /dev/null
+++ b/src/conversion/czi/pyramidWorker.ts
@@ -0,0 +1,93 @@
+import { WholeCZIHierarchy, CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex';
+import { TileBounds, execpaths } from '../types/helpers';
+import * as sharp from 'sharp';
+import { isTileRelated } from './tileExtraction';
+import { uuid } from '../../uuid'
+import * as fs from 'fs';
+import { RequestError } from '../../errors'
+const readFile = require('util').promisify(fs.readFile);
+
+const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBounds): CZITile[][] {
+
+ const relatedTiles: CZITile[][] = [];
+ for (const planeTileRow of plane.plane) {
+ let tileRow: CZITile[] = [];
+ let foundTiles: boolean = false;
+
+ for (const tile of planeTileRow) {
+
+ if (isTileRelated(
+ new TileBounds(
+ tile.x_offset,
+ tile.x_offset + tile.width,
+ tile.y_offset,
+ tile.y_offset + tile.height
+ ), desired)
+ ) {
+ tileRow.push(tile);
+ foundTiles = true;
+ }
+ }
+ if (foundTiles) {
+ relatedTiles.push(tileRow);
+ }
+ }
+ return relatedTiles;
+};
+
+export const getTile: Function = async function(imageDir: string, cVal: string, x:number = 0, y:number = 0, w:number = 1024, h:number = 1024, zoom: number = 1): Promise<Buffer> {
+ let layout: WholeCZIHierarchy = JSON.parse(await readFile(imageDir + "/layout.json", 'utf8'));
+
+ let bound: TileBounds = new TileBounds(x, x + w, y, y + h);
+ let map: CZIHeightMap;
+ try {
+ map = layout.c_values[Number(cVal)].height_map[Math.floor(Math.log2(zoom))]
+ } catch {
+ throw new RequestError(400, "bad_zoom_index")
+ }
+
+ return readFile((await getFinalTile(imageDir, map, cVal, bound)).file_path);
+}
+
+const getFinalTile: Function = async function(imageDir: string, imageTier: CZIHeightMap, cVal: string, desiredRegion: TileBounds): Promise<CZITileRequest> {
+
+ console.error("Has the calling function checked that the image has completed processing in WholeCZIHierarchy??");
+
+ let involvedTiles: string = '';
+ for (const row of imageTier.plane) {
+ for (const tile of row) {
+ involvedTiles += `${imageDir}/data/${tile.file} `
+ }
+ }
+
+ let outputFileName: string =`${imageDir}/tmp/${uuid.generate()}.png`
+ require('shelljs').exec(`${execpaths} vips arrayjoin "${involvedTiles}" ${outputFileName} --across ${imageTier.plane[0].length}`)
+
+ let extractionRegion = new TileBounds(
+ desiredRegion.left - imageTier.plane[0][0].width,
+ desiredRegion.right - imageTier.plane[0][0].width,
+ desiredRegion.top - imageTier.plane[0][0].height,
+ desiredRegion.bottom - imageTier.plane[0][0].height
+ );
+ extractionRegion.scaleDown(imageTier.zoom_level);
+
+ await sharp(outputFileName)
+ .extract({
+ top: extractionRegion.top,
+ left: extractionRegion.left,
+ width: extractionRegion.width(),
+ height: extractionRegion.height()
+ })
+ .toFile(outputFileName);
+
+ return {
+ dimensions: new TileBounds(
+ 0, extractionRegion.width(),
+ 0, extractionRegion.height()
+ ),
+ original_bounds: desiredRegion,
+ zoom_level: imageTier.zoom_level,
+ c_value: cVal,
+ file_path: outputFileName
+ };
+}
diff --git a/src/conversion/czi/tileDims.png b/src/conversion/czi/tileDims.png
new file mode 100644
index 0000000..70e2484
--- /dev/null
+++ b/src/conversion/czi/tileDims.png
Binary files differ
diff --git a/src/conversion/czi/tileExtraction.ts b/src/conversion/czi/tileExtraction.ts
new file mode 100644
index 0000000..83f63a5
--- /dev/null
+++ b/src/conversion/czi/tileExtraction.ts
@@ -0,0 +1,122 @@
+import { TileBounds } from '../types/helpers';
+
+export const isTileRelated: Function = function(origCoords: TileBounds, desired: TileBounds): boolean {
+
+ if (((desired.left >= origCoords.left) &&
+ (desired.left < origCoords.right)) ||
+
+ // Desired X on right is within the current tile
+ ((desired.right > origCoords.left) &&
+ (desired.right <= origCoords.right)) ||
+
+ // Desired tile X overlaps base tile
+ ((desired.left < origCoords.left) &&
+ (desired.right > origCoords.right))) {
+
+ // Desired Y on top is within current tile
+ if (((desired.top >= origCoords.top) &&
+ (desired.top < origCoords.bottom)) ||
+
+ // Desired Y on right is within the current tile
+ ((desired.bottom > origCoords.top) &&
+ (desired.bottom <= origCoords.bottom)) ||
+
+ // Desired tile Y overlaps whole base tile
+ ((desired.top < origCoords.top) &&
+ (desired.bottom > origCoords.bottom))) {
+
+ //If all of the if statements have passed, then this tile
+ //is part of the overlap for the new tile to be created.
+ return true;
+ }
+ }
+ return false;
+};
+
+/*
+ * Takes a base tile, and the whole bounds of a new tile, and uses this
+ * to calculate the region within the base tile that is overlapping the new tile
+ * to be extracted.
+ */
+export const regionToExtract: Function = function(baseBounds: TileBounds, desired: TileBounds, zoomLevel: number): TileBounds {
+
+ //get the base tile area and create an object for the chunk to extract
+ const chunkToExtract: TileBounds = new TileBounds(-1, -1, -1, -1);
+
+ // check if the new tile overlaps the leftmost boundary
+ if (desired.left <= baseBounds.left) {
+ chunkToExtract.left = 0;
+ } else {
+ chunkToExtract.left = desired.left - baseBounds.left;
+ }
+
+ // check if the new tile overlaps the rightmost boundary
+ if (desired.right >= baseBounds.right) {
+ chunkToExtract.right = baseBounds.right - baseBounds.left;
+ } else {
+ chunkToExtract.right = desired.right - baseBounds.left;
+ }
+
+ // check if the new tile overlaps the top boundary
+ if (desired.top <= baseBounds.top) {
+ chunkToExtract.top = 0;
+ } else {
+ chunkToExtract.top = desired.top - baseBounds.top;
+ }
+
+ // check if the new tile overlaps the bottom boundary
+ if (desired.bottom >= baseBounds.bottom) {
+ chunkToExtract.bottom = baseBounds.bottom - baseBounds.top;
+ } else {
+ chunkToExtract.bottom = desired.bottom - baseBounds.top;
+ }
+
+ if (chunkToExtract.left < 0 || chunkToExtract.right < 0 || chunkToExtract.top < 0 || chunkToExtract.bottom < 0) {
+ throw new Error('Chunk to extract from base tile has invalid bound (< 0).');
+ }
+
+ chunkToExtract.left = Math.ceil(chunkToExtract.left / zoomLevel);
+ chunkToExtract.right = Math.ceil(chunkToExtract.right / zoomLevel);
+ chunkToExtract.top = Math.ceil(chunkToExtract.top / zoomLevel);
+ chunkToExtract.bottom = Math.ceil(chunkToExtract.bottom / zoomLevel);
+
+ //return the slice within the base tile for extraction
+ return chunkToExtract;
+};
+
+// export const createHorizontalImageSlice: Function = async function (bufferBound: TileBounds, tileSize: number, tileOverlap: number, rowLength:number, row: Buffer[]): Promise<Buffer> {
+// //prepare variables to squash all of the column data into one, for this row
+// let imageVerticalSlice: SharpInstance = sharp(row[0]);
+// //check if the inital chunk needs to be extended to support the other columns
+// if ((bufferBound.right - bufferBound.left) < (tileSize - tileOverlap)) {
+// imageVerticalSlice = await imageVerticalSlice.background({r: 0, g: 0, b: 0, alpha: 0}).extend(
+// {top:0, left:0, bottom:0, right: (tileSize - (bufferBound.right - bufferBound.left))});
+// }
+// //for every column along this row, join it to the previous column data
+// for (let index = 1; index < rowLength; index++) {
+// imageVerticalSlice = await imageVerticalSlice
+// .overlayWith(row[index],
+// {top: 0, left: (bufferBound.right - bufferBound.left) + ((index -1) * tileSize)});
+// }
+// return imageVerticalSlice.toBuffer();
+// }
+//
+//
+// export const createImageFromHorizontalSlices: Function = async function(bufferBound: TileBounds, horizontalSlices: Buffer[], tileSize: number, tileOverlap: number, rowCount: number, tiles: CZITile[][]): Promise<SharpInstance> {
+// //prepare variables used to combine all rows into one image
+// let finalImage: SharpInstance = sharp(horizontalSlices[0]);
+//
+// //Check if the inital row needs to be extended to support further rows
+// if ((bufferBound.bottom - bufferBound.top) < (tileSize - tileOverlap)) {
+// finalImage = await finalImage.background({r: 0, g: 0, b: 0, alpha: 0}).extend(
+// {top:0, left:0, bottom: (tileSize - (bufferBound.bottom - bufferBound.top)), right: 0});
+// }
+// //For all further rows in the image, combine it with the previous rows' data
+// for (let index = 1; index < rowCount; index++) {
+// finalImage = finalImage.overlayWith(
+// horizontalSlices[index],
+// {top: tiles[index - 1][0].height, left: 0});
+// }
+//
+// return finalImage;
+// }
diff --git a/src/conversion/leica/requestconvertor.ts b/src/conversion/leica/requestconvertor.ts
new file mode 100644
index 0000000..50002d7
--- /dev/null
+++ b/src/conversion/leica/requestconvertor.ts
@@ -0,0 +1 @@
+import { logger } from '../../logger';
diff --git a/src/conversion/leica/scn.ts b/src/conversion/leica/scn.ts
new file mode 100644
index 0000000..5d75cb3
--- /dev/null
+++ b/src/conversion/leica/scn.ts
@@ -0,0 +1,95 @@
+import * as fs from 'fs';
+import * as sharp from 'sharp';
+// tslint:disable-next-line:no-duplicate-imports
+import { SharpInstance } from 'sharp';
+import { SupportedViews, TileBounds, writeJSONToFile, checkForOutputDirectories, execpaths } from '../types/helpers';
+import { uuid } from '../../uuid'
+import { logger } from '../../logger';
+
+// CHANGE ME FOR TESTING!!!!!
+const input: string = "diseessse1.scn"
+const baseDirname: string = '/cs/scratch/cjd24/tifers/';
+
+
+
+// Various constants for placing files and defining tiles
+const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`;
+
+const tileOverlap: number = 0; // Overlap is only half implemented
+const tileSize: number = 512;
+
+
+const crunchLeica: () => Promise<string> = async (): Promise<string> => {
+
+ try {
+ let output: string =`${baseDirname}${uuid.generate()}/`;
+ let leica: SharpInstance = sharp(baseDirname + input).png();
+ logger.debug("Read new sharp instance for lecia: " + input);
+
+ checkForOutputDirectories([output]);
+ logger.info("Creating new output directory for LECIA > DZI @ " + output);
+
+ let meta: sharp.Metadata = await leica.metadata();
+
+ let width: number = -1;
+ let height: number = -1;
+ if (meta.width !== undefined) {
+ width = meta.width;
+ }
+ if (meta.height !== undefined) {
+ height = meta.height;
+ }
+
+ let supportedViews: SupportedViews = {
+ scalable_image: {
+ width: width,
+ height: height,
+ channels:
+ [{
+ channel_id: '-1',
+ channel_name: '-1',
+ metadata: {}
+ }],
+ metadata: {
+ tile_size: tileSize,
+ max_zoom: "Not yet supported in this version of convertor",
+ tile_overlap: tileOverlap,
+ exif: meta.exif
+ }
+ }
+ }
+
+ let channels: any = [];
+ if (meta.channels !== undefined) {
+ for (let index: number = 0; index < meta.channels; index++) {
+ channels.push({
+ channel_id: `${index}`,
+ channel_name: `${meta.space}`,
+ metadata: {}
+ })
+ }
+ supportedViews.scalable_image.channels = channels;
+ }
+
+ writeJSONToFile(`${output}supported_views.json`, supportedViews)
+ logger.info("Wrote supported_views object for: " + output);
+
+ await sharp(baseDirname + input)
+ .png()
+ .tile({
+ size: tileSize,
+ overlap: tileOverlap,
+ layout: "dz"
+ })
+ .toFile(`${output}output`);
+ logger.success(`Finalised output of ${input} as .dzi`);
+ return `${output}output.dzi`;
+ }
+ catch (err) {
+ logger.failure(`Lecia conversion failed with error: ${err}`)
+ return `Lecia conversion failed with error: ${err}`;
+ }
+};
+
+
+crunchLeica().then((ret:string) => console.log(ret));
diff --git a/src/conversion/types/customPyramidIndex.ts b/src/conversion/types/customPyramidIndex.ts
new file mode 100644
index 0000000..3c367b7
--- /dev/null
+++ b/src/conversion/types/customPyramidIndex.ts
@@ -0,0 +1,37 @@
+import { TileBounds } from './helpers'
+
+//The following are interfaces for the Custom object storing Information
+//about the CUSTOM pyramid being created for this image
+export interface CZITile {
+ x_offset: number;
+ y_offset: number;
+ width: number;
+ height: number;
+ file: string;
+}
+
+export interface CZIHeightMap {
+ zoom_level: number;
+ tile_width_count?: number;
+ tile_height_count?: number;
+ plane: CZITile[][];
+}
+
+export interface WholeCZIHierarchy {
+ c_value_count: number;
+ zoom_level_count: number;
+ total_files: number;
+ complete: boolean;
+ c_values: {
+ channel_id: string,
+ height_map: CZIHeightMap[];
+ }[];
+}
+
+export interface CZITileRequest {
+ dimensions: TileBounds,
+ original_bounds: TileBounds,
+ zoom_level: number,
+ c_value: string,
+ file_path: string
+}
diff --git a/src/conversion/types/cziBinaryTypings.ts b/src/conversion/types/cziBinaryTypings.ts
new file mode 100644
index 0000000..a78b4e9
--- /dev/null
+++ b/src/conversion/types/cziBinaryTypings.ts
@@ -0,0 +1,23 @@
+//Interfaces used to define the tiles incoming from the CZI extraction
+
+export interface Dimension {
+ Dimension: string;
+ Start: number;
+ Size: number;
+}
+
+export interface DirectoryEntry {
+ DimensionCount: number;
+ DimensionEntries: Dimension[];
+}
+
+export interface SubBlock {
+ DirectoryEntry: DirectoryEntry;
+ Data: string;
+}
+
+export interface Segment {
+ Id: string;
+ UsedSize: number;
+ Data: SubBlock;
+}
diff --git a/src/conversion/types/helpers.ts b/src/conversion/types/helpers.ts
new file mode 100644
index 0000000..bb10e58
--- /dev/null
+++ b/src/conversion/types/helpers.ts
@@ -0,0 +1,106 @@
+import * as fs from 'fs';
+import { Node } from 'xml-parser';
+
+/**
+ * Interface used to define the structure of the "supportedViews" section
+ * of the protocol specification for scalable images
+ */
+export interface SupportedViews {
+ scalable_image?: {
+ width: number;
+ height: number;
+ channels:
+ {
+ channel_id: string;
+ channel_name: string;
+ metadata?: {};
+ }[];
+ real_width?: {
+ value?: number;
+ units?: string;
+ };
+ real_height?: {
+ value?: number;
+ units?: string;
+ };
+ metadata?: {};
+ };
+ tabular?: {
+ columns: string[];
+ rows: number;
+ }
+}
+
+/**
+ * Interface used to define the pixel-bounds of a 'section' within the image
+ */
+export class TileBounds {
+ public left: number;
+ public right: number;
+ public top: number;
+ public bottom: number;
+ public constructor(
+ leftBound: number,
+ rightBound: number,
+ topBound: number,
+ bottomBound: number
+ ) {
+ this.left = leftBound;
+ this.right = rightBound;
+ this.top = topBound;
+ this.bottom = bottomBound;
+ }
+ public width(): number {
+ return this.right - this.left;
+ }
+ public height(): number {
+ return this.bottom - this.top;
+ }
+ public scaleDown(level: number) {
+ this.left = Math.ceil(this.left / level),
+ this.right = Math.ceil(this.right / level),
+ this.top = Math.ceil(this.top / level),
+ this.bottom = Math.ceil(this.bottom / level)
+ }
+ public scaleUp(level: number) {
+ this.left = Math.floor(this.left * level),
+ this.right = Math.ceil(this.right * level),
+ this.top = Math.ceil(this.top * level),
+ this.bottom = Math.ceil(this.bottom * level)
+ }
+}
+
+
+
+/**
+ * function used to ensure that the directories required have been created
+ */
+export const checkForOutputDirectories: (directories: string[]) => void = (
+ directories: string[]
+): void => {
+ for (const dir of directories) {
+ if (!fs.existsSync(`${dir}`)) {
+ fs.mkdirSync(`${dir}`);
+ }
+ }
+};
+
+/**
+ * Write given JSON object to given filepath
+ */
+export const writeJSONToFile: (filePath: string, obj: object) =>
+ void = (filePath: string, obj: object): void => {
+ fs.writeFile(
+ filePath,
+ JSON.stringify(obj, null, 2),
+ (err: Error) => {
+ if (err) {
+ console.error(err.message);
+ throw err;
+ }
+ }
+ );
+ };
+
+const extensionBinariesDir: string = __dirname + `/../../../ext/bin/`;
+export const execpaths: string = `PATH="$PATH:${extensionBinariesDir}" LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${extensionBinariesDir}../lib/" `;
diff --git a/src/cors/index.d.ts b/src/cors/index.d.ts
index 81da9d4..d6e651a 100644
--- a/src/cors/index.d.ts
+++ b/src/cors/index.d.ts
@@ -1,3 +1,15 @@
import { NextFunction, Request, Response } from 'express';
-export const cors: () => (req: Request, res: Response, next: NextFunction) =>
- void;
+
+export interface CORSOptions {
+ origins?: string[] | Function;
+ methods?: string[];
+ requestHeaders?: string[];
+ responseHeaders?: string[];
+ supportsCredentials?: boolean;
+ maxAge?: number;
+ endPreflightRequests?: boolean;
+}
+
+export const cors: () =>
+ (req: Request, res: Response, next: NextFunction) =>
+ void;
diff --git a/src/cors/index.js b/src/cors/index.js
index 96ffa61..7e21093 100644
--- a/src/cors/index.js
+++ b/src/cors/index.js
@@ -1,2 +1,8 @@
-const cors = require('corser').create;
+const corser = require('corser');
+const cors = corser.create.bind(null, {
+ requestHeaders: corser.simpleRequestHeaders.concat([
+ 'Authorisation',
+ 'Authorization'
+ ])
+});
module.exports = { cors: cors };
diff --git a/src/db/.DS_Store b/src/db/.DS_Store
new file mode 100644
index 0000000..6a62f95
--- /dev/null
+++ b/src/db/.DS_Store
Binary files differ
diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts
index d3a5867..da7243d 100644
--- a/src/db/model/ContributorGroup.ts
+++ b/src/db/model/ContributorGroup.ts
@@ -1,12 +1,16 @@
-import { AllowNull, Column, DataType, HasMany, Model, Table
+import { AllowNull, Column, DataType, HasMany, Model, PrimaryKey, Table
} from 'sequelize-typescript';
import { default as UserJoinsProject } from './UserJoinsProject';
@Table
export default class ContributorGroup extends Model<ContributorGroup> {
- @AllowNull
+ @PrimaryKey
@Column(DataType.TEXT)
- public name!: string | null;
+ public name!: string;
+
+ // @PrimaryKey
+ // @Column
+ // public username!: string;
/* "Error: Foreign key for "ContributorGroup"
* is missing on "UserJoinsProject"." */
@@ -31,6 +35,9 @@ export default class ContributorGroup extends Model<ContributorGroup> {
@Column
public canEditUserPermissions!: boolean;
+ @Column
+ public canDeleteProject!: boolean;
+
@AllowNull
@Column(DataType.TEXT)
public description!: string | null;
diff --git a/src/db/model/File.ts b/src/db/model/File.ts
index 8a12431..95031e4 100644
--- a/src/db/model/File.ts
+++ b/src/db/model/File.ts
@@ -3,7 +3,9 @@ import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, HasMany,
HasOne, Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript';
import { default as User } from './User';
-import { FileTypeName, mimes } from '../../files';
+import { RequestError } from '../../errors';
+import { FileTypeName, INITIAL_METADATA, Metadata, mimes } from '../../files';
+import { match, metadata } from '../../matcher';
/*
* attributes:
@@ -11,7 +13,6 @@ import { FileTypeName, mimes } from '../../files';
* - fullPathInternal
* - uuid
* - type
- * - size
* - parentFolderId
* - containedFilesInternal
* - creatorName
@@ -31,7 +32,7 @@ export default class File extends Model<File> {
@AllowNull
@Column
- private fullPathInternal!: string;
+ public fullPathInternal!: string;
@PrimaryKey
@Column
@@ -40,9 +41,6 @@ export default class File extends Model<File> {
@Column(DataType.TEXT)
public type!: FileTypeName;
- @Column
- public size!: number;
-
@ForeignKey(() => File)
@AllowNull
@Column(DataType.TEXT)
@@ -77,6 +75,9 @@ export default class File extends Model<File> {
public status!: string;
@Column
+ public originalMimetype!: string;
+
+ @Column
private metadataInternal!: string;
public get name(): string {
@@ -117,15 +118,28 @@ export default class File extends Model<File> {
this.containedFilesInternal = files;
}
- public get metadata(): object {
- return JSON.parse(this.metadataInternal);
+ public get metadata(): Metadata {
+ return !!(this.metadataInternal) ? JSON.parse(this.metadataInternal)
+ : INITIAL_METADATA;
}
- public set metadata(metadata: object) {
- this.metadataInternal = JSON.stringify(metadata);
+ public set metadata(md: Metadata) {
+ const oldMD: Metadata = this.metadata;
+ const newMD: Metadata = md;
+ if (!match(metadata, newMD)) {
+ throw new RequestError(400, 'invalid_request');
+ }
+ 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) {
+ this.originalMimetype = mime;
this.type = mimes.get(mime) || 'generic';
}
}
diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts
index 6cda34e..7b30d56 100644
--- a/src/db/model/Project.ts
+++ b/src/db/model/Project.ts
@@ -1,5 +1,6 @@
import { default as ContributorGroup } from './ContributorGroup';
import { default as File } from './File';
+import { NotVoid } from 'lodash';
import { BelongsTo, BelongsToMany, Column, CreatedAt, DataType, ForeignKey,
Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript';
import { default as User } from './User';
@@ -92,30 +93,99 @@ export default class Project extends Model<Project> {
return;
}
- public getAccessLevel(user: User): ContributorGroup {
- throw new Error(`unimplemented, ${this}`);
+ public async hasAccessLevel(user: User, accessLevel: string): Promise<boolean> {
+ const ujps: UserJoinsProject[] | null = await UserJoinsProject.findAll({
+ include: [ ContributorGroup],
+ where: {
+ username: user.username,
+ projectName: this.name
+ }
+ });
+ if (ujps != null) {
+ const adders: ContributorGroup[] = await ujps.map((ujp: UserJoinsProject): ContributorGroup => {
+ if (ujp.contributorGroup != null) {
+ return ujp.contributorGroup;
+ } else {
+ throw new Error('Missing contributor group');
+ }
+ });
+ if (adders.some((cg: ContributorGroup): boolean => cg.name == accessLevel)) {
+ return true;
+ }
+
+ switch (accessLevel) {
+ case 'canCreateFiles':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canCreateFiles
+ );
+ case 'canDeleteFiles':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canDeleteFiles
+ );
+ case 'canViewFiles':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canViewFiles
+ );
+ case 'canAddUsers':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canAddUsers
+ );
+ case 'canRemoveUsers':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canRemoveUsers
+ );
+ case 'canEditUserPermissions':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canEditUserPermissions
+ );
+ case 'canDeleteProject':
+ return adders.some(
+ (cg: ContributorGroup): boolean => cg.canDeleteProject
+ );
+ default:
+ throw new Error('invalid access role');
+ }
+ } else {
+ return(false);
+ }
+ }
+
+ public async getAccessLevel(user: User): Promise<String[]> {
+ const ujps: UserJoinsProject[] | null = await UserJoinsProject.findAll({
+ include: [ ContributorGroup],
+ where: {
+ username: user.username,
+ projectName: this.name
+ }
+ });
+ const listContributors: String[] = await ujps.map((ujp: UserJoinsProject): String => {
+ if (ujp.contributorGroup != undefined) {
+ return ujp.contributorGroupName;
+ } else {
+ throw new Error('Invalid access');
+ }
+ });
+ return listContributors;
}
- public getUserInfo(user: User): UserInfo {
+ public async getUserInfo(user: User): Promise<UserInfo> {
return {
username: user.username,
- access_level: this.getAccessLevel(user)
- .toString()
+ access_level: (await this.getAccessLevel(user)).join()
};
}
- public get fullInfo(): ProjectFullInfo {
+ public async getFullInfo(): Promise<ProjectFullInfo> {
if (this.contributors === undefined) {
throw new Error('contributors undefined');
}
return {
project_name: this.name,
- users: this.contributors
- .map((u: User): UserInfo => this.getUserInfo(u)),
+ users: await Promise.all(this.contributors
+ .map( (u: User): Promise<UserInfo> => this.getUserInfo(u))),
public_metadata: {
creation_date: this.creationDate
},
- // TODO: Check if we have anything to use these for yet?
private_metadata: {},
admin_metadata: {}
};
diff --git a/src/db/model/User.ts b/src/db/model/User.ts
index 76e055d..3c0abe2 100644
--- a/src/db/model/User.ts
+++ b/src/db/model/User.ts
@@ -1,3 +1,4 @@
+import { RequestError } from '../../errors/errorware';
import { default as File } from './File';
import { default as Project } from './Project';
import { BelongsToMany, Column, CreatedAt, DataType, HasMany,
@@ -6,6 +7,9 @@ import { default as UserGroup } from './UserGroup';
import { default as UserHasPrivilege } from './UserHasPrivilege';
import { default as UserJoinsProject } from './UserJoinsProject';
+import ContributorGroup from './ContributorGroup';
+import { truncateFile } from '../../files';
+
@Table
export default class User extends Model<User> {
@PrimaryKey
@@ -13,7 +17,7 @@ export default class User extends Model<User> {
public username!: string;
@Column
- private readonly passwordInternal!: string;
+ private passwordInternal!: string;
@BelongsToMany(() => UserGroup, () => UserHasPrivilege)
public userGroups?: UserGroup[];
@@ -104,28 +108,59 @@ export default class User extends Model<User> {
return;
}
- // TODO implement
- public getAccessLevel(project: Project): string {
- throw new Error(`unimplemented, ${this}`);
- }
-
public hasPrivilege(privilege: string): boolean {
if (this.userGroups === undefined) {
throw new Error('usergroups undefined');
}
- return this.userGroups.some(
- (ug: UserGroup): boolean => ug.name === privilege
- );
+ if (this.userGroups.some((ug: UserGroup): boolean => ug.name == privilege)) {
+ return true;
+ }
+ switch (privilege) {
+ case 'canCreateUsers':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canCreateUsers
+ );
+ case 'canDeleteUsers':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canDeleteUsers
+ );
+ case 'canEditUsers':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canEditUsers
+ );
+ case 'canCreateProjects':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canCreateProjects
+ );
+ case 'canDeleteProjects':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canDeleteProjects
+ );
+ case 'canEditProjects':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canEditProjects
+ );
+ case 'canAccessLogs':
+ return this.userGroups.some(
+ (ug: UserGroup): boolean => ug.canAccessLogs
+ );
+ default:
+ throw new Error('privilege undefined');
+ }
+ }
+
+ public async getAccessLevel(project: Project): Promise<string> {
+ return (await project.getAccessLevel(this)).join();
}
- public getProjectInfo(project: Project): ProjectInfo {
+ public async getProjectInfo(project: Project): Promise<ProjectInfo> {
return {
project_name: project.name,
- access_level: this.getAccessLevel(project)
+ access_level: await this.getAccessLevel(project)
};
}
- public get fullInfo(): UserFullInfo {
+ public async getFullInfo(): Promise<UserFullInfo> {
// FIXME: Fetch these things if they aren't already present
if (this.userGroups === undefined) {
this.userGroups = [];
@@ -137,8 +172,8 @@ export default class User extends Model<User> {
privileges: this.userGroups
.filter((ug: UserGroup): boolean => ug.name !== null)
.map((ug: UserGroup): string => ug.name as string),
- projects : this.projects!.map(
- (p: Project): ProjectInfo => this.getProjectInfo(p)
+ projects : await Promise.all( this.projects!.map(
+ (p: Project): Promise<ProjectInfo> => this.getProjectInfo(p))
),
// TODO: Check if we have anything to use these for yet?
public_user_metadata: {},
@@ -154,15 +189,17 @@ export default class User extends Model<User> {
private_user_metadata?: Metadata;
}): void {
if (newInfo.password !== undefined) {
- if (this.authenticate(newInfo.password.old)) {
- this.password = newInfo.password.new;
+ if (!this.authenticate(newInfo.password.old)) {
+ this.passwordInternal = newInfo.password.new;
+ } else {
+ throw new RequestError(400, 'invalid_password');
}
}
}
public authenticate(password: string): boolean {
// TODO use salting (and maybe even constant-time comparison?)
- return password === this.password;
+ return password === this.passwordInternal;
}
public get password(): string {
@@ -171,7 +208,7 @@ export default class User extends Model<User> {
public set password(newPassword: string) {
// TODO use salting
- this.password = newPassword;
+ this.passwordInternal = newPassword;
}
}
diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts
index 0948517..c2aa33a 100644
--- a/src/db/model/UserJoinsProject.ts
+++ b/src/db/model/UserJoinsProject.ts
@@ -1,8 +1,8 @@
+import { default as ContributorGroup } from './ContributorGroup';
import { default as Project } from './Project';
import { BelongsTo, Column, CreatedAt, DataType, ForeignKey, Model, Table
} from 'sequelize-typescript';
import { default as User } from './User';
-import { default as ContributorGroup } from './UserGroup';
@Table
export default class UserJoinsProject extends Model<UserJoinsProject> {
@@ -14,14 +14,14 @@ export default class UserJoinsProject extends Model<UserJoinsProject> {
@Column
public projectName!: string;
+ @ForeignKey(() => ContributorGroup)
+ @Column
+ public contributorGroupName!: string;
+
@CreatedAt
@Column(DataType.DATE)
public joinDate!: Date;
- @ForeignKey(() => ContributorGroup)
- @Column
- public contributorGroupId!: number;
-
@BelongsTo(() => ContributorGroup)
public contributorGroup?: ContributorGroup;
}
diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts
index 6d87bcb..e2b5610 100644
--- a/src/errors/errorware.ts
+++ b/src/errors/errorware.ts
@@ -1,5 +1,7 @@
import { NextFunction, Request, Response } from 'express';
+import { logger } from '../logger';
+
/**
* General error and error-handling logic for the middleware stack.
*/
@@ -115,10 +117,11 @@ export type Errorware =
export const errorHandler: Errorware = (
err: Error, req: Request, res: Response, next: NextFunction
): void => {
+ logger.failure(`Responded to ${req.ip}`);
if (RequestError.is(err)) {
res.status(err.code)
.json(err.responseBlock());
} else {
- res.send(err);
+ res.status(500).send(err.stack);
}
};
diff --git a/src/files.ts b/src/files.ts
index e87d8da..19862d1 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -2,19 +2,41 @@ import { Request, Response } from 'express';
import * as fs from 'fs-extra';
import { logger } from './logger';
import * as Multer from 'multer';
-
+import * as stream from 'stream';
+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';
+import { uuid } from './uuid';
+import { main as CZICrunch } from './conversion/czi/czi'
+import { getTile } from './conversion/czi/pyramidWorker'
+import { RequestError } from './errors';
+import { toCSV as excelToCSV, buildSupportedViews } from './conversion/csv/excel';
+const readDir = require('util').promisify(fs.readdir);
+const readFile = require('util').promisify(fs.readFile);
+
-const CONTENT_BASE_DIRECTORY: string = './files';
-const LOG_BASE_DIRECTORY: string = './logs';
+const BASE_BASE: string = '/cs/scratch/cjd24/'
+const CONTENT_BASE_DIRECTORY: string = BASE_BASE + 'files';
+const LOG_BASE_DIRECTORY: string = BASE_BASE + 'logs';
+const TEMP_BASE_DIRECTORY: string = BASE_BASE + '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: {}
};
-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));
};
@@ -23,70 +45,143 @@ 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 => {
+interface TabularParameters {
+ rowstart: number;
+ rowcount: number;
+ cols: string[];
+}
+
+interface FileUploadParameters {
+ truncate: boolean;
+ overwrite: boolean;
+ offset: number;
+ action: 'set_metadata'
+ | 'delete'
+ | 'move'
+ | 'copy'
+ | 'mkdir';
+}
+
+interface TileQuery {
+ channel_name: string;
+ x_offset: number;
+ y_offset: number;
+ width: number;
+ height: number;
+ zoom_level: number;
+}
+interface Query extends
+ Partial<RawSize>,
+ Partial<TabularParameters>,
+ Partial<FileUploadParameters>,
+ Partial<TileQuery> {
+ children?: boolean;
+}
+
+const readableStream: (
+ filename: string,
+ projectName: string,
+ { offset, length }?: Query,
+ view?: ViewName
+) => fs.ReadStream = (
+ filename: string,
+ projectName: string,
+ { offset, length }: Query = { offset: undefined, length: undefined },
+ view?: ViewName
+): 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);
+ return fs.createReadStream(path(filename, projectName, view), 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) {
- cb(null, CONTENT_BASE_DIRECTORY)
- },
- 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): string =>
+ `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view || 'ORIGINAL'}`;
+
+export const originalPath: (file: string, project: string) => string =
+ (file: string, project: string): string =>
+ `${CONTENT_BASE_DIRECTORY}/${project}/${file}/ORIGINAL`;
+
+export const pathNoView: (file: string, project: string) => string =
+ (file: string, project: string): string =>
+ `${CONTENT_BASE_DIRECTORY}/${project}/${file}`;
-export const upload: Multer.Instance = Multer({ storage: storage });
+export const tempPath: (file: string, project: string) => string = (
+ file: string
+): string =>
+ `${TEMP_BASE_DIRECTORY}/${uuid.generate()}`;
-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: (data: Buffer, projectName: string, fileId: string, query: Query) => Promise<void> =
+ async(data: Buffer, projectName: string, fileId: string, query: Query): Promise<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}`);
+ // Ensure file exists
+ await fs.ensureFile(path(fileId, projectName));
+ // Truncate to offset
+ await truncateFile(fileId, projectName, query.offset || 0);
+ // Open streams to append to file
+ const rStream: stream.PassThrough = new stream.PassThrough();
+ rStream.end(data);
+ const wStream: fs.WriteStream =
+ fs.createWriteStream(path(fileId, projectName), { flags: 'a' });
+ rStream.pipe(wStream).on('error', (err: Error) => {
+ throw new RequestError(500, `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<void> => {
+ 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<void> =
+ async(fileId: string, projectName: string, newLength: number): Promise<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);
-}
+ const fd: number = await fs.open(path(fileId, projectName), 'r+');
+ 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
+ const rStream = fs.createReadStream(fromPathFull);
+ const 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;
@@ -98,17 +193,19 @@ export const files: {
logPath
};
-export type ViewName = 'raw' | 'meta';
+export type ViewName = 'raw' | 'meta' | 'tabular' | 'scalable_image';
interface Query extends Partial<RawSize> {
- children?: boolean;
+ include_children?: boolean;
}
export interface View {
- getContents: (file: File) => object;
+ getContents: (file: File, project: Project) => object | Promise<object>;
getResponseData: (file: File, project: Project, query: Query) =>
Promise<object>;
getResponseFunction: (req: Request, res: Response) => Function | null;
+ preprocess: (file: File, original: string, space: string) =>
+ Promise<void>;
}
interface MetaResponseData {
@@ -132,7 +229,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 +237,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 +262,20 @@ const metaGetResponseData: (
return data;
};
+export const getSize: (file: File, project: Project) => Promise<number> = async(
+ file: File, project: Project
+): Promise<number> => {
+ 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<object> => {
return {
- size: file.size
+ size: await getSize(file, project)
};
},
getResponseData: async(
@@ -180,7 +284,11 @@ export const views: {
return readableStream(file.uuid, project.name, query);
},
getResponseFunction: (req: Request, res: Response): Function | null => {
- return res.send;
+ return (rStream: fs.ReadStream): fs.ReadStream =>
+ rStream.pipe(res as any);
+ },
+ preprocess: async(): Promise<void> => {
+ return;
}
},
meta: {
@@ -190,11 +298,114 @@ export const views: {
getResponseData: metaGetResponseData,
getResponseFunction: (req: Request, res: Response): Function | null => {
return null;
+ },
+ preprocess: async(): Promise<void> => {
+ return;
}
- }
+ },
+ tabular: {
+ getContents: async(file: File, project: Project): Promise<object> => {
+ return await buildSupportedViews(path(file.uuid, project.name, 'tabular'));
+ },
+ getResponseData: async(
+ file: File, project: Project, query: Query
+ ): Promise<object> => {
+ const space: string = path(file.uuid, project.name, 'tabular');
+ const files: string[] = await readDir(space);
+ const select: string | undefined = files.find((name: string): boolean => name[0] === '_');
+ if (!select) {
+ throw new Error('no default sheet to show :s')
+ }
+ let rowTo = (query.rowcount)
+ ? (Number(query.rowstart) || 0) + Number(query.rowcount) -1
+ : undefined;
+ console.log(rowTo)
+ return fs.createReadStream(`${space}/${select}`)
+ .pipe(parse({
+ columns: true,
+ from: query.rowstart,
+ to: rowTo
+ })).pipe(stringify({
+ }));
+ },
+ getResponseFunction: (req: Request, res: Response): Function | null => {
+ return (stream: fs.ReadStream) => stream.pipe(res);
+ },
+ preprocess: async(file: File, original: string, space: string): Promise<void> => {
+ const mt: string = file.originalMimetype;
+ let validType: boolean = false;
+
+ if (mt.includes("csv")) {
+ validType = true;
+ } else if(mt.includes("spreadsheet")) {
+ validType = true;
+ } else if(mt.includes("ods")) {
+ validType = true;
+ } else if(mt.includes("xls")) {
+ validType = true;
+ }
+
+ if (validType) {
+ await excelToCSV(original, space, mt);
+ } else {
+ logger.warn(`unsupported file type ${mt}`);
+ }
+ }
+ },
+ scalable_image: {
+ getContents: async(file: File, project: Project): Promise<object> => {
+ return JSON.parse(await readFile(path(file.uuid, project.name, 'scalable_image') + "/supported_views.json", 'utf8'));
+ },
+ getResponseData: async(
+ file: File, project: Project, query: Query
+ ): Promise<object> => {
+ return getTile(
+ path(file.uuid, project.name, 'scalable_image') + '/',
+ query.channel_name,
+ query.x_offset,
+ query.y_offset,
+ query.width,
+ query.height,
+ query.zoom_level
+ );
+ },
+ getResponseFunction: (req: Request, res: Response): Function | null => {
+ return (stream: fs.ReadStream) => stream.pipe(res);
+ },
+ preprocess: async(file: File, original: string, space: string): Promise<void> => {
+ let isCZI: boolean = await new Promise<boolean>((res, rej) => {
+ fs.open(original, 'r', function(status, fd) {
+ if (status) {
+ logger.debug(status.message);
+ return;
+ }
+ var buffer = new Buffer(10);
+ fs.read(fd, buffer, 0, 10, 0, function(err, num) {
+ logger.debug(buffer.toString('utf8', 0, num));
+ res(buffer.toString('utf8', 0, num) === 'ZISRAWFILE');
+ });
+ });
+ });
+
+ if (isCZI) {
+ CZICrunch(original, space);
+ } else {
+ const mt: string = file.originalMimetype;
+ let validType: boolean = false;
+
+ logger.crit("FILES OTHER THAN CZI CURRENTLY NOT IMPLEMENTED")
+
+ // if (mt.includes("tif")) {
+ // await lecialol(original, space, mt);
+ // } else {
+ // logger.warn(`unsupported file type ${mt}`);
+ // }
+ }
+ }
+ }
};
-export type FileTypeName = 'generic' | 'directory';
+export type FileTypeName = 'generic' | 'directory' | 'tabular' | 'scalable_image';
export interface FileType {
supportedViews: ViewName[];
@@ -212,7 +423,35 @@ const fileTypes: {
supportedViews: [
'meta'
]
+ },
+ tabular: {
+ supportedViews: [
+ 'raw', 'meta', 'tabular'
+ ]
+ },
+ scalable_image: {
+ supportedViews: [
+ 'raw', 'meta', 'scalable_image'
+ ]
+ }
+};
+
+export const preprocess: (
+ file: File, project: Project
+) => Promise<void> = async(
+ file: File, project: Project
+): Promise<void> => {
+ const promises: Promise<void>[] = [];
+ for (const view of fileTypes[file.type].supportedViews) {
+ promises.push(views[view].preprocess(
+ file,
+ originalPath(file.uuid, project.name),
+ path(file.uuid, project.name, view)
+ ));
}
+ await Promise.all(promises);
+ file.status = 'ready';
+ await file.save();
};
class MimeTypeMap extends Map<string, string> {
@@ -231,48 +470,39 @@ class MimeTypeMap extends Map<string, string> {
}
export const mimes: MimeTypeMap = new MimeTypeMap([
- [ 'inode/directory', 'directory' ]
+ [ 'inode/directory', 'directory' ],
+ [ 'text/csv', 'tabular' ]
]);
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<void> = async(
+): Promise<void> => {
+ try {
+ await fs.mkdir(CONTENT_BASE_DIRECTORY);
+ } catch (e) {
+ logger.warn(`error when creating base folder: ${e}`);
}
-}
+};
-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<void> = async(
+ projName: string
+): Promise<void> => {
+ try {
+ await fs.mkdir(CONTENT_BASE_DIRECTORY + '/' + projName);
+ } catch (e) {
+ logger.warn(`error when creating folder for project ${projName}: ${e}`);
}
-}
+};
-export const addSubFileToFolder: (parentId: string, subFileId: string) => Promise<boolean> = async(parentId: string, subFileId: string): Promise<boolean> => {
- logger.debug(`adding file ${subFileId}) to directory ${parentId}`)
+export const addSubFileToFolder: (
+ parentId: string, subFile: File
+) => Promise<void> = async(
+ parentId: string, subFile: File
+): Promise<void> => {
+ logger.debug(`adding file ${subFile.uuid} 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;
-}
+ subFile.parentFolderId = parentId;
+ await subFile.save();
+};
diff --git a/src/index.ts b/src/index.ts
index 0074d7b..e99aa1a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,7 +1,10 @@
-
+import * as fs from 'fs-extra';
import { logger } from './logger';
logger.info('Starting up server');
+logger.info('Creating necessary directories');
+fs.ensureDirSync('logs/general');
+fs.ensureDirSync('files');
logger.info('Importing server logic');
import { default as app } from './app';
@@ -10,6 +13,7 @@ logger.info('Importing database ORM');
import { createRootFolder, rootPathId } from './files';
import { default as seq } from './db/orm';
+import { default as ContributorGroup } from './db/model/ContributorGroup';
import { default as File } from './db/model/File';
import { default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';
@@ -18,7 +22,7 @@ const DEFAULT_PORT: number = 3000;
// Use default port 3000 or port supplied by OS
const port: number = process.env.PORT
- ? process.env.PORT
+ ? Number(process.env.PORT)
: DEFAULT_PORT;
logger.info(`Port ${port} chosen`);
@@ -60,8 +64,77 @@ async function reset(): Promise<void> {
description: 'Allows Post to Log'
});
+ const userManagement: UserGroup = new UserGroup({
+ name: 'userManagement',
+ canCreateUsers: true,
+ canDeleteUsers: true,
+ canEditUsers: true,
+ isInternal: false,
+ description: 'Allows management of other users'
+ });
+
+ const projectAdmin: UserGroup = new UserGroup({
+ name: 'projectAdmin',
+ canDeleteProjects: true,
+ canEditProjects: true,
+ isInternal: false,
+ description: 'Admin privileges on other projects '
+ });
+
+ const standardUser: UserGroup = new UserGroup({
+ name: 'standardUser',
+ canCreateProjects: true,
+ isInternal: true,
+ description: 'Allows creation of new projects'
+ });
+
await logging.save();
await admin.save();
+ await userManagement.save();
+ await projectAdmin.save();
+ await standardUser.save();
+
+ const projectOwner: ContributorGroup = new ContributorGroup({
+ name: 'projectOwner',
+ canCreateFiles: true,
+ canAddUsers: true,
+ canRemoveUsers: true,
+ canDeleteFiles: true,
+ canDeleteProject: true,
+ canEditUserPermissions: true,
+ canViewFiles: true,
+ isInternal: false,
+ description: 'Project Admin'
+ });
+
+ const standardProjectUser: ContributorGroup = new ContributorGroup({
+ name: 'standardProjectUser',
+ canCreateFiles: true,
+ canViewFiles: true,
+ isInternal: false,
+ description: 'Allows working on a project'
+ });
+
+ const readOnlyProjectUser: ContributorGroup = new ContributorGroup({
+ name: 'readOnlyProjectUser',
+ canViewFiles: true,
+ isInternal: false,
+ description: 'Allows viewing of files in a project '
+ });
+
+ const projectUserManagement: ContributorGroup = new ContributorGroup({
+ name: 'projectUserManagement',
+ canAddUsers: true,
+ canEditUserPermissions: true,
+ canRemoveUsers: true,
+ isInternal: false,
+ description: 'Allows managament of users in a Project'
+ });
+
+ await projectOwner.save();
+ await standardProjectUser.save();
+ await readOnlyProjectUser.save();
+ await projectUserManagement.save();
logger.info('Adding admin user');
const root: User = new User({
@@ -93,7 +166,8 @@ async function reset(): Promise<void> {
process.exit(1);
}
- //await reset();
+ await reset();
+
logger.info('Booting ExpressJS server');
app.listen(port, (err: Error) => {
diff --git a/src/matcher/index.ts b/src/matcher/index.ts
index 0806907..e7c2f88 100644
--- a/src/matcher/index.ts
+++ b/src/matcher/index.ts
@@ -5,7 +5,9 @@ export {
exact,
optional,
alternative,
- array
+ array,
+ match,
+ metadata
} from './options';
export {
diff --git a/src/matcher/options.ts b/src/matcher/options.ts
index 62e4985..0bad627 100644
--- a/src/matcher/options.ts
+++ b/src/matcher/options.ts
@@ -89,6 +89,12 @@ export const array = (template: TemplateValue, values?: Value[]) => {
};
// tslint:disable-next-line:typedef
+export const metadata = exact({
+ version: types.integer,
+ namespaces: {}
+});
+
+// tslint:disable-next-line:typedef
const options = {
match,
exact,
diff --git a/src/mimetype.ts b/src/mimetype.ts
new file mode 100644
index 0000000..4110ae5
--- /dev/null
+++ b/src/mimetype.ts
@@ -0,0 +1,29 @@
+import * as fromData from 'file-type';
+import { lookup as fromName } from 'mime-types';
+
+const DEFAULT_MIMETYPE: string = 'application/octet-stream';
+
+export const mimetype: (
+ contentType?: string, data?: Buffer, name?: string
+) => string = (
+ contentType?: string, data?: Buffer, name?: string
+): string => {
+ if (contentType && contentType !== DEFAULT_MIMETYPE) {
+ return contentType;
+ }
+ if (data) {
+ const fType: fromData.FileTypeResult = fromData(data);
+ if (fType) {
+ return fType.mime;
+ }
+ }
+ if (name) {
+ const mType: string | false = fromName(name);
+ if (mType) {
+ return mType;
+ }
+ }
+ return DEFAULT_MIMETYPE;
+};
+
+export { extension } from 'mime-types';
diff --git a/src/serverConfig.ts b/src/serverConfig.ts
index 136995a..5d2575a 100644
--- a/src/serverConfig.ts
+++ b/src/serverConfig.ts
@@ -82,7 +82,7 @@ export class Property {
}
public set value(value: Value) {
- if (!this.readOnly) {
+ if (this.readOnly) {
throw new Error('this property is read-only');
} else if (!types[this.type](value)) {
throw new Error(`value ${value} is not of type ${this.type}`);