UploadFile / share.go
ddosvn's picture
Deploy Upload ThTuanIT Full-stack (Go + Next.js + Python hf_xet + MongoDB)
7c5da52 verified
Raw History Blame Contribute Delete
9.01 kB
package main
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
type ShareAccessRequest struct {
RequestID string `json:"request_id" bson:"request_id"`
VisitorToken string `json:"visitor_token" bson:"visitor_token"`
VisitorName string `json:"visitor_name" bson:"visitor_name"`
Note string `json:"note,omitempty" bson:"note,omitempty"`
Status string `json:"status" bson:"status"` // "pending", "approved", "rejected"
RequestedAt string `json:"requested_at" bson:"requested_at"`
UpdatedAt string `json:"updated_at" bson:"updated_at"`
}
type ShareLink struct {
ID string `json:"id" bson:"_id"`
Path string `json:"path" bson:"path"`
FileName string `json:"file_name" bson:"file_name"`
Size int64 `json:"size" bson:"size"`
Owner string `json:"owner" bson:"owner"`
Enabled bool `json:"enabled" bson:"enabled"`
RequireApproval bool `json:"require_approval" bson:"require_approval"`
CreatedAt string `json:"created_at" bson:"created_at"`
UpdatedAt string `json:"updated_at" bson:"updated_at"`
Requests []ShareAccessRequest `json:"requests" bson:"requests"`
}
type ShareStore struct {
mu sync.RWMutex
filePath string
byID map[string]*ShareLink
byPath map[string]string // remotePath -> shareID
mongo *MongoStore
}
func generateRandomToken(byteLen int) string {
b := make([]byte, byteLen)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
func NewShareStore(filePath string) (*ShareStore, error) {
s := &ShareStore{
filePath: filePath,
byID: make(map[string]*ShareLink),
byPath: make(map[string]string),
}
if err := s.load(); err != nil {
return nil, err
}
return s, nil
}
func (s *ShareStore) load() error {
s.mu.Lock()
defer s.mu.Unlock()
data, err := os.ReadFile(s.filePath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
var list []*ShareLink
if err := json.Unmarshal(data, &list); err != nil {
return nil
}
for _, item := range list {
if item != nil && item.ID != "" && item.Path != "" {
if item.Requests == nil {
item.Requests = []ShareAccessRequest{}
}
s.byID[item.ID] = item
s.byPath[item.Path] = item.ID
}
}
return nil
}
func (s *ShareStore) saveLocked() {
list := make([]*ShareLink, 0, len(s.byID))
for _, item := range s.byID {
list = append(list, item)
}
data, err := json.MarshalIndent(list, "", " ")
if err == nil {
_ = os.WriteFile(s.filePath, data, 0600)
}
}
func (s *ShareStore) AttachMongo(m *MongoStore) {
if m == nil {
return
}
s.mu.Lock()
s.mongo = m
remoteShares, err := m.LoadAllShares()
if err == nil {
for _, sh := range remoteShares {
cp := sh
if cp.Requests == nil {
cp.Requests = []ShareAccessRequest{}
}
s.byID[cp.ID] = &cp
s.byPath[cp.Path] = cp.ID
}
for _, localShare := range s.byID {
_ = m.UpsertShareDoc(*localShare)
}
s.saveLocked()
}
s.mu.Unlock()
}
func cloneShare(sh *ShareLink) *ShareLink {
if sh == nil {
return nil
}
cp := *sh
cp.Requests = make([]ShareAccessRequest, len(sh.Requests))
copy(cp.Requests, sh.Requests)
return &cp
}
func (s *ShareStore) GetByID(id string) (*ShareLink, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
sh, ok := s.byID[strings.TrimSpace(id)]
if !ok {
return nil, false
}
return cloneShare(sh), true
}
func (s *ShareStore) GetByPath(remotePath string) (*ShareLink, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
id, ok := s.byPath[remotePath]
if !ok {
return nil, false
}
sh, ok := s.byID[id]
if !ok {
return nil, false
}
return cloneShare(sh), true
}
func (s *ShareStore) ListForUser(u UserAccount) []*ShareLink {
s.mu.RLock()
defer s.mu.RUnlock()
username := strings.ToLower(strings.TrimSpace(u.Username))
out := make([]*ShareLink, 0)
for _, sh := range s.byID {
if u.Role == "admin" || strings.ToLower(sh.Owner) == username {
out = append(out, cloneShare(sh))
}
}
sort.Slice(out, func(i, j int) bool {
return out[i].UpdatedAt > out[j].UpdatedAt
})
return out
}
func (s *ShareStore) UpsertShare(remotePath, owner string, size int64, enabled, requireApproval, regenerate bool) *ShareLink {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now().Format("2006-01-02 15:04:05")
existingID, exists := s.byPath[remotePath]
var sh *ShareLink
if exists {
sh = s.byID[existingID]
}
if sh == nil {
newID := "sh_" + generateRandomToken(6)
sh = &ShareLink{
ID: newID,
Path: remotePath,
FileName: filepath.Base(remotePath),
Size: size,
Owner: strings.ToLower(strings.TrimSpace(owner)),
Enabled: enabled,
RequireApproval: requireApproval,
CreatedAt: now,
UpdatedAt: now,
Requests: []ShareAccessRequest{},
}
s.byID[newID] = sh
s.byPath[remotePath] = newID
} else {
if regenerate {
oldID := sh.ID
delete(s.byID, oldID)
if s.mongo != nil {
_ = s.mongo.DeleteShareDoc(oldID)
}
sh.ID = "sh_" + generateRandomToken(6)
sh.Requests = []ShareAccessRequest{}
s.byID[sh.ID] = sh
s.byPath[remotePath] = sh.ID
}
sh.FileName = filepath.Base(remotePath)
if size > 0 {
sh.Size = size
}
sh.Enabled = enabled
sh.RequireApproval = requireApproval
sh.UpdatedAt = now
}
s.saveLocked()
if s.mongo != nil {
_ = s.mongo.UpsertShareDoc(*sh)
}
return cloneShare(sh)
}
func (s *ShareStore) SubmitAccessRequest(shareID, visitorToken, visitorName, note string) (*ShareLink, *ShareAccessRequest, bool) {
s.mu.Lock()
defer s.mu.Unlock()
sh, ok := s.byID[strings.TrimSpace(shareID)]
if !ok || !sh.Enabled {
return nil, nil, false
}
visitorToken = strings.TrimSpace(visitorToken)
if visitorToken == "" {
visitorToken = "vt_" + generateRandomToken(8)
}
visitorName = strings.TrimSpace(visitorName)
if visitorName == "" {
visitorName = "Khách xem tệp"
}
note = strings.TrimSpace(note)
now := time.Now().Format("2006-01-02 15:04:05")
for i := range sh.Requests {
if sh.Requests[i].VisitorToken == visitorToken {
sh.Requests[i].VisitorName = visitorName
if note != "" {
sh.Requests[i].Note = note
}
if sh.Requests[i].Status != "approved" {
sh.Requests[i].Status = "pending"
}
sh.Requests[i].UpdatedAt = now
sh.UpdatedAt = now
s.saveLocked()
if s.mongo != nil {
_ = s.mongo.UpsertShareDoc(*sh)
}
reqCopy := sh.Requests[i]
return cloneShare(sh), &reqCopy, true
}
}
req := ShareAccessRequest{
RequestID: "req_" + generateRandomToken(5),
VisitorToken: visitorToken,
VisitorName: visitorName,
Note: note,
Status: "pending",
RequestedAt: now,
UpdatedAt: now,
}
sh.Requests = append([]ShareAccessRequest{req}, sh.Requests...)
sh.UpdatedAt = now
s.saveLocked()
if s.mongo != nil {
_ = s.mongo.UpsertShareDoc(*sh)
}
return cloneShare(sh), &req, true
}
func (s *ShareStore) UpdateRequestStatus(shareID, requestID, status string) (*ShareLink, bool) {
s.mu.Lock()
defer s.mu.Unlock()
sh, ok := s.byID[strings.TrimSpace(shareID)]
if !ok {
return nil, false
}
now := time.Now().Format("2006-01-02 15:04:05")
found := false
for i := range sh.Requests {
if sh.Requests[i].RequestID == requestID {
sh.Requests[i].Status = status
sh.Requests[i].UpdatedAt = now
found = true
break
}
}
if !found {
return nil, false
}
sh.UpdatedAt = now
s.saveLocked()
if s.mongo != nil {
_ = s.mongo.UpsertShareDoc(*sh)
}
return cloneShare(sh), true
}
func (s *ShareStore) CheckVisitorAccess(shareID, visitorToken string) (*ShareLink, bool, string, string) {
s.mu.RLock()
defer s.mu.RUnlock()
sh, ok := s.byID[strings.TrimSpace(shareID)]
if !ok || !sh.Enabled {
return nil, false, "disabled", ""
}
if !sh.RequireApproval {
return cloneShare(sh), true, "approved", ""
}
visitorToken = strings.TrimSpace(visitorToken)
if visitorToken != "" {
for _, r := range sh.Requests {
if r.VisitorToken == visitorToken {
return cloneShare(sh), r.Status == "approved", r.Status, r.VisitorName
}
}
}
return cloneShare(sh), false, "none", ""
}
func (s *ShareStore) RenamePath(oldPath, newPath string) {
s.mu.Lock()
defer s.mu.Unlock()
id, ok := s.byPath[oldPath]
if !ok {
return
}
delete(s.byPath, oldPath)
s.byPath[newPath] = id
if sh, exists := s.byID[id]; exists {
sh.Path = newPath
sh.FileName = filepath.Base(newPath)
sh.UpdatedAt = time.Now().Format("2006-01-02 15:04:05")
s.saveLocked()
if s.mongo != nil {
_ = s.mongo.UpsertShareDoc(*sh)
}
}
}
func (s *ShareStore) DeleteByPath(remotePath string) {
s.mu.Lock()
defer s.mu.Unlock()
id, ok := s.byPath[remotePath]
if !ok {
return
}
delete(s.byPath, remotePath)
delete(s.byID, id)
s.saveLocked()
if s.mongo != nil {
_ = s.mongo.DeleteShareDoc(id)
}
}