This repository has been archived by the owner on Dec 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
88 lines (76 loc) · 1.89 KB
/
utils.go
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
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"regexp"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
ErrUnsupportedFile = errors.New("unsupported file")
ErrFileBlocked = errors.New("file blocked")
)
func generateId() (string, error) {
// Generate bytes
b := make([]byte, 18)
_, err := rand.Read(b)
if err != nil {
return "", err
}
// Construct ID
id := base64.URLEncoding.EncodeToString(b)
id = strings.ReplaceAll(id, "-", "a")
id = strings.ReplaceAll(id, "_", "b")
id = strings.ReplaceAll(id, "=", "c")
return id, err
}
func cleanFilename(filename string) string {
re := regexp.MustCompile(`[^A-Za-z0-9\.\-\_\+\!\(\)$]`)
return re.ReplaceAllString(filename, "_")
}
// Delete unclaimed files that are more than 30 minutes old
func cleanupFiles() error {
cur, err := db.Collection("files").Find(context.TODO(), bson.M{
"claimed": false,
"uploaded_at": bson.M{"$lt": time.Now().Unix() - 1800},
})
if err != nil {
return err
}
var files []File
if err := cur.All(context.TODO(), &files); err != nil {
return err
}
for _, file := range files {
if err := file.Delete(); err != nil {
return err
}
}
return nil
}
func isFileReferenced(bucket string, hashHex string) (bool, error) {
opts := options.Count()
opts.SetLimit(1)
count, err := db.Collection("files").CountDocuments(
context.TODO(),
bson.M{"hash": hashHex, "bucket": bucket},
opts,
)
return count > 0, err
}
// Get the block status of a file by its hash.
// Returns whether it's blocked.
func getBlockStatus(hashHex string) (bool, error) {
opts := options.Count()
opts.SetLimit(1)
count, err := db.Collection("blocked_files").CountDocuments(
context.TODO(),
bson.M{"_id": hashHex},
opts,
)
return count > 0, err
}