-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.py
executable file
·427 lines (368 loc) · 14.3 KB
/
server.py
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/env python3
from pathlib import Path
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import os
import sys
from os.path import splitext, dirname, realpath, expanduser
import json
import re
from base64 import standard_b64encode
from subprocess import Popen, PIPE, DEVNULL, check_output, call
from urllib.parse import unquote, urlparse
from datetime import datetime
mpv_executable = 'mpv'
subdl_executable = 'subdl'
if os.name == 'nt':
import winreg
mpv_executable += '.com'
subdl_executable += '.bat'
script_path = Path(dirname(realpath(__file__)))
class Config(object):
def __init__(self, conf_dir):
self.dir = conf_dir
self.commands = self.mpv_commands()
self.ignored_ext = self.ignored_extensions()
self.ahk_exists = os.name == 'nt' and self._ahk_exists()
def mpv_commands(self):
commands = dict()
with (self.dir / 'commands').open() as f:
for c in f.read().splitlines():
if not c: continue
cname, command = c.split('=', 1)
commands[cname] = command
return commands
def mpv_config(self):
mpv_conf_file = self.dir / 'mpv.conf'
if not mpv_conf_file.is_file(): return []
with mpv_conf_file.open() as f:
return [
'--{}'.format(o.strip().split('#', 1)[0])
for o in f.read().splitlines()
if o and not o.strip().startswith('#')
]
def ignored_extensions(self):
iefile = self.dir / 'ignored_extensions.conf'
if not iefile.is_file(): return []
with iefile.open() as f:
return [
l for l in f.read().splitlines()
if l and not l.strip().startswith('#')
]
def ignored(self, fn):
fn = fn.lower()
for ext in self.ignored_ext:
if fn.endswith(ext):
return True
return False
def login(self, auth):
login_file = self.dir / 'login'
if not login_file.is_file(): return True
with login_file.open('rb') as f:
login = standard_b64encode(f.read().strip())
return auth == 'Basic {}'.format(login.decode())
def _ahk_exists(self):
try:
HKLM = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
reg_ahkscript_cmd = winreg.OpenKey(HKLM,
'SOFTWARE\\Classes\\AutoHotkeyScript\\Shell\\Open\\Command')
ahkscript_cmd = winreg.EnumValue(reg_ahkscript_cmd, 0)[1]
return True
except Exception as e:
print(e)
return False
@staticmethod
def folder_config(fpath):
def _regex(allowed):
def fn(inp):
match = re.match(allowed, inp)
return match.group(0) if match else None
return fn
def _allowed(val, fn):
try:
val = fn(val)
if val != None:
return True
except Exception as e:
print(e)
return False
allowed = {
'vid': int,
'aid': int,
'sid': int,
'secondary-sid': int,
'alang': _regex('^[a-z]+$'),
'slang': _regex('^[a-z]+$'),
'audio-delay': float,
'sub-delay': float,
'video-aspect': lambda a: _regex('^[0-9\.]+:[0-9\.]+$')(a) or float(a),
}
fpath = Path(fpath)
conf_path = fpath.parent / 'mpv-remote.conf'
config = []
if not conf_path.is_file(): return config
for c in conf_path.open().read().splitlines():
cmd, val = c.split('=', 1)
if _allowed(val, allowed.get(cmd)):
config.append('--{}'.format(c))
return config
class FolderContent(object):
def __init__(self, path, config):
self.path = Path(path)
self.config = config
if str(path) == 'WINROOT':
self._windows_drives()
elif str(path) == 'YTDL':
self._ytdl_playlists()
else:
self._folder_content()
def as_json(self):
return json.dumps(dict(
path=self.path.parts,
content=self.content
))
def _item_info(self, item):
try:
_ = item.stat()
return dict(
path=item.parts,
type='dir' if item.is_dir() else 'file',
modified=_.st_mtime,
size=_.st_size
)
except Exception as e:
print(e)
return
def _folder_content(self):
self.content = []
try:
for item in self.path.iterdir():
i = self._item_info(item)
if i and not self.config.ignored(i['path'][-1]):
self.content.append(i)
except Exception as e:
print(e)
def is_drive(self, d):
try: return d.is_dir()
except: return False
def _windows_drives(self):
drives = [Path('{}:\\'.format(c)) for c in map(chr, range(65, 91))]
drives = [self._item_info(d) for d in drives if self.is_drive(d)]
self.content = drives
def _ytdl_playlists(self):
ytdl_playlists = self.config.dir / 'ytdl.conf'
with ytdl_playlists.open() as f:
self.content = [dict(type='ytdl_playlist', path=url.strip())
for url in f.read().splitlines() if url.strip()]
class YtdlPlaylistContent(object):
def __init__(self, url):
self.url = url
self._parse_playlist()
self._get_playlist()
def as_json(self):
return json.dumps(dict(
path=self.url,
type=self.type,
content=self.playlist
))
def _detect_site(self):
sites = [
('http?s://(www)?\.youtube\.com', 'youtube'),
('http://www.crunchyroll.com', 'crunchyroll'),
('http?s://', 'other')
]
for pattern, name in sites:
if re.search(pattern, self.url):
return name
def _get_playlist(self):
self.type = self._detect_site()
self.playlist = []
for url in [e['url'] for e in self.raw_playlist]:
entry = dict()
if self.type == 'youtube':
try:
info = json.loads(check_output(['youtube-dl', '-J', url]).decode())
except Exception as e:
print(e)
continue
entry['url'] = 'ytdl://' + url
entry['date'] = float(datetime.strptime(info['upload_date'], '%Y%m%d').timestamp())
entry['length'] = info['duration']
entry['title'] = info['title']
elif self.type == 'crunchyroll':
entry['url'] = url
entry['title'] = url.split('/')[-1]
else:
entry['url'] = url
entry['title'] = url
self.playlist.append(entry)
def _parse_playlist(self):
ytdl_output = check_output(['youtube-dl', '-J', '--flat-playlist', self.url])
self.raw_playlist = json.loads(ytdl_output.decode())['entries']
class MpvServer(ThreadingMixIn, HTTPServer):
def add_config(self, config):
self.config = config
class MpvRequestHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, *args, **kwargs):
if self.command == 'POST':
sys.stderr.write('{addr} - - [{datetime}] "POST {path} {req_ver}" {statuscode} {data}\n'.format(
addr=self.address_string(),
datetime=self.log_date_time_string(),
path=self.path,
req_ver=self.request_version,
statuscode=args[2],
data=self.POST_data.decode(),
))
else:
BaseHTTPRequestHandler.log_message(self, *args, **kwargs)
def ask_auth(self):
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm="mpv-remote"')
self.send_header('Content-Length', 0)
self.end_headers()
def redirect(self, location):
self.send_response(302)
self.send_header('Location', location)
self.send_header('Content-Length', 0)
self.end_headers()
def respond_ok(self, data=b'', content_type='text/html; charset=utf-8', age=0):
self.send_response(200)
self.send_header('Cache-Control', 'public, max-age={}'.format(age))
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', len(data))
self.end_headers()
self.wfile.write(data)
def respond_notfound(self, data='404'.encode()):
self.send_response(404)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', len(data))
self.end_headers()
self.wfile.write(data)
def play_file(self, fpath, ytdl=False):
try:
self.server.fpath = fpath
p = self.server.mpv_process
p.stdin.write(b'quit\n')
p.stdin.flush()
p.kill()
except: pass
playlist = [fpath]
cmd = [mpv_executable, '--input-terminal=no', '--input-file=/dev/stdin', '--fs']
cmd += self.server.config.mpv_config()
if ytdl:
cmd += ['--ytdl']
else:
cmd += self.server.config.folder_config(fpath)
cmd += ['--'] + playlist
self.server.mpv_process = Popen(cmd, stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL)
def serve_static(self):
requested = unquote(self.url_parsed.path[len('/static/'):])
static_dir = script_path / 'static'
if requested not in os.listdir(str(static_dir)):
return self.respond_notfound('file not found'.encode())
try:
p = static_dir / requested
with p.open('rb') as f:
ct = {
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8'
}
ct = (ct.get(splitext(requested)[1]) or 'application/octet-stream')
self.respond_ok(
data=f.read(),
content_type=ct,
age=315360000
)
except Exception as e:
print(e)
self.respond_notfound('error reading file'.encode())
def sanitize(self, command, val):
if command in ['vol_set', 'seek', 'subdelay', 'audiodelay']:
try:
val = float(val)
except ValueError:
val = None
elif command in ['message']:
pass
else:
val = None
return command, val
def exec_command(self, command, val):
command, val = self.sanitize(command, val)
try:
mpv_stdin = self.server.mpv_process.stdin
cmd = (self.server.config.commands[command].format(val) + '\n').encode()
mpv_stdin.write(cmd)
mpv_stdin.flush()
except Exception as e: print(e)
def subdl(self):
self.exec_command('message', 'Searching subs...')
status = call([subdl_executable, '--existing=overwrite', self.server.fpath])
if status is not 0:
self.exec_command('message', 'Download failed :-(')
else:
self.exec_command('rescan', None)
self.exec_command('message', 'Success!')
def command_extras(self, c, v):
if c == 'fs' and self.server.config.ahk_exists:
call('focus_mpv.ahk', shell=True)
def control_mpv(self, command, val):
if command == 'subdl':
self.subdl()
else:
self.exec_command(command, val)
self.command_extras(command, val)
def do_GET(self):
if not self.server.config.login(self.headers.get('Authorization')):
return self.ask_auth()
try:
self.url_parsed = urlparse(self.path)
if self.url_parsed.path.startswith('/static/'):
self.serve_static()
elif self.url_parsed.path == '/':
index = script_path / 'static' / 'mpv-remote.html'
self.respond_ok(index.open('rb').read())
elif self.url_parsed.path == '/prefs':
prefs = dict(os=os.name, home=Path(expanduser('~')).parts, sep=os.sep)
self.respond_ok(json.dumps(prefs).encode(), 'text/plain; charset=utf-8')
else:
return self.respond_notfound()
except Exception as e:
self.respond_notfound(str(e).encode())
def do_POST(self):
if not self.server.config.login(self.headers.get('Authorization')):
return self.ask_auth()
content_length = int(self.headers.get('Content-Length') or 0)
self.POST_data = self.rfile.read(content_length)
try:
if self.path == '/dir':
dir_path = os.path.join(*json.loads(self.POST_data.decode()))
c = FolderContent(dir_path, self.server.config)
self.respond_ok(c.as_json().encode(), 'application/json')
elif self.path == '/ytdl_playlist':
url = json.loads(self.POST_data.decode())
playlist = YtdlPlaylistContent(url)
self.respond_ok(playlist.as_json().encode(), 'application/json')
elif self.path == '/ytdl_play':
url = json.loads(self.POST_data.decode())
self.play_file(url, ytdl=True)
self.respond_ok()
elif self.path == '/play':
file_path = os.path.join(*json.loads(self.POST_data.decode()))
self.play_file(file_path)
self.respond_ok()
elif self.path == '/control':
command = json.loads(self.POST_data.decode())
command, val = command.get('command'), command.get('val')
self.control_mpv(command, val)
self.respond_ok()
else:
return self.respond_notfound()
except Exception as e:
self.respond_notfound(str(e).encode())
if __name__ == '__main__':
srv = MpvServer(('', 9876), MpvRequestHandler)
srv.add_config(Config(script_path / 'preferences'))
srv.serve_forever()