aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorTom Harley2018-04-23 05:49:44 +0100
committerTom Harley2018-04-23 05:49:44 +0100
commit255e8f4557423c6fd6a54f899cce2271d82da279 (patch)
treef0f97fe6b14812d2b520f8c9c236c32a562d7ce8 /src
parentMerge branch 'cjd24/conversion' into trh/gets (diff)
downloadmedicine-255e8f4557423c6fd6a54f899cce2271d82da279.tar.gz
medicine-255e8f4557423c6fd6a54f899cce2271d82da279.zip

Add tabular functionality (except cols)

Diffstat (limited to 'src')
-rw-r--r--src/conversion/csv/excel.ts66
-rw-r--r--src/db/model/File.ts4
-rw-r--r--src/files.ts60
-rw-r--r--src/mimetype.ts2
4 files changed, 98 insertions, 34 deletions
diff --git a/src/conversion/csv/excel.ts b/src/conversion/csv/excel.ts
index fd74593..73563a6 100644
--- a/src/conversion/csv/excel.ts
+++ b/src/conversion/csv/excel.ts
@@ -3,10 +3,13 @@ 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) => {
@@ -25,35 +28,64 @@ const supportedViewsFromDsk: (path: string) => Promise<SupportedViews> = async(p
return supportedViewsFromMem((await readFile(path)).toString());
}
-const toCSV: (file: string) => Promise<string> = async (file: string): Promise<string> => {
+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}`);
- let temp: string[] = file.split('.')[0].split('/');
- let shortFile: string = temp[temp.length - 1];
- let path: string = file.substring(0, file.lastIndexOf('/')) + '/';
+ 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 {
- let views: any = {}; views.items = [];
+ await createFolder(output);
+ let noSheets: number = 0;
for (let name of book.SheetNames) {
- let csvify:string = xlsx.utils.sheet_to_csv(book.Sheets[name]);
- await writeFile(`${path}${shortFile}-${name}.csv`, csvify);
- views.items.push(name);
- views[name] = await supportedViewsFromMem(csvify);
- logger.info(`Wrote subsheet {${shortFile} : ${name}} as CSV.`);
+ await writeFile(`${output}/-${name}`, xlsx.utils.sheet_to_csv(book.Sheets[name]));
+ noSheets++;
}
- writeJSONToFile(`${path}${shortFile}-BASE.supported_views.json`, views[views.items[0]]);
- await writeJSONToFile(`${path}${shortFile}-ALL.supported_views.json`, views);
- return views.items === [] ? "__Empty_Book_Error" : `${path}${shortFile}-ALL.supported_views.json`;
+ rename(`${output}/-${book.SheetNames[0]}`, `${output}/_${book.SheetNames[0]}`)
+
+ return noSheets;
} catch (err) {
- logger.error(err);
- return "__conversion_to_csv_error_occurred: " + 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):
diff --git a/src/db/model/File.ts b/src/db/model/File.ts
index 5bae182..95031e4 100644
--- a/src/db/model/File.ts
+++ b/src/db/model/File.ts
@@ -75,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 {
@@ -136,6 +139,7 @@ export default class File extends Model<File> {
}
public set mimetype(mime: string) {
+ this.originalMimetype = mime;
this.type = mimes.get(mime) || 'generic';
}
}
diff --git a/src/files.ts b/src/files.ts
index 7890d84..24bee76 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -13,6 +13,9 @@ import { uuid } from './uuid';
import { RequestError } from './errors';
+import { toCSV as excelToCSV, buildSupportedViews } from './conversion/csv/excel';
+const readDir = require('util').promisify(fs.readdir);
+
const CONTENT_BASE_DIRECTORY: string = './files';
const LOG_BASE_DIRECTORY: string = './logs';
const TEMP_BASE_DIRECTORY: string = './files-temp';
@@ -74,7 +77,7 @@ const readableStream: (
filename: string,
projectName: string,
{ offset, length }: Query = { offset: undefined, length: undefined },
- view: ViewName = 'raw'
+ view?: ViewName
): fs.ReadStream => {
const options: object = {
start: offset ? offset : 0,
@@ -92,8 +95,8 @@ export const logPath: (type: string, projectName?: string) => string = (
};
export const path: (file: string, project: string, view?: ViewName) => string =
- (file: string, project: string, view: ViewName = 'raw'): string =>
- `${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`;
+ (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 =>
@@ -191,7 +194,7 @@ export interface View {
getResponseData: (file: File, project: Project, query: Query) =>
Promise<object>;
getResponseFunction: (req: Request, res: Response) => Function | null;
- preprocess: (original: string, space: string) =>
+ preprocess: (file: File, original: string, space: string) =>
Promise<void>;
}
@@ -274,7 +277,7 @@ export const views: {
return (rStream: fs.ReadStream): fs.ReadStream =>
rStream.pipe(res as any);
},
- preprocess: async(original: string, space: string): Promise<void> => {
+ preprocess: async(): Promise<void> => {
return;
}
},
@@ -286,35 +289,57 @@ export const views: {
getResponseFunction: (req: Request, res: Response): Function | null => {
return null;
},
- preprocess: async(original: string, space: string): Promise<void> => {
+ preprocess: async(): Promise<void> => {
return;
}
},
tabular: {
- getContents: (file: File): object => {
- return {
- // columns:
- // rows:
- };
+ 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> => {
- return readableStream(file.name, project.name, query)
+ 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: (query.rowstart && query.rowcount)
- ? query.rowstart + query.rowcount
- : undefined
+ to: rowTo
})).pipe(stringify({
}));
},
getResponseFunction: (req: Request, res: Response): Function | null => {
return (stream: fs.ReadStream) => stream.pipe(res);
},
- preprocess: async(original: string, space: string): Promise<void> => {
- return;
+ 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}`);
+ }
}
}
};
@@ -353,6 +378,7 @@ export const preprocess: (
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)
));
diff --git a/src/mimetype.ts b/src/mimetype.ts
index dc06d54..4110ae5 100644
--- a/src/mimetype.ts
+++ b/src/mimetype.ts
@@ -25,3 +25,5 @@ export const mimetype: (
}
return DEFAULT_MIMETYPE;
};
+
+export { extension } from 'mime-types';