feat: add automatic cleanup options for completed torrents and missing files (#1243)

This commit is contained in:
Locon213 authored and GitHub committed 2026-01-22 09:32:14 +08:00
1 parent bad7f1d06c
commit 8d33e1a5b3
23 files changed
+148 -2

No files matched your search

+4
View File
@@ -185,6 +185,10 @@ type DownloaderStoreConfig struct {
Proxy *DownloaderProxyConfig `json:"proxy"` Proxy *DownloaderProxyConfig `json:"proxy"`
Webhook *WebhookConfig `json:"webhook"` // Webhook is the webhook configuration Webhook *WebhookConfig `json:"webhook"` // Webhook is the webhook configuration
Archive *ArchiveConfig `json:"archive"` // Archive is the archive extraction configuration Archive *ArchiveConfig `json:"archive"` // Archive is the archive extraction configuration
// New fields added for auto-management
AutoDeleteTorrents bool `json:"autoDeleteTorrents"` // AutoDeleteTorrents enables automatic deletion of .torrent files after download
AutoCleanMissingFiles bool `json:"autoCleanMissingFiles"` // AutoCleanMissingFiles enables automatic cleanup of tasks with missing files
} }
func (cfg *DownloaderStoreConfig) Init() *DownloaderStoreConfig { func (cfg *DownloaderStoreConfig) Init() *DownloaderStoreConfig {
+57 -1
View File
@@ -205,6 +205,9 @@ func (d *Downloader) Setup() error {
} }
d.extensions = extensions d.extensions = extensions
// Auto-cleanup non-existing tasks on startup
d.cleanupNonExistingTasks()
// handle upload // handle upload
go func() { go func() {
for _, task := range d.tasks { for _, task := range d.tasks {
@@ -271,6 +274,51 @@ func (d *Downloader) Setup() error {
return nil return nil
} }
// cleanupNonExistingTasks checks for tasks whose files are missing on disk
// and removes them if the AutoCleanMissingFiles config is enabled.
func (d *Downloader) cleanupNonExistingTasks() {
cfg, err := d.GetConfig()
if err != nil {
return
}
// If the feature is disabled, do nothing
if !cfg.AutoCleanMissingFiles {
return
}
var tasksToDelete []string
for _, task := range d.tasks {
if task.Meta == nil || task.Meta.Res == nil {
continue
}
var targetPath string
// Determine if it is a single file or a directory (multi-file torrent)
if task.Meta.Res.Name != "" {
targetPath = task.Meta.FolderPath()
} else {
targetPath = task.Meta.SingleFilepath()
}
// Skip if path is empty
if targetPath == "" {
continue
}
// Check if file/folder exists
if _, err := os.Stat(targetPath); os.IsNotExist(err) {
d.Logger.Info().Msgf("Auto-cleanup: task %s file not found at %s, removing from list", task.ID, targetPath)
tasksToDelete = append(tasksToDelete, task.ID)
}
}
if len(tasksToDelete) > 0 {
d.Delete(&TaskFilter{IDs: tasksToDelete}, false)
}
}
func (d *Downloader) parseFm(url string) (fetcher.FetcherManager, error) { func (d *Downloader) parseFm(url string) (fetcher.FetcherManager, error) {
for _, fm := range d.cfg.FetchManagers { for _, fm := range d.cfg.FetchManagers {
for _, filter := range fm.Filters() { for _, filter := range fm.Filters() {
@@ -910,6 +958,10 @@ func (d *Downloader) watch(task *Task) {
if e, ok := task.Meta.Opts.Extra.(*http.OptsExtra); ok { if e, ok := task.Meta.Opts.Extra.(*http.OptsExtra); ok {
downloadFilePath := task.Meta.SingleFilepath() downloadFilePath := task.Meta.SingleFilepath()
if e.AutoTorrent && strings.HasSuffix(downloadFilePath, ".torrent") { if e.AutoTorrent && strings.HasSuffix(downloadFilePath, ".torrent") {
cfg, err := d.GetConfig()
shouldDelete := err == nil && cfg.AutoDeleteTorrents
go func() { go func() {
_, err2 := d.CreateDirect( _, err2 := d.CreateDirect(
&base.Request{ &base.Request{
@@ -921,8 +973,12 @@ func (d *Downloader) watch(task *Task) {
}) })
if err2 != nil { if err2 != nil {
d.Logger.Error().Err(err2).Msgf("auto create torrent task failed, task id: %s", task.ID) d.Logger.Error().Err(err2).Msgf("auto create torrent task failed, task id: %s", task.ID)
} } else {
if shouldDelete {
d.Delete(&TaskFilter{IDs: []string{task.ID}}, true)
}
}
}() }()
} }
@@ -12,6 +12,10 @@ class DownloaderConfig {
WebhookConfig webhook = WebhookConfig(); WebhookConfig webhook = WebhookConfig();
ArchiveConfig archive = ArchiveConfig(); ArchiveConfig archive = ArchiveConfig();
// New fields for auto-management
bool autoDeleteTorrents = false;
bool autoCleanMissingFiles = false;
DownloaderConfig({ DownloaderConfig({
this.downloadDir = '', this.downloadDir = '',
this.maxRunning = 0, this.maxRunning = 0,
@@ -18,7 +18,9 @@ DownloaderConfig _$DownloaderConfigFromJson(Map<String, dynamic> json) =>
..webhook = ..webhook =
WebhookConfig.fromJson(json['webhook'] as Map<String, dynamic>?) WebhookConfig.fromJson(json['webhook'] as Map<String, dynamic>?)
..archive = ..archive =
ArchiveConfig.fromJson(json['archive'] as Map<String, dynamic>?); ArchiveConfig.fromJson(json['archive'] as Map<String, dynamic>?)
..autoDeleteTorrents = json['autoDeleteTorrents'] as bool
..autoCleanMissingFiles = json['autoCleanMissingFiles'] as bool;
Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) => Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) =>
<String, dynamic>{ <String, dynamic>{
@@ -29,6 +31,8 @@ Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) =>
'proxy': instance.proxy.toJson(), 'proxy': instance.proxy.toJson(),
'webhook': instance.webhook.toJson(), 'webhook': instance.webhook.toJson(),
'archive': instance.archive.toJson(), 'archive': instance.archive.toJson(),
'autoDeleteTorrents': instance.autoDeleteTorrents,
'autoCleanMissingFiles': instance.autoCleanMissingFiles,
}; };
ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) => ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) =>
@@ -169,6 +169,46 @@ class SettingView extends GetView<SettingController> {
); );
}); });
// New: Auto Delete Torrents
final buildAutoDeleteTorrents = _buildConfigItem('autoDeleteTorrents', () {
return appController.downloaderConfig.value.autoDeleteTorrents
? 'on'.tr
: 'off'.tr;
}, (Key key) {
return Container(
alignment: Alignment.centerLeft,
child: Switch(
value: appController.downloaderConfig.value.autoDeleteTorrents,
onChanged: (bool value) async {
appController.downloaderConfig.update((val) {
val!.autoDeleteTorrents = value;
});
await debounceSave();
},
),
);
});
// New: Auto Clean Missing Files
final buildAutoCleanMissingFiles = _buildConfigItem('autoCleanMissingFiles', () {
return appController.downloaderConfig.value.autoCleanMissingFiles
? 'on'.tr
: 'off'.tr;
}, (Key key) {
return Container(
alignment: Alignment.centerLeft,
child: Switch(
value: appController.downloaderConfig.value.autoCleanMissingFiles,
onChanged: (bool value) async {
appController.downloaderConfig.update((val) {
val!.autoCleanMissingFiles = value;
});
await debounceSave();
},
),
);
});
// Archive auto extract configuration // Archive auto extract configuration
final buildAutoExtract = _buildConfigItem('autoExtract', () { final buildAutoExtract = _buildConfigItem('autoExtract', () {
return appController.downloaderConfig.value.archive.autoExtract return appController.downloaderConfig.value.archive.autoExtract
@@ -1414,6 +1454,8 @@ class SettingView extends GetView<SettingController> {
buildMaxRunning(), buildMaxRunning(),
buildDefaultDirectDownload(), buildDefaultDirectDownload(),
buildAutoStartTasks(), buildAutoStartTasks(),
buildAutoDeleteTorrents(),
buildAutoCleanMissingFiles(),
buildBrowserExtension(), buildBrowserExtension(),
buildAutoStartup(), buildAutoStartup(),
buildMenubarMode(), buildMenubarMode(),
+2
View File
@@ -42,6 +42,8 @@ const deDE = {
'maxRunning': 'Maximale Anzahl ausgeführter Aufgaben', 'maxRunning': 'Maximale Anzahl ausgeführter Aufgaben',
'defaultDirectDownload': 'Direkten Download standardmäßig aktivieren', 'defaultDirectDownload': 'Direkten Download standardmäßig aktivieren',
'autoStartTasks': 'Unvollständige Aufgaben beim Start automatisch starten', 'autoStartTasks': 'Unvollständige Aufgaben beim Start automatisch starten',
'autoDeleteTorrents': 'Automatisches Löschen von .torrent-Dateien',
'autoCleanMissingFiles': 'Automatisches Bereinigen fehlender Dateien',
'items': '@count Artikel', 'items': '@count Artikel',
'subscribeTracker': 'Abonnement-Tracker', 'subscribeTracker': 'Abonnement-Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -39,6 +39,8 @@ const enUS = {
'maxRunning': 'Max Running Tasks', 'maxRunning': 'Max Running Tasks',
'defaultDirectDownload': 'Check direct download by default', 'defaultDirectDownload': 'Check direct download by default',
'autoStartTasks': 'Auto-start incomplete tasks on startup', 'autoStartTasks': 'Auto-start incomplete tasks on startup',
'autoDeleteTorrents': 'Auto delete .torrent files',
'autoCleanMissingFiles': 'Auto clean missing files',
'items': '@count items', 'items': '@count items',
'subscribeTracker': 'Subscribe Tracker', 'subscribeTracker': 'Subscribe Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -39,6 +39,8 @@ const esES = {
'useServerCtime': 'Usar tiempo del servidor para la creación de archivos', 'useServerCtime': 'Usar tiempo del servidor para la creación de archivos',
'maxRunning': 'Máximo de Tareas en Ejecución', 'maxRunning': 'Máximo de Tareas en Ejecución',
'autoStartTasks': 'Iniciar automáticamente tareas incompletas al arrancar', 'autoStartTasks': 'Iniciar automáticamente tareas incompletas al arrancar',
'autoDeleteTorrents': 'Eliminar automáticamente archivos .torrent',
'autoCleanMissingFiles': 'Limpiar automáticamente archivos faltantes',
'items': '@count elementos', 'items': '@count elementos',
'subscribeTracker': 'Suscribirse al Tracker', 'subscribeTracker': 'Suscribirse al Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -26,6 +26,8 @@ const faIR = {
'downloadDir': 'دایرکتوری دانلود', 'downloadDir': 'دایرکتوری دانلود',
'downloadDirValid': 'لطفا دایرکتوری دانلود را انتخاب کنید', 'downloadDirValid': 'لطفا دایرکتوری دانلود را انتخاب کنید',
'connections': 'اتصالات', 'connections': 'اتصالات',
'autoDeleteTorrents': 'حذف خودکار فایل‌های .torrent',
'autoCleanMissingFiles': 'پاکسازی خودکار فایل‌های گم شده',
'items': '@count آیتم ها', 'items': '@count آیتم ها',
'subscribeTracker': 'Subscribe Tracker', 'subscribeTracker': 'Subscribe Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -40,6 +40,8 @@ const frFR = {
'maxRunning': 'Tâches en cours maximum', 'maxRunning': 'Tâches en cours maximum',
'autoStartTasks': 'autoStartTasks':
'Démarrer automatiquement les tâches incomplètes au lancement', 'Démarrer automatiquement les tâches incomplètes au lancement',
'autoDeleteTorrents': 'Supprimer automatiquement les fichiers .torrent',
'autoCleanMissingFiles': 'Nettoyer automatiquement les fichiers manquants',
'items': '@count éléments', 'items': '@count éléments',
'subscribeTracker': 'S\'abonner au tracker', 'subscribeTracker': 'S\'abonner au tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -40,6 +40,8 @@ const huHU = {
'maxRunning': 'Maximális futó feladatok', 'maxRunning': 'Maximális futó feladatok',
'defaultDirectDownload': 'defaultDirectDownload':
'Alapértelmezettként ellenőrizze a közvetlen letöltést', 'Alapértelmezettként ellenőrizze a közvetlen letöltést',
'autoDeleteTorrents': 'Automatikus .torrent fájlok törlése',
'autoCleanMissingFiles': 'Hiányzó fájlok automatikus tisztítása',
'items': '@count elem', 'items': '@count elem',
'subscribeTracker': 'Nyomkövető előfizetése', 'subscribeTracker': 'Nyomkövető előfizetése',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -39,6 +39,8 @@ const idID = {
'useServerCtime': 'Gunakan waktu server untuk pembuatan file', 'useServerCtime': 'Gunakan waktu server untuk pembuatan file',
'maxRunning': 'Tugas Maksimum yang Berjalan', 'maxRunning': 'Tugas Maksimum yang Berjalan',
'defaultDirectDownload': 'Pilih unduhan langsung sebagai opsi standar', 'defaultDirectDownload': 'Pilih unduhan langsung sebagai opsi standar',
'autoDeleteTorrents': 'Otomatis hapus file .torrent',
'autoCleanMissingFiles': 'Otomatis bersihkan file yang hilang',
'items': '@count items', 'items': '@count items',
'subscribeTracker': 'Berlangganan Tracker', 'subscribeTracker': 'Berlangganan Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -37,6 +37,8 @@ const itIT = {
'connections': 'Connessioni', 'connections': 'Connessioni',
'useServerCtime': "Utilizza l'ora del server per la creazione dei file", 'useServerCtime': "Utilizza l'ora del server per la creazione dei file",
'maxRunning': 'Numero massimo di attività in esecuzione', 'maxRunning': 'Numero massimo di attività in esecuzione',
'autoDeleteTorrents': 'Elimina automaticamente i file .torrent',
'autoCleanMissingFiles': 'Pulisci automaticamente i file mancanti',
'items': '@count elementi', 'items': '@count elementi',
'subscribeTracker': 'Iscriviti al tracker', 'subscribeTracker': 'Iscriviti al tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -30,6 +30,8 @@ const jaJP = {
'connections': '接続', 'connections': '接続',
'maxRunning': '最大実行タスク', 'maxRunning': '最大実行タスク',
'autoStartTasks': '起動時に未完了のタスクを自動的に開始', 'autoStartTasks': '起動時に未完了のタスクを自動的に開始',
'autoDeleteTorrents': '.torrentファイルを自動削除',
'autoCleanMissingFiles': '欠落ファイルを自動クリーン',
'items': '@count アイテム', 'items': '@count アイテム',
'subscribeTracker': 'トラッカーを購読', 'subscribeTracker': 'トラッカーを購読',
'subscribeFail': '登録に失敗しました。ネットワークを確認するか、後でもう一度お試しください', 'subscribeFail': '登録に失敗しました。ネットワークを確認するか、後でもう一度お試しください',
+2
View File
@@ -36,6 +36,8 @@ const plPL = {
'connections': 'Połączenia', 'connections': 'Połączenia',
'useServerCtime': 'Użyj czasu serwera do utworzenia pliku', 'useServerCtime': 'Użyj czasu serwera do utworzenia pliku',
'maxRunning': 'Maksymalna liczba zadań', 'maxRunning': 'Maksymalna liczba zadań',
'autoDeleteTorrents': 'Automatycznie usuń pliki .torrent',
'autoCleanMissingFiles': 'Automatycznie wyczyść brakujące pliki',
'items': '@count items', 'items': '@count items',
'subscribeTracker': 'Subskrybuj tracker', 'subscribeTracker': 'Subskrybuj tracker',
'subscribeFail': 'Błąd subskrypcji, sprawdź łączność z internetem', 'subscribeFail': 'Błąd subskrypcji, sprawdź łączność z internetem',
+2
View File
@@ -39,6 +39,8 @@ const ptBR = {
'useServerCtime': 'Use server time for file creation', 'useServerCtime': 'Use server time for file creation',
'maxRunning': 'Máximo de Tarefas Simultâneas', 'maxRunning': 'Máximo de Tarefas Simultâneas',
'defaultDirectDownload': 'Marcar download direto por padrão', 'defaultDirectDownload': 'Marcar download direto por padrão',
'autoDeleteTorrents': 'Excluir automaticamente arquivos .torrent',
'autoCleanMissingFiles': 'Limpar automaticamente arquivos ausentes',
'items': '@count itens', 'items': '@count itens',
'subscribeTracker': 'Assinar Rastreador', 'subscribeTracker': 'Assinar Rastreador',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -40,6 +40,8 @@ const ruRU = {
'maxRunning': 'Максимальное количество активных задач', 'maxRunning': 'Максимальное количество активных задач',
'defaultDirectDownload': 'Прямая загрузка по умолчанию', 'defaultDirectDownload': 'Прямая загрузка по умолчанию',
'autoStartTasks': 'Автоматически запускать незавершённые задачи при старте', 'autoStartTasks': 'Автоматически запускать незавершённые задачи при старте',
'autoDeleteTorrents': 'Автоудаление торрент-файлов',
'autoCleanMissingFiles': 'Автоочистка отсутствующих файлов',
'items': '@подсчет элементов', 'items': '@подсчет элементов',
'subscribeTracker': 'Подпись трекера', 'subscribeTracker': 'Подпись трекера',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -37,6 +37,8 @@ const taTA = {
'connections': 'தொடர்புகள்', 'connections': 'தொடர்புகள்',
'useServerCtime': 'Use server time for file creation', 'useServerCtime': 'Use server time for file creation',
'maxRunning': 'அதிகபட்ச இயங்கும் பணிகள்', 'maxRunning': 'அதிகபட்ச இயங்கும் பணிகள்',
'autoDeleteTorrents': 'தானாக .torrent கோப்புகளை நீக்கு',
'autoCleanMissingFiles': 'காணாமல் போன கோப்புகளை தானாக சுத்தம் செய்',
'items': '@count items', 'items': '@count items',
'subscribeTracker': 'Subscribe Tracker', 'subscribeTracker': 'Subscribe Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -39,6 +39,8 @@ const trTR = {
'useServerCtime': 'Dosya oluşturma için sunucu zamanını kullan', 'useServerCtime': 'Dosya oluşturma için sunucu zamanını kullan',
'maxRunning': 'Maksimum Çalışan Görev', 'maxRunning': 'Maksimum Çalışan Görev',
'defaultDirectDownload': 'Varsayılan olarak doğrudan indirmeyi seç', 'defaultDirectDownload': 'Varsayılan olarak doğrudan indirmeyi seç',
'autoDeleteTorrents': '.torrent dosyalarını otomatik sil',
'autoCleanMissingFiles': 'Eksik dosyaları otomatik temizle',
'items': '@count öğe', 'items': '@count öğe',
'subscribeTracker': 'Tracker Aboneliği', 'subscribeTracker': 'Tracker Aboneliği',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -39,6 +39,8 @@ const ukUA = {
'useServerCtime': 'Використовувати час сервера для створення файлу', 'useServerCtime': 'Використовувати час сервера для створення файлу',
'maxRunning': 'Макс. завдань у черзі', 'maxRunning': 'Макс. завдань у черзі',
'defaultDirectDownload': 'Пряме завантаження за замовчуванням', 'defaultDirectDownload': 'Пряме завантаження за замовчуванням',
'autoDeleteTorrents': 'Автоматично видаляти файли .torrent',
'autoCleanMissingFiles': 'Автоматично очищати відсутні файли',
'items': '@count елементів', 'items': '@count елементів',
'subscribeTracker': 'Підписатися на трекер', 'subscribeTracker': 'Підписатися на трекер',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -36,6 +36,8 @@ const viVN = {
'connections': 'Kết nối', 'connections': 'Kết nối',
'useServerCtime': 'Sử dụng thời gian máy chủ cho việc tạo tệp', 'useServerCtime': 'Sử dụng thời gian máy chủ cho việc tạo tệp',
'maxRunning': 'Số nhiệm vụ tối đa', 'maxRunning': 'Số nhiệm vụ tối đa',
'autoDeleteTorrents': 'Tự động xóa tệp .torrent',
'autoCleanMissingFiles': 'Tự động dọn dẹp tệp bị thiếu',
'items': '@count mục', 'items': '@count mục',
'subscribeTracker': 'Theo dõi Tracker', 'subscribeTracker': 'Theo dõi Tracker',
'subscribeFail': 'subscribeFail':
+2
View File
@@ -39,6 +39,8 @@ const zhCN = {
'maxRunning': '最大下载数', 'maxRunning': '最大下载数',
'defaultDirectDownload': '默认勾选直接下载', 'defaultDirectDownload': '默认勾选直接下载',
'autoStartTasks': '启动时自动开始未完成的任务', 'autoStartTasks': '启动时自动开始未完成的任务',
'autoDeleteTorrents': '自动删除 .torrent 文件',
'autoCleanMissingFiles': '自动清理缺失文件',
'items': '@count 项', 'items': '@count 项',
'subscribeTracker': '订阅 Tracker', 'subscribeTracker': '订阅 Tracker',
'subscribeFail': '订阅失败,请检查网络或稍后重试', 'subscribeFail': '订阅失败,请检查网络或稍后重试',
+2
View File
@@ -39,6 +39,8 @@ const zhTW = {
'maxRunning': '最大執行任務數', 'maxRunning': '最大執行任務數',
'defaultDirectDownload': '預設勾選直接下載', 'defaultDirectDownload': '預設勾選直接下載',
'autoStartTasks': '啟動時自動開始未完成的任務', 'autoStartTasks': '啟動時自動開始未完成的任務',
'autoDeleteTorrents': '自動刪除 .torrent 檔案',
'autoCleanMissingFiles': '自動清理缺失檔案',
'items': '@count 個項目', 'items': '@count 個項目',
'subscribeTracker': '訂閱 Tracker', 'subscribeTracker': '訂閱 Tracker',
'subscribeFail': '訂閱失敗,請檢查網路或稍後再試', 'subscribeFail': '訂閱失敗,請檢查網路或稍後再試',