-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
250 lines (227 loc) · 10.2 KB
/
Copy pathplugin.py
File metadata and controls
250 lines (227 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""
Dispatcharr VOD Preferences
===========================
Controls which provider stream Dispatcharr serves for a VOD title through its
proxy, where the native behaviour is pure account priority:
* Prefer a quality tier (e.g. 4K) across providers, and/or
* Remember the stream you pick in the Dispatcharr UI and reuse it as that
title's durable default (so the proxy serves the same stream).
See patch.py for the full design writeup and the selection ladder. This module
is the plugin entry point: it applies the monkeypatch at import time (Dispatcharr
imports an enabled plugin's code in every uWSGI worker at boot) and reverts it in
stop().
Author: andyj682
License: MIT
"""
import logging
logger = logging.getLogger("plugins.dispatcharr_vod_preferences")
# Apply the patch as soon as the module is imported. Dispatcharr only imports an
# enabled plugin's code, and under `lazy-apps = true` every uWSGI worker imports
# it at boot -- so importing == "this worker should be patched".
try:
from . import patch as _patch
except Exception: # pragma: no cover - fall back to flat import layout
import patch as _patch
try:
_patch.install()
except Exception: # never break app startup because of the plugin
logger.exception("[VOD-PREF] auto-install on import failed")
def _format_picks(picks):
"""Human-readable one-line-per-pick summary for the UI message."""
if not picks:
return "No saved picks."
lines = []
for key, rec in sorted(picks.items()):
acct = rec.get("m3u_account_id") if isinstance(rec, dict) else "?"
if isinstance(rec, dict) and "stream_id" in rec:
target = f"account {acct}, stream {rec.get('stream_id')}"
else:
# Show-level pick: provider for the whole series (stmdb:/simdb:/series:).
target = f"account {acct} (whole series)"
lines.append(f" {key} -> {target}")
return f"{len(picks)} saved pick(s):\n" + "\n".join(lines)
class Plugin:
name = "Dispatcharr VOD Preferences"
version = "1.0.0"
description = (
"Greater control over which VOD stream Dispatcharr serves through its "
"proxy for a given title (control not exposed to clients): prefer a "
"quality tier (e.g. 4K) across providers, and/or remember the stream you "
"pick in the UI as that title's durable default."
)
author = "andyj682"
help_url = ""
fields = [
{
"id": "prefer_quality",
"label": "Prefer quality",
"type": "select",
"default": "off",
"help_text": (
"Re-order a title's provider streams by quality before serving. "
"Quality is inferred per stream from, in order: actual video pixel "
"dimensions (ground truth, when known), then explicit "
"quality/resolution, the provider stream name, and the M3U account "
"name -- so a '... 4K' provider, or a stream/title containing "
"'4K'/'2160p', is recognised, while a genuinely 1080p stream "
"mislabeled '4K' still ranks as 1080p. Streams with no quality "
"signal keep their native account-priority order."
),
# Only Off / Prefer 4K are exposed: on real provider data the sub-4K
# streams carry no resolution label, so finer tiers never light up and
# "Prefer 1080p" would be misleading. The full tier ladder still lives
# in patch.py (_QUALITY_PRIORITY) and a "1080p" value is still honoured
# if set -- re-add the option here if a provider ever labels sub-4K.
"options": [
{"value": "off", "label": "Off (native account priority)"},
{"value": "4k", "label": "Prefer 4K"},
],
},
{
"id": "remember_ui_picks",
"label": "Remember my UI pick",
"type": "boolean",
"default": True,
"help_text": (
"When you play a specific stream from the Dispatcharr UI, save it "
"as the default so the proxy serves it next time. Movies "
"remember the exact stream; TV remembers the PROVIDER for the whole "
"series (picking a stream on one episode makes that provider the "
"default for every episode of the show). Applied ahead of the "
"quality rule; dropped automatically if the provider stops carrying "
"the title."
),
},
{
"id": "clear_key",
"label": "Title key to clear",
"type": "string",
"default": "",
"placeholder": "e.g. tmdb:954 (or a bare tmdb/imdb id)",
"help_text": (
"Type the key of a saved pick here (copy it from 'List saved "
"picks'), then click 'Clear one' on the Actions tab. Leave blank "
"otherwise."
),
},
{
"id": "_info",
"label": "",
"type": "info",
"description": (
"Selection order (most specific first): explicit request pick -> "
"saved UI pick -> quality rule -> native account priority. Use the "
"buttons below to inspect or clear saved picks."
),
},
]
actions = [
{
"id": "status",
"label": "Show patch status",
"description": "Report whether the preferences patch is active in the "
"worker that handles this request.",
"button_label": "Check status",
"button_variant": "outline",
},
{
"id": "list_saved",
"label": "List saved picks",
"description": "Show the remembered per-title stream picks.",
"button_label": "List saved picks",
"button_variant": "outline",
},
{
"id": "clear_title",
"label": "Clear one saved pick",
"description": "Remove the saved pick whose key is entered in the "
"'Title key to clear' box on the Settings tab. Type the "
"key there first, then click here.",
"button_label": "Clear one",
"button_variant": "outline",
},
{
"id": "clear_saved",
"label": "Clear all saved picks",
"description": "Remove every remembered per-title stream pick.",
"button_label": "Clear all",
"button_variant": "default",
"button_color": "red",
"confirm": {
"title": "Clear all saved picks?",
"message": "This permanently removes every remembered per-title "
"stream pick. Quality preferences are unaffected.",
},
},
]
def run(self, action=None, params=None, context=None):
params = params or {}
context = context or {}
if action == "enable":
ok = _patch.install()
return {
"status": "ok" if ok else "error",
"message": "VOD preferences patch installed"
if ok else "Failed to install (see logs)",
}
if action == "disable":
_patch.uninstall()
return {"status": "ok", "message": "VOD preferences patch reverted"}
if action == "status":
import os
settings = context.get("settings", {})
return {
"status": "ok",
"message": (
f"active={_patch._ACTIVE} in worker pid={os.getpid()} "
f"(reflects ONE worker; check logs for all worker pids). "
f"prefer_quality={settings.get('prefer_quality', 'off')}, "
f"remember_ui_picks={settings.get('remember_ui_picks', True)}, "
f"saved_picks={len(_patch.get_saved_picks())}"
),
}
if action == "list_saved":
picks = _patch.get_saved_picks()
return {"status": "ok", "message": _format_picks(picks), "picks": picks}
if action == "clear_saved":
try:
removed = _patch.clear_all_saved()
return {"status": "ok", "message": f"Cleared {removed} saved pick(s)."}
except Exception as exc:
logger.exception("[VOD-PREF] clear_saved failed")
return {"status": "error", "message": f"Failed to clear: {exc}"}
if action == "clear_title":
# The Plugins UI has no per-action parameter input, but it DOES save
# settings before running an action -- so the key is read from the
# 'clear_key' settings field. (params are still honoured if a caller
# provides them via the API directly.)
settings = context.get("settings", {})
key = (
(settings.get("clear_key") or "").strip()
or params.get("title_key")
or params.get("key")
or params.get("title")
or params.get("tmdb")
or params.get("imdb")
or params.get("value")
)
if not key:
return {
"status": "error",
"message": "Type a title key (from 'List saved picks') or a "
"tmdb/imdb id into the 'Title key to clear' field, "
"then click 'Clear one'.",
}
try:
removed = _patch.clear_saved_key(key)
if removed:
return {"status": "ok", "message": f"Removed saved pick for '{key}'."}
return {"status": "ok", "message": f"No saved pick matched '{key}'."}
except Exception as exc:
logger.exception("[VOD-PREF] clear_title failed")
return {"status": "error", "message": f"Failed to clear: {exc}"}
return {"status": "error", "message": f"Unknown action: {action}"}
def stop(self, context=None):
"""Called by Dispatcharr on disable / delete / reload."""
_patch.uninstall()
return {"status": "ok", "message": "VOD preferences patch reverted"}