-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathplugin.py
More file actions
268 lines (246 loc) · 11.2 KB
/
Copy pathplugin.py
File metadata and controls
268 lines (246 loc) · 11.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import os
import shutil
import stat
import subprocess
import re
from pathlib import Path
from urllib.parse import urlparse
from core.models import StreamProfile
from apps.plugins.models import PluginConfig
class Plugin:
name = "Dispatchwrapparr"
version = "1.7.6"
description = "An intelligent DRM/Clearkey capable stream profile for Dispatcharr"
profile_name = "Dispatchwrapparr"
# Directory where dispatchwrapparr will be copied to
dw_path = "/data/dispatchwrapparr"
dw_dst = dw_path + "/dispatchwrapparr.py"
# Directory where the streamlink DRM plugins will be copied to
drm_plugin_path = dw_path + "/drmplugins"
dashdrm_dst = drm_plugin_path + "/dashdrm.py"
hlsdrm_dst = drm_plugin_path + "/hlsdrm.py"
# Finds the directory where the plugin is installed
plugin_dir = Path(__file__).resolve().parent
# Source of bundled python code for install
dw_src = plugin_dir / "dispatchwrapparr.py"
dashdrm_src = plugin_dir / "dashdrm.py"
hlsdrm_src = plugin_dir / "hlsdrm.py"
# Generate the plugin key
plugin_key = plugin_dir.name.replace(" ", "_").lower()
# Default stream profile name
default_profile_name = "Dispatchwrapparr"
@staticmethod
def parse_version(version_str):
# parse a version string into a comparable tuple of ints. Returns None if unparseable
if not version_str:
return None
try:
return tuple(int(x) for x in version_str.strip().split("."))
except (ValueError, AttributeError):
return None
def __init__(self):
self.actions = []
try:
self.context = PluginConfig.objects.get(key=self.plugin_key)
self.settings = self.context.settings
except PluginConfig.DoesNotExist:
self.context = None
self.settings = {}
if os.path.isfile(self.dw_dst) is False:
# on load, check if the file exists. If not, invoke installation
self.install()
else:
self.local_version, self.local_version_error = self.check_local_version()
self.packaged_version = self.version
local_v = self.parse_version(self.local_version)
package_v = self.parse_version(self.packaged_version)
if local_v is not None and package_v is not None and package_v > local_v:
# packaged version is newer than local version, invoke installation to update
self.install()
# Dispatchwrapparr fields for profile creation
self.fields = [
{
"id": "profile_name",
"label": "Profile Name *",
"type": "string",
"default": "",
"description": "Mandatory: Enter a name for your stream profile",
},
{
"id": "loglevel", "label": "Log Level", "type": "select", "default": "INFO",
"options": [
{"value": "INFO", "label": "INFO"},
{"value": "CRITICAL", "label": "CRITICAL"},
{"value": "ERROR", "label": "ERROR"},
{"value": "WARNING", "label": "WARNING"},
{"value": "DEBUG", "label": "DEBUG"},
{"value": "NOTSET", "label": "NOTSET"},
]
},
{
"id": "proxy",
"label": "Proxy Server",
"type": "string",
"default": "",
"description": "Optional: Use an http proxy server for streams in this profile | Default: leave blank | Eg: 'http://proxy.address:8080'",
},
{
"id": "proxybypass",
"label": "Proxy Bypass",
"type": "string",
"default": "",
"description": "Optional: If using an http proxy server, enter a comma-delimited list of hostnames to bypass | Default: leave blank | Eg: '.example.com,.example.local:8080,192.168.0.2'",
},
{
"id": "clearkeys",
"label": "Clearkeys JSON file/URL",
"type": "string",
"default": "",
"description": "Optional: Specify a json file or URL that can be used to match DRM clearkeys to URL's (See Dispatchwrapparr documentation) | Default: leave blank | Eg: 'clearkeys.json' or 'https://path.to.clearkeys.api/clearkeys.json'",
},
{
"id": "cookies",
"label": "Cookies TXT file",
"type": "string",
"default": "",
"description": "Optional: Specify a cookies.txt file in Mozilla format containing session information for streams | Default: leave blank | Eg: 'cookies.txt'",
},
{
"id": "footnote",
"label": "Note:",
"type": "info",
"description": "Please click the 'Docs' link in the plugin description for more advanced options. New profiles added via this plugin will only become available after refreshing Dispatcharr from your browser!"
}
]
confirm_profile = {
"required": True,
"title": "Create stream profile?",
"message": "New profiles added via this plugin will only become available after refreshing Dispatcharr from your browser!",
}
self.actions = [
{
"id": "generate_profile",
"label": "Generate Stream Profile",
"button_label": "Generate Stream Profile",
"button_color": "green",
"description": "Create a new stream profile for Dispatchwrapparr with the specified settings",
"confirm": confirm_profile
},
]
# Versioning functions
def check_local_version(self):
"""Returns (version_string_or_None, error_string_or_None)"""
if os.path.isfile(self.dw_dst):
try:
result = subprocess.run(
["python3", self.dw_dst, "-v"],
capture_output=True,
text=True,
)
if result.returncode == 0:
tokens = result.stdout.strip().split()
if len(tokens) >= 2:
return tokens[1].strip(), None
else:
return None, "Version output was unexpected: " + result.stdout.strip()
else:
error = (result.stderr.strip() or result.stdout.strip() or "Unknown error (no output)")
return None, error
except Exception as e:
return None, str(e)
else:
return None, None
# Handles installation and updates
def install(self):
# Make dispatchwrapparr directory
os.makedirs(self.dw_path, exist_ok=True)
# Make drm plugin directory
os.makedirs(self.drm_plugin_path, exist_ok=True)
# copy self.install_source from source to destination
shutil.copy2(self.dw_src, self.dw_dst)
shutil.copy2(self.dashdrm_src, self.dashdrm_dst)
shutil.copy2(self.hlsdrm_src, self.hlsdrm_dst)
# set dispatchwrapparr.py executable
st = os.stat(self.dw_dst)
os.chmod(self.dw_dst, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
# Check if URL is valid
def is_valid_url(self, url: str) -> bool:
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False
def is_valid_proxy_bypass(self, value: str) -> bool:
# Checks for compatible formats for env var NO_PROXY format
noproxy_regex = re.compile(
r'^(\.?[A-Za-z0-9.-]+(:\d+)?|\d{1,3}(\.\d{1,3}){3}(:\d+)?)$'
)
if not value:
return True # empty is valid (no bypass)
parts = [v.strip() for v in value.split(",") if v.strip()]
for part in parts:
if not noproxy_regex.match(part):
return False
return True
def generate_profile(self):
if (self.settings.get("profile_name") or None) is None:
return {"status": "error", "message": "Please specify a profile name!"}
path = os.path.dirname(self.dw_dst)
profile_name = self.settings.get("profile_name")
if StreamProfile.objects.filter(name__iexact=profile_name).first():
return {"status": "error", "message": f"Profile '{profile_name}' already exists, please choose a different name!"}
parameters = [
"-ua", "{userAgent}",
"-i", "{streamUrl}",
"-loglevel", (self.settings.get("loglevel") or "INFO").strip()
]
# Validate and set proxy settings
proxy = (self.settings.get("proxy") or "").strip()
if proxy:
if self.is_valid_url(proxy) is False:
return {"status": "error", "message": f"Proxy Server: '{proxy}' is not a valid proxy server!"}
parameters += ["-proxy", proxy]
# Validate and set proxy bypass settings
proxybypass = (self.settings.get("proxybypass") or "").strip()
if proxybypass and not proxy:
return {"status": "error", "message": f"Proxy Bypass cannot be used without a proxy!"}
if proxy and proxybypass:
if self.is_valid_proxy_bypass(proxybypass) is False:
return {"status": "error", "message": f"Proxy Bypass: '{proxybypass}' is not valid for NO_PROXY format"}
parameters += ["-proxybypass", proxybypass]
# Validate and set clearkeys sources
clearkeys = (self.settings.get("clearkeys") or "").strip()
if clearkeys:
# Check if it's a valid URL or if a file exists
if self.is_valid_url(clearkeys) or os.path.isfile(clearkeys) or os.path.isfile(os.path.join(path,clearkeys)):
parameters += ["-clearkeys", clearkeys]
else:
return {"status": "error", "message": f"Clearkeys: The file/url '{clearkeys}' does not exist or is invalid"}
# Validate and set cookies file
cookies = (self.settings.get("cookies") or "").strip()
if cookies:
if os.path.isfile(cookies) or os.path.isfile(os.path.join(path,cookies)):
parameters += ["-cookies", cookies]
else:
return {"status": "error", "message": f"Cookies: The file '{cookies}' does not exist!"}
# Convert all paramaters into a string
parameter_string = " ".join(parameters)
profile = StreamProfile(
name=profile_name,
command=self.dw_dst,
parameters=parameter_string,
locked=False,
is_active=True,
)
profile.save()
return {
"status": "ok",
"message": f"Created '{profile_name}' profile"
}
# Main run function
def run(self, action: str, params: dict, context: dict):
self.settings = context.get("settings", {})
self.logger = context.get("logger")
if action == "generate_profile":
return self.generate_profile()
return {"status": "error", "message": f"Unknown action: {action}"}