-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedia_storage.go
96 lines (81 loc) · 2.33 KB
/
media_storage.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
89
90
91
92
93
94
95
96
package main
import (
"errors"
"fmt"
"gorm.io/gorm"
"os"
"strconv"
"strings"
"time"
)
const (
TTLDuration = 7 * 24 * time.Hour // 7-day expiration
)
func (gateway *Gateway) uploadMediaGetUrls(mms *MsgQueueItem) ([]string, error) {
var mediaUrls []string
if len(mms.Files) > 0 {
for _, i := range mms.Files {
if strings.Contains(i.ContentType, "application/smil") {
continue
}
id, err := gateway.saveMsgFileMedia(i)
if err != nil {
return mediaUrls, err
}
mediaUrls = append(mediaUrls, os.Getenv("SERVER_ADDRESS")+"/media/"+strconv.Itoa(int(id)))
}
return mediaUrls, nil
}
return mediaUrls, nil
}
type MediaFile struct {
ID uint `gorm:"primaryKey" json:"id"`
FileName string `json:"file_name"`
ContentType string `json:"content_type"`
Base64Data string `json:"base64_data"`
UploadAt time.Time `json:"upload_at"`
ExpiresAt time.Time `gorm:"index" json:"expires_at"`
}
func (gateway *Gateway) cleanUpExpiredMediaFiles() {
ticker := time.NewTicker(24 * time.Hour) // Adjust the interval as needed
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := gateway.DB.Where("expires_at < ?", time.Now()).Delete(&MediaFile{}).Error
if err != nil {
// Log the error
fmt.Printf("Failed to clean up expired media files: %v\n", err)
}
}
}
}
func (gateway *Gateway) saveMsgFileMedia(file MsgFile) (uint, error) {
mediaFile := MediaFile{
FileName: file.Filename,
ContentType: file.ContentType,
Base64Data: string(file.Content),
UploadAt: time.Now(),
ExpiresAt: time.Now().Add(TTLDuration),
}
if err := gateway.DB.Create(&mediaFile).Error; err != nil {
return 0, fmt.Errorf("failed to insert media file to db: %v", err)
}
return mediaFile.ID, nil
}
func (gateway *Gateway) getMediaFile(fileID uint) (*MediaFile, error) {
var mediaFile MediaFile
if err := gateway.DB.First(&mediaFile, fileID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("media file not found: %d", fileID)
}
return nil, fmt.Errorf("failed to retrieve media file: %v", err)
}
// Check if the media file has expired
if time.Now().After(mediaFile.ExpiresAt) {
// Optionally delete the expired media file
gateway.DB.Delete(&mediaFile)
return nil, fmt.Errorf("media file has expired: %d", fileID)
}
return &mediaFile, nil
}