This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebFileSystem.ts
1196 lines (1047 loc) · 46.6 KB
/
WebFileSystem.ts
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {v2 as webdav} from "webdav-server";
import * as mime from 'mime-types'
import {Path} from "webdav-server/lib/manager/v2/Path";
import {
CreateInfo,
CreationDateInfo,
DeleteInfo,
LastModifiedDateInfo,
LockManagerInfo,
MoveInfo,
OpenReadStreamInfo,
OpenWriteStreamInfo,
PropertyManagerInfo,
ReadDirInfo,
RenameInfo,
SizeInfo,
TypeInfo
} from "webdav-server/lib/manager/v2/fileSystem/ContextInfo";
import {ReturnCallback, SimpleCallback} from "webdav-server/lib/manager/v2/fileSystem/CommonTypes";
import {Readable, Writable} from "stream";
import {ILockManager} from "webdav-server/lib/manager/v2/fileSystem/LockManager";
import {IPropertyManager} from "webdav-server/lib/manager/v2/fileSystem/PropertyManager";
import User from "./User";
import logger from './logger';
import api from './api';
import {AxiosResponse} from "axios";
class WebFileSystemSerializer implements webdav.FileSystemSerializer {
uid(): string {
return "WebFileSystemSerializer_1.0.0";
}
serialize(fs: WebFileSystem, callback: ReturnCallback<any>) {
callback(null, {
props: fs.props
});
}
unserialize(serializedData: any, callback: ReturnCallback<WebFileSystem>) {
const fs = new WebFileSystem();
fs.props = new webdav.LocalPropertyManager(serializedData.props);
callback(null, fs);
}
}
interface Resource {
id: string,
type: webdav.ResourceType,
size: number,
creationDate: number,
lastModifiedDate: number,
owner?: boolean,
permissions: {
read: boolean,
write: boolean,
delete: boolean,
create: boolean
},
role?: string,
}
interface ResourceResponse {
_id: string,
name: string,
isDirectory: boolean,
createdAt: string,
updatedAt: string,
permissions: Permissions[],
size: number
}
interface Permissions {
read: boolean,
write: boolean,
delete: boolean,
create: boolean,
refId?: string,
refPermModel?: string
}
interface S3Header {
'Content-Type': string,
'x-amz-meta-name': string,
'x-amz-meta-flat-name': string,
'x-amz-meta-thumbnail': string
}
interface WritableURLResponse {
url: string,
header: S3Header
}
class WebFileSystem extends webdav.FileSystem {
props: webdav.IPropertyManager;
locks: webdav.ILockManager;
resources: Map<string, Map<string, Resource>>
rootPath: string
constructor (rootPath?: string) {
super(new WebFileSystemSerializer());
this.props = new webdav.LocalPropertyManager();
this.locks = new webdav.LocalLockManager();
this.resources = new Map();
this.rootPath = rootPath ? rootPath : 'courses'
}
_propertyManager (path: Path, info: PropertyManagerInfo, callback: ReturnCallback<IPropertyManager>) : void {
callback(null, this.props)
}
_lockManager (path: Path, info:LockManagerInfo, callback:ReturnCallback<ILockManager>) : void {
callback(null, this.locks)
}
/*
* Returns whether a given path was already loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {boolean} Existence of resource
*/
resourceExists(path: Path, user: User): boolean {
return this.resources.get(user.uid).has(path.toString())
}
/*
* Deletes a given resource from local cache
*
* @param {Path} path Path to resource
* @param {User} user Current user
*/
deleteResourceLocally (path: Path, user: User): void {
this.resources.get(user.uid).delete(path.toString())
}
/*
* Gets ID by path and user and returns null if resource not loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {string} ID of resource
*/
getID(path: Path, user: User) : string {
return this.resourceExists(path, user) ? this.resources.get(user.uid).get(path.toString()).id : null
}
/*
* Gets permissions by path and user and returns null if resource not loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {Permissions} Permissions of resource
*/
testPermission(path: Path, user: User, permission: string) : boolean {
return this.resourceExists(path, user) ? this.resources.get(user.uid).get(path.toString()).permissions[permission] : null
}
/*
* Tests read permission of resource and returns null if resource not loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {boolean} Read-permission of file
*/
canRead(path: Path, user: User) : boolean {
return this.testPermission(path, user, 'read')
}
/*
* Tests write permission of resource and returns null if resource not loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {boolean} Write-permission of file
*/
canWrite(path: Path, user: User) : boolean {
return this.testPermission(path, user, 'write')
}
/*
* Tests create permission of resource and returns null if resource not loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {boolean} Create-permission of file
*/
canCreate(path: Path, user: User) : boolean {
return this.testPermission(path, user, 'create')
}
/*
* Tests delete permission of resource and returns null if resource not loaded
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {boolean} Delete-permission of file
*/
canDelete(path: Path, user: User) : boolean {
return this.testPermission(path, user, 'delete')
}
/*
* Returns the owner ID of the given resource
*
* @param {Path} path Path of the resource
* @param {User} user Current user
*
* @return {string} owner ID
*/
getOwnerID (path: Path, user: User): string {
if (this.rootPath === 'my') {
return user.uid
} else {
return this.getID(new Path(path.rootName()), user)
}
}
/*
* Returns the parent ID of the given resource
*
* @param {Path} path Path of the resource
* @param {User} user Current user
*
* @return {string} parent ID
*/
getParentID (path: Path, user: User): string {
if (this.rootPath === 'my') {
return this.resourceExists(path, user) ? this.getID(path, user) : user.uid
} else {
return this.getID(path, user)
}
}
/*
* Returns true if the filename is valid
*
* @param {string} name Name of the file
*
* @return {Boolean} true if fileName is valid, false else
*/
validFileName(name: string): boolean {
return !name.match(/[#%^[\],<>?/|~{}]+/)
}
/*
* Loads the root directories of the user
*
* @param {User} user Current user
*
* @return {Promise<string[]>} List of root directories
*/
async loadRootDirectories(user: User) : Promise<string[]> {
if (this.rootPath !== 'my') {
let qs
let url
switch (this.rootPath) {
case 'courses':
qs = {$or: [
{ userIds: user.uid },
{ teacherIds: user.uid },
{ substitutionIds: user.uid },
],}
url = `/courses`
break
case 'teams':
url = `/teams`
break
case 'shared':
qs= {
$and: [
{ permissions: { $elemMatch: { refPermModel: 'user', refId: user.uid } } },
{ creator: { $ne: user.uid } },
],
}
url= `/files`
break
default:
return []
}
const res = await api({user}).get(url, {params: qs})
const data = res.data
logger.debug(`WebFileSystem.loadRootDirectories.res.data: ${JSON.stringify(data)}`)
// TODO: make this look fancy :)
let adder
if (this.rootPath === 'shared'){
adder = this.addFileToResources.bind(this)
} else {
adder = (path: Path, user: User, resource : ResourceResponse) => {
this.resources.get(user.uid).set(path.toString(), {
type: webdav.ResourceType.Directory,
id: resource._id,
size: null,
creationDate: null,
lastModifiedDate: null,
permissions: null
});
}
}
for (const resource of data.data) {
adder(new Path([resource.name]), user, resource)
// TODO: Maybe can be integrated more beautiful
if (this.rootPath === 'teams') {
const res = await api({user}).get('/teams/' + resource._id)
logger.debug(`response Data on load teams: ${res.data}`)
this.resources.get(user.uid).get('/' + resource.name).role = res.data.user.role
}
}
return data['data'].map((resource) => resource.name)
} else {
return await this.loadDirectory(new Path([]), user)
}
}
/*
* Populates permissions by combining user and roles permissions
*
* @param {Array<Permissions>} permissions Permissions of one file or directory
* @param {User} user Current user
*
* @return {Permissions} Permission object containing write, read, create and delete permissions
*/
populatePermissions(file: ResourceResponse, path: Path, user: User): Permissions {
const filePermissions = {
write: false,
read: false,
create: false,
delete: false
}
// TODO: Make it prettier
file.permissions.filter((role) => (role.refPermModel == 'user' && role.refId == user.uid) ||
(role.refPermModel == 'role' && (user.roles.includes(role.refId) ||
(this.rootPath === 'teams' && role.refId == this.resources.get(user.uid).get('/' + path.rootName()).role))))
.forEach((role) => {
filePermissions.write = role.write ? true : filePermissions.write
filePermissions.read = role.read ? true : filePermissions.read
filePermissions.create = role.create ? true : filePermissions.create
filePermissions.delete = role.delete ? true : filePermissions.delete
})
logger.debug(`File-Permissions: ${JSON.stringify(filePermissions)}`)
return filePermissions
}
/*
* Loads the resources of the given directory
*
* @param {Path} path Path of the directory
* @param {User} user Current user
*
* @return {Promise<string[]>} List of resources in directory
*/
async loadDirectory (path: Path, user: User) : Promise<string[]> {
const owner = this.getOwnerID(path, user)
const parent = this.getParentID(path, user)
try {
const res = await api({user}).get('/fileStorage?owner=' + owner + (parent != owner ? '&parent=' + parent : ''));
const data: ResourceResponse[] = res.data;
logger.debug(`Load Directory Response Data: ${JSON.stringify(data)}`)
if (this.rootPath === 'teams') {
const teamRes = await api({user}).get('teams/' + owner)
logger.debug(`Response Data on load Directory in teams: ${JSON.stringify(teamRes.data)}`)
}
const resources = []
for (const resource of data) {
this.addFileToResources(path.getChildPath(resource.name), user, resource)
resources.push(resource.name)
}
return resources
} catch (error) {
logger.error(`WebFileSystem.loadDirectory.error.${error.response.data.code}: ${error.response.data.message} uid: ${user.uid}`, error)
this.deleteResourceLocally(path, user)
if (error.response.data.code === 404) {
throw webdav.Errors.ResourceNotFound
} else {
throw webdav.Errors.Forbidden
}
}
}
/*
* Loads every parent path until the given path
*
* @param {Path} path Path to load
* @param {User} user Current user
*
* @return {Promise<Boolean>} Returns whether the path exists
*/
async loadPath(path: Path, user: User) : Promise<boolean> {
await this.loadRootDirectories(user)
let currentPath = path.getParent()
while (!this.resourceExists(path, user)) {
if (this.resourceExists(currentPath, user)) {
try {
const resources = await this.loadDirectory(currentPath, user)
if (!resources.includes(path.paths[currentPath.paths.length])) {
return false
}
currentPath = currentPath.getChildPath(path.paths[currentPath.paths.length])
} catch (error) {
return false
}
} else {
if (currentPath.hasParent()) {
currentPath = currentPath.getParent()
} else {
return false;
}
}
}
return true
}
/*
* Returns given metadata of a resource
*
* @param {Path} path Path of the resource
* @param {string} key Property name
* @param {User} user Current user
*
* @return {Promise<number>} Metadata value
*/
async getMetadata(path: Path, key: string, user: User) : Promise<number> {
if (this.resourceExists(path, user)) {
const value = this.resources.get(user.uid).get(path.toString())[key]
if (value) {
return value
}
} else {
if (await this.loadPath(path, user)) {
const value = this.resources.get(user.uid).get(path.toString())[key]
if (value) {
return value
}
} else {
return -1
}
}
}
/*
* Creates an entry in resources-map if it not exists
*
* @param {string} uid User-ID of the logged in user
*
*/
createUserFileSystem(uid: string): void {
if (!this.resources.has(uid)) {
this.resources.set(uid, new Map())
}
}
/*
* Adds a file object returned by SC-Server to this.resources
*
* @param {Path} path Path to resource
* @param {User} user Current user
* @param {ResourceResponse} file File JSON-Object returned by server
*
* @return {Resource} Resource object saved to this.resources
*/
addFileToResources (path: Path, user: User, file: ResourceResponse): Resource {
const creationDate = new Date(file.createdAt)
const lastModifiedDate = new Date(file.updatedAt)
const permissions = this.populatePermissions(file, path, user)
const resource: Resource = {
type: file.isDirectory ? webdav.ResourceType.Directory : webdav.ResourceType.File,
id: file._id,
size: file.size,
creationDate: creationDate.getTime(),
lastModifiedDate: lastModifiedDate.getTime(),
owner: file.permissions[0].refId == user.uid,
permissions
}
this.resources.get(user.uid).set(path.toString(), resource);
return resource
}
/*
* Retrieves a download-URL of an existing S3-file
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {Promise<string>} Signed URL
*/
async retrieveSignedUrl (path: Path, user: User): Promise<string> {
try {
const res = await api({user}).get('/fileStorage/signedUrl?file=' + this.getID(path, user))
if (res.data.url) {
return res.data.url
}
} catch (error) {
if (error.response?.data?.code === 404) {
this.deleteResourceLocally(path, user)
throw webdav.Errors.ResourceNotFound
}
}
throw webdav.Errors.Forbidden
}
async _openReadStream (path: Path, info: OpenReadStreamInfo, callback: ReturnCallback<Readable>) : Promise<void> {
logger.info("Reading file: " + path.toString())
if (info.context.user) {
const user: User = <User> info.context.user
this.createUserFileSystem(user.uid)
if (this.canRead(path, user)) {
try {
const url = await this.retrieveSignedUrl(path, user)
logger.info("Signed URL: " + url)
const file = await api({}).get(url, { responseType: 'arraybuffer' })
const buffer = await file.data
callback(null, new webdav.VirtualFileReadable([ buffer ]))
} catch (error) {
logger.error(`WebFileSystem._openReadStream.retrieveSignedUrl.error: ${error.message} uid: ${user.uid}`, error)
callback(error)
}
} else {
logger.warn(`WebFileSystem._openReadStream.permissions.read.false : Reading not allowed! uid: ${user.uid}`)
callback(webdav.Errors.Forbidden)
}
} else {
logger.warn(`WebFileSystem._openReadStream.context.user.false : ${webdav.Errors.BadAuthentication.message}`)
callback(webdav.Errors.BadAuthentication)
}
}
async _readDir(path: Path, info: ReadDirInfo, callback: ReturnCallback<string[] | Path[]>): Promise<void> {
logger.info("Reading dir: " + path)
if (info.context.user) {
const user: User = <User> info.context.user
this.createUserFileSystem(user.uid)
if (path.isRoot()) {
callback(null, await this.loadRootDirectories(user))
} else {
if (this.resourceExists(path, user)) {
try {
callback(null, await this.loadDirectory(path, user))
} catch (error) {
// Error callback doesn't seem to work here in _readDir (at least with Cyberduck)
// TODO: Fix this problem because otherwise you can open ghost directories which leads to problems
callback(error)
}
} else {
if (await this.loadPath(path, user)) {
try {
callback(null, await this.loadDirectory(path, user))
} catch (error) {
callback(error)
}
} else {
logger.error(`WebFileSystem._readDir.loadPath.false : Directory could not be found! uid: ${user.uid} path: ${path.toString()}`, new Error('Stack-Tracer'))
callback(webdav.Errors.ResourceNotFound)
}
}
}
} else {
logger.warn(`WebFileSystem._readDir.context.user.false : ${webdav.Errors.BadAuthentication.message} path: ${path.toString()}`)
callback(webdav.Errors.BadAuthentication)
}
}
async _type(path: Path, info: TypeInfo, callback: ReturnCallback<webdav.ResourceType>): Promise<void> {
logger.info("Checking type: " + path)
// For guest users
if (path.isRoot()) {
callback(null, webdav.ResourceType.Directory);
} else if (info.context.user) {
const user: User = <User> info.context.user
this.createUserFileSystem(user.uid)
if (this.resourceExists(path, user)) {
callback(null, this.resources.get(user.uid).get(path.toString()).type)
} else {
if (await this.loadPath(path, user)) {
callback(null, this.resources.get(user.uid).get(path.toString()).type)
} else {
logger.error(`WebFileSystem._type.loadPath.false : File could not be found! uid: ${info.context.user.uid} path: ${path.toString()}`, new Error('Stack-Tracer'))
callback(webdav.Errors.ResourceNotFound)
}
}
} else {
logger.warn(`WebFileSystem._type.context.user.false : ${webdav.Errors.BadAuthentication.message} path: ${path.toString()}`)
callback(webdav.Errors.BadAuthentication)
}
}
async _size(path: Path, ctx: SizeInfo, callback: ReturnCallback<number>): Promise<void> {
logger.info("Checking size: " + path);
if (ctx.context.user) {
this.createUserFileSystem(ctx.context.user.uid)
const size = await this.getMetadata(path, 'size', <User>ctx.context.user)
if (size >= 0) {
callback(null, size)
} else {
callback(webdav.Errors.None)
}
} else {
logger.warn(`WebFileSystem._size.user.false : ${webdav.Errors.BadAuthentication.message}`)
callback(webdav.Errors.BadAuthentication)
}
}
async _creationDate(path: Path, ctx: CreationDateInfo, callback: ReturnCallback<number>): Promise<void> {
logger.info("Checking creation date: " + path);
if (ctx.context.user) {
this.createUserFileSystem(ctx.context.user.uid)
const creationDate = await this.getMetadata(path, 'creationDate', <User>ctx.context.user)
if (creationDate >= 0) {
callback(null, creationDate)
} else {
callback(webdav.Errors.None)
}
} else {
logger.warn(`WebFileSystem._creationDate.user.false : ${webdav.Errors.BadAuthentication.message}`)
callback(webdav.Errors.BadAuthentication)
}
}
async _lastModifiedDate(path: Path, ctx: LastModifiedDateInfo, callback: ReturnCallback<number>): Promise<void> {
logger.info("Checking last modified date: " + path);
if (ctx.context.user) {
this.createUserFileSystem(ctx.context.user.uid)
const lastModifiedDate = await this.getMetadata(path, 'lastModifiedDate', <User>ctx.context.user)
if (lastModifiedDate >= 0) {
callback(null, lastModifiedDate)
} else {
callback(webdav.Errors.None)
}
} else {
logger.warn(`WebFileSystem._lastModifiedDate.user.false : ${webdav.Errors.BadAuthentication.message}`)
callback(webdav.Errors.BadAuthentication)
}
}
/*
* Creates resource with given path (only docx, pptx or xlsx)
*
* @param {Path} path Path of the resource
* @param {User} user Current user
* @param {webdav.ResourceType} type Type of the new resource
*
* @return {Promise<Error>} Error or null depending on success of creation
*/
async createResource (path: Path, user: User, type: webdav.ResourceType) : Promise<Error> {
// checks if file already exists and if filename contains bad characters (e.g. "§%?&....")
if (!this.validFileName(path.fileName())){
logger.info(`Name ${path.fileName()} not allowed.`)
return webdav.Errors.Forbidden
} else if ((await this.loadDirectory(path.getParent(), user)).includes(path.fileName())) {
logger.info(`Resource ${path} already exists.`)
return webdav.Errors.ResourceAlreadyExists
} else if (this.resourceExists(path, user)) {
this.deleteResourceLocally(path, user)
}
if (!this.resources.get(user.uid).get(path.getParent().toString())?.permissions || this.canCreate(path.getParent(), user)) {
if (type.isDirectory || ['docx', 'pptx', 'xlsx'].includes(mime.extension(mime.lookup(path.fileName())))) {
const owner = this.getOwnerID(path, user)
const parent = this.getParentID(path.getParent(), user)
const body = {
name: path.fileName(),
parent: (parent != owner) ? parent : undefined
}
if (owner !== user.uid) {
body['owner'] = owner
}
try {
const res = await api({user , json: true}).post('/fileStorage' + (type.isDirectory ? '/directories' : '/files/new'), body);
const data = res.data;
logger.debug(`WebFileSystem.createResource.post: res.data: ${JSON.stringify(data)}`)
if (data._id) {
this.addFileToResources(path, user, data)
} else {
logger.error(webdav.Errors.Forbidden.message, new Error('Stack-Tracer'))
return webdav.Errors.Forbidden
}
} catch (error) {
logger.error(`WebFileSystem.createResource.error.${error.response.data.code}: ${error.response.data.message} uid: ${user.uid}`, error)
return webdav.Errors.Forbidden
}
} else {
try {
const data = await this.requestWritableSignedUrl(path, user)
await this.writeToSignedUrl(data.url, data.header, [])
const file = await this.writeToFileStorage(path, user, data.header, [])
logger.debug(`createResource response data: ${file}`)
if (file._id) {
this.addFileToResources(path, user, file)
} else {
logger.error(webdav.Errors.Forbidden.message)
return webdav.Errors.Forbidden
}
} catch (error) {
logger.error(`Failed to create Ressource: uid: ${user.uid} path: ${path.toString()}`, error)
return error
}
}
} else {
logger.error(`WebFileSystem.createResource.permissions.false : Creating resource not allowed! uid: ${user.uid} path: ${path.toString()}`, new Error('Stack-Tracer'))
return webdav.Errors.Forbidden
}
return null
}
async _create(path: Path, ctx: CreateInfo, callback: SimpleCallback): Promise<void> {
logger.info("Creating resource: " + path)
if (ctx.context.user) {
const user: User = <User> ctx.context.user
this.createUserFileSystem(user.uid)
if (!path.hasParent()) {
if (this.rootPath === 'my') {
callback(await this.createResource(path, user, ctx.type))
} else {
logger.error(`WebFileSystem._create.isAtRootLevel.true : Creating resource not allowed! path: ${path.toString()} uid: ${user.uid}`, new Error('Stack-Tracer'))
callback(webdav.Errors.Forbidden)
}
} else if (this.resourceExists(path.getParent(), user)) {
callback(await this.createResource(path, user, ctx.type))
} else {
if (await this.loadPath(path.getParent(), user)) {
callback(await this.createResource(path, user, ctx.type))
} else {
logger.error(`WebFileSystem._create.loadPath.false : Resource could not be found! path: ${path.toString()} uid: ${user.uid}`, new Error('Stack-Tracer'))
callback(webdav.Errors.ResourceNotFound)
}
}
} else {
logger.warn(`WebFileSystem._create.context.user.false : ${webdav.Errors.BadAuthentication.message} path: ${path.toString()}`)
callback(webdav.Errors.BadAuthentication)
}
}
/*
* Deletes resource with given path
*
* @param {Path} path Path of the resource
* @param {User} user Current user
*
* @return {Promise<Error>} Error or null depending on success of deletion
*/
async deleteResource (path: Path, user: User) : Promise<Error> {
// Web Client checks user permission instead of file permission, but SC-Server checks specific permission
// if (this.canDelete(path, user)) {
if (user.permissions.includes('FILE_DELETE')) {
const type: webdav.ResourceType = this.resources.get(user.uid).get(path.toString()).type
const res = await api({user}).delete('/fileStorage' + (type.isDirectory ? '/directories?_id=' : '?_id=') + this.getID(path, user));
const data = res.data;
// Server returns error if not allowed
if (data.code) {
logger.error(`WebFileSystem.deleteResource.data.code.${data.code}: ${data.message} uid: ${user.uid}`, new Error('Stack-Tracer'))
if (data.code === 403 && data.errors?.code !== 404) {
return webdav.Errors.Forbidden
}
} else {
logger.debug(`WebFileSystem.deleteResource.data.code.null: res.data: ${JSON.stringify(data)}`)
}
this.deleteResourceLocally(path, user)
return null
} else {
logger.error(`WebFileSystem.deleteResource.deletePermission.false : Deleting resource not allowed! uid: ${user.uid} path: ${path.toString()}`, new Error('Stack-Tracer'))
return webdav.Errors.Forbidden
}
}
async _delete(path: Path, ctx: DeleteInfo, callback: SimpleCallback): Promise<void> {
logger.info("Deleting resource: " + path)
if (ctx.context.user) {
const user: User = <User> ctx.context.user
this.createUserFileSystem(user.uid)
if (!path.hasParent() && (this.rootPath === 'courses' || this.rootPath === 'teams')) {
callback(webdav.Errors.Forbidden)
return
}
if (this.resourceExists(path, user)) {
callback(await this.deleteResource(path, user))
} else {
if (await this.loadPath(path, user)) {
callback(await this.deleteResource(path, user))
} else {
logger.error(`WebFileSystem._delete.loadPath.false : Resource could not be found! uid: ${user.uid} path: ${path.toString()}`, new Error('Stack-Tracer'))
callback(webdav.Errors.ResourceNotFound)
}
}
} else {
logger.warn(`WebFileSystem._delete.context.user.false : ${webdav.Errors.BadAuthentication.message}`)
callback(webdav.Errors.BadAuthentication)
}
}
/*
* Requests writable signed URL of SC file storage to a S3 bucket
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {Promise<WritableURLResponse>} JSON-Response of SC-Server containing URL and header.
*/
async requestWritableSignedUrl (path: Path, user: User): Promise<WritableURLResponse> {
const filename = path.fileName()
const contentType = mime.lookup(filename) || 'application/octet-stream'
const parent = this.getParentID(path.getParent(), user)
let res
if (this.resourceExists(path, user)) {
try {
res = await api({user, json: true}).patch('/fileStorage/signedUrl/' + this.getID(path, user))
} catch (error) {
logger.error(`WebFileSystem.requestWritableSignedUrl.error.${error.response.data.code}: ${error.response.data.message} uid: ${user.uid}`, new Error('Stack-Tracer'))
if (error.response.data.code === 404) {
this.deleteResourceLocally(path, user)
return this.requestWritableSignedUrl(path, user)
} else {
throw webdav.Errors.Forbidden
}
}
if (res.data.code) {
logger.error(`WebFileSystem.requestWritableSignedUrl.error.${res.data.code}: ${res.data.message} uid: ${user.uid}`, new Error('Stack-Tracer'))
throw webdav.Errors.Forbidden
}
} else {
try {
res = await api({user, json: true}).post('/fileStorage/signedUrl', {
filename,
fileType: contentType,
parent: this.getOwnerID(path, user) != parent ? parent : undefined
})
} catch (error) {
logger.error(`WebFileSystem.requestWritableSignedUrl.error.${error.response.data.code}: ${error.response.data.message} uid: ${user.uid}`, error)
throw webdav.Errors.Forbidden
}
}
const data = res.data
logger.debug(`requestWritableSignedUrl res data: ${data}`)
return data
}
async writeToSignedUrl (url: string, header: S3Header, content: ReadonlyArray<Uint8Array>): Promise<void> {
await api({}).put(url,
Buffer.concat(content),
{
headers: {
...header
},
})
}
/*
* Registers a file to the file storage of SC-Server
*
* @param {Path} path Path to resource
* @param {User} user Current user
* @param {S3Header} header S3-Header returned by S3-Request
* @param {ReadonlyArray<Uint8Array>} contents Contents of stream
*
* @return {Promise<ResourceResponse>} File Object of the new file
*/
async writeToFileStorage (path: Path, user: User, header: S3Header, content: ReadonlyArray<Uint8Array>): Promise<ResourceResponse> {
const owner = this.getOwnerID(path, user)
const parent = this.getParentID(path.getParent(), user)
const type = mime.lookup(path.fileName()) || 'application/octet-stream'
const body = {
name: path.fileName(),
parent: parent != owner ? parent : undefined,
type,
size: Buffer.concat(content).byteLength,
storageFileName: header['x-amz-meta-flat-name'],
thumbnail: header['x-amz-meta-thumbnail']
}
if (owner !== user.uid) {
body['owner'] = owner
}
try {
const res = await api({user, json: true}).post('/fileStorage', body)
return res.data
} catch (error) {
logger.error(`WebFileSystem.writeToFileStorage.error.${error.response.data.code}: ${error.response.data.message} uid: ${user.uid}`, error)
throw webdav.Errors.Forbidden
}
}
/*
* Creates a write stream and stores file when finished
*
* @param {Path} path Path to resource
* @param {User} user Current user
*
* @return {webdav.VirtualFileWritable} Writable stream
*/
processStream(path: Path, user: User): webdav.VirtualFileWritable {
const contents = []
const stream = new webdav.VirtualFileWritable(contents)
stream.on('finish', async () => {
try {
const data = await this.requestWritableSignedUrl(path, user)
if (data.url) {
await this.writeToSignedUrl(data.url, data.header, contents)
if (!this.resourceExists(path, user)) {
const file = await this.writeToFileStorage(path, user, data.header, contents)
logger.info(`Response Data on writeToFileStorage: ${file}`)
if (file._id) {
this.addFileToResources(path, user, file)
} else {
logger.error(`WebFileSystem.processStream.file._id.false: ${webdav.Errors.Forbidden.message} uid: ${user.uid}`, new Error('Stack-Tracer'))
}
} else {
const res = await api({user, json: true}).patch('/files/' + this.getID(path, user), {
size: Buffer.concat(contents).byteLength,
updatedAt: new Date().toISOString()
})
this.resources.get(user.uid).get(path.toString()).size = Buffer.concat(contents).byteLength
this.resources.get(user.uid).get(path.toString()).lastModifiedDate = Date.now()
logger.debug(`processStream: ${JSON.stringify(res.data)}`)
}
} else {
logger.error(`WebFileSystem.processStream.data.url.false: ${webdav.Errors.Forbidden.message} uid: ${user.uid}`, new Error('Stack-Tracer'))
}
} catch (error) {
logger.error(`WebFileSystem.processStream.onFinish.error: ${error.message} uid: ${user.uid}`,error)
}
})
return stream