Proper log rotation, filename compatibility with windows

This commit is contained in:
Ben Adrian Sarmiento
2024-07-06 12:44:25 +02:00
parent b501b800dd
commit 467f51bdec
6 changed files with 67 additions and 15 deletions

View File

@@ -8,6 +8,8 @@ import (
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
@@ -185,7 +187,7 @@ func (t *TorrentManager) getTorrentFiles(parentDir string) mapset.Set[string] {
}
func (t *TorrentManager) writeTorrentToFile(torrent *Torrent) {
filePath := "data/" + t.GetKey(torrent) + ".zurgtorrent"
filePath := "data/" + t.getTorrentFilename(torrent) + ".zurgtorrent"
file, err := os.Create(filePath)
if err != nil {
t.log.Warnf("Cannot create file %s: %v", filePath, err)
@@ -534,3 +536,58 @@ func (t *TorrentManager) initializeDirectoryMaps() {
// t.RootNode.AddChild(fs.NewFileNode(directory, true))
}
}
func (t *TorrentManager) getTorrentFilename(torrent *Torrent) string {
if t.Config.EnableRetainRDTorrentName() {
return sanitizeFileName(torrent.Name)
}
// drop the extension from the name
if t.Config.EnableRetainFolderNameExtension() && strings.Contains(torrent.Name, torrent.OriginalName) {
return sanitizeFileName(torrent.Name)
}
ret := strings.TrimSuffix(torrent.OriginalName, ".mp4")
ret = strings.TrimSuffix(ret, ".mkv")
return sanitizeFileName(ret)
}
func (t *TorrentManager) getTorrentInfoFilename(torrent *realdebrid.TorrentInfo) string {
if t.Config.EnableRetainRDTorrentName() {
return sanitizeFileName(torrent.Name)
}
// drop the extension from the name
if t.Config.EnableRetainFolderNameExtension() && strings.Contains(torrent.Name, torrent.OriginalName) {
return sanitizeFileName(torrent.Name)
}
ret := strings.TrimSuffix(torrent.OriginalName, ".mp4")
ret = strings.TrimSuffix(ret, ".mkv")
return sanitizeFileName(ret)
}
// sanitizeFileName takes a string and converts it to a valid Windows filename
func sanitizeFileName(input string) string {
if !isWindows() {
return input
}
// Define a regex pattern to match invalid filename characters
invalidChars := regexp.MustCompile(`[<>:"/\\|?*]+`)
// Replace invalid characters with an underscore
sanitized := invalidChars.ReplaceAllString(input, "_")
// Trim leading and trailing whitespace and dots
sanitized = strings.TrimSpace(sanitized)
sanitized = strings.Trim(sanitized, ".")
// Ensure the filename is not empty
if sanitized == "" {
sanitized = "default_filename"
}
return sanitized
}
func isWindows() bool {
return runtime.GOOS == "windows"
}