diff options
| author | cjd24 | 2018-04-23 08:43:10 +0100 |
|---|---|---|
| committer | cjd24 | 2018-04-23 08:43:10 +0100 |
| commit | f1e8003fd621a40e2386c310a2189bb9a13b0c9d (patch) | |
| tree | a0323aa44d4e9ee87bc9b5fb98e769c4af79265d /src | |
| parent | Add tabular functionality (except cols) (diff) | |
| download | medicine-f1e8003fd621a40e2386c310a2189bb9a13b0c9d.tar.gz medicine-f1e8003fd621a40e2386c310a2189bb9a13b0c9d.zip | |
BIG FILTHY COMMIT OF SCARY STUFF
Diffstat (limited to 'src')
| -rw-r--r-- | src/FileRouter.ts | 2 | ||||
| -rw-r--r-- | src/app.ts | 10 | ||||
| -rw-r--r-- | src/conversion/csv/excel.ts | 1 | ||||
| -rw-r--r-- | src/conversion/czi/czi.ts | 26 | ||||
| -rw-r--r-- | src/conversion/czi/pyramidWorker.ts | 19 | ||||
| -rw-r--r-- | src/files.ts | 90 | ||||
| -rw-r--r-- | src/index.ts | 2 |
7 files changed, 127 insertions, 23 deletions
diff --git a/src/FileRouter.ts b/src/FileRouter.ts index bb022d3..c8884f7 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -1019,7 +1019,7 @@ export class FileRouter { this.router.get ('/projects/:project_name/files/*', getFilePath); this.router.post( '/projects/:project_name/files/*', - bodyParser.raw({ type: '*/*' }), postFilePath); + bodyParser.raw({ type: '*/*', limit: '20GB' }), postFilePath); this.router.get ('/projects/:project_name/files_by_id/:id', getFileId); } @@ -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 index 73563a6..3f5d30b 100644 --- a/src/conversion/csv/excel.ts +++ b/src/conversion/csv/excel.ts @@ -4,6 +4,7 @@ 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); diff --git a/src/conversion/czi/czi.ts b/src/conversion/czi/czi.ts index 429f60d..33bc738 100644 --- a/src/conversion/czi/czi.ts +++ b/src/conversion/czi/czi.ts @@ -16,7 +16,6 @@ const readdir = require('util').promisify(fs.readdir); const exists = require('util').promisify(fs.exists); // Various constants for placing files and defining tiles -const testFile: string = '/cs/scratch/cjd24/0701.czi' let extractDirectory: string = ""; let outputImageData: string = ""; let outputImageDirectory: string = ""; @@ -378,6 +377,9 @@ const cleanSupportedViewObject: (obj: parsexml.Node[]) => object = ( 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[] @@ -398,6 +400,9 @@ const supportedViews: SupportedViews = { metadata: {} } }; +if (!supportedViews.scalable_image) { + throw new Error("SupportedView.scalable_image does not exist where it should."); +} supportedViews.scalable_image.channels.pop(); /* tslint:disable:curly cyclomatic-complexity */ @@ -412,6 +417,9 @@ const parseExtractedXML: (xmlFile: string) => void = async( // 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') { @@ -738,6 +746,9 @@ const createSupportedViewsObject: () => void = async(): Promise<void> => { // 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, @@ -756,6 +767,9 @@ const buildCustomPyramids: () => Promise<boolean> = async(): Promise<boolean> => 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."); + } for (const cval of supportedViews.scalable_image.channels) { errorOccurred = false; @@ -789,9 +803,9 @@ const buildCustomPyramids: () => Promise<boolean> = async(): Promise<boolean> => return errorOccurred; }; -const initialExtractAndConvert: (absFilePath: string) => Promise<void> = async (absFilePath: string): Promise<void> => { +const initialExtractAndConvert: (absFilePath: string, space: string) => Promise<void> = async (absFilePath: string, space: string): Promise<void> => { - outputImageData = `${absFilePath.split('.')[0]}-processed`; + outputImageData = space; extractDirectory = outputImageData + "/extract/"; outputImageDirectory = outputImageData + "/data/"; @@ -841,12 +855,12 @@ process.on("warning", (err: any) => console.warn(err)) * Main function used to call the rest of the relevant code to crunch a CZI * extraction. */ -const main: () => Promise<void> = async (): Promise<void> => { +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(testFile); + await initialExtractAndConvert(original, space); console.log('\n>> Checking/Creating output directories...'); checkForOutputDirectories([outputImageDirectory, `${outputImageData}/tmp/`]); @@ -866,7 +880,7 @@ const main: () => Promise<void> = async (): Promise<void> => { console.error(Err); } }; -main(); +// main(); // /* tslint:disable */ // async function main2() { diff --git a/src/conversion/czi/pyramidWorker.ts b/src/conversion/czi/pyramidWorker.ts index 5e6911c..6b12409 100644 --- a/src/conversion/czi/pyramidWorker.ts +++ b/src/conversion/czi/pyramidWorker.ts @@ -1,8 +1,11 @@ -import { CZIHeightMap, CZITile, CZITileRequest } from '../types/customPyramidIndex'; +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[][] { @@ -32,6 +35,20 @@ const findRelatedTiles: Function = function(plane: CZIHeightMap, desired: TileBo 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??"); diff --git a/src/files.ts b/src/files.ts index 24bee76..19862d1 100644 --- a/src/files.ts +++ b/src/files.ts @@ -3,22 +3,23 @@ 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 TEMP_BASE_DIRECTORY: string = './files-temp'; +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'; export interface Metadata { version: number; @@ -61,10 +62,19 @@ interface FileUploadParameters { | '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<FileUploadParameters>, + Partial<TileQuery> { children?: boolean; } @@ -183,7 +193,7 @@ export const files: { logPath }; -export type ViewName = 'raw' | 'meta' | 'tabular'; +export type ViewName = 'raw' | 'meta' | 'tabular' | 'scalable_image'; interface Query extends Partial<RawSize> { include_children?: boolean; @@ -341,10 +351,61 @@ export const views: { 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' | 'tabular'; +export type FileTypeName = 'generic' | 'directory' | 'tabular' | 'scalable_image'; export interface FileType { supportedViews: ViewName[]; @@ -367,7 +428,12 @@ const fileTypes: { supportedViews: [ 'raw', 'meta', 'tabular' ] - } + }, + scalable_image: { + supportedViews: [ + 'raw', 'meta', 'scalable_image' + ] + } }; export const preprocess: ( diff --git a/src/index.ts b/src/index.ts index ffb6f68..e99aa1a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -166,7 +166,7 @@ async function reset(): Promise<void> { process.exit(1); } - // /await reset(); + await reset(); logger.info('Booting ExpressJS server'); |
