-
Notifications
You must be signed in to change notification settings - Fork 2
/
DLNAmpvRenderer.py
3199 lines (3091 loc) · 147 KB
/
DLNAmpvRenderer.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# DLNAmpvRenderer v1.3.2 (https://github.com/PCigales/DLNAmpvRenderer)
# Copyright © 2022 PCigales
# This program is licensed under the GNU GPLv3 copyleft license (see https://www.gnu.org/licenses)
import threading
import msvcrt
import ctypes, ctypes.wintypes
import os
from functools import partial
import socket
import socketserver
import selectors
import urllib.parse, urllib.request, urllib.error
import ssl
import struct
import email.utils
from xml.dom import minidom
import time
import uuid
import subprocess
import json
import html
from io import BytesIO
import locale
import argparse
NAME = 'DLNAmpvRenderer'
UDN = 'uuid:' + str(uuid.uuid5(uuid.NAMESPACE_URL, 'DLNAmpvRenderer'))
FR_STRINGS = {
'license': 'Ce programme est sous licence copyleft GNU GPLv3 (voir https://www.gnu.org/licenses)',
'help': 'affichage du message d\'aide et interruption du script',
'parser_ip': 'adresse IP du renderer [auto-sélectionnée par défaut - "0.0.0.0", soit toutes les interfaces, si option présente sans mention d\'adresse]',
'parser_port': 'port TCP du renderer [8000 par défaut]',
'parser_name': 'nom du renderer [DLNAmpvRenderer par défaut]',
'parser_minimized': 'passage en mode minimisé quand inactif [désactivé par défaut]',
'parser_fullscreen': 'passage en mode plein écran à chaque session [désactivé par défaut]',
'parser_mkv': 'masque la prise en charge du format matroska à WMPDMC pour permettre le contrôle distant [désactivé par défaut]',
'parser_trust': 'désactive la vérification des adresses avant leur transmission à mpv [désactivé par défaut]',
'parser_subtitles': 'active la recherche systématique de sous-titres [désactivé par défaut]',
'parser_gapless': 'active la lecture sans blanc (sous réserve de compatibilité avec le contrôleur), avec préchargement audio (pourrait faire dysfonctionner mpv) si "p" mentionné [désactivé par défaut]',
'parser_verbosity': 'niveau de verbosité de 0 à 2 [0 par défaut]',
'keyboard_s': 'Appuyez sur "S" ou fermez mpv pour quitter',
'enabled': 'activé',
'disabled': 'désactivé',
'keyboard_m': 'Appuyez sur "M" pour activer/désactiver le passage en mode minimisé quand inactif - mode actuel: %s',
'keyboard_f': 'Appuyez sur "F" pour activer/désactiver le passage en mode plein écran à chaque session - mode actuel: %s',
'mode_m': 'Passage en mode minimisé quand inactif: %s',
'mode_f': 'Passage en mode plein écran à chaque session: %s',
'player_failure': 'Lecteur - échec du lancement',
'ip_failure': 'Échec de la récupération de l\'addresse ip de l\'hôte',
'request_failure': 'Échec du démarrage de l\'écoute des requêtes à l\'adresse %s:%s',
'current_content': 'Contenu en cours: %s | %s | %s',
'next_content': 'Prochain contenu: %s | %s | %s …',
'next_current': '… en cours',
'video': 'vidéo',
'audio': 'audio',
'image': 'image'
}
EN_STRINGS = {
'license': 'This program is licensed under the GNU GPLv3 copyleft license (see https://www.gnu.org/licenses)',
'help': 'display of the help message and interruption of the script',
'parser_ip': 'IP address of the renderer [auto-selected by default - "0.0.0.0", meaning all interfaces, if option present with no address mention]',
'parser_port': 'TCP port of the renderer [8000 by default]',
'parser_name': 'name of the renderer [DLNAmpvRenderer by default]',
'parser_minimized': 'switching to minimized mode when idle [disabled by default]',
'parser_fullscreen': 'switching to fullscreen mode at each session [disabled by default]',
'parser_mkv': 'mask support of matroska format to WMPDMC to allow the remote control [disabled by default]',
'parser_trust': 'disable the checking of the addresses before their transmission to mpv [disabled by default]',
'parser_subtitles': 'enable systematic search for subtitles [disabled by default]',
'parser_gapless': 'enable gapless playback (subject to controller compatibility), with audio prefetch (might make mpv malfunction) if "p" mentioned [disabled by default]',
'parser_verbosity': 'level of verbosity from 0 to 2 [0 by default]',
'keyboard_s': 'Press "S" or close mpv to exit',
'enabled': 'enabled',
'disabled': 'disabled',
'keyboard_m': 'Press "M" to toggle the switching to minimized mode when idle - current mode: %s',
'keyboard_f': 'Press "F" to toggle the switching to fullscreen mode at each session - current mode: %s',
'mode_m': 'Switching to minimized mode when idle: %s',
'mode_f': 'Switching to fullscreen mode at each session: %s',
'player_failure': 'Player - launch failure',
'ip_failure': 'Failure of the retrieval of the host ip address',
'request_failure': 'Failure of the startup of the listening of requests at the address %s:%s',
'current_content': 'Current content: %s | %s | %s',
'next_content': 'Next content: %s | %s | %s …',
'next_current': '… current',
'video': 'video',
'audio': 'audio',
'image': 'image'
}
locale.setlocale(locale.LC_TIME, '')
LSTRINGS = EN_STRINGS
try:
if locale.getlocale()[0][:2].lower() == 'fr':
LSTRINGS = FR_STRINGS
except:
pass
class log_event:
def __init__(self, verbosity):
self.verbosity = verbosity
def log(self, msg, level):
if level <= self.verbosity:
print(time.strftime('%x %X', time.localtime()), ':', msg)
def _open_url(url, method=None, timeout=None, test_range=False):
header = {'User-Agent': 'Lavf'}
if method and test_range:
if method.upper() == 'HEAD':
header['Range'] = 'bytes=0-'
req = urllib.request.Request(url, headers=header, method=method)
rep = None
try:
rep = urllib.request.urlopen(req, data=None, timeout=timeout)
except urllib.error.HTTPError as e:
if e.code == 406 and test_range and (method or '').upper() == 'HEAD':
del header['Range']
req = urllib.request.Request(url, headers=header, method=method)
rep = None
try:
rep = urllib.request.urlopen(req, data=None, timeout=timeout)
except:
pass
except:
pass
return rep
def _XMLGetNodeText(node):
text = []
for childNode in node.childNodes:
if childNode.nodeType == node.TEXT_NODE:
text.append(childNode.data)
return(''.join(text))
class HTTPExplodedMessage():
__slots__ = ('method', 'path', 'version', 'code', 'message', 'headers', 'body', 'expect_close')
def __init__(self):
self.method = self.path = self.version = self.code = self.message = self.body = self.expect_close = None
self.headers = {}
def __bool__(self):
return self.method is not None or self.code is not None
def clear(self):
self.__init__()
return self
def header(self, name, default=None):
return self.headers.get(name.title(), default)
def in_header(self, name, value):
h = self.header(name)
return False if h is None else (value.lower() in map(str.strip, h.lower().split(',')))
def __repr__(self):
if self:
try:
return '\r\n'.join(('<HTTPExplodedMessage at %#x>\r\n----------' % id(self), (' '.join(filter(None, (self.method, self.path, self.version, self.code, self.message)))), *map(': '.join, self.headers.items()), '----------\r\nLength of body: %s byte(s)' % len(self.body or ''), '----------\r\nClose expected: %s' % self.expect_close))
except:
return '<HTTPExplodedMessage at %#x>\r\n<corrupted object>' % id(self)
else:
return '<HTTPExplodedMessage at %#x>\r\n<no message>' % id(self)
class HTTPMessage():
@staticmethod
def _read_headers(msg, http_message):
if not msg:
return False
a = None
for msg_line in msg.replace('\r\n', '\n').split('\n')[:-2]:
if a is None:
try:
a, b, c = msg_line.strip().split(None, 2)
except:
try:
a, b, c = *msg_line.strip().split(None, 2), ''
except:
return False
else:
try:
header_name, header_value = msg_line.split(':', 1)
except:
return False
header_name = header_name.strip().title()
if header_name:
header_value = header_value.strip()
if header_name not in ('Content-Length', 'Location', 'Host') and http_message.headers.get(header_name):
if header_value:
http_message.headers[header_name] += ', ' + header_value
else:
http_message.headers[header_name] = header_value
else:
return False
if a is None:
return False
if a[:4].upper() == 'HTTP':
http_message.version = a.upper()
http_message.code = b
http_message.message = c
else:
http_message.method = a.upper()
http_message.path = b
http_message.version = c.upper()
http_message.expect_close = http_message.in_header('Connection', 'close') or (http_message.version.upper() != 'HTTP/1.1' and not http_message.in_header('Connection', 'keep-alive'))
return True
def __new__(cls, message=None, body=True, decode='utf-8', timeout=5, max_length=1048576, max_hlength=1048576):
http_message = HTTPExplodedMessage()
if message is None:
return http_message
max_hlength = min(max_length, max_hlength)
rem_length = max_hlength
iss = isinstance(message, socket.socket)
if not iss:
msg = message[0]
else:
message.settimeout(timeout)
msg = b''
while True:
msg = msg.lstrip(b'\r\n')
if msg and msg[0] < 0x20:
return http_message
body_pos = msg.find(b'\r\n\r\n')
if body_pos >= 0:
body_pos += 4
break
body_pos = msg.find(b'\n\n')
if body_pos >= 0:
body_pos += 2
break
if not iss or rem_length <= 0:
return http_message
try:
bloc = message.recv(min(rem_length, 1048576))
if not bloc:
return http_message
except:
return http_message
rem_length -= len(bloc)
msg = msg + bloc
if not cls._read_headers(msg[:body_pos].decode('ISO-8859-1'), http_message):
return http_message.clear()
if not iss:
http_message.expect_close = True
if http_message.code in ('100', '101', '204', '304'):
http_message.body = b''
return http_message
if not body:
http_message.body = msg[body_pos:]
return http_message
rem_length += max_length - max_hlength
chunked = http_message.in_header('Transfer-Encoding', 'chunked')
if chunked:
body_len = -1
else:
body_len = http_message.header('Content-Length')
if body_len is None:
if not iss or (http_message.code in ('200', '206') and http_message.expect_close):
body_len = -1
else:
body_len = 0
else:
try:
body_len = max(0, int(body_len))
except:
return http_message.clear()
if http_message.in_header('Expect', '100-continue') and iss:
if body_pos + body_len - len(msg) <= rem_length:
try:
message.sendall('HTTP/1.1 100 Continue\r\n\r\n'.encode('ISO-8859-1'))
except:
return http_message.clear()
else:
try:
message.sendall(('HTTP/1.1 413 Payload too large\r\nContent-Length: 0\r\nDate: %s\r\nCache-Control: no-cache, no-store, must-revalidate\r\n\r\n' % email.utils.formatdate(time.time(), usegmt=True)).encode('ISO-8859-1'))
except:
pass
return http_message.clear()
if not chunked:
if body_len < 0:
if not iss:
http_message.body = msg[body_pos:]
else:
bbuf = BytesIO()
rem_length -= bbuf.write(msg[body_pos:])
while rem_length > 0:
try:
bw = bbuf.write(message.recv(min(rem_length, 1048576)))
if not bw:
break
rem_length -= bw
except:
return http_message.clear()
if rem_length <= 0:
return http_message.clear()
http_message.body = bbuf.getvalue()
elif len(msg) < body_pos + body_len:
if not iss or body_pos + body_len - len(msg) > rem_length:
return http_message.clear()
bbuf = BytesIO()
body_len -= bbuf.write(msg[body_pos:])
while body_len:
try:
bw = bbuf.write(message.recv(min(body_len, 1048576)))
if not bw:
return http_message.clear()
body_len -= bw
except:
return http_message.clear()
http_message.body = bbuf.getvalue()
else:
http_message.body = msg[body_pos:body_pos+body_len]
else:
bbuf = BytesIO()
buff = msg[body_pos:]
while True:
chunk_pos = -1
rem_slength = max_hlength - len(buff)
while chunk_pos < 0:
buff = buff.lstrip(b'\r\n')
chunk_pos = buff.find(b'\r\n')
if chunk_pos >= 0:
chunk_pos += 2
break
chunk_pos = buff.find(b'\n')
if chunk_pos >= 0:
chunk_pos += 1
break
if not iss or rem_slength <= 0 or rem_length <= 0:
return http_message.clear()
try:
bloc = message.recv(min(rem_length, rem_slength, 1048576))
if not bloc:
return http_message.clear()
except:
return http_message.clear()
rem_length -= len(bloc)
rem_slength -= len(bloc)
buff = buff + bloc
try:
chunk_len = int(buff[:chunk_pos].split(b';', 1)[0].rstrip(b'\r\n'), 16)
if not chunk_len:
break
except:
return http_message.clear()
if chunk_pos + chunk_len - len(buff) > rem_length:
return http_message.clear()
if len(buff) < chunk_pos + chunk_len:
if not iss:
return http_message.clear()
chunk_len -= bbuf.write(buff[chunk_pos:])
while chunk_len:
try:
bw = bbuf.write(message.recv(min(chunk_len, 1048576)))
if not bw:
return http_message.clear()
chunk_len -= bw
except:
return http_message.clear()
rem_length -= bw
buff = b''
else:
bbuf.write(buff[chunk_pos:chunk_pos+chunk_len])
buff = buff[chunk_pos+chunk_len:]
http_message.body = bbuf.getvalue()
rem_length = min(rem_length, max_hlength - body_pos - len(buff) + chunk_pos)
while not (b'\r\n\r\n' in buff or b'\n\n' in buff):
if not iss or rem_length <= 0:
return http_message.clear()
try:
bloc = message.recv(min(rem_length, 1048576))
if not bloc:
return http_message.clear()
except:
return http_message.clear()
rem_length -= len(bloc)
buff = buff + bloc
if http_message.body:
try:
if decode:
http_message.body = http_message.body.decode(decode)
except:
return http_message.clear()
return http_message
class HTTPRequest():
SSLContext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
SSLContext.check_hostname = False
SSLContext.verify_mode = ssl.CERT_NONE
RequestPattern = \
'%s %s HTTP/1.1\r\n' \
'Host: %s\r\n%s' \
'\r\n'
def __new__(cls, url, method=None, headers=None, data=None, timeout=30, max_length=1073741824, max_hlength=1048576, pconnection=None, ip=''):
if url is None:
return HTTPMessage()
if method is None:
method = 'GET' if data is None else 'POST'
redir = 0
try:
url_p = urllib.parse.urlsplit(url, allow_fragments=False)
if headers is None:
headers = {}
hitems = headers.items()
if pconnection is None:
pconnection = [None]
hccl = True
else:
hccl = 'close' in (e.strip() for k, v in hitems if k.lower() == 'connection' for e in v.lower().split(','))
headers = {k: v for k, v in hitems if k.lower() not in ('host', 'content-length', 'connection', 'expect')}
if 'accept-encoding' not in (k.lower() for k, v in hitems):
headers['Accept-Encoding'] = 'identity'
if data is not None:
if 'chunked' not in (e.strip() for k, v in hitems if k.lower() == 'transfer-encoding' for e in v.lower().split(',')):
headers['Content-Length'] = str(len(data))
headers['Connection'] = 'close' if hccl else 'keep-alive'
except:
return HTTPMessage()
while True:
try:
if pconnection[0] is None:
if url_p.scheme.lower() == 'http':
pconnection[0] = socket.create_connection((url_p.hostname, url_p.port if url_p.port is not None else 80), timeout=timeout, source_address=(ip, 0))
elif url_p.scheme.lower() == 'https':
n, s, p = url_p.netloc.rpartition(':')
if s != ':' or ']' in p:
n = url_p.netloc
pconnection[0] = cls.SSLContext.wrap_socket(socket.create_connection((url_p.hostname, url_p.port if url_p.port is not None else 443), timeout=timeout, source_address=(ip, 0)), server_side=False, server_hostname=n)
else:
raise
else:
try:
pconnection[0].settimeout(timeout)
except:
pass
msg = cls.RequestPattern % (method, (url_p.path + ('?' + url_p.query if url_p.query else '')).replace(' ', '%20') or '/', url_p.netloc, ''.join(k + ': ' + v + '\r\n' for k, v in headers.items()))
pconnection[0].sendall(msg.encode('iso-8859-1') + (data or b''))
code = '100'
while code == '100':
resp = HTTPMessage(pconnection[0], body=(method.upper() != 'HEAD'), decode=None, timeout=timeout, max_length=max_length, max_hlength=max_hlength)
code = resp.code
if code == '100':
redir += 1
if redir > 5:
raise
if code is None:
raise
if code[:2] == '30' and code != '304':
if resp.header('location'):
url = urllib.parse.urljoin(url, resp.header('location'))
urlo_p = url_p
url_p = urllib.parse.urlsplit(url, allow_fragments=False)
if headers['Connection'] == 'close' or resp.expect_close or (urlo_p.scheme != url_p.scheme or urlo_p.netloc != url_p.netloc):
try:
pconnection[0].close()
except:
pass
pconnection[0] = None
headers['Connection'] = 'close'
redir += 1
if redir > 5:
raise
if code == '303':
if method.upper() != 'HEAD':
method = 'GET'
data = None
for k in list(headers.keys()):
if k.lower() in ('transfer-encoding', 'content-length', 'content-type'):
del headers[k]
else:
raise
else:
break
except:
try:
pconnection[0].close()
except:
pass
pconnection[0] = None
return HTTPMessage()
if headers['Connection'] == 'close' or resp.expect_close:
try:
pconnection[0].close()
except:
pass
pconnection[0] = None
return resp
ULONG = ctypes.wintypes.ULONG
ULONG_PTR = ctypes.wintypes.WPARAM
DWORD = ctypes.wintypes.DWORD
LPDWORD = ctypes.wintypes.LPDWORD
USHORT = ctypes.wintypes.USHORT
BOOL = ctypes.wintypes.BOOL
PVOID = ctypes.wintypes.LPVOID
HANDLE = ctypes.wintypes.HANDLE
POINTER = ctypes.POINTER
pointer = ctypes.pointer
LPWSTR = ctypes.wintypes.LPWSTR
WINFUNCTYPE = ctypes.WINFUNCTYPE
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.CreateEventW.restype = HANDLE
kernel32.CreateEventW.argtypes = (PVOID, BOOL, BOOL, LPWSTR)
kernel32.SetEvent.restype = BOOL
kernel32.SetEvent.argtypes = (HANDLE,)
kernel32.ResetEvent.restype = BOOL
kernel32.ResetEvent.argtypes = (HANDLE,)
kernel32.CreateFileW.restype = HANDLE
kernel32.CreateFileW.argtypes = (LPWSTR, DWORD, DWORD, PVOID, DWORD, DWORD, HANDLE)
kernel32.WriteFileEx.restype = BOOL
kernel32.WriteFileEx.argtypes = (HANDLE, PVOID, DWORD, PVOID, PVOID)
kernel32.ReadFileEx.restype = BOOL
kernel32.ReadFileEx.argtypes = (HANDLE, PVOID, DWORD, PVOID, PVOID)
kernel32.WaitForSingleObjectEx.restype = DWORD
kernel32.WaitForSingleObjectEx.argtypes = (HANDLE, DWORD, BOOL)
kernel32.GetOverlappedResultEx.restype = BOOL
kernel32.GetOverlappedResultEx.argtypes = (HANDLE, PVOID, LPDWORD, DWORD, BOOL)
kernel32.CancelIoEx.restype = BOOL
kernel32.CancelIoEx.argtypes = (HANDLE, PVOID)
kernel32.CloseHandle.restype = BOOL
kernel32.CloseHandle.argtypes = (HANDLE,)
class OVERLAPPED_STRUCT(ctypes.Structure):
_fields_ = [('Offset', DWORD),('OffsetHigh', DWORD)]
class OVERLAPPED_UNION(ctypes.Union):
_anonymous_ = ('u', )
_fields_ = [('u', OVERLAPPED_STRUCT), ('Pointer', PVOID)]
class OVERLAPPED(ctypes.Structure):
_anonymous_ = ('u', )
_fields_ = [('Internal', ULONG_PTR), ('InternalHigh', ULONG_PTR), ('u', OVERLAPPED_UNION), ('hEvent', HANDLE)]
LPOVERLAPPED = POINTER(OVERLAPPED)
LPOVERLAPPED_COMPLETION_ROUTINE = WINFUNCTYPE(None, DWORD, DWORD, LPOVERLAPPED)
class IPCmpvControler(threading.Thread):
SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
@staticmethod
def _Py_Completion_Routine(dwErrorCode, dwNumberOfBytesTransfered, lpOverlapped):
kernel32.SetEvent(lpOverlapped.contents.hEvent)
def __init__(self, title_name='mpv', verbosity=0):
self.verbosity = verbosity
self.logger = log_event(verbosity)
self.title_name = title_name
threading.Thread.__init__(self)
self.ReadFileEx_Completion_Routine = LPOVERLAPPED_COMPLETION_ROUTINE(self._Py_Completion_Routine)
self.WriteFileEx_Completion_Routine = LPOVERLAPPED_COMPLETION_ROUTINE(self._Py_Completion_Routine)
self.lpOverlapped_r = pointer(OVERLAPPED())
self.lpOverlapped_w = pointer(OVERLAPPED())
self.lpOverlapped_r.contents.hEvent = kernel32.CreateEventW(None, True, False, urllib.parse.quote(self.title_name, safe='') + '_read')
self.lpOverlapped_w.contents.hEvent = kernel32.CreateEventW(None, True, False, urllib.parse.quote(self.title_name, safe='') + '_write')
self.NumberOfBytesTransferred_r = DWORD()
self.NumberOfBytesTransferred_w = DWORD()
self.Pipe_handle = None
self.Cmd_Event = kernel32.CreateEventW(None, True, False, urllib.parse.quote(self.title_name, safe='') + '_input')
self.Msg_event = threading.Event()
self.Cmd_buffer = ["run", ('get_property', 'command-list'), ('set_property', 'script-opts', 'osc-visibility=never'), ('observe_property', 1, 'time-pos'), ('observe_property', 2, 'pause'), ('observe_property', 3, 'duration'), ('observe_property', 4, 'mute'), ('observe_property', 5, 'volume'), ('observe_property', 6, 'playlist-playing-pos'), ('observe_property', 7, 'idle-active'), ('set_property', 'title', '${?media-title:${media-title}}${!media-title:No file} - %s' % title_name)]
self.Msg_buffer = ['run']
self.Read_pending = False
kernel32.ResetEvent(self.lpOverlapped_r.contents.hEvent)
self.Write_pending = False
kernel32.ResetEvent(self.lpOverlapped_w.contents.hEvent)
kernel32.ResetEvent(self.Cmd_Event)
self.Player_events = []
self.Player_loadfile_options_pos = None
self.Player_status = "NO_MEDIA_PRESENT"
self.Player_time_pos = ""
self.Player_duration = ""
self.Player_mute = False
self.Player_volume = 0
self.Player_paused = True
self.Player_event_event = threading.Event()
def manage_incoming_msg(self):
while self.Msg_buffer[0] == "run":
while len(self.Msg_buffer) > 1:
self.Msg_event.clear()
msg = self.Msg_buffer.pop(1)
if not msg:
continue
self.logger.log('Lecteur - message reçu: %s' % msg, 2)
try:
msg_dict = json.loads(msg)
except:
continue
ev = msg_dict.get('event')
if ev:
if ev == "property-change":
name = msg_dict.get('name', '')
if name == "duration":
if 'data' in msg_dict:
durat_sec = int(msg_dict['data'])
durat = '%d:%02d:%02d' % (durat_sec // 3600, (durat_sec % 3600) // 60, durat_sec % 60)
if self.Player_duration != durat:
self.Player_duration = durat
self.Player_events.append(('CurrentMediaDuration', durat))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('CurrentMediaDuration', durat), 1)
elif name == "time-pos":
if 'data' in msg_dict:
time_sec = int(msg_dict['data'])
time_pos = '%d:%02d:%02d' % (time_sec // 3600, (time_sec % 3600) // 60, time_sec % 60)
if self.Player_time_pos != time_pos:
self.Player_time_pos = time_pos
self.Player_events.append(('RelativeTimePosition', time_pos))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('RelativeTimePosition', time_pos), 2)
else:
self.Player_time_pos = ""
self.Player_events.append(('RelativeTimePosition', ""))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('RelativeTimePosition', ''), 2)
elif name == "mute":
if 'data' in msg_dict:
self.Player_mute = msg_dict['data']
self.Player_events.append(('Mute', self.Player_mute))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('Mute', self.Player_mute), 2)
elif name == "volume":
if 'data' in msg_dict:
self.Player_volume = int(float(msg_dict['data']))
self.Player_events.append(('Volume', self.Player_volume))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('Volume', self.Player_volume), 2)
elif name == "idle-active":
if msg_dict.get('data') == True and self.Player_status != "NO_MEDIA_PRESENT":
self.Player_status = "STOPPED"
self.Player_events.append(('TransportState', "STOPPED"))
self.Player_time_pos = ""
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "STOPPED"), 1)
elif name == "pause":
if msg_dict.get('data') == True:
self.Player_paused = True
if self.Player_status == "PLAYING":
self.Player_status = "PAUSED_PLAYBACK"
self.Player_events.append(('TransportState', "PAUSED_PLAYBACK"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "PAUSED_PLAYBACK"), 1)
elif msg_dict.get('data') == False:
self.Player_paused = False
if self.Player_status == "PAUSED_PLAYBACK":
self.Player_status = "PLAYING"
self.Player_events.append(('TransportState', "PLAYING"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "PLAYING"), 1)
elif name == "playlist-playing-pos":
if msg_dict.get('data', '') == 1:
self.Player_events.append(('Playlist', "1"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('Playlist', "1"), 1)
elif ev == "start-file":
self.Player_time_pos = ""
self.Player_duration = ""
self.Player_status = "TRANSITIONING"
self.Player_events.append(('TransportState', "STARTING"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "TRANSITIONING"), 2)
elif ev == "end-file":
if msg_dict.get('reason').lower() == "error":
self.Player_events.append(('TransportStatus', "ERROR_OCCURRED"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportStatus', "ERROR_OCCURRED"), 2)
elif ev == 'seek':
self.Player_status = "TRANSITIONING"
self.Player_events.append(('TransportState', "TRANSITIONING"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "TRANSITIONING"), 2)
elif ev == "playback-restart":
if self.Player_paused:
self.Player_status = "PAUSED_PLAYBACK"
self.Player_events.append(('TransportState', "PAUSED_PLAYBACK"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "PAUSED_PLAYBACK"), 1)
else:
self.Player_status = "PLAYING"
self.Player_events.append(('TransportState', "PLAYING"))
self.Player_event_event.set()
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "PLAYING"), 1)
elif msg_dict.get('request_id') == 0:
try:
self.Player_loadfile_options_pos = next(i for i, a in enumerate(next(c['args'] for c in msg_dict['data'] if c['name'] == 'loadfile')) if a['name'] == 'options')
self.Player_loadfile_options_pos = max(self.Player_loadfile_options_pos, 2)
except:
self.Player_loadfile_options_pos = 3
self.Player_events.append(('command-list', "loadfile"))
self.Player_event_event.set()
if self.Msg_buffer[0] == "run":
self.Msg_event.wait()
self.Msg_event.clear()
def run_mpv(self):
self.logger.log('Lecteur - lancement', 1)
try:
process_result = subprocess.run(r'"%s\%s"' % (IPCmpvControler.SCRIPT_PATH, 'mpv.bat'), env={**os.environ, 'renderer_name': urllib.parse.quote(self.title_name, safe='')}, capture_output=False)
except:
pass
self.logger.log('Lecteur: fermeture', 1)
if self.Player_status != "STOPPED":
self.Player_status = "STOPPED"
self.logger.log('Lecteur - événement enregistré: %s = "%s"' % ('TransportState', "STOPPED"), 1)
self.Player_events.append(('TransportState', "STOPPED"))
self.Cmd_buffer[0] = "quit"
self.Msg_buffer[0] = "quit"
self.Player_event_event.set()
kernel32.SetEvent(self.Cmd_Event)
def run(self):
self.mpv_thread = threading.Thread(target=self.run_mpv)
self.mpv_thread.start()
request_id = 0
while self.Cmd_buffer[0] != "quit":
hnd = kernel32.CreateFileW(r'\\.\pipe\mpv_%s' % urllib.parse.quote(self.title_name, safe=''), 0xc0000000, 0, None, 4, 0x60000000, None)
if kernel32.GetLastError() == 2:
time.sleep(0.2)
else:
self.Pipe_handle = hnd
break
if kernel32.GetLastError() == 2:
self.logger.log(LSTRINGS['player_failure'], 0)
return False
self.incoming_msg_thread = threading.Thread(target=self.manage_incoming_msg)
self.incoming_msg_thread.start()
w = 0
msg_buffer = ctypes.create_string_buffer(15001)
msg_chunk = ""
while self.Cmd_buffer[0] == "run":
kernel32.ResetEvent(self.Cmd_Event)
if not self.Write_pending and len(self.Cmd_buffer) > 1:
cmd = self.Cmd_buffer.pop(1)
msg = None
try:
msg = ctypes.create_string_buffer(json.dumps({'command': cmd, 'request_id': request_id}).encode('UTF-8'))
msg[len(msg) - 1] = b'\n'
except:
continue
if not msg:
continue
request_id += 1
kernel32.WriteFileEx(self.Pipe_handle, msg, len(msg), self.lpOverlapped_w, self.WriteFileEx_Completion_Routine)
self.logger.log('Lecteur - message transmis: %s' % msg.value, 2)
self.Write_pending = True
if not self.Read_pending:
ctypes.memset(msg_buffer, 0, 15001)
kernel32.ReadFileEx(self.Pipe_handle, msg_buffer, 15000, self.lpOverlapped_r, self.ReadFileEx_Completion_Routine)
self.Read_pending = True
w = kernel32.WaitForSingleObjectEx(self.Cmd_Event, -1, True)
if w == 0x000000C0 or w == 0:
if self.Write_pending:
self.NumberOfBytesTransferred_w.value = 0
if kernel32.GetOverlappedResultEx(self.Pipe_handle, self.lpOverlapped_w, ctypes.byref(self.NumberOfBytesTransferred_w), 1, False) != 0:
kernel32.ResetEvent(self.lpOverlapped_w.contents.hEvent)
self.Write_pending = False
self.logger.log('Lecteur - écrit dans le tuyau: %d octets' % self.NumberOfBytesTransferred_w.value, 2)
self.NumberOfBytesTransferred_r.value = 0
if kernel32.GetOverlappedResultEx(self.Pipe_handle, self.lpOverlapped_r, ctypes.byref(self.NumberOfBytesTransferred_r), 1, False) != 0:
kernel32.ResetEvent(self.lpOverlapped_r.contents.hEvent)
self.Read_pending = False
self.logger.log('Lecteur - lu depuis le tuyau: %d octets' % self.NumberOfBytesTransferred_r.value, 2)
if not self.Read_pending:
l = self.NumberOfBytesTransferred_r.value
if l != 0:
msg_buffer[l] = b"\x00"
msg_list = ((msg_chunk + msg_buffer[:l+1].decode('UTF-8')) if msg_chunk else msg_buffer[:l+1].decode('UTF-8')).splitlines()
self.Msg_buffer.extend(msg_list[:-1])
msg_chunk = msg_list[-1][:-1]
self.Msg_event.set()
self.Msg_buffer[0] = "quit"
self.Msg_event.set()
msg = ctypes.create_string_buffer(json.dumps({'command': ['quit'], 'request_id': request_id}).encode('UTF-8'))
msg[len(msg) - 1] = b'\n'
kernel32.CancelIoEx(self.Pipe_handle, None)
kernel32.WriteFileEx(self.Pipe_handle, msg, len(msg), self.lpOverlapped_w, self.WriteFileEx_Completion_Routine)
self.logger.log('Lecteur - message transmis: %s' % msg.value, 1)
kernel32.CloseHandle(self.Pipe_handle)
def stop(self):
self.Cmd_buffer[0] = "quit"
kernel32.SetEvent(self.Cmd_Event)
class DLNAArgument:
def __init__(self):
self.Name = None
self.Direction = None
self.Event = None
self.Type = None
self.AllowedValueList = None
self.AllowedValueRange = None
self.DefaultValue = None
class DLNAAction:
def __init__(self):
self.Name = None
self.Arguments = []
class DLNAService:
def __init__(self):
self.Type = None
self.Id = None
self.ControlURL = None
self.SubscrEventURL = None
self.DescURL = None
self.Actions = []
self.EventThroughLastChange = None
class DLNASearchServer():
def __init__(self, renderer, verbosity):
self.logger = log_event(verbosity)
self.Renderer = renderer
self.__shutdown_request = False
self.__is_shut_down = threading.Event()
self.__is_shut_down.set()
self.Sockets = ()
def handle(self, i, msg, addr):
sock = self.Sockets[i]
ip = self.Renderer.Ips[i]
req = HTTPMessage((msg, sock))
if req.method != 'M-SEARCH':
return
if req.header('ST', '').lower() not in (s.lower() for s in ('ssdp:all', 'upnp:rootdevice', 'urn:schemas-upnp-org:device:MediaRenderer:1', 'urn:schemas-upnp-org:service:AVTransport:1', UDN)):
return
self.logger.log('Réception, sur l\'interface %s, d\'un message de recherche de renderer de %s:%s' % (ip, *addr), 2)
if self.__shutdown_request or self.__is_shut_down.is_set():
return
resp = 'HTTP/1.1 200 OK\r\n' \
'Cache-Control: max-age=1800\r\n' \
'Date: %s\r\n' \
'Ext: \r\n' \
'Location: %s\r\n' \
'Server: DLNAmpvRenderer\r\n' \
'ST: %s\r\n' \
'USN: %s::%s\r\n' \
'Content-Length: 0\r\n' \
'\r\n' % (email.utils.formatdate(time.time(), usegmt=True), (self.Renderer.DescURL % ip), req.header('ST'), UDN, req.header('ST'))
try:
sock.sendto(resp.encode('ISO-8859-1'), addr)
self.logger.log('Envoi, sur l\'interface %s, de la réponse au message de recherche de renderer de %s:%s' % (ip, *addr), 2)
except:
self.logger.log('Échec de l\'envoi, sur l\'interface %s, de la réponse au message de recherche de renderer de %s:%s' % (ip, *addr), 2)
def serve_forever(self):
self.__is_shut_down.clear()
self.__shutdown_request = True
self.Sockets = tuple(socket.socket(type=socket.SOCK_DGRAM) for ip in self.Renderer.Ips)
with selectors.DefaultSelector() as selector:
for i in range(len(self.Renderer.Ips)):
sock = self.Sockets[i]
ip = self.Renderer.Ips[i]
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((ip, 1900))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, struct.pack('4s4s', socket.inet_aton('239.255.255.250'), socket.inet_aton(ip)))
selector.register(sock, selectors.EVENT_READ, i)
self.__shutdown_request = False
self.logger.log('Mise en place de l\'écoute de recherche de renderer sur l\'interface %s' % ip, 2)
except:
self.logger.log('Échec de la mise en place de l\'écoute de recherche de renderer sur l\'interface %s' % ip, 1)
while not self.__shutdown_request:
ready = selector.select(0.5)
if self.__shutdown_request:
break
for r in ready:
try:
self.handle(r[0].data, *self.Sockets[r[0].data].recvfrom(8192))
except:
pass
self.__shutdown_request = False
self.__is_shut_down.set()
def shutdown(self):
self.__shutdown_request = True
for sock in self.Sockets:
try:
sock.close()
except:
pass
self.__is_shut_down.wait()
def __enter__(self):
return self
def __exit__(self, *args):
pass
class DLNARequestServer(socketserver.ThreadingTCPServer):
allow_reuse_address = True
request_queue_size = 100
block_on_close = False
def __init__(self, *args, verbosity, **kwargs):
self.logger = log_event(verbosity)
super().__init__(*args, **kwargs)
self.__dict__['_BaseServer__is_shut_down'].set()
def process_request_thread(self, request, client_address):
try:
self.logger.log('Connexion de %s:%s sur l\'interface %s' % (*client_address, request.getsockname()[0]), 2)
except:
pass
super().process_request_thread(request, client_address)
def shutdown(self):
super().shutdown()
self.socket.close()
def server_close(self):
pass
class DLNARequestHandler(socketserver.BaseRequestHandler):
def __init__(self, *args, renderer, **kwargs):
self.Renderer = renderer
try:
super().__init__(*args, **kwargs)
except:
pass
def handle(self):
if not self.Renderer.is_request_manager_running:
return
req = HTTPMessage(self.request)
if not self.Renderer.is_request_manager_running or not req.method:
return
self.server.logger.log('Réception de la requête %s' % req.method, 2)
if req.method == 'OPTIONS':
resp = 'HTTP/1.1 200 OK\r\n' \
'Content-Length: 0\r\n' \
'Date: ' + email.utils.formatdate(time.time(), usegmt=True) + '\r\n' \
'Connection: close\r\n' \
'Server: DLNAmpvRenderer\r\n' \
'Allow: OPTIONS, HEAD, GET, POST, SUBSCRIBE, UNSUBSCRIBE\r\n' \
'\r\n'
try:
self.request.sendall(resp.encode('ISO-8859-1'))
self.server.logger.log('Réponse à la requête %s' % req.method, 2)
except:
self.server.logger.log('Échec de la réponse à la requête %s' % req.method, 2)
elif req.method in ('GET', 'HEAD'):
resp = 'HTTP/1.1 200 OK\r\n' \
'Content-Type: ##type##\r\n' \
'Content-Length: ##len##\r\n' \
'Date: ' + email.utils.formatdate(time.time(), usegmt=True) + '\r\n' \
'Connection: close\r\n' \
'Server: DLNAmpvRenderer\r\n' \
'\r\n'
resp_err = 'HTTP/1.1 404 File not found\r\n' \
'Content-Length: 0\r\n' \
'Date: ' + email.utils.formatdate(time.time(), usegmt=True) + '\r\n' \
'Server: DLNAmpvRenderer\r\n' \
'Connection: close\r\n' \
'\r\n'
resp_body = b''
self.server.logger.log('Réception de la requête %s %s' % (req.method, req.path), 2)
dict_scpd = {'/D_S': 'Device_SCPD', '/RC_S': 'RenderingControl_SCPD', '/CM_S': 'ConnectionManager_SCPD', '/AVT_S': 'AVTransport_SCPD'}
if req.path.upper() in dict_scpd:
resp_body = (getattr(DLNARenderer, dict_scpd[req.path]) % (() if req.path != '/AVT_S' else ((DLNARenderer.AVTransport_SCPD_Gapless if self.Renderer.Gapless else ''),))).encode('utf-8')
try:
if req.method == 'GET':
self.request.sendall(resp.replace('##type##', 'text/xml; charset="utf-8"').replace('##len##', str(len(resp_body))).encode('ISO-8859-1') + resp_body)
else:
self.request.sendall(resp.replace('##type##', 'text/xml; charset="utf-8"').replace('##len##', str(len(resp_body))).encode('ISO-8859-1'))
self.server.logger.log('Réponse à la requête %s: %s' % (req.method, dict_scpd[req.path]), 1)
except:
self.server.logger.log('Échec de la réponse à la requête %s: %s' % (req.method, dict_scpd[req.path]), 1)
elif req.path.lower() == '/icon.png':
resp_body = self.Renderer.Icon
try:
if req.method == 'GET':
self.request.sendall(resp.replace('##type##', 'image/png').replace('##len##', str(len(resp_body))).encode('ISO-8859-1') + resp_body)