-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
vfs.js
386 lines (336 loc) · 9.2 KB
/
vfs.js
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
/*
* OS.js - JavaScript Cloud/Web Desktop Platform
*
* Copyright (c) 2011-2020, Anders Evenrud <andersevenrud@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Anders Evenrud <andersevenrud@gmail.com>
* @license Simplified BSD License
*/
/**
* Get parent directory
* @param {string} path Directory
* @return {string} Parent directory
*/
export const parentDirectory = path => path
.replace(/\/$/, '')
.split('/')
.filter((item, index, arr) => index < (arr.length - 1))
.join('/')
.replace(/(\/+)?$/, '/');
/**
* Joins paths
* @param {string[]} args paths
* @return {string}
*/
export const pathJoin = (...args) => args
.map((str, index) => {
if (index > 0) {
str = str.replace(/^\/?/, '');
}
return str.replace(/\/?$/, '');
})
.join('/');
/*
* Sort by locale string
*/
const sortString = (k, d) => (a, b) => d === 'asc'
? String(a[k]).localeCompare(b[k])
: String(b[k]).localeCompare(a[k]);
/*
* Sort by date
*/
const sortDate = (k, d) => (a, b) => d === 'asc'
? (new Date(a[k])) > (new Date(b[k]))
: (new Date(b[k])) > (new Date(a[k]));
/*
* Sort by educated guess
*/
const sortDefault = (k, d) => (a, b) =>
(a[k] < b[k])
? -1
: ((a[k] > b[k])
? (d === 'asc' ? 1 : 0)
: (d === 'asc' ? 0 : 1));
/*
* Sorts an array of files
*/
const sortFn = t => {
if (t === 'string') {
return sortString;
} else if (t === 'date') {
return sortDate;
}
return sortDefault;
};
/*
* Map of sorters from readdir attributes
*/
const sortMap = {
size: sortFn('number'),
mtime: sortFn('date'),
ctime: sortFn('date'),
atime: sortFn('date')
};
/**
* Creates "special" directory entries
* @param {string} path The path to the readdir root
* @return {Object[]}
*/
const createSpecials = path => {
const specials = [];
const stripped = path.replace(/\/+/g, '/')
.replace(/^(\w+):/, '') || '/';
if (stripped !== '/') {
specials.push({
isDirectory: true,
isFile: false,
mime: null,
size: 0,
stat: {},
filename: '..',
path: parentDirectory(path) || '/'
});
}
return specials;
};
/**
* Creates a FileReader (promisified)
* @param {string} method The method to call
* @param {ArrayBuffer} ab The ArrayBuffer
* @param {string} mime The MIME type
* @return {Promise}
*/
const createFileReader = (method, ab, mime) => new Promise((resolve, reject) => {
const b = new Blob([ab], {type: mime});
const r = new FileReader();
r.onerror = e => reject(e);
r.onloadend = () => resolve(r.result);
r[method](b);
});
/**
* Converts a number (bytez) into human-readable string
* @param {Number} bytes Input
* @param {Boolean} [si=false] Use SI units
* @return {string}
*/
export const humanFileSize = (bytes, si = false) => {
if (isNaN(bytes) || typeof bytes !== 'number') {
bytes = 0;
}
const thresh = si ? 1000 : 1024;
const units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
if (bytes < thresh) {
return bytes + ' B';
}
let u = -1;
do {
bytes /= thresh;
++u;
} while (bytes >= thresh);
return `${bytes.toFixed(1)} ${units[u]}`;
};
/**
* Transforms a readdir result
* @param {object} root The path to the readdir root
* @param Object[] files An array of readdir results
* @param {object} options Options
* @param {Boolean} [options.showHiddenFiles=false] Show hidden files
* @param {Function} [options.filter] A filter
* @param {string} [options.sortBy='filename'] Sort by this attribute
* @param {string} [options.sortDir='asc'] Sort in this direction
* @return {Object[]}
*/
export const transformReaddir = ({path}, files, options = {}) => {
options = {
showHiddenFiles: false,
sortBy: 'filename',
sortDir: 'asc',
...options
};
let {sortDir, sortBy, filter} = options;
if (typeof filter !== 'function') {
filter = () => true;
}
if (['asc', 'desc'].indexOf(sortDir) === -1) {
sortDir = 'asc';
}
const filterHidden = options.showHiddenFiles
? () => true
: file => file.filename.substr(0, 1) !== '.';
const sorter = sortMap[sortBy]
? sortMap[sortBy]
: sortFn('string');
const modify = (file) => ({
...file,
humanSize: humanFileSize(file.size)
});
// FIXME: Optimize this to one chain!
const sortedSpecial = createSpecials(path)
.sort(sorter(sortBy, sortDir))
.map(modify);
const sortedDirectories = files.filter(file => file.isDirectory)
.sort(sorter(sortBy, sortDir))
.filter(filterHidden)
.filter(filter)
.map(modify);
const sortedFiles = files.filter(file => !file.isDirectory)
.sort(sorter(sortBy, sortDir))
.filter(filterHidden)
.filter(filter)
.map(modify);
return [
...sortedSpecial,
...sortedDirectories,
...sortedFiles
];
};
/**
* Transform an ArrayBuffer
* @param {ArrayBuffer} ab The ArrayBuffer
* @param {string} mime The MIME type
* @param {string} type Transform to this type
* @return {DOMString|string|Blob|ArrayBuffer}
*/
export const transformArrayBuffer = (ab, mime, type) => {
if (type === 'string') {
return createFileReader('readAsText', ab, mime);
} else if (type === 'uri') {
return createFileReader('readAsDataURL', ab, mime);
} else if (type === 'blob') {
return Promise.resolve(new Blob([ab], {type: mime}));
}
return Promise.resolve(ab);
};
/**
* Gets an icon from file stat
* @param {object} file The file stat object
* @return {string|object}
*/
export const getFileIcon = map => {
const find = file => {
const found = Object.keys(map).find(re => {
const regexp = new RegExp(re);
return regexp.test(file.mime);
});
return found
? map[found]
: {name: 'application-x-executable'};
};
return file => file.isDirectory
? {name: 'folder'}
: find(file);
};
/**
* Creates a file iter for scandir
* @param {object} stat file stat
* @return {object}
*/
export const createFileIter = stat => ({
isDirectory: false,
isFile: true,
mime: 'application/octet-stream',
icon: null,
size: -1,
path: null,
filename: null,
label: null,
stat: {},
id: null,
parent_id: null,
...stat
});
/**
* Get basename of a file
* @param {string} path The path
* @return {string}
*/
export const basename = path => path.split('/').reverse()[0];
/*
* Get path of a file
* @param {string} path The path
* @return {string}
*/
export const pathname = path => {
const split = path.split('/');
if (split.length === 2) {
split[1] = '';
} else {
split.splice(split.length - 1, 1);
}
return split.join('/');
};
/**
* Gets prefix from vfs path
* @param {string} str Input
* @return {string}
*/
export const parseMontpointPrefix = str => {
const re = /^([\w-_]+):+(.*)/;
const match = String(str)
.replace(/\+/g, '/')
.match(re);
const [prefix] = Array.from(match || [])
.slice(1);
return prefix;
};
/**
* Filters a mountpoint by user groups
* @return {boolean}
*/
export const filterMountByGroups = userGroups => (mountGroups, strict = true) =>
mountGroups instanceof Array
? mountGroups[strict ? 'every' : 'some'](g => userGroups.indexOf(g) !== -1)
: true;
/**
* Creates a list of VFS events to simulate server-side
* file watching
* @return {object[]}
*/
export const createWatchEvents = (method, args) => {
const events = [];
const options = args[args.length - 1] || {};
const movement = ['move', 'rename', 'copy'].indexOf(method) !== -1;
const invalid = ['readdir', 'download', 'url', 'exists', 'readfile', 'search', 'stat'].indexOf(method) !== -1;
const path = i => typeof i === 'string' ? i : i.path;
if (!invalid) {
const obj = {
method,
source: path(args[0]),
pid: options.pid
};
events.push(['osjs/vfs:directoryChanged', {
...obj,
path: pathname(path(args[0])),
}]);
if (movement) {
events.push(['osjs/vfs:directoryChanged', {
...obj,
path: pathname(path(args[1]))
}]);
}
}
return events;
};