-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathofsf.go
More file actions
1066 lines (864 loc) · 25.6 KB
/
ofsf.go
File metadata and controls
1066 lines (864 loc) · 25.6 KB
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type UpdateFileRequest struct {
Updates []UpdateChange `json:"updates" binding:"required"`
}
type GetFilesRequest struct {
Username string `json:"username" binding:"required"`
UUIDs []string `json:"uuids" binding:"required"`
}
type FileMetadata struct {
Entry FileEntry `json:"entry"`
Index int `json:"index"`
}
type FileEntry []any
type FileEntryStruct struct {
Type string `json:"type"`
Name string `json:"name"`
Location string `json:"location"`
Data string `json:"data"`
DataSecondary any `json:"data_secondary"`
X int64 `json:"x"`
Y int64 `json:"y"`
Id any `json:"id"`
Created int64 `json:"created"`
Edited int64 `json:"edited"`
Icon string `json:"icon"`
Size int64 `json:"size"`
Permissions []string `json:"permissions"`
UUID string `json:"uuid"`
}
type FolderEntryStruct struct {
Name string `json:"name"`
Location string `json:"location"`
Data []any `json:"data"`
DataSecondary any `json:"data_secondary"`
X int64 `json:"x"`
Y int64 `json:"y"`
Id any `json:"id"`
Created int64 `json:"created"`
Edited int64 `json:"edited"`
Icon string `json:"icon"`
Size int64 `json:"size"`
Permissions []string `json:"permissions"`
UUID string `json:"uuid"`
}
type GetFileSizesRequest struct {
UUIDs []string `json:"uuids" binding:"required"`
}
type FileStat struct {
UUID string `json:"uuid"`
Size int64 `json:"size,omitempty"`
ModTime time.Time `json:"mtime,omitempty"`
Ok bool `json:"ok"`
}
var fs *FileSystem = NewFileSystem()
func updateFiles(c *gin.Context) {
user := c.MustGet("user").(*User)
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read request body"})
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
var req UpdateFileRequest
if err := c.ShouldBindJSON(&req); err != nil {
fmt.Println("Raw body:", string(bodyBytes))
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
maxSize := user.GetSubscriptionBenefits().FileSystem_Size
result := fs.HandleOFSFUpdate(user.GetUsername(), req.Updates, maxSize)
statusCode := http.StatusOK
if result.Payload == "Max Upload Size Exceeded" {
statusCode = http.StatusRequestEntityTooLarge
} else if result.Payload != "Successfully Updated Origin Files" {
statusCode = http.StatusBadRequest
}
c.JSON(statusCode, result)
}
func getFilesByUUIDs(c *gin.Context) {
user := c.MustGet("user").(*User)
var req GetFilesRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
files, err := fs.GetFilesByUUIDs(user.GetUsername(), req.UUIDs)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"files": files})
}
func getUserFileSize(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
size, err := fs.GetUserFileSize(username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"username": username, "size": size})
}
func deleteAllUserFiles(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
if err := fs.DeleteUserFileSystem(username); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "deleted", "username": username})
}
func getFilesIndex(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
index, err := fs.GetFilesIndexWithThreshold(username, 50*1024)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
jsonData, err := json.Marshal(index)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize OFSF data"})
return
}
c.Header("Content-Length", fmt.Sprintf("%d", len(jsonData)))
c.Header("Content-Type", "application/octet-stream")
c.Header("Cache-Control", "no-cache")
c.Data(http.StatusOK, "application/octet-stream", jsonData)
}
func getFilesAll(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
index, err := fs.GetFilesIndexWithThreshold(username, 0)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
jsonData, err := json.Marshal(index)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize OFSF data"})
return
}
c.Header("Content-Length", fmt.Sprintf("%d", len(jsonData)))
c.Header("Content-Type", "application/octet-stream")
c.Header("Cache-Control", "no-cache")
c.Data(http.StatusOK, "application/octet-stream", jsonData)
}
func getFileSizes(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
var req GetFileSizesRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
stats, err := fs.GetFileStats(username, req.UUIDs)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"stats": stats})
}
func getFileByUUID(c *gin.Context) {
user := c.MustGet("user").(*User)
uuid := c.Query("uuid")
if uuid == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "UUID is required"})
return
}
username := user.GetUsername()
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
file, err := fs.GetFileByUUID(username, uuid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
jsonData, err := json.Marshal(file)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize OFSF data"})
return
}
c.Header("Content-Length", fmt.Sprintf("%d", len(jsonData)))
c.Header("Content-Type", "application/octet-stream")
c.Header("Cache-Control", "no-cache, max-age=0")
c.Data(http.StatusOK, "application/octet-stream", jsonData)
}
func getFileByPath(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
path := c.Param("path")
if path == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Path is required"})
return
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
path = strings.ToLower(path)
index, err := fs.loadPathIndex(username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to load path index"})
return
}
uuid, ok := index[path]
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "File not found"})
return
}
entry, err := fs.GetFileByUUID(username, uuid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
data, err := json.Marshal(entry)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to serialize file"})
return
}
c.Header("Content-Length", fmt.Sprintf("%d", len(data)))
c.Header("Content-Type", "application/octet-stream")
c.Header("Cache-Control", "no-cache, max-age=0")
c.Data(http.StatusOK, "application/octet-stream", data)
}
func getPathIndex(c *gin.Context) {
user := c.MustGet("user").(*User)
username := user.GetUsername()
index, err := fs.loadPathIndex(username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to load path index"})
return
}
c.JSON(http.StatusOK, gin.H{"index": index, "username": username})
}
const (
fileEntrySize = 14
fileDir = "./rotur/files"
defaultOFSF = "./rotur/base.ofsf"
)
type UpdateChange struct {
Command string `json:"command"`
UUID string `json:"uuid"`
Dta any `json:"dta"`
Idx any `json:"idx"`
}
type UpdateRequest struct {
Payload []UpdateChange `json:"payload"`
Offset string `json:"offset"`
}
type UpdateResult struct {
Payload string `json:"payload"`
UsedSize int `json:"used_size,omitempty"`
AvailableSize int `json:"available_size,omitempty"`
}
type FileSystem struct {
mu sync.RWMutex
}
func NewFileSystem() *FileSystem {
return &FileSystem{}
}
func (fs *FileSystem) HandleOFSFUpdate(username Username, updates []UpdateChange, maxSize int) UpdateResult {
fmt.Printf("\033[92m[+] OFSF\033[0m | %s processing %d file updates\n", username, len(updates))
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
// Process all updates while holding the lock
fs.mu.Lock()
for _, change := range updates {
switch change.Command {
case "UUIDa":
fs.handleAddUnsafe(username, change)
case "UUIDr":
fs.handleReplaceUnsafe(username, change)
case "UUIDd":
fs.handleDeleteUnsafe(username, change)
}
}
fs.mu.Unlock()
usedSize, err := fs.calculateTotalSize(username)
if err != nil {
return UpdateResult{Payload: "Error calculating size"}
}
availableSize := maxSize - usedSize
if usedSize > maxSize {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | User %s exceeded upload storage limit (used: %d, available: %d)\n",
username, usedSize, availableSize)
return UpdateResult{
Payload: "Max Upload Size Exceeded",
UsedSize: usedSize,
AvailableSize: availableSize,
}
}
fmt.Printf("\033[92m[+] OFSF\033[0m | Updated %s files (used: %d, available: %d)\n",
username, usedSize, availableSize)
return UpdateResult{
Payload: "Successfully Updated Origin Files",
UsedSize: usedSize,
AvailableSize: availableSize,
}
}
func extractIndex(v any) int {
switch x := v.(type) {
case float64:
return int(x) - 1
case int:
return x - 1
case string:
var i int
fmt.Sscanf(x, "%d", &i)
return i - 1
default:
return 0
}
}
// handleAddUnsafe assumes the lock is already held
func (fs *FileSystem) handleAddUnsafe(username Username, change UpdateChange) {
if len(change.UUID) != 32 {
return
}
path := filepath.Join(fileDir, string(username), change.UUID+".json")
if _, err := os.Stat(path); err == nil {
return
}
dta, ok := change.Dta.([]any)
if !ok || len(dta) > fileEntrySize {
return
}
dta[7] = time.Now().UnixMilli()
dta[8] = dta[7]
meta := FileMetadata{
Entry: dta,
Index: 0,
}
data, err := json.Marshal(meta)
if err != nil {
log.Printf("Error marshaling metadata: %v", err)
return
}
if err := os.WriteFile(path, data, 0644); err != nil {
log.Printf("Error writing file %s: %v", path, err)
return
}
// Load and update path index (unsafe version - no locking)
idx, _ := fs.loadPathIndexUnsafe(username)
idx[entryToPath(dta, username)] = change.UUID
fs.savePathIndexUnsafe(username, idx)
}
// handleReplaceUnsafe assumes the lock is already held
func (fs *FileSystem) handleReplaceUnsafe(username Username, change UpdateChange) {
entry, err := fs.getFileByUUIDUnsafe(username, change.UUID)
if err != nil {
return
}
oldPath := entryToPath(entry, username)
idx := extractIndex(change.Idx)
entry[8] = time.Now().UnixMilli()
if idx >= 0 && idx < len(entry) {
entry[idx] = change.Dta
}
newPath := entryToPath(entry, username)
fs.setFileByUUIDUnsafe(username, change.UUID, entry)
if oldPath != newPath {
index, _ := fs.loadPathIndexUnsafe(username)
delete(index, oldPath)
index[newPath] = change.UUID
fs.savePathIndexUnsafe(username, index)
}
}
// handleDeleteUnsafe assumes the lock is already held
func (fs *FileSystem) handleDeleteUnsafe(username Username, change UpdateChange) {
filePath := filepath.Join(fileDir, string(username), change.UUID+".json")
os.Remove(filePath)
idx, _ := fs.loadPathIndexUnsafe(username)
for path, uuid := range idx {
if uuid == change.UUID {
delete(idx, path)
break
}
}
fs.savePathIndexUnsafe(username, idx)
}
func userIndexPath(username Username) string {
return filepath.Join(fileDir, string(username), ".index.json")
}
func (fs *FileSystem) RenameUserFileSystem(oldUsername Username, newUsername Username) {
index, err := fs.loadPathIndex(oldUsername)
if err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Failed to load path index: %v\n", err)
return
}
oldLocationPrefix := strings.ToLower("origin/(c) users/" + string(oldUsername))
newLocationPrefix := strings.ToLower("origin/(c) users/" + string(newUsername))
fs.mu.Lock()
defer fs.mu.Unlock()
for path, uuid := range index {
cut, ok := strings.CutPrefix(strings.ToLower(path), oldLocationPrefix)
if !ok {
continue
}
newPath := newLocationPrefix + cut
index[newPath] = uuid
fs.handleReplaceUnsafe(oldUsername, UpdateChange{
Command: "UUIDr",
UUID: uuid,
Dta: newPath,
Idx: 3,
})
delete(index, path)
}
fs.savePathIndexUnsafe(oldUsername, index)
oldUserDir := filepath.Join(fileDir, string(oldUsername))
newUserDir := filepath.Join(fileDir, string(newUsername))
if err := os.Rename(oldUserDir, newUserDir); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Failed to rename user directory: %v\n", err)
}
}
type PathIndex map[string]string
// rebuildPathIndexUnsafe assumes the lock is already held
func (fs *FileSystem) rebuildPathIndexUnsafe(username Username) (PathIndex, error) {
userDir := filepath.Join(fileDir, string(username))
idx := make(PathIndex)
entries, err := os.ReadDir(userDir)
if err != nil {
if os.IsNotExist(err) {
if err := fs.savePathIndexUnsafe(username, idx); err != nil {
return nil, err
}
return idx, nil
}
return nil, err
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
continue
}
if entry.Name() == ".index.json" {
continue
}
filePath := filepath.Join(userDir, entry.Name())
data, err := os.ReadFile(filePath)
if err != nil {
continue
}
var meta FileMetadata
if err := json.Unmarshal(data, &meta); err != nil || meta.Entry == nil {
continue
}
path := entryToPath(meta.Entry, username)
uuid := strings.TrimSuffix(entry.Name(), ".json")
idx[path] = uuid
}
if err := fs.savePathIndexUnsafe(username, idx); err != nil {
return nil, err
}
fmt.Printf("\033[93m[~] OFSF\033[0m | Rebuilt path index for %s (%d entries)\n",
username, len(idx))
return idx, nil
}
// loadPathIndexUnsafe assumes the lock is already held
func (fs *FileSystem) loadPathIndexUnsafe(username Username) (PathIndex, error) {
path := userIndexPath(username)
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return fs.rebuildPathIndexUnsafe(username)
}
return nil, err
}
var idx PathIndex
if err := json.Unmarshal(data, &idx); err != nil {
return fs.rebuildPathIndexUnsafe(username)
}
return idx, nil
}
// loadPathIndex is the public version that acquires the lock
func (fs *FileSystem) loadPathIndex(username Username) (PathIndex, error) {
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
path := userIndexPath(username)
// First check if index exists with read lock
fs.mu.RLock()
_, err := os.Stat(path)
fs.mu.RUnlock()
if err == nil {
fs.mu.RLock()
data, readErr := os.ReadFile(path)
fs.mu.RUnlock()
if readErr == nil {
fmt.Println("Loading path index for", username)
var idx PathIndex
if unmarshalErr := json.Unmarshal(data, &idx); unmarshalErr == nil {
return idx, nil
}
}
}
fs.mu.Lock()
defer fs.mu.Unlock()
fmt.Println("Rebuilding path index for", username)
return fs.rebuildPathIndexUnsafe(username)
}
// savePathIndexUnsafe assumes the lock is already held
func (fs *FileSystem) savePathIndexUnsafe(username Username, idx PathIndex) error {
path := userIndexPath(username)
tmp := path + ".tmp"
data, err := json.Marshal(idx)
if err != nil {
return err
}
if err := os.WriteFile(tmp, data, 0644); err != nil {
return err
}
return os.Rename(tmp, path) // atomic on POSIX
}
func entryToLocation(entry FileEntry, username Username) string {
location := strings.ToLower(getStringOrEmpty(entry[2]))
if strings.HasPrefix(location, "origin/(c) users/") {
parts := strings.Split(location, "/")
if len(parts) >= 3 {
rest := parts[3:]
location = "origin/(c) users/" + string(username.ToLower())
if len(rest) > 0 {
location += "/" + strings.Join(rest, "/")
}
}
}
return location
}
func joinNoClean(a, b string) string {
a = strings.TrimRight(a, "/")
b = strings.TrimLeft(b, "/")
if a == "" {
return b
}
if b == "" {
return a
}
return a + "/" + b
}
func entryToPath(entry FileEntry, username Username) string {
name := getStringOrEmpty(entry[1]) + getStringOrEmpty(entry[0])
return strings.ToLower(
joinNoClean(
entryToLocation(entry, username),
name,
),
)
}
func (fs *FileSystem) GetFileStats(username Username, uuids []string) ([]FileStat, error) {
if err := fs.migrateFromLegacy(username); err != nil {
return nil, err
}
fs.mu.RLock()
defer fs.mu.RUnlock()
userDir := filepath.Join(fileDir, string(username))
stats := make([]FileStat, 0, len(uuids))
for _, uuid := range uuids {
path := filepath.Join(userDir, uuid+".json")
info, err := os.Stat(path)
if err != nil {
stats = append(stats, FileStat{
UUID: uuid,
Ok: false,
})
continue
}
stats = append(stats, FileStat{
UUID: uuid,
Size: info.Size(),
ModTime: info.ModTime().UTC(),
Ok: true,
})
}
return stats, nil
}
func (fs *FileSystem) GetUserPath(username Username) string {
return filepath.Join(fileDir, string(username))
}
func (fs *FileSystem) migrateFromLegacy(username Username) error {
fs.mu.Lock()
defer fs.mu.Unlock()
legacyPath := filepath.Join(fileDir, string(username)+".ofsf")
newPath := filepath.Join(fileDir, string(username))
if dirExists(newPath) {
return nil
}
if !fileExists(legacyPath) {
copyAndReplace(defaultOFSF, legacyPath, "${USERNAME}", string(username))
}
fmt.Printf("\033[93m[~] OFSF\033[0m | Migrating %s from legacy format\n", username)
data, err := os.ReadFile(legacyPath)
if err != nil {
return err
}
if len(data) == 0 {
os.Remove(legacyPath)
return nil
}
var filesList []any
if err := json.Unmarshal(data, &filesList); err != nil {
return err
}
userDir := fs.GetUserPath(username)
if err := os.MkdirAll(userDir, 0755); err != nil {
return err
}
pathIndex := PathIndex{}
index := 0
for i := 0; i+fileEntrySize <= len(filesList); i += fileEntrySize {
entry := filesList[i : i+fileEntrySize]
if uuid, ok := entry[13].(string); ok {
metadata := FileMetadata{
Entry: entry,
Index: index,
}
internalPath := entryToPath(entry, username)
pathIndex[internalPath] = uuid
entryData, err := json.Marshal(metadata)
if err != nil {
log.Printf("Error marshaling entry data: %v", err)
continue
}
filePath := filepath.Join(userDir, uuid+".json")
if err := os.WriteFile(filePath, entryData, 0644); err != nil {
log.Printf("Error writing file %s: %v", filePath, err)
continue
}
index++
}
}
filePath := filepath.Join(userDir, ".index.json")
data, err = json.Marshal(pathIndex)
if err == nil {
if writeErr := os.WriteFile(filePath, data, 0644); writeErr != nil {
log.Printf("Error writing index file %s: %v", filePath, writeErr)
}
} else {
log.Printf("Error marshaling path index: %v", err)
}
os.Remove(legacyPath)
fmt.Printf("\033[92m[+] OFSF\033[0m | Migration complete for %s\n", username)
return nil
}
// getFileByUUIDUnsafe assumes the lock is already held
func (fs *FileSystem) getFileByUUIDUnsafe(username Username, uuid string) (FileEntry, error) {
userDir := fs.GetUserPath(username)
filePath := filepath.Join(userDir, uuid+".json")
data, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
var metadata FileMetadata
err = json.Unmarshal(data, &metadata)
if err != nil || metadata.Entry == nil {
return nil, fmt.Errorf("file not found with the provided UUID")
}
if metadata.Entry[0] != ".folder" {
switch metadata.Entry[3].(type) {
case map[string]any, []any:
metadata.Entry[3] = JSONStringify(metadata.Entry[3])
}
}
return metadata.Entry, nil
}
// GetFileByUUID is the public version that acquires the lock
func (fs *FileSystem) GetFileByUUID(username Username, uuid string) (FileEntry, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
return fs.getFileByUUIDUnsafe(username, uuid)
}
// setFileByUUIDUnsafe assumes the lock is already held
func (fs *FileSystem) setFileByUUIDUnsafe(username Username, uuid string, file FileEntry) error {
userDir := fs.GetUserPath(username)
filePath := filepath.Join(userDir, uuid+".json")
if file[0] != ".folder" {
switch file[3].(type) {
case map[string]any, []any:
file[3] = JSONStringify(file[3])
}
}
data, err := json.Marshal(FileMetadata{
Entry: file,
Index: 0,
})
if err != nil {
return err
}
if err := os.WriteFile(filePath, data, 0644); err != nil {
return err
}
return nil
}
// SetFileByUUID is the public version that acquires the lock
func (fs *FileSystem) SetFileByUUID(username Username, uuid string, file FileEntry) error {
fs.mu.Lock()
defer fs.mu.Unlock()
return fs.setFileByUUIDUnsafe(username, uuid, file)
}
func (fs *FileSystem) calculateTotalSize(username Username) (int, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
userDir := fs.GetUserPath(username)
totalSize := 0
entries, err := os.ReadDir(userDir)
if err != nil {
if os.IsNotExist(err) {
return 0, nil
}
return 0, err
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
totalSize += int(info.Size())
}
return totalSize, nil
}
func (fs *FileSystem) GetFilesByUUIDs(username Username, uuids []string) (map[string]FileEntry, error) {
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
fs.mu.RLock()
defer fs.mu.RUnlock()
result := make(map[string]FileEntry)
userDir := fs.GetUserPath(username)
for _, uuid := range uuids {
filePath := filepath.Join(userDir, uuid+".json")
data, err := os.ReadFile(filePath)
if err != nil {
continue
}
var metadata FileMetadata
if err := json.Unmarshal(data, &metadata); err == nil && metadata.Entry != nil {
result[uuid] = metadata.Entry
}
}
return result, nil
}
func (fs *FileSystem) DeleteUserFileSystem(username Username) error {
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
fs.mu.Lock()
defer fs.mu.Unlock()
userDir := fs.GetUserPath(username)
if err := os.RemoveAll(userDir); err != nil {
if os.IsNotExist(err) {
fmt.Printf("No files found for user %s to delete\n", username)
return nil
}
return err
}
legacyPath := filepath.Join(fileDir, string(username)+".ofsf")
os.Remove(legacyPath)
fmt.Printf("Successfully deleted files for user %s\n", username)
return nil
}
func (fs *FileSystem) GetUserFileSize(username Username) (string, error) {
if err := fs.migrateFromLegacy(username); err != nil {
fmt.Printf("\033[91m[-] OFSF Error\033[0m | Migration failed: %v\n", err)
}
size, err := fs.calculateTotalSize(username)
if err != nil {
return "", err
}
switch {
case size >= 1<<30:
return fmt.Sprintf("%.4f GB", float64(size)/(1<<30)), nil
case size >= 1<<20:
return fmt.Sprintf("%.2f MB", float64(size)/(1<<20)), nil
case size >= 1<<10:
return fmt.Sprintf("%.2f KB", float64(size)/(1<<10)), nil
default:
return fmt.Sprintf("%d bytes", size), nil
}
}
func (fs *FileSystem) GetFilesIndexWithThreshold(username Username, sizeThreshold int) ([]any, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
userDir := fs.GetUserPath(username)