-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpathDB.mjs
552 lines (546 loc) · 16 KB
/
pathDB.mjs
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import fs from 'fs';
const errors = { OPERATION_LOCKED: 'OPERATION_LOCKED' };
function addPredefinedFunctions() {
this.skipUpdate = true;
this.addStructureFunction('list', ({ getObject }) => {
const copy = { ...getObject() };
delete copy.extention;
delete copy.path;
delete copy.list;
delete copy.getAbsolutePath;
return Object.keys(copy);
});
this.addStructureFunction('getAbsolutePath', () => this.folderLocation);
this.addDirFunction(
'getAbsolutePath',
({ path }) => `${this.folderLocation}/${path}`
);
this.addDirFunction('isDirectory', () => true);
this.addDirFunction('isFile', () => false);
this.addDirFunction('list', object => {
const copy = { ...this.get(object.path) };
delete copy.key;
delete copy.path;
delete copy.isHidden;
delete copy.extention;
for (let func of this.functionNames.dir) {
delete copy[func];
}
return Object.keys(copy);
});
this.addDirFunction('includes', ({ getObject }, key) =>
getObject()
.list()
.includes(key)
);
this.addDirFunction('new', function({ path }, name, content = null) {
return new Promise((resolve, reject) => {
const lockKey = `/${path}/${name}`;
const location = `${this.folderLocation}/${path}/${name}`;
if (!this.lock.includes(lockKey)) {
this.lock.push(lockKey);
if (content) {
fs.writeFile(
`${this.folderLocation}/${path}/${name}`,
content,
err => {
this.lock.splice(this.lock.indexOf(location), 1);
err ? reject(err) : resolve(this.update());
}
);
} else {
fs.mkdir(`${this.folderLocation}/${path}/${name}`, err => {
this.lock.splice(this.lock.indexOf(location), 1);
err ? reject(err) : resolve(this.update());
});
}
} else {
reject({
type: this.errors.OPERATION_LOCKED,
message: 'Already creating a new object at given location.',
lock: { key: lockKey }
});
}
});
});
this.addDirFunction('delete', ({ path }) => {
const deleteFolderRecursive = path => {
return new Promise(async (resolve, reject) => {
try {
if (fs.existsSync(path)) {
for (let file of fs.readdirSync(path)) {
const curPath = `${path}/${file}`;
if (fs.lstatSync(curPath).isDirectory()) {
// recurse
await deleteFolderRecursive(curPath);
} else {
// delete file
fs.unlinkSync(curPath);
}
}
fs.rmdirSync(path);
resolve(this.update());
}
} catch (err) {
reject(err);
}
});
};
return deleteFolderRecursive(`${this.folderLocation}/${path}`);
});
this.addFileFunction(
'getAbsolutePath',
({ path }) => `${this.folderLocation}/${path}`
);
this.addFileFunction('isDirectory', () => false);
this.addFileFunction('isFile', () => true);
this.addFileFunction('read', async function({ path, extention }) {
if (!this.cache[path]) {
const data = await new Promise(async (resolve, reject) => {
while (this.lock.includes(path)) {
await new Promise(resolve => setTimeout(() => resolve(), 100));
}
fs.readFile(`${this.folderLocation}/${path}`, (err, data) =>
err
? reject(err)
: resolve(
typeof extention === 'string' &&
extention.toLowerCase() === 'json'
? JSON.parse(data.toString())
: data
)
);
});
this.cache[path] = { data, extention };
}
return this.cache[path].data;
});
this.addFileFunction('write', function({ path }, content) {
return new Promise(async (resolve, reject) => {
while (this.lock.includes(path)) {
await new Promise(resolve => setTimeout(() => resolve(), 100));
}
this.lock.push(path);
fs.writeFile(`${this.folderLocation}/${path}`, content, err => {
this.lock.splice(this.lock.indexOf(path), 1);
err ? reject(err) : resolve(this.update());
});
});
});
this.addFileFunction('delete', function({ path }) {
return new Promise((resolve, reject) =>
fs.unlink(`${this.folderLocation}/${path}`, err =>
err ? reject(err) : resolve(this.update())
)
);
});
this.skipUpdate = false;
}
export default class PathDB {
lock = [];
cache = {};
database = { paths: [], structure: {} };
functions = {
dir: [],
file: [],
structure: []
};
functionNames = { dir: [], file: [], structure: [] };
constructor(folderLocation) {
this.errors = errors;
this.folderLocation = folderLocation.replace('\\', '/');
if (this.folderLocation.endsWith('/')) {
this.folderLocation = this.folderLocation.substring(
0,
folderLocation.length - 1
);
}
addPredefinedFunctions.bind(this)();
this.initialRun = true;
this.update();
this.initialRun = false;
}
update() {
if (!this.skipUpdate) {
this.database.paths = map(this.folderLocation);
this.database.structure = obj.bind(this)(
this.database.paths,
this.functions,
this.folderLocation
);
}
this.updateCache();
}
updateCache() {
if (!this.updatingCache) {
this.updatingCache = true;
new Promise(async resolve => {
for (let path in this.cache) {
while (this.lock.includes(path)) {
await new Promise(resolve => setTimeout(() => resolve(), 100));
}
fs.readFile(`${this.folderLocation}/${path}`, (err, data) => {
if (err) {
throw new Error(err);
} else {
this.cache[path].data =
typeof this.cache[path].extention === 'string' &&
this.cache[path].extention.toLowerCase() === 'json'
? JSON.parse(data.toString())
: data;
}
});
}
resolve((this.updatingCache = false));
});
}
}
monitor(interval = 100) {
if (!this.isMonitoring) {
this.isMonitoring = true;
this.interval = setInterval(() => {
this.update();
}, interval);
}
}
stop() {
this.isMonitoring = true;
clearInterval(this.interval);
}
operationIsLocked(key) {
return this.lock.includes[key];
}
get paths() {
return this.database.paths;
}
get structure() {
for (let { funcName, func } of this.functions.structure) {
this.database.structure[funcName] = func.bind(this, {
getObject: () => this.database.structure,
path: '',
extention: null
});
}
return this.database.structure;
}
get(path) {
return getStructureObject(this.structure, path);
}
create(
path,
filename = null,
filecontent = null,
options = { force: false }
) {
const { force } = arguments[arguments.length - 1];
path = checkPath(path);
const pathEntrys = path.split('/');
let potentialPath = `${this.folderLocation}`;
for (let i = 0; i < pathEntrys.length; i++) {
potentialPath = `${potentialPath}/${pathEntrys[i]}`;
if (fs.existsSync(potentialPath)) {
if (fs.lstatSync(potentialPath).isFile()) {
try {
if (!force) {
throw new Error(
`Creating path: '${path}' has not succeeded, path: '${potentialPath.replace(
this.folderLocation,
''
)}' is a file.\nSet attribute force to true to override blocking chains.`
);
} else {
fs.unlinkSync(potentialPath, err => {
if (err) throw new Error(err);
});
fs.mkdirSync(potentialPath);
}
} catch (err) {
console.error(err);
return false;
}
}
continue;
} else {
fs.mkdirSync(potentialPath);
}
}
if (typeof filename === 'string') {
fs.writeFileSync(
`${this.folderLocation}/${path}/${filename}`,
typeof filecontent === 'object' &&
filecontent.constructor.name === 'Object'
? ''
: filecontent
);
}
return true;
}
delete(path) {
path = checkPath(path);
const deleteFolderRecursive = path => {
try {
if (fs.existsSync(path)) {
for (let file of fs.readdirSync(path)) {
const curPath = `${path}/${file}`;
if (fs.lstatSync(curPath).isDirectory()) {
// recurse
deleteFolderRecursive(curPath);
} else {
// delete file
fs.unlinkSync(curPath);
}
}
fs.rmdirSync(path);
}
return true;
} catch (err) {
console.error(err);
return false;
}
};
let isRegisteredPath = false;
for (let registeredPath of this.paths) {
if (registeredPath.startsWith(path)) {
isRegisteredPath = true;
break;
}
}
if (isRegisteredPath) {
if (!fs.existsSync(`${this.folderLocation}/${path}`)) {
this.database.paths = this.paths.filter(
registeredPath => registeredPath !== path
);
return true;
}
if (fs.lstatSync(`${this.folderLocation}/${path}`).isDirectory()) {
return deleteFolderRecursive(`${this.folderLocation}/${path}`);
}
}
if (fs.lstatSync(`${this.folderLocation}/${path}`).isFile()) {
fs.unlinkSync(`${this.folderLocation}/${path}`);
return true;
}
return false;
}
addStructureFunction(funcName, func) {
if (this.functionNames.structure.includes(funcName)) {
const functionIndex = this.functionNames.indexOf(funcName);
if (functionIndex >= 0) {
this.functionNames.structure.splice(functionIndex, 1);
this.functions.structure.splice(functionIndex, 1);
}
}
this.functionNames.structure.push(funcName);
this.functions.structure.push({ funcName, func });
this.update();
}
addDirFunction(funcName, func, target = '*') {
if (!this.functionNames.dir.includes(funcName)) {
this.functionNames.dir.push(funcName);
}
this.functions.dir.push({ target, funcName, func });
this.update();
}
addFileFunction(funcName, func, target = '*.*') {
if (!this.functionNames.file.includes(funcName)) {
this.functionNames.file.push(funcName);
}
this.functions.file.push({ target, funcName, func });
this.update();
}
}
function map(source, initialSource = null) {
if (initialSource === null) {
initialSource = source;
}
let mapped = [];
if (fs.lstatSync(source).isDirectory()) {
const files = fs.readdirSync(source);
if (files.length === 0) {
mapped = [...mapped, `${source.replace(initialSource, '')}`];
} else {
files.forEach(function(file) {
try {
if (fs.lstatSync(`${source}/${file}`).isDirectory()) {
mapped = [...mapped, ...map(`${source}/${file}`, initialSource)];
} else {
mapped = [
...mapped,
`${source.replace(initialSource, '')}/${file}`
];
}
} catch (err) {
console.error(err);
}
});
}
} else if (fs.lstatSync(source).isFile()) {
mapped.push(
source.startsWith(initialSource + '/')
? source.replace(initialSource + '/', '')
: source.replace(initialSource, '')
);
}
return mapped;
}
function join(obj1, obj2) {
let finalObject = { ...obj1 };
for (let key in obj2) {
if (typeof finalObject[key] !== 'object') {
finalObject[key] = {};
}
if (typeof obj2[key] === 'object') {
finalObject[key] = join(finalObject[key], obj2[key]);
} else {
finalObject[key] = obj2[key];
}
}
return finalObject;
}
function obj(mapped, functions, folderLocation) {
let objectified = [];
let obj = {};
for (let path of mapped) {
const objectifiedPath = objectify.bind(this)(
path,
functions,
folderLocation
);
if (objectifiedPath) {
objectified.push(objectifiedPath);
}
}
for (let object of objectified) {
obj = join(obj, object);
}
return obj;
}
function objectify(
path,
functions,
folderLocation = undefined,
currentPath = ''
) {
path = checkPath(path);
currentPath = checkPath(currentPath);
let key = undefined;
if (path.includes('/')) {
key = path.substring(0, path.indexOf('/') + 1).replace('/', '');
} else {
key = path;
}
if (!fs.existsSync(`${folderLocation}/${currentPath}/${key}`)) {
return;
}
let objectKey = `${key}`;
let isHidden = false;
let extention = undefined;
if (objectKey.startsWith('.')) {
isHidden = true;
objectKey = objectKey.substring(1, objectKey.length);
}
if (
objectKey.includes('.') &&
fs.lstatSync(`${folderLocation}/${currentPath}/${key}`).isFile()
) {
extention = objectKey.substring(
objectKey.lastIndexOf('.') + 1,
objectKey.length
);
objectKey = objectKey.substring(0, objectKey.lastIndexOf('.'));
}
const requestedFunctions = {};
const objectifiedPath = {
[objectKey]: {
key: objectKey,
path: `${currentPath}/${key}`,
isHidden,
extention,
...(key === path
? {}
: (() => {
const objectifiedPath = objectify.bind(this)(
path.substring(path.indexOf('/') + 1, path.length),
functions,
folderLocation,
`${currentPath}/${key}`
);
return objectifiedPath ? objectifiedPath : {};
})())
}
};
if (typeof functions === 'object' && typeof folderLocation === 'string') {
if (fs.lstatSync(`${folderLocation}/${currentPath}/${key}`).isDirectory()) {
for (let i = 0; i < functions.dir.length; i++) {
let { target, funcName, func } = functions.dir[i];
if (target === '*' || target === objectKey || target === key) {
requestedFunctions[funcName] = func.bind(this, {
...objectifiedPath[objectKey],
getObject: () => this.get(`${currentPath}/${key}`)
});
}
}
} else if (
fs.lstatSync(`${folderLocation}/${currentPath}/${key}`).isFile()
) {
for (let i = 0; i < functions.file.length; i++) {
let { target, funcName, func } = functions.file[i];
if (target === '*.*' || target === objectKey || target === key) {
requestedFunctions[funcName] = func.bind(this, {
...objectifiedPath[objectKey],
getObject: () => this.get(`${currentPath}/${key}`)
});
}
}
}
}
objectifiedPath[objectKey] = {
...objectifiedPath[objectKey],
...requestedFunctions
};
return objectifiedPath;
}
function checkPath(path) {
path = path.replace('\\', '/');
if (path.startsWith('/')) {
path = path.substring(1, path.length);
}
if (path.endsWith('/')) {
path = path.substring(0, path.length - 1);
}
return path;
}
function getStructureObject(structure, path) {
path = checkPath(path);
const [key, ...otherKeys] = path.split('/');
if (structure[key] === undefined) {
return undefined;
} else if (otherKeys.length >= 1) {
return getStructureObject(structure[key], otherKeys.join('/'));
} else {
return structure[key];
}
}
// function list /*directory*/() {}
// function read /*file*/() {}
// function del /*file or directory*/() {}
// function toPath() {}
// const pathdb = new PathDB('C:/Users/Patryk Sitko/Desktop/my-videos-app/media');
// pathdb.monitor();
// console.log(pathdb.get('/series/naruto copy/season/1/episode/2'));
// setTimeout(
// async () =>
// console.log(await pathdb.structure.series.naruto['image.png'].read()),
// 1000
// );
// setInterval(
// () =>
// console.log(pathdb.structure.series.anime.naruto.season['1'].episode[1]),
// 10
// );
// pathdb.stop();
// console.log(
// fs
// .lstatSync('C:/Users/Patryk Sitko/Desktop/my-videos-app/.dockerignore')
// .isFile()
// );