Skip to content

One self-hosted app for your shows, movies and music.

HolyArrs 1.0.7 (#181)

CoderLuii7fe71aed381b
diff --git a/.github/readme/README.ar.md b/.github/readme/README.ar.md
index 89656fb..0f78549 100644
--- a/.github/readme/README.ar.md
+++ b/.github/readme/README.ar.md
@@ -202,7 +202,7 @@ docker compose up -d
| الوسم | استخدمه لـ |
| :----: | --- |
| `latest` | أحدث إصدار. |
-| `1.0.6` | إصدار واحد بعينه. لا يتحرك أبدًا. |
+| `1.0.7` | إصدار واحد بعينه. لا يتحرك أبدًا. |
## الاستخدام
diff --git a/.github/readme/README.de.md b/.github/readme/README.de.md
index a1fdef8..59d56dd 100644
--- a/.github/readme/README.de.md
+++ b/.github/readme/README.de.md
@@ -200,7 +200,7 @@ Die Images liegen auf Docker Hub als [`holyarrs/holyarrs`](https://hub.docker.co
| Tag | Dafür nutzen |
| :----: | --- |
| `latest` | Die neueste Version. |
-| `1.0.6` | Eine genaue Version. Sie ändert sich nie. |
+| `1.0.7` | Eine genaue Version. Sie ändert sich nie. |
## Verwendung
diff --git a/.github/readme/README.es.md b/.github/readme/README.es.md
index 33ccd97..d692d26 100644
--- a/.github/readme/README.es.md
+++ b/.github/readme/README.es.md
@@ -200,7 +200,7 @@ Las imágenes están en Docker Hub como [`holyarrs/holyarrs`](https://hub.docker
| Etiqueta | Para qué sirve |
| :----: | --- |
| `latest` | La versión más reciente. |
-| `1.0.6` | Una versión exacta. Nunca se mueve. |
+| `1.0.7` | Una versión exacta. Nunca se mueve. |
## Uso
diff --git a/.github/readme/README.fr.md b/.github/readme/README.fr.md
index dc2a2ee..8b0cfb9 100644
--- a/.github/readme/README.fr.md
+++ b/.github/readme/README.fr.md
@@ -200,7 +200,7 @@ Les images sont sur Docker Hub sous le nom [`holyarrs/holyarrs`](https://hub.doc
| Étiquette | À utiliser pour |
| :----: | --- |
| `latest` | La version la plus récente. |
-| `1.0.6` | Une version précise. Elle ne bouge jamais. |
+| `1.0.7` | Une version précise. Elle ne bouge jamais. |
## Utilisation
diff --git a/.github/readme/README.hi.md b/.github/readme/README.hi.md
index 0231b8a..2968826 100644
--- a/.github/readme/README.hi.md
+++ b/.github/readme/README.hi.md
@@ -200,7 +200,7 @@ NAS पर चला रहे हैं? देखिए [Unraid, Synology औ
| टैग | किसके लिए |
| :----: | --- |
| `latest` | नवीनतम रिलीज़। |
-| `1.0.6` | एक तय वर्ज़न। यह कभी नहीं बदलता। |
+| `1.0.7` | एक तय वर्ज़न। यह कभी नहीं बदलता। |
## इस्तेमाल
diff --git a/.github/readme/README.it.md b/.github/readme/README.it.md
index e986b6f..540a250 100644
--- a/.github/readme/README.it.md
+++ b/.github/readme/README.it.md
@@ -200,7 +200,7 @@ Le immagini sono su Docker Hub come [`holyarrs/holyarrs`](https://hub.docker.com
| Tag | A cosa serve |
| :----: | --- |
| `latest` | La versione più recente. |
-| `1.0.6` | Una versione esatta. Non cambia mai. |
+| `1.0.7` | Una versione esatta. Non cambia mai. |
## Utilizzo
diff --git a/.github/readme/README.ja.md b/.github/readme/README.ja.md
index 86dca02..345bc5f 100644
--- a/.github/readme/README.ja.md
+++ b/.github/readme/README.ja.md
@@ -200,7 +200,7 @@ NAS をお使いですか。[Unraid、Synology などの NAS](https://docs.HolyA
| タグ | 用途 |
| :----: | --- |
| `latest` | 最新のリリース。 |
-| `1.0.6` | 特定の1つのバージョンです。動くことはありません。 |
+| `1.0.7` | 特定の1つのバージョンです。動くことはありません。 |
## 使い方
diff --git a/.github/readme/README.ko.md b/.github/readme/README.ko.md
index 176739d..9d4c7d2 100644
--- a/.github/readme/README.ko.md
+++ b/.github/readme/README.ko.md
@@ -200,7 +200,7 @@ NAS를 쓰세요? [Unraid, Synology 및 기타 NAS](https://docs.HolyArrs.com/ru
| 태그 | 용도 |
| :----: | --- |
| `latest` | 최신 릴리스. |
-| `1.0.6` | 정확히 한 버전이에요. 절대 움직이지 않아요. |
+| `1.0.7` | 정확히 한 버전이에요. 절대 움직이지 않아요. |
## 사용법
diff --git a/.github/readme/README.nl.md b/.github/readme/README.nl.md
index 24907e6..cc67d9c 100644
--- a/.github/readme/README.nl.md
+++ b/.github/readme/README.nl.md
@@ -200,7 +200,7 @@ De images staan op Docker Hub als [`holyarrs/holyarrs`](https://hub.docker.com/r
| Tag | Gebruik het voor |
| :----: | --- |
| `latest` | De nieuwste versie. |
-| `1.0.6` | Eén exacte versie. Die verandert nooit. |
+| `1.0.7` | Eén exacte versie. Die verandert nooit. |
## Gebruik
diff --git a/.github/readme/README.pl.md b/.github/readme/README.pl.md
index 06dcf44..5fa2f8f 100644
--- a/.github/readme/README.pl.md
+++ b/.github/readme/README.pl.md
@@ -200,7 +200,7 @@ Image'e są na Docker Hub jako [`holyarrs/holyarrs`](https://hub.docker.com/r/ho
| Tag | Do czego użyć |
| :----: | --- |
| `latest` | Najnowsza wersja. |
-| `1.0.6` | Jedna dokładna wersja. Nigdy się nie zmienia. |
+| `1.0.7` | Jedna dokładna wersja. Nigdy się nie zmienia. |
## Użycie
diff --git a/.github/readme/README.pt-BR.md b/.github/readme/README.pt-BR.md
index 7d17ae2..ec8c7cf 100644
--- a/.github/readme/README.pt-BR.md
+++ b/.github/readme/README.pt-BR.md
@@ -200,7 +200,7 @@ As imagens ficam no Docker Hub como [`holyarrs/holyarrs`](https://hub.docker.com
| Tag | Use para |
| :----: | --- |
| `latest` | A versão mais recente. |
-| `1.0.6` | Uma versão exata. Nunca muda. |
+| `1.0.7` | Uma versão exata. Nunca muda. |
## Uso
diff --git a/.github/readme/README.ru.md b/.github/readme/README.ru.md
index 619506c..09c7f66 100644
--- a/.github/readme/README.ru.md
+++ b/.github/readme/README.ru.md
@@ -200,7 +200,7 @@ HolyArrs только читает ваши старые приложения и
| Тег | Для чего |
| :----: | --- |
| `latest` | Самая новая версия. |
-| `1.0.6` | Одна точная версия. Никогда не сдвигается. |
+| `1.0.7` | Одна точная версия. Никогда не сдвигается. |
## Использование
diff --git a/.github/readme/README.tr.md b/.github/readme/README.tr.md
index bcf7e2e..8419f63 100644
--- a/.github/readme/README.tr.md
+++ b/.github/readme/README.tr.md
@@ -200,7 +200,7 @@ NAS mı kullanıyorsun? [Unraid, Synology ve diğer NAS cihazları](https://docs
| Etiket | Ne için kullanılır |
| :----: | --- |
| `latest` | En yeni sürüm. |
-| `1.0.6` | Tam olarak tek bir sürüm. Asla değişmez. |
+| `1.0.7` | Tam olarak tek bir sürüm. Asla değişmez. |
## Kullanım
diff --git a/.github/readme/README.uk.md b/.github/readme/README.uk.md
index 2a9e859..e6cabc9 100644
--- a/.github/readme/README.uk.md
+++ b/.github/readme/README.uk.md
@@ -200,7 +200,7 @@ HolyArrs лише читає твої старі застосунки й ніч
| Тег | Для чого |
| :----: | --- |
| `latest` | Найновіша версія. |
-| `1.0.6` | Одна точна версія. Вона ніколи не змінюється. |
+| `1.0.7` | Одна точна версія. Вона ніколи не змінюється. |
## Використання
diff --git a/.github/readme/README.zh-CN.md b/.github/readme/README.zh-CN.md
index 730edce..8fe2f51 100644
--- a/.github/readme/README.zh-CN.md
+++ b/.github/readme/README.zh-CN.md
@@ -200,7 +200,7 @@ HolyArrs 只读取你的旧应用,不会改动它们里面的任何东西,
| 标签 | 用途 |
| :----: | --- |
| `latest` | 最新版本。 |
-| `1.0.6` | 固定的某一个版本,永远不会变。 |
+| `1.0.7` | 固定的某一个版本,永远不会变。 |
## 用法
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5f00ca5..40e46ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,16 @@
All notable changes to HolyArrs are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/).
+## 1.0.7
+
+### Added
+
+- Pick rules can take their release scores from TRaSH Guides, and sync them again later without duplicates. ([#172](https://github.com/HolyArrs/HolyArrs/issues/172))
+
+### Fixed
+
+- Opening HolyArrs by a name it won't save on now shows how to allow that name, on every page, before you try to save. ([#178](https://github.com/HolyArrs/HolyArrs/issues/178))
+
## 1.0.6
### Added
diff --git a/README.md b/README.md
index b0f26bc..e347741 100644
--- a/README.md
+++ b/README.md
@@ -200,7 +200,7 @@ Images live on Docker Hub as [`holyarrs/holyarrs`](https://hub.docker.com/r/holy
| Tag | Use it for |
| :----: | --- |
| `latest` | The newest release. |
-| `1.0.6` | One exact version. It never moves. |
+| `1.0.7` | One exact version. It never moves. |
## Usage
diff --git a/VERSION b/VERSION
index af0b7dd..238d6e8 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.0.6
+1.0.7
diff --git a/app/backend/cmd/holyarrs/openapi.json b/app/backend/cmd/holyarrs/openapi.json
index 4778e38..108b326 100644
--- a/app/backend/cmd/holyarrs/openapi.json
+++ b/app/backend/cmd/holyarrs/openapi.json
@@ -22415,6 +22415,39 @@
"x-holyarrs-scope": "write"
}
},
+ "/api/v1/pick-rules/{id}/trash": {
+ "post": {
+ "description": "Send {\"app\": \"sonarr\" or \"radarr\", \"profile_id\": \"<TRaSH id>\"}. Makes or updates synced traits and sets their points in these Pick rules; sending it again re-syncs without duplicates.",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "id",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "What the sync did"
+ },
+ "400": {
+ "description": "Bad request"
+ },
+ "404": {
+ "description": "No such Pick rules or profile"
+ },
+ "502": {
+ "description": "TRaSH Guides could not be read"
+ }
+ },
+ "summary": "Apply or re-sync a TRaSH Guides profile",
+ "x-holyarrs-part": "media",
+ "x-holyarrs-permission": "settings",
+ "x-holyarrs-scope": "write"
+ }
+ },
"/api/v1/public/signin-art": {
"get": {
"description": "The sign-in page's backdrops; open to everyone. Only picture addresses with their native width and height (a textless backdrop, an optional textless poster for tall screens, and a logo): never names, ids or counts. Kid-safe titles only (movies up to PG-13, shows up to TV-PG, never unrated). From the Library when \"Show Library art on the sign-in page\" is on and 6 or more titles qualify, else from trending titles. Kept 6 hours; each address may call it 20 times a minute (429 with Retry-After past that).",
@@ -29305,6 +29338,26 @@
"x-holyarrs-scope": "read"
}
},
+ "/api/v1/trash/profiles": {
+ "get": {
+ "description": "Profiles for ?app=sonarr (shows) or radarr (movies), read from the TRaSH Guides repository and kept for an hour.",
+ "responses": {
+ "200": {
+ "description": "The profiles"
+ },
+ "400": {
+ "description": "Unknown app"
+ },
+ "502": {
+ "description": "TRaSH Guides could not be read"
+ }
+ },
+ "summary": "List TRaSH Guides profiles",
+ "x-holyarrs-part": "media",
+ "x-holyarrs-permission": "settings",
+ "x-holyarrs-scope": "admin"
+ }
+ },
"/api/v1/turned-down": {
"delete": {
"description": "Every turned-down Release may be picked again.",
diff --git a/app/backend/cmd/holyarrs/trash_test.go b/app/backend/cmd/holyarrs/trash_test.go
new file mode 100644
index 0000000..657ce27
--- /dev/null
+++ b/app/backend/cmd/holyarrs/trash_test.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/downloads"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/library"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/library/trashtest"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/mediafiles"
+)
+
+// TRaSH Guides: profiles are listed, applying one scores Releases through
+// synced traits, and a second sync makes no new traits.
+//
+// route: GET /api/v1/trash/profiles
+// route: POST /api/v1/pick-rules/{id}/trash
+func TestTrashProfileApplied(t *testing.T) {
+ srv, _, _ := lbLibSetup(t)
+ t.Cleanup(func() { mediafiles.SetOwnTraits(nil) })
+ old := downloads.TrashClient
+ c := library.NewTrashGuides()
+ c.Raw, c.API = trashtest.Serve(t, trashtest.Files)
+ downloads.TrashClient = c
+ t.Cleanup(func() { downloads.TrashClient = old })
+
+ var list struct {
+ Profiles []struct{ ID, Name string } `json:"profiles"`
+ }
+ _ = json.Unmarshal(lbDo(t, "GET", srv.URL+"/api/v1/trash/profiles?app=sonarr", "", 200), &list)
+ if len(list.Profiles) != 1 || list.Profiles[0].ID != "p1" {
+ t.Fatalf("profiles: %+v", list)
+ }
+ lbDo(t, "GET", srv.URL+"/api/v1/trash/profiles?app=lidarr", "", 400)
+
+ var p mediafiles.PickRules
+ _ = json.Unmarshal(lbDo(t, "POST", srv.URL+"/api/v1/pick-rules", lbRuleJSON(t, "Synced", []string{"show"}, mediafiles.GoodEveryday()), 201), &p)
+ path := fmt.Sprintf("%s/api/v1/pick-rules/%d/trash", srv.URL, p.ID)
+ var res struct {
+ Added int `json:"added"`
+ Updated int `json:"updated"`
+ Scored []struct {
+ Name string `json:"name"`
+ Points int `json:"points"`
+ } `json:"scored"`
+ Skipped []struct {
+ Name string `json:"name"`
+ Kinds []string `json:"kinds"`
+ } `json:"skipped"`
+ }
+ _ = json.Unmarshal(lbDo(t, "POST", path, `{"app":"sonarr","profile_id":"p1"}`, 200), &res)
+ if res.Added != 3 || len(res.Scored) != 3 || len(res.Skipped) != 1 || res.Skipped[0].Kinds[0] != "language" {
+ t.Fatalf("first sync: %+v", res)
+ }
+ _ = json.Unmarshal(lbDo(t, "POST", path, `{"app":"sonarr","profile_id":"p1"}`, 200), &res)
+ if res.Added != 0 || res.Updated != 3 {
+ t.Fatalf("second sync: %+v", res)
+ }
+ lbDo(t, "POST", path, `{"app":"sonarr","profile_id":"nope"}`, 404)
+ lbDo(t, "POST", path, `{"app":"lidarr","profile_id":"p1"}`, 400)
+
+ var traits struct {
+ OwnTraits []downloads.OwnTraitView `json:"own_traits"`
+ }
+ _ = json.Unmarshal(lbDo(t, "GET", srv.URL+"/api/v1/own-traits", "", 200), &traits)
+ synced := 0
+ for _, tr := range traits.OwnTraits {
+ if tr.Source == "trash" {
+ synced++
+ lbDo(t, "PUT", fmt.Sprintf("%s/api/v1/own-traits/%d", srv.URL, tr.ID), `{"name":"x","match":"name","terms":["x"]}`, 400)
+ }
+ }
+ if synced != 3 {
+ t.Fatalf("synced traits: %d", synced)
+ }
+}
diff --git a/app/backend/internal/accounts/host_banner_test.go b/app/backend/internal/accounts/host_banner_test.go
new file mode 100644
index 0000000..febfb97
--- /dev/null
+++ b/app/backend/internal/accounts/host_banner_test.go
@@ -0,0 +1,30 @@
+package accounts
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+// The public auth state names a host saves are refused on, so the app can
+// say so on arrival; an allowed name gets no such field.
+func TestStateNamesARefusedHost(t *testing.T) {
+ f := gated(t, Options{})
+ _ = ownerOf(t, f)
+ read := func(host string) map[string]any {
+ resp, body := hostDo(t, client(t), "GET", f.srv.URL+"/api/v1/auth/state", host, "", nil)
+ if resp.StatusCode != 200 {
+ t.Fatalf("state on %s: %d %s", host, resp.StatusCode, body)
+ }
+ var m map[string]any
+ if err := json.Unmarshal([]byte(body), &m); err != nil {
+ t.Fatal(err)
+ }
+ return m
+ }
+ if got := read("media.example.com")["host_refused"]; got != "media.example.com" {
+ t.Fatalf("refused name: %v", got)
+ }
+ if got, ok := read("127.0.0.1")["host_refused"]; ok {
+ t.Fatalf("an IP address is allowed, got %v", got)
+ }
+}
diff --git a/app/backend/internal/accounts/scope_routes.go b/app/backend/internal/accounts/scope_routes.go
index 8288297..7c6a282 100644
--- a/app/backend/internal/accounts/scope_routes.go
+++ b/app/backend/internal/accounts/scope_routes.go
@@ -10,6 +10,7 @@ import (
// RouteScopes names routes whose scope is not the one the method and
// RoutePerms give them (see RouteScope).
var RouteScopes = map[string]string{
+ "GET /api/v1/trash/profiles": webserver.ScopeAdmin,
"GET /api/v1/downloads/{id}/swarm": webserver.ScopeAdmin,
"GET /api/v1/downloads/{id}/detail": webserver.ScopeAdmin,
"GET /api/v1/downloads/{id}/files": webserver.ScopeAdmin,
diff --git a/app/backend/internal/accounts/scopes.go b/app/backend/internal/accounts/scopes.go
index e8b1fd6..50b5e7a 100644
--- a/app/backend/internal/accounts/scopes.go
+++ b/app/backend/internal/accounts/scopes.go
@@ -319,6 +319,8 @@ var RoutePerms = map[string]webserver.Perm{
"POST /api/v1/own-traits": webserver.PermSettings,
"PUT /api/v1/own-traits/{id}": webserver.PermSettings,
"DELETE /api/v1/own-traits/{id}": webserver.PermSettings,
+ "GET /api/v1/trash/profiles": webserver.PermSettings,
+ "POST /api/v1/pick-rules/{id}/trash": webserver.PermSettings,
"GET /api/v1/never-add": webserver.PermManageLibrary,
"POST /api/v1/never-add": webserver.PermManageLibrary,
"DELETE /api/v1/never-add/{id}": webserver.PermManageLibrary,
diff --git a/app/backend/internal/accounts/setup_owner.go b/app/backend/internal/accounts/setup_owner.go
index 45fbe95..34974c4 100644
--- a/app/backend/internal/accounts/setup_owner.go
+++ b/app/backend/internal/accounts/setup_owner.go
@@ -36,6 +36,11 @@ func (a *Auth) state(w http.ResponseWriter, r *http.Request) {
if a.configUnmapped {
out["config_unmapped"] = true
}
+ // Opened by a name saves are refused on: say so on arrival, not on the
+ // first save.
+ if !a.hostAllowed(r) {
+ out["host_refused"] = echoHost(r.Host)
+ }
if !ok {
out["setup_ways"] = setupWays
}
diff --git a/app/backend/internal/core/database/migrations/main/0097_own_trait_formats.sql b/app/backend/internal/core/database/migrations/main/0097_own_trait_formats.sql
new file mode 100644
index 0000000..0a31784
--- /dev/null
+++ b/app/backend/internal/core/database/migrations/main/0097_own_trait_formats.sql
@@ -0,0 +1,8 @@
+-- Own traits synced from TRaSH Guides (#172). A synced trait keeps where it
+-- came from (source "trash", source_id "<app>:<trash id>") so a later sync
+-- updates it in place, and holds its tests in specs: every test kind must
+-- pass, like a release format in the old apps.
+ALTER TABLE own_traits ADD COLUMN source TEXT NOT NULL DEFAULT '';
+ALTER TABLE own_traits ADD COLUMN source_id TEXT NOT NULL DEFAULT '';
+ALTER TABLE own_traits ADD COLUMN specs TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(specs));
+CREATE UNIQUE INDEX own_traits_source ON own_traits(source, source_id) WHERE source != '';
diff --git a/app/backend/internal/core/parts/table.go b/app/backend/internal/core/parts/table.go
index 65f641d..2545e1e 100644
--- a/app/backend/internal/core/parts/table.go
+++ b/app/backend/internal/core/parts/table.go
@@ -399,6 +399,8 @@ var routeOwners = map[string]Owner{
"POST /api/v1/own-traits": Media,
"PUT /api/v1/own-traits/{id}": Media,
"DELETE /api/v1/own-traits/{id}": Media,
+ "GET /api/v1/trash/profiles": Media,
+ "POST /api/v1/pick-rules/{id}/trash": Media,
"GET /api/v1/never-add": Media,
"POST /api/v1/never-add": Media,
"DELETE /api/v1/never-add/{id}": Media,
diff --git a/app/backend/internal/downloads/routes.go b/app/backend/internal/downloads/routes.go
index c531565..7296f67 100644
--- a/app/backend/internal/downloads/routes.go
+++ b/app/backend/internal/downloads/routes.go
@@ -48,4 +48,6 @@ func (h *Handlers) Routes(m *http.ServeMux) {
m.HandleFunc("POST /api/v1/own-traits", h.addOwnTrait)
m.HandleFunc("PUT /api/v1/own-traits/{id}", h.editOwnTrait)
m.HandleFunc("DELETE /api/v1/own-traits/{id}", h.deleteOwnTrait)
+ m.HandleFunc("GET /api/v1/trash/profiles", h.listTrashProfiles)
+ m.HandleFunc("POST /api/v1/pick-rules/{id}/trash", h.applyTrash)
}
diff --git a/app/backend/internal/downloads/routes_own_traits.go b/app/backend/internal/downloads/routes_own_traits.go
index eb17625..3a35ac8 100644
--- a/app/backend/internal/downloads/routes_own_traits.go
+++ b/app/backend/internal/downloads/routes_own_traits.go
@@ -19,6 +19,10 @@ type OwnTraitView struct {
Name string `json:"name"`
Match string `json:"match"`
Terms []string `json:"terms"`
+ // Source is "trash" for a trait synced from TRaSH Guides, which tests
+ // Specs and cannot be edited by hand.
+ Source string `json:"source,omitempty"`
+ Specs []mediafiles.OwnSpec `json:"specs,omitempty"`
}
func viewOfOwnTrait(t mediafiles.OwnTrait) OwnTraitView {
@@ -26,7 +30,7 @@ func viewOfOwnTrait(t mediafiles.OwnTrait) OwnTraitView {
if terms == nil {
terms = []string{}
}
- return OwnTraitView{ID: t.ID, Key: mediafiles.OwnTraitKey(t.ID), Name: t.Name, Match: t.Match, Terms: terms}
+ return OwnTraitView{ID: t.ID, Key: mediafiles.OwnTraitKey(t.ID), Name: t.Name, Match: t.Match, Terms: terms, Source: t.Source, Specs: t.Specs}
}
const ownTraitHelp = `send {"name": "...", "match": "name" or "group", "terms": ["word", "/pattern/"]}`
diff --git a/app/backend/internal/downloads/routes_trash.go b/app/backend/internal/downloads/routes_trash.go
new file mode 100644
index 0000000..0c52c0e
--- /dev/null
+++ b/app/backend/internal/downloads/routes_trash.go
@@ -0,0 +1,86 @@
+package downloads
+
+import (
+ "errors"
+ "net/http"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/core/database"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/core/webserver"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/library"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/mediafiles"
+)
+
+// TrashClient reads TRaSH Guides; tests point it at a local server.
+var TrashClient = library.NewTrashGuides()
+
+// listTrashProfiles answers the TRaSH Guides profiles for ?app=sonarr
+// (shows) or radarr (movies).
+func (h *Handlers) listTrashProfiles(w http.ResponseWriter, r *http.Request) {
+ app := r.URL.Query().Get("app")
+ if app != "sonarr" && app != "radarr" {
+ webserver.Fail(w, http.StatusBadRequest, "app must be sonarr (shows) or radarr (movies)")
+ return
+ }
+ d, err := TrashClient.Load(r.Context(), app)
+ if err != nil {
+ webserver.Fail(w, http.StatusBadGateway, err.Error())
+ return
+ }
+ out := d.Profiles
+ if out == nil {
+ out = []library.TrashProfile{}
+ }
+ webserver.WriteJSON(w, http.StatusOK, map[string]any{"profiles": out})
+}
+
+const trashHelp = `send {"app": "sonarr" or "radarr", "profile_id": "<TRaSH profile id>"}`
+
+// applyTrash applies a TRaSH Guides profile to Pick rules {id}. Sending it
+// again re-syncs: synced traits are updated, never made twice.
+func (h *Handlers) applyTrash(w http.ResponseWriter, r *http.Request) {
+ id, ok := h.pickRulesID(w, r)
+ if !ok {
+ return
+ }
+ var in struct {
+ App string `json:"app"`
+ ProfileID string `json:"profile_id"`
+ }
+ if !webserver.Decode(w, r, &in, trashHelp) {
+ return
+ }
+ if in.App != "sonarr" && in.App != "radarr" {
+ webserver.Fail(w, http.StatusBadRequest, "app must be sonarr (shows) or radarr (movies)")
+ return
+ }
+ res, err := library.ApplyTrash(r.Context(), h.Store, TrashClient, id, in.App, in.ProfileID, webserver.ActorOr(r, database.Actor{Kind: "user", ID: 1}))
+ var fe *mediafiles.FieldError
+ switch {
+ case err == nil:
+ case errors.Is(err, library.ErrTrashProfile):
+ webserver.Fail(w, http.StatusNotFound, err.Error())
+ return
+ case errors.Is(err, database.ErrNotFound), errors.As(err, &fe), errors.Is(err, library.ErrOwnTraitName):
+ h.pickRulesError(w, r, id, err)
+ return
+ default:
+ webserver.Fail(w, http.StatusBadGateway, err.Error())
+ return
+ }
+ u, err := library.PickRulesUse(r.Context(), h.Store, id)
+ if err != nil {
+ webserver.Internal(w, "downloads", err)
+ return
+ }
+ if res.Scored == nil {
+ res.Scored = []library.TrashScored{}
+ }
+ if res.Skipped == nil {
+ res.Skipped = []library.TrashSkipped{}
+ }
+ webserver.WriteJSON(w, http.StatusOK, map[string]any{
+ "pick_rules": detailOfPickRules(res.PickRules, u),
+ "added": res.Added, "updated": res.Updated,
+ "scored": res.Scored, "skipped": res.Skipped,
+ })
+}
diff --git a/app/backend/internal/library/owntraits.go b/app/backend/internal/library/owntraits.go
index 3beed59..3c3d35d 100644
--- a/app/backend/internal/library/owntraits.go
+++ b/app/backend/internal/library/owntraits.go
@@ -99,6 +99,9 @@ func UpdateOwnTrait(ctx context.Context, st *database.Store, id int64, in OwnTra
if err := database.Get(ctx, tx, "own_traits", id, &t); err != nil {
return err
}
+ if t.Source != "" {
+ return &mediafiles.FieldError{Field: "terms", Text: "This trait comes from TRaSH Guides; sync the Pick rules again to update it."}
+ }
if err := ownNameTaken(tx, next.Name, id); err != nil {
return err
}
diff --git a/app/backend/internal/library/trash.go b/app/backend/internal/library/trash.go
new file mode 100644
index 0000000..1a93da7
--- /dev/null
+++ b/app/backend/internal/library/trash.go
@@ -0,0 +1,195 @@
+package library
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "slices"
+ "sort"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/mediafiles"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/core/database"
+ domain "github.com/HolyArrs/holyarrs/app/backend/internal/core/model"
+)
+
+// TrashResult says what applying a TRaSH Guides profile did.
+type TrashResult struct {
+ PickRules mediafiles.PickRules `json:"pick_rules"`
+ Added int `json:"added"` // synced traits made
+ Updated int `json:"updated"` // synced traits already there, refreshed
+ Scored []TrashScored `json:"scored"`
+ Skipped []TrashSkipped `json:"skipped"`
+}
+
+// TrashScored is one synced trait and the points it now gives.
+type TrashScored struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Points int `json:"points"`
+}
+
+// ErrTrashProfile says the TRaSH profile asked for is not there.
+var ErrTrashProfile = errors.New("no such TRaSH Guides profile")
+
+// pickMaxTraits matches the Pick rules limit on listed traits.
+const pickMaxTraits = 64
+
+// ApplyTrash applies TRaSH profile profileID (of app sonarr or radarr) to
+// Pick rules id: each format it can test becomes a synced trait (made once,
+// updated in place on later syncs), the rules' points list gets the
+// profile's scores in place of the ones a previous sync put there, and the
+// minimum, good enough and upgrade points follow the profile. Points for
+// your own traits and built-in traits stay as they are.
+func ApplyTrash(ctx context.Context, st *database.Store, c *TrashGuides, id int64, app, profileID string, by domain.Actor) (TrashResult, error) {
+ var res TrashResult
+ d, err := c.Load(ctx, app)
+ if err != nil {
+ return res, err
+ }
+ prof, ok := d.Profile(profileID)
+ if !ok {
+ return res, ErrTrashProfile
+ }
+ plan := d.Build(prof)
+ res.Skipped = plan.Skipped
+
+ var p mediafiles.PickRules
+ if err := database.Get(ctx, st.Read(), "pick_rules", id, &p); err != nil {
+ return res, err
+ }
+ if mediafiles.IsMusicRules(p.Body) {
+ return res, &mediafiles.FieldError{Field: "body", Text: "TRaSH Guides profiles are for shows and movies, not music."}
+ }
+
+ keys := make([]string, len(plan.Traits))
+ err = st.Write(ctx, func(tx *sql.Tx) error {
+ res.Added, res.Updated = 0, 0
+ for i, pl := range plan.Traits {
+ t := pl.Trait
+ var old mediafiles.OwnTrait
+ rows, err := database.Select[mediafiles.OwnTrait](ctx, tx, "own_traits", "source = ? AND source_id = ?", t.Source, t.SourceID)
+ if err != nil {
+ return err
+ }
+ if len(rows) > 0 {
+ old = rows[0]
+ }
+ name, err := freeTraitName(tx, t.Name, app, old.ID)
+ if err != nil {
+ return err
+ }
+ if old.ID != 0 {
+ old.Name, old.Match, old.Terms, old.Specs = name, t.Match, t.Terms, t.Specs
+ if err := database.Update(tx, "own_traits", &old, by); err != nil {
+ return err
+ }
+ keys[i] = mediafiles.OwnTraitKey(old.ID)
+ res.Updated++
+ continue
+ }
+ t.Name = name
+ nid, err := database.Insert(tx, "own_traits", &t, by)
+ if err != nil {
+ return err
+ }
+ keys[i] = mediafiles.OwnTraitKey(nid)
+ res.Added++
+ }
+ return nil
+ })
+ if err != nil {
+ return res, err
+ }
+ reload(ctx, st)
+
+ // The points list: keep what is not from TRaSH, put the profile's in.
+ synced, err := syncedKeys(ctx, st)
+ if err != nil {
+ return res, err
+ }
+ b := p.Body
+ kept := slices.DeleteFunc(slices.Clone(b.Traits), func(tp mediafiles.TraitPoints) bool { return synced[tp.Trait] })
+ var add []mediafiles.TraitPoints
+ for i, pl := range plan.Traits {
+ add = append(add, mediafiles.TraitPoints{Trait: keys[i], Points: pl.Points})
+ }
+ if room := pickMaxTraits - len(kept); len(add) > room {
+ // Keep the strongest scores; the rest are reported.
+ sort.SliceStable(add, func(i, j int) bool { return abs(add[i].Points) > abs(add[j].Points) })
+ for _, tp := range add[max(room, 0):] {
+ res.Skipped = append(res.Skipped, TrashSkipped{Name: traitName(plan, keys, tp.Trait), Reason: "Pick rules hold at most 64 traits"})
+ }
+ add = add[:max(room, 0)]
+ }
+ b.Traits = append(kept, add...)
+ for _, tp := range add {
+ res.Scored = append(res.Scored, TrashScored{Key: tp.Trait, Name: traitName(plan, keys, tp.Trait), Points: tp.Points})
+ }
+ clamp := func(n int) int { return max(-TrashMaxPoints, min(TrashMaxPoints, n)) }
+ b.MinPoints = clamp(prof.MinScore)
+ g := clamp(prof.CutoffScore)
+ b.GoodEnoughPoints = &g
+ b.UpgradeMinPoints = clamp(prof.MinUpgradeScore)
+ b.Synced = &mediafiles.SyncedProfile{From: "trash", App: app, ProfileID: prof.ID, Name: prof.Name, At: time.Now().UTC().Format(time.RFC3339)}
+ res.PickRules, err = UpdatePickRules(ctx, st, id, PickRulesInput{Name: p.Name, Kinds: p.Kinds, Body: b}, by)
+ return res, err
+}
+
+func abs(n int) int {
+ if n < 0 {
+ return -n
+ }
+ return n
+}
+
+func traitName(plan TrashPlan, keys []string, key string) string {
+ if i := slices.Index(keys, key); i >= 0 {
+ return plan.Traits[i].Trait.Name
+ }
+ return key
+}
+
+// syncedKeys lists the Pick rules keys of every synced trait.
+func syncedKeys(ctx context.Context, st *database.Store) (map[string]bool, error) {
+ ts, err := database.Select[mediafiles.OwnTrait](ctx, st.Read(), "own_traits", "source != ''")
+ if err != nil {
+ return nil, err
+ }
+ m := make(map[string]bool, len(ts))
+ for _, t := range ts {
+ m[mediafiles.OwnTraitKey(t.ID)] = true
+ }
+ return m, nil
+}
+
+// freeTraitName finds a name no other trait has: the format's own name,
+// then with "(shows)" or "(movies)", then numbered.
+func freeTraitName(tx *sql.Tx, name, app string, self int64) (string, error) {
+ word := "shows"
+ if app == "radarr" {
+ word = "movies"
+ }
+ try := []string{name, name + " (" + word + ")"}
+ for n := 2; n < 20; n++ {
+ try = append(try, fmt.Sprintf("%s (%s %d)", name, word, n))
+ }
+ for _, t := range try {
+ if utf8.RuneCountInString(t) > 60 {
+ t = string([]rune(t)[:60])
+ }
+ t = strings.TrimSpace(t)
+ err := ownNameTaken(tx, t, self)
+ if err == nil {
+ return t, nil
+ }
+ if !errors.Is(err, ErrOwnTraitName) {
+ return "", err
+ }
+ }
+ return "", ErrOwnTraitName
+}
diff --git a/app/backend/internal/library/trash_guides.go b/app/backend/internal/library/trash_guides.go
new file mode 100644
index 0000000..184d4ab
--- /dev/null
+++ b/app/backend/internal/library/trash_guides.go
@@ -0,0 +1,418 @@
+// TRaSH Guides: HolyArrs reads TRaSH Guides (github.com/TRaSH-Guides/Guides, MIT)
+// profiles and release formats and turns them into HolyArrs synced traits
+// with points. Only the parts HolyArrs can test the same way are taken;
+// the rest is reported as skipped, never dropped silently.
+package library
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/mediafiles"
+)
+
+// TrashProfile is one TRaSH profile, as listed for picking.
+type TrashProfile struct {
+ ID string `json:"id"`
+ App string `json:"app"` // sonarr (shows) or radarr (movies)
+ Name string `json:"name"`
+ Description string `json:"description"`
+ URL string `json:"url"`
+
+ ScoreSet string `json:"-"`
+ MinScore int `json:"min_points"`
+ CutoffScore int `json:"good_enough_points"`
+ MinUpgradeScore int `json:"upgrade_min_points"`
+ FormatItems map[string]string `json:"-"` // name -> trash id
+}
+
+type rawTrashProfile struct {
+ TrashID string `json:"trash_id"`
+ Name string `json:"name"`
+ Description string `json:"trash_description"`
+ URL string `json:"trash_url"`
+ ScoreSet string `json:"trash_score_set"`
+ MinFormatScore int `json:"minFormatScore"`
+ CutoffScore int `json:"cutoffFormatScore"`
+ MinUpgradeScore int `json:"minUpgradeFormatScore"`
+ FormatItems map[string]string `json:"formatItems"`
+}
+
+// TrashFormat is one TRaSH release format.
+type TrashFormat struct {
+ ID string `json:"trash_id"`
+ Name string `json:"name"`
+ Scores map[string]int `json:"trash_scores"`
+ Specs []TrashSpec `json:"specifications"`
+}
+
+// TrashSpec is one test of a TrashFormat.
+type TrashSpec struct {
+ Name string `json:"name"`
+ Implementation string `json:"implementation"`
+ Negate bool `json:"negate"`
+ Required bool `json:"required"`
+ Fields struct {
+ Value json.RawMessage `json:"value"`
+ } `json:"fields"`
+}
+
+// TrashGroupFormat is one format in a TrashGroup.
+type TrashGroupFormat struct {
+ Name string `json:"name"`
+ ID string `json:"trash_id"`
+ Required bool `json:"required"`
+ Default bool `json:"default"`
+}
+
+// TrashGroup is a TRaSH format group: formats added to the profiles it names.
+type TrashGroup struct {
+ Name string `json:"name"`
+ Default string `json:"default"`
+ Formats []TrashGroupFormat `json:"custom_formats"`
+ Profiles struct {
+ Include map[string]string `json:"include"`
+ } `json:"quality_profiles"`
+}
+
+// TrashData is everything read for one app.
+type TrashData struct {
+ App string
+ Profiles []TrashProfile
+ Formats map[string]TrashFormat // by trash id
+ Groups []TrashGroup
+}
+
+// TrashGuides fetches TRaSH Guides. Raw and API can point at a test server.
+type TrashGuides struct {
+ HTTP *http.Client
+ Raw string // raw files base, no trailing "/"
+ API string // GitHub contents API base for listing a folder
+ Ref string
+
+ mu sync.Mutex
+ cache map[string]trashCached
+}
+
+type trashCached struct {
+ at time.Time
+ d *TrashData
+}
+
+// NewTrashGuides reads from GitHub.
+func NewTrashGuides() *TrashGuides {
+ return &TrashGuides{
+ HTTP: &http.Client{Timeout: 30 * time.Second},
+ Raw: "https://raw.githubusercontent.com/TRaSH-Guides/Guides",
+ API: "https://api.github.com/repos/TRaSH-Guides/Guides/contents",
+ Ref: "master",
+ }
+}
+
+const trashCacheFor = time.Hour
+
+// Load reads one app's profiles, formats and groups (kept for an hour, so
+// picking a profile and then applying it reads GitHub once).
+func (c *TrashGuides) Load(ctx context.Context, app string) (*TrashData, error) {
+ if app != "sonarr" && app != "radarr" {
+ return nil, fmt.Errorf("unknown TRaSH app %q", app)
+ }
+ c.mu.Lock()
+ if e, ok := c.cache[app]; ok && time.Since(e.at) < trashCacheFor {
+ c.mu.Unlock()
+ return e.d, nil
+ }
+ c.mu.Unlock()
+ d := &TrashData{App: app, Formats: map[string]TrashFormat{}}
+ dir := "docs/json/" + app
+ for _, part := range []string{"quality-profiles", "cf", "cf-groups"} {
+ names, err := c.list(ctx, dir+"/"+part)
+ if err != nil {
+ return nil, err
+ }
+ bodies := make([][]byte, len(names))
+ errs := make([]error, len(names))
+ sem := make(chan struct{}, 8)
+ var wg sync.WaitGroup
+ for i, n := range names {
+ wg.Add(1)
+ sem <- struct{}{}
+ go func() {
+ defer func() { <-sem; wg.Done() }()
+ bodies[i], errs[i] = c.get(ctx, c.Raw+"/"+c.Ref+"/"+dir+"/"+part+"/"+n)
+ }()
+ }
+ wg.Wait()
+ for i, body := range bodies {
+ if errs[i] != nil {
+ return nil, errs[i]
+ }
+ switch part {
+ case "quality-profiles":
+ var r rawTrashProfile
+ if json.Unmarshal(body, &r) == nil && r.TrashID != "" {
+ d.Profiles = append(d.Profiles, TrashProfile{ID: r.TrashID, App: app, Name: r.Name,
+ Description: trashPlain(r.Description), URL: r.URL, ScoreSet: r.ScoreSet,
+ MinScore: r.MinFormatScore, CutoffScore: r.CutoffScore, MinUpgradeScore: r.MinUpgradeScore,
+ FormatItems: r.FormatItems})
+ }
+ case "cf":
+ var f TrashFormat
+ if json.Unmarshal(body, &f) == nil && f.ID != "" {
+ d.Formats[f.ID] = f
+ }
+ case "cf-groups":
+ var g TrashGroup
+ if json.Unmarshal(body, &g) == nil {
+ d.Groups = append(d.Groups, g)
+ }
+ }
+ }
+ }
+ sort.Slice(d.Profiles, func(i, j int) bool { return d.Profiles[i].Name < d.Profiles[j].Name })
+ sort.Slice(d.Groups, func(i, j int) bool { return d.Groups[i].Name < d.Groups[j].Name })
+ c.mu.Lock()
+ if c.cache == nil {
+ c.cache = map[string]trashCached{}
+ }
+ c.cache[app] = trashCached{time.Now(), d}
+ c.mu.Unlock()
+ return d, nil
+}
+
+func (c *TrashGuides) list(ctx context.Context, path string) ([]string, error) {
+ body, err := c.get(ctx, c.API+"/"+path+"?ref="+c.Ref)
+ if err != nil {
+ return nil, err
+ }
+ var items []struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ }
+ if err := json.Unmarshal(body, &items); err != nil {
+ return nil, fmt.Errorf("TRaSH Guides list %s: %w", path, err)
+ }
+ var out []string
+ for _, it := range items {
+ if it.Type == "file" && strings.HasSuffix(it.Name, ".json") {
+ out = append(out, it.Name)
+ }
+ }
+ return out, nil
+}
+
+func (c *TrashGuides) get(ctx context.Context, url string) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("User-Agent", "HolyArrs")
+ res, err := c.HTTP.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("TRaSH Guides could not be reached: %w", err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("TRaSH Guides answered %s", res.Status)
+ }
+ return io.ReadAll(io.LimitReader(res.Body, 4<<20))
+}
+
+func trashPlain(s string) string {
+ s = strings.ReplaceAll(s, "<br>", " ")
+ return strings.Join(strings.Fields(s), " ")
+}
+
+// Profile finds a profile by id.
+func (d *TrashData) Profile(id string) (TrashProfile, bool) {
+ for _, p := range d.Profiles {
+ if p.ID == id {
+ return p, true
+ }
+ }
+ return TrashProfile{}, false
+}
+
+// TrashPlanned is one format turned into a synced trait with its points.
+type TrashPlanned struct {
+ Trait mediafiles.OwnTrait
+ Points int
+}
+
+// TrashSkipped is a format HolyArrs left out, and why.
+type TrashSkipped struct {
+ Name string `json:"name"`
+ Kinds []string `json:"kinds,omitempty"` // test kinds HolyArrs cannot run yet
+ Reason string `json:"reason"`
+}
+
+// TrashPlan is what applying a profile does.
+type TrashPlan struct {
+ Profile TrashProfile
+ Traits []TrashPlanned
+ Skipped []TrashSkipped
+}
+
+// trashSkippedKinds names the test kinds HolyArrs skips, for the app and docs.
+var trashSkippedKinds = map[string]string{
+ "LanguageSpecification": "language",
+ "IndexerFlagSpecification": "indexer flag",
+ "ReleaseTypeSpecification": "release type",
+ "SizeSpecification": "size",
+ "YearSpecification": "year",
+}
+
+// Sources the old apps number, mapped to HolyArrs sources.
+var (
+ trashSonarrSources = map[int]string{1: "tv", 2: "tv", 3: "web_dl", 4: "web_rip", 5: "dvd", 6: "bluray", 7: "remux,disc_image"}
+ trashRadarrSources = map[int]string{1: "cam", 2: "telesync", 5: "dvd", 6: "tv", 7: "web_dl", 8: "web_rip", 9: "bluray,remux,disc_image"}
+)
+
+// TrashMaxPoints is the Pick rules points bound; TRaSH scores past it are cut.
+const TrashMaxPoints = 10000
+
+// Build plans applying profile p: its own formats plus the required and
+// default formats of the default groups that include it.
+func (d *TrashData) Build(p TrashProfile) TrashPlan {
+ plan := TrashPlan{Profile: p}
+ seen := map[string]bool{}
+ var order []string
+ add := func(id string) {
+ if id != "" && !seen[id] {
+ seen[id] = true
+ order = append(order, id)
+ }
+ }
+ names := make([]string, 0, len(p.FormatItems))
+ for n := range p.FormatItems {
+ names = append(names, n)
+ }
+ sort.Strings(names)
+ for _, n := range names {
+ add(p.FormatItems[n])
+ }
+ for _, g := range d.Groups {
+ if g.Default != "true" {
+ continue
+ }
+ in := false
+ for _, id := range g.Profiles.Include {
+ in = in || id == p.ID
+ }
+ if !in {
+ continue
+ }
+ for _, f := range g.Formats {
+ if f.Required || f.Default {
+ add(f.ID)
+ }
+ }
+ }
+ set := p.ScoreSet
+ if set == "" {
+ set = "default"
+ }
+ for _, id := range order {
+ f, ok := d.Formats[id]
+ if !ok {
+ plan.Skipped = append(plan.Skipped, TrashSkipped{Name: id, Reason: "listed, but its file is missing"})
+ continue
+ }
+ score, ok := f.Scores[set]
+ if !ok {
+ score, ok = f.Scores["default"]
+ }
+ if !ok || score == 0 {
+ continue // no points: it would change nothing
+ }
+ specs, kinds := trashConvert(d.App, f.Specs)
+ if len(kinds) > 0 {
+ plan.Skipped = append(plan.Skipped, TrashSkipped{Name: f.Name, Kinds: kinds, Reason: "it tests something HolyArrs cannot test yet"})
+ continue
+ }
+ score = max(-TrashMaxPoints, min(TrashMaxPoints, score))
+ plan.Traits = append(plan.Traits, TrashPlanned{Points: score, Trait: mediafiles.OwnTrait{
+ Name: f.Name, Match: "name", Source: "trash", SourceID: d.App + ":" + f.ID, Specs: specs, Terms: []string{},
+ }})
+ }
+ return plan
+}
+
+// trashConvert turns a format's tests into synced trait tests; kinds lists the
+// test kinds it could not take (then the whole format is skipped, since a
+// half-tested format would match the wrong Releases).
+func trashConvert(app string, in []TrashSpec) ([]mediafiles.OwnSpec, []string) {
+ var out []mediafiles.OwnSpec
+ bad := map[string]bool{}
+ for _, s := range in {
+ o := mediafiles.OwnSpec{Name: s.Name, Negate: s.Negate, Required: s.Required}
+ var str string
+ var num int
+ if json.Unmarshal(s.Fields.Value, &num) != nil {
+ _ = json.Unmarshal(s.Fields.Value, &str)
+ num, _ = strconv.Atoi(str)
+ }
+ switch s.Implementation {
+ case "ReleaseTitleSpecification", "ReleaseGroupSpecification":
+ o.Kind = "name"
+ if s.Implementation == "ReleaseGroupSpecification" {
+ o.Kind = "group"
+ }
+ if _, err := mediafiles.CompileSpecPattern(str); err != nil || str == "" {
+ bad["unreadable pattern"] = true
+ continue
+ }
+ o.Value = str
+ case "SourceSpecification":
+ m := trashSonarrSources
+ if app == "radarr" {
+ m = trashRadarrSources
+ }
+ v, ok := m[num]
+ if !ok {
+ bad["source"] = true
+ continue
+ }
+ o.Kind, o.Value = "source", v
+ case "ResolutionSpecification":
+ if num <= 0 {
+ bad["resolution"] = true
+ continue
+ }
+ o.Kind, o.Value = "resolution", strconv.Itoa(num)
+ case "QualityModifierSpecification":
+ // Movies: 4 is a full disc, 5 a remux; the rest have no match here.
+ switch num {
+ case 4:
+ o.Kind, o.Value = "source", "disc_image"
+ case 5:
+ o.Kind, o.Value = "source", "remux"
+ default:
+ bad["quality modifier"] = true
+ continue
+ }
+ default:
+ w := trashSkippedKinds[s.Implementation]
+ if w == "" {
+ w = strings.ToLower(strings.TrimSuffix(s.Implementation, "Specification"))
+ }
+ bad[w] = true
+ continue
+ }
+ out = append(out, o)
+ }
+ kinds := make([]string, 0, len(bad))
+ for k := range bad {
+ kinds = append(kinds, k)
+ }
+ sort.Strings(kinds)
+ return out, kinds
+}
diff --git a/app/backend/internal/library/trash_guides_test.go b/app/backend/internal/library/trash_guides_test.go
new file mode 100644
index 0000000..1b791bb
--- /dev/null
+++ b/app/backend/internal/library/trash_guides_test.go
@@ -0,0 +1,58 @@
+package library
+
+import (
+ "context"
+ "testing"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/library/trashtest"
+)
+
+// TestBuild: a profile brings its own formats and its default groups'
+// ones; scores past the Pick rules bound are cut; a format with a test
+// kind HolyArrs cannot run is skipped and named, never half-taken.
+func TestBuild(t *testing.T) {
+ c := NewTrashGuides()
+ c.Raw, c.API = trashtest.Serve(t, trashtest.Files)
+ d, err := c.Load(context.Background(), "sonarr")
+ if err != nil {
+ t.Fatal(err)
+ }
+ p, ok := d.Profile("p1")
+ if !ok || p.Description != "Line one line two" || p.CutoffScore != 10000 {
+ t.Fatalf("profile: %+v %v", p, ok)
+ }
+ plan := d.Build(p)
+ got := map[string]int{}
+ for _, pl := range plan.Traits {
+ got[pl.Trait.Name] = pl.Points
+ if pl.Trait.Source != "trash" || pl.Trait.SourceID == "" || len(pl.Trait.Specs) == 0 {
+ t.Errorf("trait %+v lacks its source or tests", pl.Trait)
+ }
+ }
+ want := map[string]int{"HEVC": -500, "Good group": 1700, "LQ": -10000}
+ if len(got) != len(want) {
+ t.Fatalf("traits %v, want %v", got, want)
+ }
+ for k, v := range want {
+ if got[k] != v {
+ t.Errorf("%s = %d, want %d", k, got[k], v)
+ }
+ }
+ if len(plan.Skipped) != 1 || plan.Skipped[0].Name != "Lang only" || len(plan.Skipped[0].Kinds) != 1 || plan.Skipped[0].Kinds[0] != "language" {
+ t.Fatalf("skipped: %+v", plan.Skipped)
+ }
+ for _, pl := range plan.Traits {
+ if pl.Trait.Name == "Good group" {
+ if s := pl.Trait.Specs[1]; s.Kind != "source" || s.Value != "web_dl" {
+ t.Errorf("source test: %+v", s)
+ }
+ }
+ }
+}
+
+// TestLoadUnknownApp refuses apps other than sonarr and radarr.
+func TestLoadUnknownApp(t *testing.T) {
+ if _, err := NewTrashGuides().Load(context.Background(), "lidarr"); err == nil {
+ t.Fatal("lidarr was accepted")
+ }
+}
diff --git a/app/backend/internal/library/trash_live_test.go b/app/backend/internal/library/trash_live_test.go
new file mode 100644
index 0000000..f70354d
--- /dev/null
+++ b/app/backend/internal/library/trash_live_test.go
@@ -0,0 +1,75 @@
+package library
+
+import (
+ "time"
+
+ "context"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/mediafiles"
+ "os"
+ "testing"
+)
+
+// TestLive reads the real TRaSH Guides; run with HOLYARRS_TRASH_LIVE=1.
+func TestLive(t *testing.T) {
+ if os.Getenv("HOLYARRS_TRASH_LIVE") == "" {
+ t.Skip("set HOLYARRS_TRASH_LIVE=1 to read the real TRaSH Guides")
+ }
+ c := NewTrashGuides()
+ for _, app := range []string{"sonarr", "radarr"} {
+ d, err := c.Load(context.Background(), app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(d.Profiles) == 0 || len(d.Formats) == 0 {
+ t.Fatalf("%s: %d profiles, %d formats", app, len(d.Profiles), len(d.Formats))
+ }
+ for _, p := range d.Profiles {
+ plan := d.Build(p)
+ t.Logf("%s %-32s scored %2d skipped %2d", app, p.Name, len(plan.Traits), len(plan.Skipped))
+ for _, s := range plan.Skipped {
+ if len(s.Kinds) > 0 && s.Kinds[0] == "unreadable pattern" {
+ t.Errorf("%s: %s has a pattern regexp2 cannot read", app, s.Name)
+ }
+ }
+ }
+ }
+}
+
+// TestLiveScores scores real-looking Release names with the real
+// WEB-1080p profile; run with HOLYARRS_TRASH_LIVE=1.
+func TestLiveScores(t *testing.T) {
+ if os.Getenv("HOLYARRS_TRASH_LIVE") == "" {
+ t.Skip("set HOLYARRS_TRASH_LIVE=1 to read the real TRaSH Guides")
+ }
+ d, err := NewTrashGuides().Load(context.Background(), "sonarr")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var prof TrashProfile
+ for _, p := range d.Profiles {
+ if p.Name == "WEB-1080p" {
+ prof = p
+ }
+ }
+ plan := d.Build(prof)
+ var ts []mediafiles.OwnTrait
+ body := mediafiles.GoodEveryday()
+ for i, pl := range plan.Traits {
+ tr := pl.Trait
+ tr.ID = int64(i + 1)
+ ts = append(ts, tr)
+ body.Traits = append(body.Traits, mediafiles.TraitPoints{Trait: mediafiles.OwnTraitKey(tr.ID), Points: pl.Points})
+ }
+ body.Traits = body.Traits[len(mediafiles.GoodEveryday().Traits):]
+ mediafiles.SetOwnTraits(ts)
+ t.Cleanup(func() { mediafiles.SetOwnTraits(nil) })
+ for _, name := range []string{
+ "Arcane.S01E01.1080p.NF.WEB-DL.DDP5.1.H.264-FLUX",
+ "Arcane.S01E01.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb",
+ "Arcane.S01E01.1080p.WEB.H264-HOLYARRS",
+ "Arcane.S01E01.1080p.WEB-DL.x265-YIFY",
+ "Arcane.S01E01.1080p.WEBRip.AV1-LAMA",
+ } {
+ t.Logf("%6d %s", mediafiles.CurrentOf(name, time.Time{}, body).Points, name)
+ }
+}
diff --git a/app/backend/internal/library/trash_test.go b/app/backend/internal/library/trash_test.go
new file mode 100644
index 0000000..8e096af
--- /dev/null
+++ b/app/backend/internal/library/trash_test.go
@@ -0,0 +1,86 @@
+package library
+
+import (
+ "context"
+ "testing"
+
+ domain "github.com/HolyArrs/holyarrs/app/backend/internal/core/model"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/library/trashtest"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/mediafiles"
+)
+
+// TestApplyTrash: applying a profile makes synced traits with its points,
+// keeps the person's own points, and a second sync updates in place.
+func TestApplyTrash(t *testing.T) {
+ st := open(t)
+ ctx := context.Background()
+ t.Cleanup(func() { mediafiles.SetOwnTraits(nil) })
+ c := NewTrashGuides()
+ c.Raw, c.API = trashtest.Serve(t, trashtest.Files)
+
+ mine, err := CreateOwnTrait(ctx, st, OwnTraitInput{Name: "HEVC", Match: "name", Terms: []string{"hevc"}}, domain.System)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := mediafiles.GoodEveryday()
+ body.Traits = append(body.Traits, mediafiles.TraitPoints{Trait: mediafiles.OwnTraitKey(mine.ID), Points: 7})
+ p, err := CreatePickRules(ctx, st, PickRulesInput{Name: "Mine", Kinds: []string{"show"}, Body: body}, domain.System)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := ApplyTrash(ctx, st, c, p.ID, "sonarr", "p1", domain.System)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.Added != 3 || res.Updated != 0 || len(res.Skipped) != 1 {
+ t.Fatalf("first sync: %+v", res)
+ }
+ b := res.PickRules.Body
+ if b.Synced == nil || b.Synced.ProfileID != "p1" || b.MinPoints != 0 || b.GoodEnoughPoints == nil || *b.GoodEnoughPoints != 10000 || b.UpgradeMinPoints != 1 {
+ t.Fatalf("rules: %+v", b)
+ }
+ points := map[string]int{}
+ for _, tp := range b.Traits {
+ points[tp.Trait] = tp.Points
+ }
+ if points[mediafiles.OwnTraitKey(mine.ID)] != 7 {
+ t.Fatal("the person's own points were lost")
+ }
+ ts, _ := OwnTraits(ctx, st)
+ names := map[string]bool{}
+ for _, tr := range ts {
+ names[tr.Name] = true
+ }
+ if !names["HEVC (shows)"] || !names["LQ"] {
+ t.Fatalf("names: %v", names)
+ }
+
+ again, err := ApplyTrash(ctx, st, c, p.ID, "sonarr", "p1", domain.System)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if again.Added != 0 || again.Updated != 3 {
+ t.Fatalf("re-sync: %+v", again)
+ }
+ if ts2, _ := OwnTraits(ctx, st); len(ts2) != len(ts) {
+ t.Fatalf("re-sync made %d traits, had %d", len(ts2), len(ts))
+ }
+ if len(again.PickRules.Body.Traits) != len(b.Traits) {
+ t.Fatalf("re-sync points list %d, was %d", len(again.PickRules.Body.Traits), len(b.Traits))
+ }
+
+ // A synced trait cannot be edited by hand.
+ var synced mediafiles.OwnTrait
+ for _, tr := range ts {
+ if tr.Source == "trash" {
+ synced = tr
+ }
+ }
+ if _, err := UpdateOwnTrait(ctx, st, synced.ID, OwnTraitInput{Name: "X", Match: "name", Terms: []string{"x"}}, domain.System); err == nil {
+ t.Fatal("a synced trait was edited")
+ }
+ if _, err := ApplyTrash(ctx, st, c, p.ID, "sonarr", "nope", domain.System); err != ErrTrashProfile {
+ t.Fatalf("unknown profile: %v", err)
+ }
+}
diff --git a/app/backend/internal/library/trashtest/trashtest.go b/app/backend/internal/library/trashtest/trashtest.go
new file mode 100644
index 0000000..73d7d28
--- /dev/null
+++ b/app/backend/internal/library/trashtest/trashtest.go
@@ -0,0 +1,59 @@
+// Package trashtest serves a small made-up TRaSH Guides tree for tests.
+package trashtest
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path"
+ "strings"
+ "testing"
+)
+
+// Files is the made-up sonarr tree: one profile, three formats (a name
+// test, a group-and-source test, and one with a language test HolyArrs
+// skips) and one default group adding a fourth.
+var Files = map[string]string{
+ "docs/json/sonarr/quality-profiles/test-1080p.json": `{"trash_id":"p1","name":"Test 1080p","trash_description":"Line one<br>line two",
+ "minFormatScore":0,"cutoffFormatScore":10000,"minUpgradeFormatScore":1,
+ "formatItems":{"HEVC":"f1","Good group":"f2","Lang only":"f3"}}`,
+ "docs/json/sonarr/cf/hevc.json": `{"trash_id":"f1","name":"HEVC","trash_scores":{"default":-500},
+ "specifications":[{"name":"x265","implementation":"ReleaseTitleSpecification","negate":false,"required":true,"fields":{"value":"[xh][ ._-]?265|\\bHEVC\\b"}}]}`,
+ "docs/json/sonarr/cf/good-group.json": `{"trash_id":"f2","name":"Good group","trash_scores":{"default":1700},
+ "specifications":[{"name":"Group","implementation":"ReleaseGroupSpecification","negate":false,"required":false,"fields":{"value":"^(GOODA)$"}},
+ {"name":"WEB","implementation":"SourceSpecification","negate":false,"required":false,"fields":{"value":3}}]}`,
+ "docs/json/sonarr/cf/lang.json": `{"trash_id":"f3","name":"Lang only","trash_scores":{"default":-10000},
+ "specifications":[{"name":"Not English","implementation":"LanguageSpecification","negate":true,"required":false,"fields":{"value":1}}]}`,
+ "docs/json/sonarr/cf/lq.json": `{"trash_id":"f4","name":"LQ","trash_scores":{"default":-20000},
+ "specifications":[{"name":"LQ","implementation":"ReleaseGroupSpecification","negate":false,"required":false,"fields":{"value":"^(BADGRP)$"}}]}`,
+ "docs/json/sonarr/cf-groups/unwanted.json": `{"name":"Unwanted","default":"true",
+ "custom_formats":[{"name":"LQ","trash_id":"f4","required":false,"default":true}],
+ "quality_profiles":{"include":{"Test 1080p":"p1"}}}`,
+ "docs/json/radarr/quality-profiles/none.json": `{"trash_id":"m1","name":"Movie test","formatItems":{}}`,
+}
+
+// Serve starts a server for files and answers the raw-files and listing
+// bases to point a TRaSH Guides reader at.
+func Serve(t testing.TB, files map[string]string) (raw, api string) {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ p := r.URL.Path
+ if dir, ok := strings.CutPrefix(p, "/api/"); ok {
+ var items []map[string]string
+ for f := range files {
+ if path.Dir(f) == dir {
+ items = append(items, map[string]string{"name": path.Base(f), "type": "file"})
+ }
+ }
+ _ = json.NewEncoder(w).Encode(items)
+ return
+ }
+ if body, ok := files[strings.TrimPrefix(p, "/raw/master/")]; ok {
+ _, _ = w.Write([]byte(body))
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ return srv.URL + "/raw", srv.URL + "/api"
+}
diff --git a/app/backend/internal/mediafiles/judge_own_formats.go b/app/backend/internal/mediafiles/judge_own_formats.go
new file mode 100644
index 0000000..b14d295
--- /dev/null
+++ b/app/backend/internal/mediafiles/judge_own_formats.go
@@ -0,0 +1,112 @@
+package mediafiles
+
+import (
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/dlclark/regexp2"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/core/releasename"
+)
+
+// Synced traits (TRaSH Guides) carry patterns written for the old apps'
+// .NET engine, with look-arounds Go's own engine lacks, so they run on
+// regexp2 with a time limit per test.
+
+type ownSpec struct {
+ OwnSpec
+ re *regexp2.Regexp
+ sources []string
+ res int
+}
+
+const specTimeout = 50 * time.Millisecond
+
+// CompileSpecPattern reads a synced pattern the way the old apps do
+// (ignoring case).
+func CompileSpecPattern(p string) (*regexp2.Regexp, error) {
+ re, err := regexp2.Compile(p, regexp2.IgnoreCase)
+ if err != nil {
+ return nil, err
+ }
+ re.MatchTimeout = specTimeout
+ return re, nil
+}
+
+// compileSpecs prepares a synced trait's tests; ok is false when one
+// cannot be read, and the trait then never matches.
+func compileSpecs(specs []OwnSpec) ([]ownSpec, bool) {
+ out := make([]ownSpec, 0, len(specs))
+ for _, s := range specs {
+ o := ownSpec{OwnSpec: s}
+ switch s.Kind {
+ case "name", "group":
+ re, err := CompileSpecPattern(s.Value)
+ if err != nil {
+ return nil, false
+ }
+ o.re = re
+ case "source":
+ o.sources = strings.Split(s.Value, ",")
+ case "resolution":
+ n, err := strconv.Atoi(s.Value)
+ if err != nil {
+ return nil, false
+ }
+ o.res = n
+ default:
+ return nil, false
+ }
+ out = append(out, o)
+ }
+ return out, len(out) > 0
+}
+
+func (s ownSpec) test(p releasename.Result) bool {
+ var hit bool
+ switch s.Kind {
+ case "name":
+ hit, _ = s.re.MatchString(p.Original)
+ case "group":
+ hit = p.Group.Value != ""
+ if hit {
+ hit, _ = s.re.MatchString(p.Group.Value)
+ }
+ case "source":
+ hit = p.Source.Conf != releasename.Unknown && slices.Contains(s.sources, p.Source.Value)
+ case "resolution":
+ hit = p.Resolution.Conf != releasename.Unknown && p.Resolution.Value == s.res
+ }
+ return hit != s.Negate
+}
+
+// formatMatches runs a synced trait's tests: per kind, every required
+// test passes and at least one of the others (if any).
+func formatMatches(name string, specs []ownSpec, p releasename.Result) (bool, string) {
+ type kindState struct{ optional, optionalHit bool }
+ kinds := map[string]*kindState{}
+ for _, s := range specs {
+ k := kinds[s.Kind]
+ if k == nil {
+ k = &kindState{}
+ kinds[s.Kind] = k
+ }
+ ok := s.test(p)
+ if s.Required {
+ if !ok {
+ return false, name + ": " + s.Name + " does not fit"
+ }
+ continue
+ }
+ k.optional = true
+ k.optionalHit = k.optionalHit || ok
+ }
+ for kind, k := range kinds {
+ if k.optional && !k.optionalHit {
+ return false, name + ": no " + kind + " test fits"
+ }
+ }
+ return true, name + ": fits"
+}
diff --git a/app/backend/internal/mediafiles/judge_own_formats_test.go b/app/backend/internal/mediafiles/judge_own_formats_test.go
new file mode 100644
index 0000000..9ba8333
--- /dev/null
+++ b/app/backend/internal/mediafiles/judge_own_formats_test.go
@@ -0,0 +1,53 @@
+package mediafiles
+
+import (
+ "testing"
+
+ "github.com/HolyArrs/holyarrs/app/backend/internal/core/database"
+ "github.com/HolyArrs/holyarrs/app/backend/internal/core/releasename"
+)
+
+// TestSyncedTraitTests: per kind, required tests must all pass and one of
+// the others must; negate turns a test around; look-behind patterns work.
+func TestSyncedTraitTests(t *testing.T) {
+ t.Cleanup(func() { SetOwnTraits(nil) })
+ SetOwnTraits([]OwnTrait{
+ {Meta: database.Meta{ID: 1}, Name: "HEVC not 4K", Match: "name", Specs: []OwnSpec{
+ {Name: "x265", Kind: "name", Value: `[xh][ ._-]?265|\bHEVC\b`, Required: true},
+ {Name: "Not 2160p", Kind: "resolution", Value: "2160", Negate: true, Required: true},
+ }},
+ {Meta: database.Meta{ID: 2}, Name: "Web", Match: "name", Specs: []OwnSpec{
+ {Name: "WEB-DL", Kind: "source", Value: "web_dl"},
+ {Name: "WEBRip", Kind: "source", Value: "web_rip"},
+ }},
+ {Meta: database.Meta{ID: 3}, Name: "Group", Match: "name", Specs: []OwnSpec{
+ {Name: "Good", Kind: "group", Value: `^(GOODA|GOODB)$`},
+ }},
+ {Meta: database.Meta{ID: 4}, Name: "Lookbehind", Match: "name", Specs: []OwnSpec{
+ {Name: "DV not HDR10", Kind: "name", Value: `(?<!HDR10[ ._-])\bDV\b`},
+ }},
+ {Meta: database.Meta{ID: 5}, Name: "Broken", Match: "name", Specs: []OwnSpec{{Name: "bad", Kind: "name", Value: `(`}}},
+ })
+ cases := []struct {
+ id int64
+ name string
+ want bool
+ }{
+ {1, "Show.S01E01.1080p.WEB-DL.x265-GOODA", true},
+ {1, "Show.S01E01.2160p.WEB-DL.x265-GOODA", false},
+ {1, "Show.S01E01.1080p.WEB-DL.H264-GOODA", false},
+ {2, "Show.S01E01.1080p.WEBRip.H264-GOODA", true},
+ {2, "Show.S01E01.1080p.BluRay.H264-GOODA", false},
+ {3, "Show.S01E01.1080p.BluRay.H264-GOODB", true},
+ {3, "Show.S01E01.1080p.BluRay.H264-OTHER", false},
+ {4, "Movie.2024.2160p.WEB-DL.DV.H265-GOODA", true},
+ {4, "Movie.2024.2160p.WEB-DL.HDR10.DV.H265-GOODA", false},
+ {5, "Movie.2024.2160p.WEB-DL.H265-GOODA", false},
+ }
+ for _, c := range cases {
+ got, why := ownMatches(c.id, releasename.Parse(c.name, releasename.Hints{}))
+ if got != c.want {
+ t.Errorf("trait %d on %s = %v (%s), want %v", c.id, c.name, got, why, c.want)
+ }
+ }
+}
diff --git a/app/backend/internal/mediafiles/judge_own_traits.go b/app/backend/internal/mediafiles/judge_own_traits.go
index 04911c2..33c7c9d 100644
--- a/app/backend/internal/mediafiles/judge_own_traits.go
+++ b/app/backend/internal/mediafiles/judge_own_traits.go
@@ -18,6 +18,10 @@ type ownTrait struct {
group bool
plain []string // lowercased words
pats []*regexp.Regexp
+ // specs is set for a synced trait (and then decides alone); bad says a
+ // synced trait had a test that could not be read.
+ specs []ownSpec
+ bad bool
}
var ownTraits atomic.Pointer[map[int64]ownTrait]
@@ -28,6 +32,12 @@ func SetOwnTraits(ts []OwnTrait) {
m := make(map[int64]ownTrait, len(ts))
for _, t := range ts {
o := ownTrait{name: t.Name, group: t.Match == "group"}
+ if len(t.Specs) > 0 {
+ o.specs, o.bad = compileSpecs(t.Specs)
+ o.bad = !o.bad
+ m[t.ID] = o
+ continue
+ }
for _, term := range t.Terms {
if p, ok := TermPattern(term); ok {
if re, err := regexp.Compile("(?i)" + p); err == nil {
@@ -56,6 +66,12 @@ func ownMatches(id int64, p releasename.Result) (bool, string) {
if !ok {
return false, "a trait that was deleted"
}
+ if t.bad {
+ return false, t.name + ": a test could not be read"
+ }
+ if t.specs != nil {
+ return formatMatches(t.name, t.specs, p)
+ }
if t.group {
g := p.Group.Value
if g == "" {
diff --git a/app/backend/internal/mediafiles/own_traits.go b/app/backend/internal/mediafiles/own_traits.go
index 0262a8a..2f44b7a 100644
--- a/app/backend/internal/mediafiles/own_traits.go
+++ b/app/backend/internal/mediafiles/own_traits.go
@@ -20,6 +20,25 @@ type OwnTrait struct {
Name string `db:"name"`
Match string `db:"match"` // name, group
Terms []string `db:"terms,json"`
+ // Source and SourceID say where a synced trait came from ("trash",
+ // "sonarr:<trash id>"); empty for a trait a person made. A synced
+ // trait tests Specs instead of Terms.
+ Source string `db:"source"`
+ SourceID string `db:"source_id"`
+ Specs []OwnSpec `db:"specs,json"`
+}
+
+// OwnSpec is one test of a synced trait. Kind is name or group (a
+// pattern), source (one of the HolyArrs sources, comma-separated) or
+// resolution (a number). Tests of one kind pass when every Required one
+// passes and, if there are others, at least one of those does; the trait
+// matches when every kind passes. Negate turns a test's answer around.
+type OwnSpec struct {
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Value string `json:"value"`
+ Negate bool `json:"negate,omitempty"`
+ Required bool `json:"required,omitempty"`
}
// OwnTraitPrefix starts the key of an own trait in Pick rules.
diff --git a/app/backend/internal/mediafiles/pick_rules.go b/app/backend/internal/mediafiles/pick_rules.go
index 5db0a9d..79d519e 100644
--- a/app/backend/internal/mediafiles/pick_rules.go
+++ b/app/backend/internal/mediafiles/pick_rules.go
@@ -63,6 +63,17 @@ type PickRulesBody struct {
Order string `json:"order"` // quality_then_points, points_then_quality
UpgradeMinPoints int `json:"upgrade_min_points"`
ProperPolicy ProperPolicy `json:"proper_policy"`
+ // Synced names the TRaSH Guides profile last applied, for re-syncing.
+ Synced *SyncedProfile `json:"synced,omitempty"`
+}
+
+// SyncedProfile is a TRaSH Guides profile applied to Pick rules.
+type SyncedProfile struct {
+ From string `json:"from"` // trash
+ App string `json:"app"` // sonarr or radarr
+ ProfileID string `json:"profile_id"`
+ Name string `json:"name"`
+ At string `json:"at"`
}
// GoodEverydayName is the default preset's name.
diff --git a/app/backend/internal/mediafiles/testdata/pin_catalog_layouts.golden.txt b/app/backend/internal/mediafiles/testdata/pin_catalog_layouts.golden.txt
index 4945c12..869afca 100644
--- a/app/backend/internal/mediafiles/testdata/pin_catalog_layouts.golden.txt
+++ b/app/backend/internal/mediafiles/testdata/pin_catalog_layouts.golden.txt
@@ -202,8 +202,12 @@ Language LanguageRule `json:"language"`
Order string `json:"order"`
UpgradeMinPoints int `json:"upgrade_min_points"`
ProperPolicy ProperPolicy `json:"proper_policy"`
+Synced *SyncedProfile `json:"synced,omitempty"`
== OwnTrait
Meta Meta ``
Name string `db:"name"`
Match string `db:"match"`
Terms []string `db:"terms,json"`
+Source string `db:"source"`
+SourceID string `db:"source_id"`
+Specs []OwnSpec `db:"specs,json"`
diff --git a/app/backend/tools/structurecheck/testdata/baseline-migrations.txt b/app/backend/tools/structurecheck/testdata/baseline-migrations.txt
index fbb37b6..9bc6432 100644
--- a/app/backend/tools/structurecheck/testdata/baseline-migrations.txt
+++ b/app/backend/tools/structurecheck/testdata/baseline-migrations.txt
@@ -95,3 +95,4 @@ main 0093_save_space_best_presets.sql f9de965106eefec2f7a200e5260f4d52435d0098d0
main 0094_rename_lite_standard.sql 7163e4cc1bf0559b63da2c5bc69591622b11debbce05478b7dc501c6fb4fc665
main 0095_move_credentials_all_apps.sql 8f260f0257a530fb505d16bf62d2e23ee2e0b4a3dbaa6fcee066063e908d21e2
main 0096_first_run_done_existing.sql aa342047b49b9a88d8fe9d38ae845c7704fa0a7f784e31c6895c931bd3240f9b
+main 0097_own_trait_formats.sql cac39ed4cf83a0859d870e4157cfad6d2d17a7c7674a51d490b165d5fbe3c60d
diff --git a/app/backend/tools/structurecheck/testdata/json-keys.txt b/app/backend/tools/structurecheck/testdata/json-keys.txt
index 28e11b7..6eaa2be 100644
--- a/app/backend/tools/structurecheck/testdata/json-keys.txt
+++ b/app/backend/tools/structurecheck/testdata/json-keys.txt
@@ -358,6 +358,7 @@ cursor
custom_formats
cut
cutoff
+cutoffFormatScore
cutoff_score
cw
d
@@ -538,6 +539,7 @@ feed
feed_check_minutes
fell_back
fetched_at
+fields
file
file_id
file_ids
@@ -579,6 +581,7 @@ forced
foreign_parts_only
forgotten
format
+formatItems
formats
forward
found
@@ -691,6 +694,7 @@ images
imdb
imdbId
imdb_id
+implementation
import_lists
import_min_track_kb
import_min_video_mb
@@ -701,6 +705,7 @@ in_library
in_use
inactive_minutes
inactive_seeding_time_limit
+include
included
incomplete
index
@@ -872,6 +877,8 @@ migrates
migration
mimeType
min
+minFormatScore
+minUpgradeFormatScore
min_free_mb
min_from
min_password_length
@@ -956,6 +963,7 @@ needs_input
needs_key
needs_password
needs_reentry
+negate
neighbor_region
network
networks
@@ -1290,6 +1298,7 @@ report_id
requested_by
requests
require_two_factor_admins
+required
reset_time_utc
resolution
resource
@@ -1341,6 +1350,7 @@ scope
scopes
score
score_parts
+scored
scores
searchForMissingEpisodes
searchForMovie
@@ -1479,6 +1489,8 @@ sources
spec
special
specials_folder
+specifications
+specs
speed
speed_limit
speedlimit_abs
@@ -1535,6 +1547,7 @@ sync_every_hours
sync_from_fps
sync_step_ms
sync_to_fps
+synced
t
t24
t64
@@ -1644,6 +1657,11 @@ traits
trakt
translations
transmission
+trash_description
+trash_id
+trash_score_set
+trash_scores
+trash_url
tries
trigger
trimmed
diff --git a/app/backend/tools/structurecheck/testdata/route-table.txt b/app/backend/tools/structurecheck/testdata/route-table.txt
index 4794647..632e259 100644
--- a/app/backend/tools/structurecheck/testdata/route-table.txt
+++ b/app/backend/tools/structurecheck/testdata/route-table.txt
@@ -228,6 +228,7 @@ GET /api/v1/trailer/batch auth=signed_in scope=read assurance=false part=media
GET /api/v1/trailer/stream/{id}/manifest.m3u8 auth=signed_in scope=read assurance=false part=media
GET /api/v1/trailer/stream/{id}/seg/{n} auth=signed_in scope=read assurance=false part=media
GET /api/v1/trailer/{kind}/{tmdb_id} auth=signed_in scope=read assurance=false part=media
+GET /api/v1/trash/profiles auth=settings scope=admin assurance=false part=media
GET /api/v1/turned-down auth=manage_library scope=read assurance=false part=media
GET /api/v1/users auth=users scope=admin assurance=false part=core
GET /api/v1/users/invites auth=users scope=admin assurance=false part=core
@@ -397,6 +398,7 @@ POST /api/v1/parts/{part}/on auth=users scope=control assurance=false part=core
POST /api/v1/parts/{part}/restart auth=users scope=control assurance=false part=core
POST /api/v1/people/{id}/movies/review auth=signed_in scope=read assurance=false part=movies
POST /api/v1/pick-rules auth=settings scope=write assurance=false part=media
+POST /api/v1/pick-rules/{id}/trash auth=settings scope=write assurance=false part=media
POST /api/v1/releases/{id}/choose auth=manage_library scope=write assurance=false part=media
POST /api/v1/releases/{id}/turn-down auth=manage_library scope=write assurance=false part=media
POST /api/v1/rename auth=manage_library scope=write assurance=false part=media
diff --git a/app/frontend/src/lib/core/session.svelte.ts b/app/frontend/src/lib/core/session.svelte.ts
index 4a92439..a57ec18 100644
--- a/app/frontend/src/lib/core/session.svelte.ts
+++ b/app/frontend/src/lib/core/session.svelte.ts
@@ -52,6 +52,7 @@ interface AuthState {
safe_mode?: boolean;
min_password_length?: number;
config_unmapped?: boolean;
+ host_refused?: string;
}
// One session store per client; the default one is exported below.
export function createSession(client: Client = defaultClient) {
@@ -78,6 +79,7 @@ export function createSession(client: Client = defaultClient) {
safeMode: boolean;
held: string[];
configUnmapped: boolean;
+ hostRefused: string;
minPassword: number;
}>({
state: 'unknown',
@@ -100,6 +102,7 @@ export function createSession(client: Client = defaultClient) {
safeMode: false,
held: [],
configUnmapped: false,
+ hostRefused: '',
minPassword: 8
});
@@ -111,6 +114,7 @@ export function createSession(client: Client = defaultClient) {
s.setupWays = st.setup_ways?.length ? st.setup_ways : ['password'];
if (st.safe_mode !== undefined) s.safeMode = !!st.safe_mode;
s.configUnmapped = !!st.config_unmapped;
+ s.hostRefused = st.host_refused ?? '';
}
// Failure keeps the last value; the server checks the length again.
diff --git a/app/frontend/src/lib/downloads/OwnTraits.svelte b/app/frontend/src/lib/downloads/OwnTraits.svelte
index 12b63c1..1a2ba6d 100644
--- a/app/frontend/src/lib/downloads/OwnTraits.svelte
+++ b/app/frontend/src/lib/downloads/OwnTraits.svelte
@@ -38,6 +38,11 @@
{ value: 'name', label: 'Words in the name' },
{ value: 'group', label: 'Release group' }
];
+ // Traits synced from TRaSH Guides sit apart: there can be dozens, and only a sync changes them.
+ const handMade = $derived((list ?? []).filter((t) => !t.source));
+ const synced = $derived((list ?? []).filter((t) => t.source === 'trash'));
+ const specWord = { name: 'name', group: 'group', source: 'source', resolution: 'resolution' } as const;
+ const specSummary = (t: OwnTrait) => (t.specs ?? []).map((s) => `${s.negate ? 'not ' : ''}${s.name} (${specWord[s.kind] ?? s.kind})`).join(', ');
const summary = (t: OwnTrait) => `${t.match === 'group' ? 'Release group' : 'Name has'}: ${t.terms.join(', ')}`;
// The sheet that makes or changes one trait.
@@ -121,11 +126,11 @@
<LoadError hasData={false} message={error} onretry={load} busy={loading} />
{:else if list}
{#if error}<LoadError hasData message={error} onretry={load} busy={loading} />{/if}
- {#if list.length === 0}
+ {#if handMade.length === 0}
<EmptyState compact icon="star" title="No traits of your own" text="Make one for a word like a subtitle language, or for release groups you like or avoid." action={mayEdit ? { label: 'Make a trait', icon: 'plus', onclick: () => openSheet(null) } : undefined} />
{:else}
<ul class="rows" data-testid="own-traits">
- {#each list as t (t.id)}
+ {#each handMade as t (t.id)}
<li data-testid="own-trait">
<span class="grow">
<b>{t.name}</b>
@@ -140,6 +145,25 @@
</ul>
{#if mayEdit}<div><Button icon="plus" onclick={() => openSheet(null)} data-testid="own-trait-add">Make a trait</Button></div>{/if}
{/if}
+ {#if synced.length}
+ <details class="synced" data-testid="synced-traits">
+ <summary>From TRaSH Guides ({synced.length})</summary>
+ <p class="xs muted">Sync a set of Pick rules again to update these</p>
+ <ul class="rows">
+ {#each synced as t (t.id)}
+ <li data-testid="synced-trait">
+ <span class="grow">
+ <b>{t.name}</b>
+ <span class="xs muted meta">{specSummary(t)}</span>
+ </span>
+ {#if mayEdit}<span class="acts">
+ <Menu label="More for {t.name}" items={[{ label: 'Remove', icon: 'trash', destructive: true, onselect: () => ((removing = t), (removeError = ''), (removeOpen = true)) }]} />
+ </span>{/if}
+ </li>
+ {/each}
+ </ul>
+ </details>
+ {/if}
{/if}
</SettingsCard>
@@ -177,6 +201,8 @@
<style>
.form { display: flex; flex-direction: column; gap: 16px; }
+ .synced > summary { cursor: pointer; font-weight: 600; padding: 4px 0; }
+ .synced > p { margin: 4px 0 8px; }
.meta { display: block; overflow-wrap: anywhere; }
.acts { display: flex; align-items: center; gap: 4px; flex: none; }
@media (max-width: 520px) {
diff --git a/app/frontend/src/lib/downloads/types.ts b/app/frontend/src/lib/downloads/types.ts
index 28a05d3..a49198d 100644
--- a/app/frontend/src/lib/downloads/types.ts
+++ b/app/frontend/src/lib/downloads/types.ts
@@ -33,6 +33,8 @@ export interface PickRulesBody {
order: 'quality_then_points' | 'points_then_quality';
upgrade_min_points: number;
proper_policy: { mode: 'take_any' | 'same_group_only' | 'prefer_only' | 'ignore'; max_age_days?: number };
+ /** Set when a TRaSH Guides profile was applied. */
+ synced?: SyncedProfile;
}
/** One of your own traits: a test on the Release name or release group, named by key in Pick rules (own:<id>). */
@@ -43,6 +45,48 @@ export interface OwnTrait {
match: 'name' | 'group';
/** Plain words (any case) or /pattern/. */
terms: string[];
+ /** "trash" for a trait synced from TRaSH Guides: it tests specs and is changed only by syncing again. */
+ source?: string;
+ specs?: OwnSpec[];
+}
+
+/** One test of a synced trait. */
+export interface OwnSpec {
+ name: string;
+ kind: 'name' | 'group' | 'source' | 'resolution';
+ value: string;
+ negate?: boolean;
+ required?: boolean;
+}
+
+/** The TRaSH Guides profile last applied to a set of Pick rules. */
+export interface SyncedProfile {
+ from: 'trash';
+ app: 'sonarr' | 'radarr';
+ profile_id: string;
+ name: string;
+ at: string;
+}
+
+/** A TRaSH Guides profile to pick from. */
+export interface TrashProfile {
+ id: string;
+ app: 'sonarr' | 'radarr';
+ name: string;
+ description: string;
+ url: string;
+ min_points: number;
+ good_enough_points: number;
+ upgrade_min_points: number;
+}
+
+/** What applying a TRaSH Guides profile did. */
+export interface TrashResult {
+ pick_rules: PickRulesDetail;
+ added: number;
+ updated: number;
+ scored: { key: string; name: string; points: number }[];
+ skipped: { name: string; kinds?: string[]; reason: string }[];
}
/** Counts what uses one set of Pick rules. */
diff --git a/app/frontend/src/routes/+layout.svelte b/app/frontend/src/routes/+layout.svelte
index 606a662..0f65b1c 100644
--- a/app/frontend/src/routes/+layout.svelte
+++ b/app/frontend/src/routes/+layout.svelte
@@ -473,6 +473,12 @@
and schedules are off until HolyArrs starts again without safe mode.
</div>
{/if}
+{#if session.s.hostRefused}
+ <div class="safe-banner" role="status" data-testid="host-refused">
+ <b>Changes can't be saved on {session.s.hostRefused}.</b> HolyArrs only saves on names you allow. Open it once by its IP address,
+ then add {session.s.hostRefused} under Settings › Sign-in › Allowed host names. No restart needed.
+ </div>
+{/if}
{#if bare}
{@render children()}
{:else if !ready}
diff --git a/app/frontend/src/routes/settings/pick-rules/[id]/+page.svelte b/app/frontend/src/routes/settings/pick-rules/[id]/+page.svelte
index 0c49abb..88e555e 100644
--- a/app/frontend/src/routes/settings/pick-rules/[id]/+page.svelte
+++ b/app/frontend/src/routes/settings/pick-rules/[id]/+page.svelte
@@ -11,7 +11,7 @@
import EmptyState from '#lib/ui/EmptyState.svelte';
import LoadError from '#lib/ui/LoadError.svelte';
import { applySize, blankBody, checkBody, copyName, fieldKey, isMusic, isOwnTrait, kindChoices, languages, neverChoices, orderChoices, preferChoices, properChoices, sizeFields, stepLabel, tidyBody, toggleKind, traitLabel, traitsFor, usedWords, type RulesKind, type SizeFields } from '#lib/downloads/index.ts';
- import type { OwnTrait, PickRulesBody, PickRulesDetail, PickRulesUse } from '#lib/downloads/index.ts';
+ import type { OwnTrait, PickRulesBody, PickRulesDetail, PickRulesUse, TrashProfile, TrashResult } from '#lib/downloads/index.ts';
import { tick, untrack } from 'svelte';
import { page } from '$app/state';
import { goto } from '$app/navigation';
@@ -147,6 +147,54 @@
document.getElementById(`trait-${i}`)?.focus();
}
+ // TRaSH Guides: pick a profile, apply it; its scores become synced traits with points here.
+ let trashApp = $state<'sonarr' | 'radarr'>('sonarr');
+ let trashProfiles = $state<TrashProfile[] | null>(null);
+ let trashPick = $state('');
+ let trashBusy = $state(false);
+ let trashLoading = $state(false);
+ let trashError = $state('');
+ let trashResult = $state<TrashResult | null>(null);
+ const trashChoice = $derived(trashProfiles?.find((p) => p.id === trashPick));
+ const trashApps = [
+ { value: 'sonarr' as const, label: 'Shows' },
+ { value: 'radarr' as const, label: 'Movies' }
+ ];
+
+ async function loadTrash() {
+ trashLoading = true;
+ trashError = '';
+ try {
+ const app = trashApp;
+ const list = (await api.get<{ profiles: TrashProfile[] }>(`/trash/profiles?app=${app}`)).profiles;
+ if (app !== trashApp) return;
+ trashProfiles = list;
+ const synced = form.body.synced;
+ trashPick = synced && synced.app === app && list.some((p) => p.id === synced.profile_id) ? synced.profile_id : (list[0]?.id ?? '');
+ } catch (e) {
+ trashError = message(e);
+ } finally {
+ trashLoading = false;
+ }
+ }
+
+ async function applyTrash(app: 'sonarr' | 'radarr', profileId: string) {
+ if (id === null) return;
+ trashBusy = true;
+ trashError = '';
+ try {
+ const r = await api.post<TrashResult>(`/pick-rules/${id}/trash`, { app, profile_id: profileId });
+ mine = (await api.get<{ own_traits: OwnTrait[] }>('/own-traits')).own_traits;
+ show(r.pick_rules);
+ trashResult = r;
+ toasts.push(`${r.pick_rules.body.synced?.name ?? 'Profile'} applied`, 'ok', { body: `${r.scored.length} traits scored` });
+ } catch (e) {
+ trashError = message(e);
+ } finally {
+ trashBusy = false;
+ }
+ }
+
function addTo(list: 'must_have' | 'never', trait: string) {
if (trait && !form.body[list].includes(trait)) form.body[list] = [...form.body[list], trait];
}
@@ -352,6 +400,56 @@
{/snippet}
</SettingsCard>
+ {#if !music && id !== null}
+ <SettingsCard id="rules-trash" title="TRaSH Guides" description="Use a TRaSH profile's scores as points">
+ {#if form.body.synced}
+ <div class="synced-row" data-testid="trash-synced">
+ <span class="grow">
+ <b>{form.body.synced.name}</b>
+ <span class="xs muted">{form.body.synced.app === 'radarr' ? 'Movies' : 'Shows'} · synced {new Date(form.body.synced.at).toLocaleString()}</span>
+ </span>
+ {#if mayEdit}<Button icon="refresh" busy={trashBusy} disabled={dirty} onclick={() => form.body.synced && applyTrash(form.body.synced.app, form.body.synced.profile_id)} data-testid="trash-resync">Sync again</Button>{/if}
+ </div>
+ {/if}
+ {#if mayEdit}
+ <div class="field">
+ <span class="label" id="trash-app-label">Profiles for</span>
+ <SegmentedControl options={trashApps} bind:value={trashApp} label="Profiles for" testid="trash-app" onchange={() => ((trashProfiles = null), void loadTrash())} />
+ </div>
+ {#if trashProfiles === null}
+ <div><Button busy={trashLoading} onclick={loadTrash} data-testid="trash-load">Show TRaSH profiles</Button></div>
+ {:else if trashProfiles.length === 0}
+ <p class="hint">TRaSH Guides lists no profiles here</p>
+ {:else}
+ <Field id="trash-profile" label="Profile" hint={trashChoice?.description}>
+ <select id="trash-profile" class="input" bind:value={trashPick} data-testid="trash-profile">
+ {#each trashProfiles as p (p.id)}<option value={p.id}>{p.name}</option>{/each}
+ </select>
+ </Field>
+ <p class="hint">Replaces points from an earlier sync, and sets fewest points, good enough points and upgrade points to the profile's. Your own points stay.</p>
+ <div><Button variant="primary" busy={trashBusy} disabled={dirty || !trashPick} onclick={() => applyTrash(trashApp, trashPick)} data-testid="trash-apply">Apply profile</Button></div>
+ {#if dirty}<p class="hint">Save or undo your changes first</p>{/if}
+ {/if}
+ {/if}
+ {#if trashError}<p class="form-error" role="alert">{trashError}</p>{/if}
+ {#if trashResult}
+ <div class="trash-result" data-testid="trash-result">
+ <p class="small">{trashResult.scored.length} traits scored · {trashResult.added} new · {trashResult.updated} updated</p>
+ {#if trashResult.skipped.length}
+ <details>
+ <summary class="small">{trashResult.skipped.length} left out</summary>
+ <ul class="skipped" data-testid="trash-skipped">
+ {#each trashResult.skipped as s (s.name)}
+ <li class="xs"><b>{s.name}</b> <span class="muted">{s.kinds?.length ? `tests ${s.kinds.join(', ')}` : s.reason}</span></li>
+ {/each}
+ </ul>
+ </details>
+ {/if}
+ </div>
+ {/if}
+ </SettingsCard>
+ {/if}
+
<SettingsCard id="rules-must-never" title="Must have and Never">
<div class="field">
<span class="label" id="must-label">Must have</span>
@@ -435,6 +533,9 @@
<style>
/* The fieldset only turns the form read only; it adds no box of its own. */
.all { display: contents; border: 0; padding: 0; margin: 0; }
+ .synced-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
+ .synced-row .grow { display: flex; flex-direction: column; min-width: 0; flex: 1; }
+ .skipped { margin: 8px 0 0; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; }
.loading { display: flex; flex-direction: column; gap: 16px; }
.ro { font: var(--t-body); }
.hint a { color: var(--accent-text); font-weight: 600; }
diff --git a/docs/README.md b/docs/README.md
index 28d0c28..62d5285 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -26,7 +26,7 @@ Writing code for HolyArrs? Go to [For developers](#for-developers).
| Subtitles | [Subtitles](library/subtitles.md) |
| Files and folders | [Library folders](library/folders.md), [codecs and media inspection](library/codecs-inspection.md), [audio versions](library/audio-versions.md), [protected copies](library/protected-copies.md) |
| Media servers | [Plex, Jellyfin and Emby](library/media-servers.md) |
-| Metadata | [Metadata and privacy](library/metadata.md), [trailers](library/trailers.md), [data packs](library/data-packs.md) |
+| Metadata | [Metadata and privacy](library/metadata.md), [trailers](library/trailers.md), [data packs](library/data-packs.md), [TRaSH Guides scores](library/trash-guides.md) |
| Accounts | [Sign-in and passwords](users/sign-in.md), [users and roles](users/roles.md), [kid accounts](users/kids.md), [signed-in devices](users/sessions.md) |
| Alerts | [Alerts](users/alerts.md) |
| Moving from other apps | [Move from other apps](migrate/index.md), [how HolyArrs reads them](migrate/what-is-read.md) |
diff --git a/docs/dev/api-routes.md b/docs/dev/api-routes.md
index 9c73207..ac20e2c 100644
--- a/docs/dev/api-routes.md
+++ b/docs/dev/api-routes.md
@@ -9,7 +9,7 @@ Look up a route and the permission it needs. To call one, start with [The HolyAr
<!-- Generated by app/backend/tools/apidoc from the route-table snapshot. Do not edit by hand. -->
-520 routes. Regenerate with `go run ./app/backend/tools/apidoc`.
+522 routes. Regenerate with `go run ./app/backend/tools/apidoc`.
The Auth column is the permission a caller needs, as pinned in the snapshot. The Purpose column is filled only where the route registration has a comment.
@@ -581,6 +581,7 @@ The Auth column is the permission a caller needs, as pinned in the snapshot. The
| GET | `/api/v1/pick-rules/{id}` | manage_library | |
| PUT | `/api/v1/pick-rules/{id}` | settings | |
| DELETE | `/api/v1/pick-rules/{id}` | settings | |
+| POST | `/api/v1/pick-rules/{id}/trash` | settings | |
## public
@@ -801,6 +802,12 @@ The Auth column is the permission a caller needs, as pinned in the snapshot. The
| GET | `/api/v1/trailer/stream/{id}/seg/{n}` | signed_in | |
| GET | `/api/v1/trailer/{kind}/{tmdb_id}` | signed_in | |
+## trash
+
+| Method | Path | Auth | Purpose |
+|---|---|---|---|
+| GET | `/api/v1/trash/profiles` | settings | |
+
## turned-down
| Method | Path | Auth | Purpose |
diff --git a/docs/library/index.md b/docs/library/index.md
index 744dd0c..92448ac 100644
--- a/docs/library/index.md
+++ b/docs/library/index.md
@@ -19,6 +19,7 @@ Set up the folders, subtitles, audio and media server links that decide how your
| [Media servers](media-servers.md) | Link Jellyfin, Plex or Emby and map paths between containers |
| [Metadata](metadata.md) | Where names, dates and posters come from, and what your install sends |
| [Data packs](data-packs.md) | Copy Pick rules and naming patterns between installs with a JSON pack |
+| [TRaSH Guides scores](trash-guides.md) | Use a TRaSH Guides profile's scores as Pick rules points, and sync again later |
| [Trailers](trailers.md) | Turn trailers on or off and fix trailers that do not play |
New install: start with [Library folders](folders.md). The shared-folder layout that keeps imports instant is in [Folders and hardlinks](../start/folders.md).
diff --git a/docs/library/trash-guides.md b/docs/library/trash-guides.md
new file mode 100644
index 0000000..70eb672
--- /dev/null
+++ b/docs/library/trash-guides.md
@@ -0,0 +1,76 @@
+---
+title: TRaSH Guides scores
+description: Apply a TRaSH Guides profile to Pick rules so its release scores become points, and sync again when the guides change.
+level: Advanced
+---
+
+Use the scores from a [TRaSH Guides](https://trash-guides.info) profile as points in your Pick rules. Each Release gets the sum of the scores that fit its name, and the higher total wins.
+
+## Before you start
+
+- You can change settings.
+- The Pick rules set is for movies or shows, not music.
+- HolyArrs can reach `github.com`. The profiles are read from the TRaSH Guides repository each time you open the list (kept for an hour).
+
+## Apply a profile
+
+1. Open **Settings > Pick rules** and open a set. Save any changes first.
+2. In **TRaSH Guides**, pick **Shows** or **Movies**, then **Show TRaSH profiles**.
+3. Pick a profile and select **Apply profile**.
+
+HolyArrs then:
+
+- makes one trait for each scored TRaSH entry it can test, listed under **Your traits > From TRaSH Guides**,
+- puts those traits in **Traits and points** with the TRaSH score as points,
+- sets **Fewest points a Release needs**, the good enough points and **Points a better copy must add** to the profile's numbers.
+
+Points you gave built-in traits or your own traits stay as they are. Your quality steps and **Good enough at** stay too; set them to match the profile yourself.
+
+## Sync again
+
+Select **Sync again** on the set. HolyArrs reads the profile again, updates the traits it made earlier in place and replaces the points from the last sync. Nothing is made twice. A trait synced from TRaSH Guides can't be changed by hand; remove it if you don't want it.
+
+## Check the scores
+
+Open **Choose a release** on a title. Each Release shows its points and which traits gave them, including the synced ones.
+
+## What is left out
+
+After applying, **left out** lists every TRaSH entry HolyArrs didn't take, and why. An entry is taken whole or not at all, so a left-out entry never scores half.
+
+| TRaSH test | Taken? |
+|---|---|
+| Release name pattern | Yes |
+| Release group pattern | Yes |
+| Source (TV, WEB-DL, WEBRip, DVD, Blu-ray, remux) | Yes, read from the name |
+| Resolution | Yes, read from the name |
+| Remux or full disc (movies) | Yes, as a source |
+| Language | Not yet |
+| Indexer flags | Not yet |
+| Release type (single episode or season pack) | Not yet |
+| Size, year and other kinds | Not yet |
+
+TRaSH entries with no score in the profile are skipped quietly, since they change nothing. Optional TRaSH groups (the ones a profile doesn't include by default) aren't added; give those traits points yourself after a sync if you want them.
+
+Pick rules hold at most 64 traits. If a sync would go over, the strongest scores are kept and the rest are listed.
+
+## Problems
+
+| You see | Do this |
+|---|---|
+| TRaSH Guides could not be reached | Check that HolyArrs can reach `github.com`, then try again. |
+| TRaSH Guides answered 403 | GitHub limits how often one address may list files. Wait an hour and try again. |
+| **Apply profile** is greyed out | Save or undo your changes to the set first. |
+
+## For experts
+
+| Route | What it does |
+|---|---|
+| `GET /api/v1/trash/profiles?app=sonarr` | Lists profiles (`sonarr` for shows, `radarr` for movies). |
+| `POST /api/v1/pick-rules/{id}/trash` | Applies `{"app": "sonarr", "profile_id": "<TRaSH id>"}`. Send it again to re-sync. |
+
+The answer lists `scored` (trait key, name, points), `skipped` (name, test kinds, reason), and how many traits were `added` and `updated`. The set's `body.synced` holds the profile last applied.
+
+A synced trait keeps its TRaSH id, so a sync finds it again even after you rename the profile. Its patterns are read the way TRaSH writes them, look-arounds included, with a time limit per test.
+
+TRaSH Guides is MIT licensed. HolyArrs reads it at the moment you ask; nothing from it ships inside HolyArrs.
diff --git a/go.mod b/go.mod
index 9b300a6..4060457 100644
--- a/go.mod
+++ b/go.mod
@@ -22,6 +22,7 @@ require (
github.com/andybalholm/brotli v1.2.7 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/windows v1.0.1 // indirect
+ github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
diff --git a/go.sum b/go.sum
index df0b560..2ead65d 100644
--- a/go.sum
+++ b/go.sum
@@ -11,6 +11,8 @@ github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
+github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4=