File size: 6,080 Bytes
7c5da52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package main

import (
	"context"
	"log"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MongoStore struct {
	client     *mongo.Client
	db         *mongo.Database
	usersCol   *mongo.Collection
	ownersCol  *mongo.Collection
	filesCol   *mongo.Collection
	sharesCol  *mongo.Collection
	dbName     string
}

type mongoOwnerDoc struct {
	ID        string   `bson:"_id"`
	Path      string   `bson:"path"`
	Owners    []string `bson:"owners"`
	UpdatedAt string   `bson:"updated_at"`
}

type mongoFileMetaDoc struct {
	ID        string `bson:"_id"`
	Path      string `bson:"path"`
	Owner     string `bson:"owner"`
	Size      int64  `bson:"size"`
	UpdatedAt string `bson:"updated_at"`
}

func NewMongoStore(uri, dbName string) (*MongoStore, error) {
	uri = strings.TrimSpace(uri)
	if uri == "" {
		return nil, nil
	}
	if dbName == "" {
		dbName = "upload_thtuanit"
	}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	clientOpts := options.Client().
		ApplyURI(uri).
		SetServerSelectionTimeout(10 * time.Second).
		SetMaxPoolSize(20)

	client, err := mongo.Connect(ctx, clientOpts)
	if err != nil {
		return nil, err
	}
	if err := client.Ping(ctx, nil); err != nil {
		_ = client.Disconnect(context.Background())
		return nil, err
	}

	db := client.Database(dbName)
	ms := &MongoStore{
		client:    client,
		db:        db,
		usersCol:  db.Collection("users"),
		ownersCol: db.Collection("file_owners"),
		filesCol:  db.Collection("files_metadata"),
		sharesCol: db.Collection("shares"),
		dbName:    dbName,
	}
	log.Printf("Connected to MongoDB Atlas successfully (database=%s)", dbName)
	return ms, nil
}

// --- Users Collection Operations ---

func (m *MongoStore) LoadAllUsers() ([]UserAccount, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	cur, err := m.usersCol.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)

	var out []UserAccount
	for cur.Next(ctx) {
		var u UserAccount
		if err := cur.Decode(&u); err == nil && u.Username != "" {
			out = append(out, u)
		}
	}
	return out, cur.Err()
}

func (m *MongoStore) UpsertUserDoc(u UserAccount) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	key := strings.ToLower(strings.TrimSpace(u.Username))
	doc := bson.M{
		"_id":           key,
		"username":      u.Username,
		"display_name":  u.DisplayName,
		"role":          u.Role,
		"password_salt": u.PasswordSalt,
		"password_hash": u.PasswordHash,
		"permissions": bson.M{
			"can_upload": u.Permissions.CanUpload,
			"can_delete": u.Permissions.CanDelete,
			"can_rename": u.Permissions.CanRename,
		},
		"active":     u.Active,
		"created_at": u.CreatedAt,
	}
	_, err := m.usersCol.UpdateOne(
		ctx,
		bson.M{"_id": key},
		bson.M{"$set": doc},
		options.Update().SetUpsert(true),
	)
	return err
}

func (m *MongoStore) DeleteUserDoc(username string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	key := strings.ToLower(strings.TrimSpace(username))
	_, err := m.usersCol.DeleteOne(ctx, bson.M{"_id": key})
	return err
}

// --- File Owners Collection Operations ---

func (m *MongoStore) LoadAllOwners() (map[string][]string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	cur, err := m.ownersCol.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)

	res := make(map[string][]string)
	for cur.Next(ctx) {
		var doc mongoOwnerDoc
		if err := cur.Decode(&doc); err == nil && doc.Path != "" && len(doc.Owners) > 0 {
			res[doc.Path] = doc.Owners
		}
	}
	return res, cur.Err()
}

func (m *MongoStore) UpsertOwnerDoc(remotePath string, owners []string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	now := time.Now().Format("2006-01-02 15:04:05")
	doc := mongoOwnerDoc{
		ID:        remotePath,
		Path:      remotePath,
		Owners:    owners,
		UpdatedAt: now,
	}
	_, err := m.ownersCol.UpdateOne(
		ctx,
		bson.M{"_id": remotePath},
		bson.M{"$set": doc},
		options.Update().SetUpsert(true),
	)
	return err
}

func (m *MongoStore) DeleteOwnerDoc(remotePath string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_, err := m.ownersCol.DeleteOne(ctx, bson.M{"_id": remotePath})
	_, _ = m.filesCol.DeleteOne(ctx, bson.M{"_id": remotePath})
	return err
}

func (m *MongoStore) UpsertFileMeta(remotePath, owner string, size int64) {
	ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
	defer cancel()
	doc := mongoFileMetaDoc{
		ID:        remotePath,
		Path:      remotePath,
		Owner:     strings.ToLower(strings.TrimSpace(owner)),
		Size:      size,
		UpdatedAt: time.Now().Format("2006-01-02 15:04:05"),
	}
	_, _ = m.filesCol.UpdateOne(
		ctx,
		bson.M{"_id": remotePath},
		bson.M{"$set": doc},
		options.Update().SetUpsert(true),
	)
}

// --- Shares Collection Operations ---

func (m *MongoStore) LoadAllShares() ([]ShareLink, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	cur, err := m.sharesCol.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)

	var out []ShareLink
	for cur.Next(ctx) {
		var sh ShareLink
		if err := cur.Decode(&sh); err == nil && sh.ID != "" && sh.Path != "" {
			out = append(out, sh)
		}
	}
	return out, cur.Err()
}

func (m *MongoStore) UpsertShareDoc(sh ShareLink) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	_, err := m.sharesCol.UpdateOne(
		ctx,
		bson.M{"_id": sh.ID},
		bson.M{"$set": sh},
		options.Update().SetUpsert(true),
	)
	return err
}

func (m *MongoStore) DeleteShareDoc(shareID string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_, err := m.sharesCol.DeleteOne(ctx, bson.M{"_id": shareID})
	return err
}