1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
|
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 { RequestError } from './errors';
const CONTENT_BASE_DIRECTORY: string = './files';
const LOG_BASE_DIRECTORY: string = './logs';
const TEMP_BASE_DIRECTORY: string = './files-temp';
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 => {
return fs.createWriteStream(path(filename, projectName));
};
interface RawSize {
offset: number;
length: number;
}
interface TabularParameters {
rowstart: number;
rowcount: number;
cols: string[];
}
interface FileUploadParameters {
truncate: boolean;
overwrite: boolean;
offset: number;
action: 'set_metadata'
| 'delete'
| 'move'
| 'copy'
| 'mkdir';
}
interface Query extends
Partial<RawSize>,
Partial<TabularParameters>,
Partial<FileUploadParameters> {
children?: boolean;
}
const readableStream: (
filename: string, projectName: string, { offset, length }?: Query
) => fs.ReadStream = (
filename: string, projectName: string, { offset, length }: Query =
{ offset: undefined, length: undefined }
): fs.ReadStream => {
const options: object = {
start: offset ? offset : 0,
end: offset && length ? offset + length : undefined
};
return fs.createReadStream(path(filename, projectName), options);
};
export const logPath: (type: string, projectName?: string) => string = (
type: string, projectName?: string
): string => {
return projectName
? `${LOG_BASE_DIRECTORY}/projects/${projectName}/${type}`
: `${LOG_BASE_DIRECTORY}/general/${type}`;
};
export const path: (file: string, project: string, view?: ViewName) => string =
(file: string, project: string, view: ViewName = 'raw'): string =>
`${CONTENT_BASE_DIRECTORY}/${project}/${file}/${view}`;
export const pathNoView: (file: string, project: string) => string =
(file: string, project: string): string =>
`${CONTENT_BASE_DIRECTORY}/${project}/${file}`;
export const tempPath: (file: string, project: string) => string = (
file: string
): string =>
`${TEMP_BASE_DIRECTORY}/${uuid.generate()}`;
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
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 = async(
fileId: string, projectName: string
): Promise<void> => {
await fs.remove(`${CONTENT_BASE_DIRECTORY}/${projectName}/${fileId}`);
};
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 = 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;
writableStream: (f: string, p: string) => fs.WriteStream;
logPath: (t: string, p?: string) => string;
} = {
path,
writableStream,
logPath
};
export type ViewName = 'raw' | 'meta' | 'tabular';
interface Query extends Partial<RawSize> {
include_children?: boolean;
}
export interface View {
getContents: (file: File, project: Project) => object | Promise<object>;
getResponseData: (file: File, project: Project, query: Query) =>
Promise<object>;
getResponseFunction: (req: Request, res: Response) => Function | null;
}
interface MetaResponseData {
file_path: string;
file_name: string;
id: string;
type: FileTypeName;
metadata: object;
status: string;
supported_views: {
[key: string]: object | undefined;
};
children?: MetaResponseData[];
}
const metaGetResponseData: (
file: File, project: Project, query: Query
) => Promise<MetaResponseData> = async(
file: File, project: Project, query: Query
): Promise<MetaResponseData> => {
const data: MetaResponseData = {
file_path: file.fullPath,
file_name: file.name,
id: file.uuid,
type: file.type,
metadata: file.metadata,
status: file.status,
supported_views: {}
};
for (const view of fileTypes[file.type].supportedViews) {
data.supported_views[view] =
await views[view].getContents(file, project);
}
if (query.include_children) {
data.children = [];
const children: File[] | null = await File.findAll({
where: {
parentFolderId: file.uuid
}
});
if (children != null) {
for (const child of children) {
data.children.push(await metaGetResponseData(
child,
project,
{
...query,
include_children: undefined
}
));
}
}
}
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: async(file: File, project: Project): Promise<object> => {
return {
size: await getSize(file, project)
};
},
getResponseData: async(
file: File, project: Project, query: Query
): Promise<object> => {
return readableStream(file.uuid, project.name, query);
},
getResponseFunction: (req: Request, res: Response): Function | null => {
return (stream: fs.ReadStream) => stream.pipe(res);
}
},
meta: {
getContents: (file: File): object => {
return {};
},
getResponseData: metaGetResponseData,
getResponseFunction: (req: Request, res: Response): Function | null => {
return null;
}
},
tabular: {
getContents: (file: File): object => {
return {
// columns:
// rows:
};
},
getResponseData: async(
file: File, project: Project, query: Query
): Promise<object> => {
return readableStream(file.name, project.name, query)
.pipe(parse({
columns: true,
from: query.rowstart,
to: (query.rowstart && query.rowcount)
? query.rowstart + query.rowcount
: undefined
})).pipe(stringify({
}));
},
getResponseFunction: (req: Request, res: Response): Function | null => {
return (stream: fs.ReadStream) => stream.pipe(res);
}
}
};
export type FileTypeName = 'generic' | 'directory' | 'tabular';
export interface FileType {
supportedViews: ViewName[];
}
const fileTypes: {
[type: string]: FileType;
} = {
generic: {
supportedViews: [
'raw', 'meta'
]
},
directory: {
supportedViews: [
'meta'
]
},
tabular: {
supportedViews: [
'raw', 'meta', 'tabular'
]
}
};
class MimeTypeMap extends Map<string, string> {
public constructor(pairs: [string, FileTypeName][]) {
super(pairs);
}
public get(mime: string): FileTypeName {
const ret: string | undefined = super.get(mime);
if (ret) {
return ret as FileTypeName;
} else {
return 'generic';
}
}
}
export const mimes: MimeTypeMap = new MimeTypeMap([
[ 'inode/directory', 'directory' ],
[ 'text/csv', 'tabular' ]
]);
export const rootPathId: string = '0';
export const rootPathFile: File | null = null;
export const createRootFolder: () => Promise<void> = async(
): Promise<void> => {
if (!(await fs.access(CONTENT_BASE_DIRECTORY))) {
await fs.mkdir(CONTENT_BASE_DIRECTORY);
}
};
export const createProjectFolder: (name: string) => Promise<void> = async(
projName: string
): Promise<void> => {
if (!(await fs.access(CONTENT_BASE_DIRECTORY + '/' + projName))) {
await fs.mkdir(CONTENT_BASE_DIRECTORY + '/' + projName);
}
};
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
subFile.parentFolderId = parentId;
await subFile.save();
};
|