1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2025-06-01 02:59:24 +02:00

Delete expired attachments based on mod time instead of DB entry to avoid races

This commit is contained in:
Philipp Heckel 2022-07-08 10:00:04 -04:00
parent 3e53d8a2c7
commit 10a9aca2a1
6 changed files with 65 additions and 43 deletions

View file

@ -2,16 +2,18 @@ package server
import (
"errors"
"fmt"
"heckel.io/ntfy/util"
"io"
"os"
"path/filepath"
"regexp"
"sync"
"time"
)
var (
fileIDRegex = regexp.MustCompile(`^[-_A-Za-z0-9]+$`)
fileIDRegex = regexp.MustCompile(fmt.Sprintf(`^[-_A-Za-z0-9]{%d}$`, messageIDLength))
errInvalidFileID = errors.New("invalid file ID")
errFileExists = errors.New("file exists")
)
@ -88,6 +90,25 @@ func (c *fileCache) Remove(ids ...string) error {
return nil
}
// Expired returns a list of file IDs for expired files
func (c *fileCache) Expired(olderThan time.Time) ([]string, error) {
entries, err := os.ReadDir(c.dir)
if err != nil {
return nil, err
}
var ids []string
for _, e := range entries {
info, err := e.Info()
if err != nil {
continue
}
if info.ModTime().Before(olderThan) && fileIDRegex.MatchString(e.Name()) {
ids = append(ids, e.Name())
}
}
return ids, nil
}
func (c *fileCache) Size() int64 {
c.mu.Lock()
defer c.mu.Unlock()