Repository navigation
Expand file tree
/
Copy pathtwitch.py
More file actions
2888 lines (2662 loc) · 123 KB
/
Copy pathtwitch.py
File metadata and controls
2888 lines (2662 loc) · 123 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
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
import base64
import collections
import hashlib
import json
import math
import os
import random
import re
import socket
import ssl
import struct
import threading
import time
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")
def read(path, default=None):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()
except OSError:
return default
def belacoder_running():
try:
for d in os.listdir("/proc"):
if d.isdigit() and (read(f"/proc/{d}/comm", "") or "").strip() == "belacoder":
return True
except OSError:
pass
return False
class TwitchStore:
NAME_RE = re.compile(r"[A-Za-z0-9_]{3,25}")
TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{20,100}")
DEFAULT_MESSAGE = "Akkustand niedrig, bitte Akku wechseln: {Kamera} ({Prozent} %)"
DEFAULTS = {"enabled": False, "login": "", "token": "", "channel": "", "threshold": 10, "message": DEFAULT_MESSAGE, "only_live": True, "via_account": False}
def __init__(self, path):
self.path = path
self.lock = threading.Lock()
self.data = dict(self.DEFAULTS)
self.warned = {}
self.account = None
self.bot = None
try:
with open(path) as f:
saved = json.load(f)
except (OSError, ValueError):
saved = None
if isinstance(saved, dict):
self._adopt(saved)
@classmethod
def _name(cls, v, error):
if not isinstance(v, str):
raise ValueError(error)
v = v.strip()
if v and not cls.NAME_RE.fullmatch(v):
raise ValueError(error)
return v.lower()
@classmethod
def _token(cls, v):
if not isinstance(v, str):
raise ValueError("Token: 20 bis 100 Zeichen, nur Buchstaben, Ziffern, _ und -")
v = v.strip()
if not v:
return ""
if v[:6].lower() == "oauth:":
v = v[6:]
if not cls.TOKEN_RE.fullmatch(v):
raise ValueError("Token: 20 bis 100 Zeichen, nur Buchstaben, Ziffern, _ und -")
return v
@staticmethod
def _threshold(v):
if isinstance(v, float) and v.is_integer():
v = int(v)
if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 50:
raise ValueError("Warnen bei: Zahl von 1 bis 50")
return v
@staticmethod
def _message(v):
if not isinstance(v, str) or not 1 <= len(v.strip()) <= 300:
raise ValueError("Nachricht: 1 bis 300 Zeichen")
v = v.strip()
if any(not ch.isprintable() for ch in v):
raise ValueError("Nachricht: keine Sonderzeichen oder Zeilenumbrüche")
if v[0] in "/.":
raise ValueError("Nachricht: darf nicht mit / oder . beginnen")
return v
ERR_CHANNEL = "Kanal: 3 bis 25 Zeichen, nur Buchstaben, Ziffern und _"
ERR_LOGIN = "Bot-Konto: 3 bis 25 Zeichen, nur Buchstaben, Ziffern und _"
ERR_MISSING = "Bitte Kanal, Bot-Konto und Token eintragen"
def _adopt(self, saved):
for key, check in (("login", lambda v: self._name(v, self.ERR_LOGIN)), ("channel", lambda v: self._name(v, self.ERR_CHANNEL)), ("token", self._token),
("threshold", self._threshold), ("message", self._message)):
if key in saved:
try:
self.data[key] = check(saved[key])
except ValueError:
pass
if isinstance(saved.get("only_live"), bool):
self.data["only_live"] = saved["only_live"]
d = self.data
d["via_account"] = saved.get("via_account") is True
d["enabled"] = saved.get("enabled") is True and (bool(d["channel"] and d["login"] and d["token"]) or d["via_account"])
w = saved.get("warned")
if isinstance(w, dict):
self.warned = {k: float(t) for k, t in w.items() if isinstance(k, str) and KEY_RE.match(k) and isinstance(t, (int, float)) and not isinstance(t, bool)
and math.isfinite(t) and t > 0}
def _write(self, data, warned):
os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
tmp = self.path + ".tmp"
try:
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
os.fchmod(f.fileno(), 0o600)
json.dump(dict(data, warned=warned), f, indent=1)
os.replace(tmp, self.path)
except OSError:
try:
os.remove(tmp)
except OSError:
pass
raise
def set(self, req):
if not isinstance(req, dict):
raise ValueError("Ungültige Anfrage")
with self.lock:
new = dict(self.data)
for key in ("enabled", "only_live"):
if key in req:
if not isinstance(req[key], bool):
raise ValueError("ja oder nein")
new[key] = req[key]
if "channel" in req:
new["channel"] = self._name(req["channel"], self.ERR_CHANNEL)
if "login" in req:
new["login"] = self._name(req["login"], self.ERR_LOGIN)
if "token" in req:
new["token"] = self._token(req["token"]) or new["token"]
if "threshold" in req:
new["threshold"] = self._threshold(req["threshold"])
if "message" in req:
new["message"] = self._message(req["message"])
acc = self.account.login() if self.account else ""
bot = self.bot.login() if self.bot else ""
manual = bool(new["channel"] and new["login"] and new["token"])
if new["enabled"] and not (manual or acc or (bot and new["channel"])):
raise ValueError(self.ERR_MISSING)
new["via_account"] = bool(new["enabled"] and not manual)
try:
self._write(new, self.warned)
except OSError:
raise RuntimeError("Die Einstellungen konnten nicht gespeichert werden")
self.data = new
def public(self):
with self.lock:
d = self.data
acc = self.account.login() if self.account else ""
bot = self.bot.login() if self.bot else ""
return {"enabled": d["enabled"], "channel": d["channel"] or acc, "login": d["login"], "token_set": bool(d["token"]), "threshold": d["threshold"],
"message": d["message"], "only_live": d["only_live"], "account": acc, "bot": bot}
def settings(self):
with self.lock:
d = dict(self.data)
acc = self.account.login() if self.account else ""
if acc:
tok = self.account.token()
d["login"], d["token"] = acc, tok
d["channel"] = d["channel"] or acc
return d
def channel_name(self):
with self.lock:
ch = self.data["channel"]
return ch or (self.account.login() if self.account else "")
def notify_settings(self):
d = self.settings()
bot = self.bot.login() if self.bot else ""
if bot:
d["login"], d["token"] = bot, self.bot.token()
elif self.bot and self.bot.state == "abgelaufen":
d["token"] = ""
return d
def warned_keys(self):
with self.lock:
return list(self.warned)
def is_warned(self, key):
with self.lock:
return key in self.warned
def _flush(self):
try:
self._write(self.data, self.warned)
except OSError:
pass
def mark_warned(self, key, when):
with self.lock:
self.warned[key] = float(when)
self._flush()
def unwarn(self, key):
with self.lock:
if self.warned.pop(key, None) is not None:
self._flush()
class _IrcLines:
MAX = 16384
def __init__(self, sock, clock):
self.sock, self.clock, self.buf = sock, clock, b""
def get(self, until):
while True:
i = self.buf.find(b"\n")
if i >= 0:
line, self.buf = self.buf[:i], self.buf[i + 1:]
return line.rstrip(b"\r").decode("utf-8", "replace")
if len(self.buf) > self.MAX:
raise EOFError
left = until - self.clock()
if left <= 0:
return None
self.sock.settimeout(left)
try:
chunk = self.sock.recv(4096)
except socket.timeout:
return None
if not chunk:
raise EOFError
self.buf += chunk
class TwitchChat:
HOST, PORT = "irc.chat.twitch.tv", 6697
MAX_BYTES = 450
OK = "Gesendet"
NO_CONNECT = "Keine Verbindung zu Twitch"
NO_TLS = "Sichere Verbindung zu Twitch nicht möglich (Zertifikat oder Uhrzeit der Box prüfen)"
LOGIN_FAILED = "Anmeldung fehlgeschlagen (Token ungültig oder ohne Recht zum Schreiben)"
NO_ANSWER = "Keine Antwort von Twitch (Zeitüberschreitung)"
CLOSED = "Twitch hat die Verbindung beendet"
NOT_ALLOWED = "Der Bot darf im Kanal nicht schreiben (z. B. nur F
10BC8
ollower)"
LOGIN_NOTICE_RE = re.compile(r"authentication failed|login unsuccessful|improperly formatted", re.I)
def __init__(self, host=None, port=None, tls=True, context=None, connect_timeout=10.0, total=15.0, notice_wait=2.0, clock=time.monotonic, paths=None):
self.paths = paths or ChatPaths()
self.host, self.port, self.tls, self.context = host or self.HOST, port or self.PORT, tls, context
self.connect_timeout, self.total, self.notice_wait, self.clock = connect_timeout, total, notice_wait, clock
@staticmethod
def clean_text(text):
t = "".join(" " if unicodedata.category(ch) == "Zs" else ch for ch in text).strip()
bad = ("Cc", "Zl", "Zp", "Cs", "Co", "Cn")
if not t or any(unicodedata.category(ch) in bad or ch in "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069" for ch in t) or t[0] in "/.":
return None
raw = t.encode("utf-8")
return t if len(raw) <= TwitchChat.MAX_BYTES else raw[:TwitchChat.MAX_BYTES].decode("utf-8", "ignore").rstrip()
@staticmethod
def _parse(line):
if line.startswith("@"):
line = line.partition(" ")[2]
if line.startswith(":"):
line = line.partition(" ")[2]
cmd, _, rest = line.partition(" ")
return cmd.upper(), rest
@staticmethod
def _notice_text(rest):
return rest[1:] if rest.startswith(":") else rest.partition(" :")[2]
@staticmethod
def _scrub(text, token):
text = text.replace(token, "…")
text = " ".join("".join(ch if ch.isprintable() else " " for ch in text).split())
return text[:120] + ("…" if len(text) > 120 else "")
@staticmethod
def _pong(sock, rest):
arg = "".join(ch for ch in rest if ch.isprintable())[:100]
sock.sendall(b"PONG " + arg.encode("utf-8") + b"\r\n")
def send(self, login, token, channel, text):
try:
return self._send(login, token, channel, text)
except Exception:
return False, "unbekannter Fehler"
def _send(self, login, token, channel, text):
if not all(isinstance(v, str) for v in (login, token, channel, text)):
return False, "Ungültige Anfrage"
login, channel, body = login.lower(), channel.lower(), self.clean_text(text)
if body is None or not (TwitchStore.NAME_RE.fullmatch(login) and TwitchStore.NAME_RE.fullmatch(channel) and TwitchStore.TOKEN_RE.fullmatch(token)):
return False, "Ungültige Anfrage"
until = self.clock() + self.total
try:
sock, _ = self.paths.connect(self.host, self.port, timeout=max(0.1, min(self.connect_timeout, until - self.clock())))
except OSError:
return False, self.NO_CONNECT
try:
if self.tls:
try:
sock = (self.context or ssl.create_default_context()).wrap_socket(sock, server_hostname=self.host)
except ssl.SSLError:
return False, self.NO_TLS
except OSError:
return False, self.NO_CONNECT
return self._talk(sock, login, token, channel, body, until)
except (EOFError, OSError):
return False, self.CLOSED
finally:
try:
sock.close()
except OSError:
pass
def _talk(self, sock, login, token, channel, body, until):
rd = _IrcLines(sock, self.clock)
sock.settimeout(max(0.1, until - self.clock()))
sock.sendall(b"PASS oauth:" + token.encode("ascii") + b"\r\nNICK " + login.encode("ascii") + b"\r\n")
while True:
line = rd.get(until)
if line is None:
return False, self.NO_ANSWER
cmd, rest = self._parse(line)
if cmd == "001":
break
if cmd == "PING":
self._pong(sock, rest)
elif cmd in ("464", "465") or (cmd == "NOTICE" and self.LOGIN_NOTICE_RE.search(self._notice_text(rest))):
return False, self.LOGIN_FAILED
chan = channel.encode("ascii")
sock.settimeout(max(0.1, until - self.clock()))
sock.sendall(b"CAP REQ :twitch.tv/commands\r\nJOIN #" + chan + b"\r\nPRIVMSG #" + chan + b" :" + body.encode("utf-8") + b"\r\n")
notice, end = None, min(self.clock() + self.notice_wait, until)
try:
while notice is None:
line = rd.get(end)
if line is None:
break
cmd, rest = self._parse(line)
if cmd == "PING":
self._pong(sock, rest)
elif cmd == "NOTICE":
notice = self._scrub(self._notice_text(rest), token)
except EOFError:
pass
try:
sock.sendall(b"QUIT\r\n")
except OSError:
pass
if notice is None:
return True, self.OK
return False, self.NOT_ALLOWED + (": " + notice if notice else "")
def _ascii_digits(v):
return isinstance(v, str) and v.isascii() and v.isdigit()
class ChatPaths:
def __init__(self, sources=None, clock=time.monotonic, links_file="/run/pipbox-send/srtla-links.txt"):
self.sources, self.clock, self.links_file = sources, clock, links_file
self.bad = {}
self.lock = threading.Lock()
def _quality(self):
out = {}
try:
with open(self.links_file, errors="replace") as f:
lines = f.read()[-6000:].splitlines()
except OSError:
return out
for ln in lines:
m = re.search(r"links: (\d+\.\d+\.\d+\.\d+) .*?guete=(-?\d+) (genutzt|reserve)", ln)
if m:
g = int(m.group(2))
out[m.group(1)] = (9999 if g < 0 else g) + (0 if m.group(3) == "genutzt" else 100000)
return out
def order(self):
try:
srcs = [x for x in (self.sources() if self.sources else []) if isinstance(x, str) and x]
except Exception:
srcs = []
q = self._quality()
now = self.clock()
with self.lock:
good = [x for x in srcs if self.bad.get(x, 0) <= now]
bad = [x for x in srcs if x not in good]
good.sort(key=lambda x: q.get(x, 50000))
return good + [None] + bad
def fail(self, src, hold=300.0):
if src:
with self.lock:
self.bad[src] = self.clock() + hold
def connect(self, host, port, timeout=6.0):
last = OSError()
for src in self.order():
try:
return socket.create_connection((host, port), timeout=timeout, source_address=(src, 0) if src else None), src
except socket.gaierror as e:
raise e
except OSError as e:
last = e
self.fail(src, 120.0)
raise last
def request(self, method, url, data=None, headers=None, timeout=15.0, limit=200_000, prefer=False):
import http.client
import urllib.parse
u = urllib.parse.urlsplit(url)
cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
target = u.path + ("?" + u.query if u.query else "")
order = self.order()
if prefer is not False and prefer in order:
order.remove(prefer)
order.insert(0, prefer)
for src in order:
conn = None
try:
conn = cls(u.hostname, u.port, timeout=timeout, source_address=(src, 0) if src else None)
try:
conn.connect()
except socket.gaierror:
return 0, b""
except (OSError, http.client.HTTPException, ValueError):
self.fail(src, 120.0)
continue
try:
conn.request(method, target, body=data, headers=headers or {})
r = conn.getresponse()
status = r.status
try:
return status, r.read(limit)
except (OSError, http.client.HTTPException, ValueError):
self.fail(src, 120.0)
if once:
return status, b""
raise
except (OSError, http.client.HTTPException, ValueError):
self.fail(src, 120.0)
if once:
return -1, b""
except (OSError, http.client.HTTPException, ValueError):
self.fail(src, 120.0)
finally:
try:
if conn:
conn.close()
except OSError:
pass
return 0, b""
class TwitchLogin:
CLIENT_ID = "a9w1hzb4d6nu70re8wxt6rpyxths35"
ID_BASE = "https://id.twitch.tv/oauth2/"
SCOPES = "chat:read chat:edit user:write:chat"
CMD_SCOPES = ("channel:manage:vips channel:manage:moderators moderator:manage:chat_settings moderator:manage:announcements "
"channel:manage:raids channel:manage:broadcast")
MOD_BASE = "moderator:manage:banned_users moderator:manage:chat_messages"
MOD_SCOPES = MOD_BASE + " " + CMD_SCOPES
EVENT_SCOPES = "moderator:read:followers channel:read:redemptions"
SCOPES_MOD = "chat:read chat:edit user:write:chat " + MOD_SCOPES
GRANT = "urn:ietf:params:oauth:grant-type:device_code"
OWNER_RE = re.compile(r"[0-9a-f]{64}")
KEY_RE = re.compile(r"[A-Za-z0-9_-]{32,128}")
MAX_OWNERS = 5
DEMO_LOGIN = "demo_streamer"
ERR_NOT_OWNER = "Das ist nicht das Konto des Streamers dieser Box"
ERR_NO_CHANNEL = "Bitte zuerst eintragen, auf welchem Konto gestreamt wird (Kanal)"
REFRESH_BEFORE = 600
KEEP_EVERY = 30.0
ERR_NET = "Keine Verbindung zu Twitch"
ERR_DENIED = "Die Anmeldung wurde abgelehnt oder ist abgelaufen"
def __init__(self, path, client_id=None, id_base=None, clock=time.time, sleep=time.sleep, demo=False, paths=None):
self.paths = paths or ChatPaths()
self.path, self.client_id = path, client_id or self.CLIENT_ID
self.base = id_base or self.ID_BASE
self.clock, self.sleep, self.demo = clock, sleep, demo
self.lock = threading.RLock()
self.tokens = None
self.pending = None
self.state, self.error = "aus", ""
self.gen = 0
self.claim_fail = None
try:
with open(path) as f:
saved = json.load(f)
if isinstance(saved, dict) and isinstance(saved.get("access"), str) and isinstance(saved.get("refresh"), str):
self.tokens = {"access": saved["access"], "refresh": saved["refresh"], "expires_at": float(saved.get("expires_at", 0)),
"login": str(saved.get(
10BC8
"login", ""))[:25], "user_id": str(saved.get("user_id", ""))[:20],
"scopes": [str(x)[:60] for x in saved.get("scopes", [])][:30], "mod_off": saved.get("mod_off") is True,
"owners": [x for x in saved.get("owners", []) if isinstance(x, str) and self.OWNER_RE.fullmatch(x)][:self.MAX_OWNERS]}
self.state = "angemeldet"
except (OSError, ValueError, TypeError):
pass
def _call(self, url, fields=None, headers=None, >
import urllib.parse
data = urllib.parse.urlencode(fields).encode() if fields is not None else None
hdr = dict(headers or {}, **{"User-Agent": "irl4you-box"})
if data is not None:
hdr["Content-Type"] = "application/x-www-form-urlencoded"
status, body = self.paths.request("POST" if data is not None else "GET", url, data, hdr, >
try:
out = json.loads(body.decode("utf-8", "replace") or "{}")
except ValueError:
out = {}
return status, out if isinstance(out, dict) else {}
def _write(self, tokens=None):
os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
tmp = self.path + ".tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
with os.fdopen(fd, "w") as f:
os.fchmod(f.fileno(), 0o600)
json.dump(tokens if tokens is not None else self.tokens, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, self.path)
try:
dfd = os.open(os.path.dirname(os.path.abspath(self.path)), os.O_RDONLY)
try:
os.fsync(dfd)
finally:
os.close(dfd)
except OSError:
pass
except OSError:
try:
os.remove(tmp)
except OSError:
pass
raise
def status(self):
if self.demo:
with self.lock:
self._demo_step()
t, p, state = self.tokens, self.pending, self.state
scopes = list((t or {}).get("scopes", []))
has = bool(self.MOD_SCOPES) and all(x in scopes for x in self.MOD_SCOPES.split())
ev = all(x in scopes for x in self.EVENT_SCOPES.split())
out = {"state": state, "login": (t or {}).get("login", ""), "scopes": scopes, "error": self.error,
"mod": has and not (t or {}).get("mod_off"),
"mod_scope": has,
"events": ev,
"helix_chat": "user:write:chat" in scopes}
if p and state == "wartet":
out.update(code=p["user_code"], uri=p["uri"], expires_in=max(0, int(p["expires_at"] - self.clock())))
return out
def ready(self):
return bool(self.tokens)
def login(self):
t = self.tokens
return t.get("login", "") if t else ""
def user_id(self):
t = self.tokens
return t.get("user_id", "") if t else ""
def token(self):
t = self.tokens
if not t:
return ""
if t["expires_at"] - self.clock() < 60:
with self.lock:
if self.tokens and self.tokens["expires_at"] - self.clock() < 60:
self.refresh()
t = self.tokens
if t and t["expires_at"] - self.clock() > 0:
return t["access"]
return ""
def scopes_for(self, mod=False, events=False, everything=False):
want = self.SCOPES.split()
have = set(((self.tokens or {}).get("scopes")) or [])
if everything:
mod = events = True
for flag, group in ((mod, self.MOD_SCOPES), (events, self.EVENT_SCOPES)):
for sc in group.split():
if (flag or sc in have) and sc not in want:
want.append(sc)
return " ".join(want)
@classmethod
def owner_hash(cls, key):
if not isinstance(key, str) or not cls.KEY_RE.fullmatch(key):
return None
return hashlib.sha256(key.encode("ascii")).hexdigest()
def is_owner(self, key):
h = self.owner_hash(key)
t = self.tokens
return bool(h and t and h in (t.get("owners") or []))
def start(self, mod=False, events=False, everything=False, owner_key=None, claim=False, expect=None):
scopes = self.scopes_for(mod, events, everything)
owner = self.owner_hash(owner_key)
with self.lock:
if self.claim_fail and self.claim_fail.get("owner") == owner:
self.claim_fail = None
if (self.state == "wartet" and self.pending and self.pending["expires_at"] > self.clock() and self.pending.get("scopes") == scopes
and self.pending.get("owner") == owner):
return self.status()
self.gen += 1
gen = self.gen
self.error = ""
if self.demo:
self.pending = {"device_code": "demo", "user_code": "ABCD-EFGH", "uri": "https://www.twitch.tv/activate?device-code=ABCDEFGH",
"expires_at": self.clock() + 1800, "interval": 5, "since": self.clock(), "scopes": scopes, "owner": owner, "claim": bool(claim),
"expect": str(expect or "").lower()[:25]}
self.state = "wartet"
return self.status()
st, d = self._call(self.base + "device", {"client_id": self.client_id, "scopes": scopes})
if st != 200 or not all(isinstance(d.get(k), str) for k in ("device_code", "user_code", "verification_uri")):
self.state, self.error = ("angemeldet" if self.tokens else "fehler", self.ERR_NET if st == 0 else "Twitch hat die Anmeldung nicht angenommen")
raise ValueError(self.error)
try:
interval = max(2, min(30, int(d.get("interval", 5))))
expires = max(60, min(3600, int(d.get("expires_in", 1800))))
except (TypeError, ValueError):
interval, expires = 5, 1800
uri = d["verification_uri"][:300]
if not re.match(r"https://(www\.|id\.)?twitch\.tv/", uri):
uri = "https://www.twitch.tv/activate"
self.pending = {"device_code": d["device_code"], "user_code": d["user_code"][:20], "uri": uri,
"expires_at": self.clock() + expires, "interval": interval, "scopes": scopes, "owner": owner, "claim": bool(claim),
"expect": str(expect or "").lower()[:25]}
self.state = "wartet"
threading.Thread(target=self._poll, args=(gen,), daemon=True).start()
return self.status()
def cancel(self):
with self.lock:
self.gen += 1
self.pending = None
if self.state == "wartet":
self.state = "angemeldet" if self.tokens else "aus"
return self.status()
def _poll(self, gen):
while True:
with self.lock:
p = self.pending
if gen != self.gen or not p or self.state != "wartet":
return
if p["expires_at"] <= self.clock():
self.state, self.error, self.pending = ("angemeldet" if self.tokens else "fehler"), self.ERR_DENIED, None
return
wait, device, scopes = p["interval"], p["device_code"], p.get("scopes", self.SCOPES)
self.sleep(wait)
st, d = self._call(self.base + "token", {"client_id": self.client_id, "scopes": scopes, "device_code": device, "grant_type": self.GRANT}, >
with self.lock:
if gen != self.gen or self.state != "wartet":
if st == 200 and isinstance(d.get("access_token"), str):
self._call(self.base + "revoke", {"client_id": self.client_id, "token": d["access_token"]})
return
if st == 200 and isinstance(d.get("access_token"), str) and isinstance(d.get("refresh_token"), str):
self._adopt(d)
return
msg = str(d.get("message", "")).lower()
if st == 400 and "authorization_pending" in msg:
continue
if st == 400 and "slow_down" in msg:
self.pending["interval"] = min(30, self.pending["interval"] + 5)
continue
if st <= 0 or st >= 500:
continue
if st == 429:
self.pending["interval"] = min(30, self.pending["interval"] + 5)
continue
self.state, self.error, self.pending = ("angemeldet" if self.tokens else "fehler"), self.ERR_DENIED, None
return
def _adopt(self, d):
scopes = d.get("scope")
scopes = [str(x)[:60] for x in scopes][:30] if isinstance(scopes, list) else self.SCOPES.split()
try:
expires = max(60.0, float(d.get("expires_in", 14400)))
except (TypeError, ValueError):
expires = 14400.0
old = self.tokens or {}
pend = (self.pending or {}).get("owner")
want = (self.pending or {}).get("expect") or old.get("login")
if (self.pending or {}).get("claim") and want:
st0, v0 = self._call(self.base + "validate", None, {"Authorization": "OAuth " + d["access_token"]})
who = v0.get("login", "").lower() if st0 == 200 and isinstance(v0.get("login"), str) else ""
if who != want:
self._call(self.base + "revoke", {"client_id": self.client_id, "token": d["access_token"]})
self.claim_fail = {"owner": pend, "error": self.ERR_NOT_OWNER}
self.pending, self.state, self.error = None, ("angemeldet" if self.tokens else "aus"), ""
return
t = {"access": d["access_token"], "refresh": d["refresh_token"], "expires_at": self.clock() + expires, "scopes": scopes,
"login": old.get("login", ""), "user_id": old.get("user_id", ""), "mod_off": old.get("mod_off") is True,
"owners": list(old.get("owners") or [])}
werr = False
try:
self._write(t)
except OSError:
werr = True
st, v = self._call(self.base + "validate", None, {"Authorization": "OAuth " + t["access"]})
changed = False
if st == 200 and isinstance(v.get("login"), str):
new = (v["login"][:25].lower(), str(v.get("user_id", ""))[:20], [str(x)[:60] for x in v["scopes"]][:30] if isinstance(v.get("scopes"), list) else scopes)
changed = new != (t["login"], t["user_id"], t["scopes"])
if t["login"] and new[0] != t["login"]:
t["owners"] = []
t["login"], t["user_id"], t["scopes"] = new
if pend and pend not in t["owners"]:
t["owners"] = (t["owners"] + [pend])[-self.MAX_OWNERS:]
changed = True
self.tokens = t
self.pending, self.state, self.error = None, "angemeldet", ""
if changed:
try:
self._write()
werr = False
except OSError:
werr = True
if werr:
self.error = "Die Anmeldung konnte nicht gespeichert werden"
def refresh(self):
with self.lock:
if not self.tokens:
return False
if self.clock() < getattr(self, "next_try", 0.0):
return False
st, d = self._call(self.base + "token", {"client_id": self.client_id, "grant_type": "refresh_token", "refresh_token": self.tokens["refresh"]}, >
if st == 200 and isinstance(d.get("access_token"), str) and isinstance(d.get("refresh_token"), str):
self.fails, self.next_try = 0, 0.0
self._adopt(d)
return True
if st <= 0 or st == 429 or st >= 500:
self.fails = getattr(self, "fails", 0) + 1
self.next_try = self.clock() + min(300.0, 15.0 * 2 ** min(self.fails, 5))
return False
if st in (400, 401):
keep = self.tokens.get("login", "")
self.tokens, self.pending, self.state = None, None, "abgelaufen"
self.error = keep
try:
os.remove(self.path)
except OSError:
pass
return False
def keep(self):
while True:
try:
if self.tokens and self.tokens["expires_at"] - self.clock() < self.REFRESH_BEFORE:
with self.lock:
if self.tokens and self.tokens["expires_at"] - self.clock() < self.REFRESH_BEFORE:
self.refresh()
except Exception:
pass
self.sleep(self.KEEP_EVERY)
def set_mod(self, on):
with self.lock:
t = self.tokens
if not t:
raise ValueError("Zuerst mit Twitch anmelden")
has = bool(self.MOD_SCOPES) and all(x in t.get("scopes", []) for x in self.MOD_SCOPES.split())
if on and not has:
raise ValueError("Moderation braucht eine neue Anmeldung bei Twitch")
t["mod_off"] = not on
try:
self._write()
except OSError:
pass
return self.status()
def refresh_now(self):
with self.lock:
self.next_try = 0.0
return bool(self.tokens) and self.refresh()
def logout(self):
with self.lock:
self.gen += 1
t = self.tokens
self.tokens, self.pending, self.state, self.error = None, None, "aus", ""
try:
os.remove(self.path)
except OSError:
pass
if t and not self.demo:
self._call(self.base + "revoke", {"client_id": self.client_id, "token": t["access"]})
return self.status()
def _demo_step(self):
if self.state == "wartet" and self.pending and self.clock() - self.pending.get("since", 0) > 6:
self.tokens = {"access": "demo", "refresh": "demo", "expires_at": self.clock() + 14400, "login": self.DEMO_LOGIN, "user_id": "1",
"scopes": (self.pending.get("scopes") or self.SCOPES).split(), "owners": [self.pending["owner"]] if self.pending.get("owner") else []}
self.pending, self.state = None, "angemeldet"
class TwitchBotLogin(TwitchLogin):
SCOPES = "chat:read chat:edit"
MOD_SCOPES = EVENT_SCOPES = ""
class TwitchModLogin(TwitchLogin):
MOD_SCOPES = "moderator:manage:banned_users moderator:manage:chat_messages moderator:manage:chat_settings moderator:manage:announcements"
EVENT_SCOPES = CMD_SCOPES = ""
DEMO_LOGIN = "demo_moderator"
class ModSessions:
MAX = 12
def __init__(self, state_dir, demo=False, paths=None, id_base=None, client_id=None, clock=time.time, sleep=time.sleep):
self.dir, self.demo, self.paths = state_dir, demo, paths
self.kw = {"clock": clock, "sleep": sleep}
if id_base:
self.kw["id_base"] = id_base
if client_id:
self.kw["client_id"] = client_id
self.items = {}
self.lock = threading.Lock()
def _path(self, h):
return os.path.join(self.dir, "twitch-mod-%s.json" % h[:32])
def _make(self, h):
return TwitchModLogin(self._path(h), demo=self.demo, paths=self.paths, **self.kw)
def _count(self):
try:
return len([n for n in os.listdir(self.dir) if n.startswith("twitch-mod-") and n.endswith(".json")])
except OSError:
return 0
def get(self, key):
h = TwitchLogin.owner_hash(key)
if not h:
return None
with self.lock:
s = self.items.get(h)
if s is None and os.path.exists(self._path(h)):
s = self.items[h] = self._make(h)
return s
def start(self, key, mod=True):
h = TwitchLogin.owner_hash(key)
if not h:
raise ValueError("Dieser Browser kann sich nicht anmelden")
with self.lock:
s = self.items.get(h)
if s is None:
if self._count() >= self.MAX and not os.path.exists(self._path(h)):
raise ValueError("Es sind schon zu viele Moderatoren angemeldet")
s = self.items[h] = self._make(h)
return s.start(mod=bool(mod), owner_key=key)
def logout(self, key):
s = self.get(key)
if s is not None:
s.logout()
h = TwitchLogin.owner_hash(key)
if h:
with self.lock:
self.items.pop(h, None)
try:
os.remove(self._path(h))
except OSError:
pass
class TwitchAccounts:
NONE_STATUS = {"state": "aus", "login": "", "scopes": [], "error": "", "mod": False, "mod_scope": False, "events": False, "helix_chat": False}
CHECK_TTL = 300.0
def __init__(self, box, sessions, check=None, clock=time.time, store=None):
self.box, self.sessions, self.check, self.clock, self.store = box, sessions, check, clock, store
self.known = {}
self.lock = threading.Lock()
def _is_channel_mod(self, acct):
if self.check is None:
return None
uid = acct.user_id()
now = self.clock()
with self.lock:
hit = self.known.get(uid)
if hit and now - hit[0] < self.CHECK_TTL:
return hit[1]
try:
ans = self.check(uid)
except Exception:
ans = None
with self.lock:
if len(self.known) > 100:
self.known.clear()
self.known[uid] = (now, ans)
return ans
def streamer_name(self):
name = self.box.login()
if name:
return name
if self.store is not None:
with self.store.lock:
return str(self.store.data.get("channel") or "").lower()
return ""
def pick(self, key):
if self.box.ready():
if self.box.is_owner(key):
return "owner", self.box
elif not self.streamer_name():
return "owner", self.box
s = self.sessions.get(key)
if s is not None and self.sessions.demo:
s.status()
if s is not None and s.ready():
if s.status()["mod"] and self._is_channel_mod(s) is not False:
return "mod", s
return "user", s
return "none", None
def status(self, key):
role, acct = self.pick(key)
boxlogin = self.box.login()
if role == "owner":
st = self.box.status()
elif role in ("mod", "user"):
st = acct.status()
if role == "user":
st["mod"] = False
else:
h = TwitchLogin.owner_hash(key)
s = self.sessions.get(key)
st = dict(self.NONE_STATUS, scopes=[])
if s is not None and s.state != "aus":
own = s.status()
st.update({k: own[k] for k in ("state", "error", "code", "uri", "expires_in") if k in own})
elif h and self.box.state == "wartet" and (self.box.pending or {}).get("owner") == h:
own = self.box.status()
st.update({k: own[k] for k in ("state", "code", "uri", "expires_in") if k in own})
cf = self.box.claim_fail
if cf and h and cf.get("owner") == h and st["state"] != "wartet":
st["state"], st["error"] = "fehler", cf["error"]
name = self.streamer_name()
st["role"], st["box_login"], st["streamer"] = role, boxlogin, name
st["need_channel"] = bool(role == "owner" and not self.box.ready() and not name)
return st
class ThirdPartyEmotes:
TTL = 1800.0
RETRY = 300.0
MAX = 8000
NAME_RE = re.compile(r"[A-Za-z0-9_:()!.\-]{1,40}")
BTTV_ID, STV_ID, FFZ_ID = re.compile(r"[0-9a-f]{24}"), re.compile(r"[0-9A-Za-z]{26}"), re.compile(r"[0-9]{1,9}")
URLS = {"bttv": "https://cdn.betterttv.net/emote/%s/2x.webp", "7tv": "https://cdn.7tv.app/emote/%s/2x.webp", "ffz": "https://cdn.frankerfacez.com/emote/%s/2"}
HOSTS = re.compile(r"https://(cdn\.betterttv\.net|cdn\.7tv\.app|cdn\.frankerfacez\.com)/")
def __init__(self, paths=None, fetch=None, clock=time.monotonic):
self.paths, self.fetch, self.clock = paths, fetch or self._fetch, clock
self.lock = threading.Lock()
self.map, self.room, self.until, self.thread = {}, None, 0.0, None
self.users, self.uq, self.uthread, self.on_user = collections.OrderedDict(), collections.deque(), None, None
self.personal = collections.OrderedDict()
self.sthread, self.stouch, self.sroom, self.sretry, self.sfails = None, 0.0, "", 0.0, 0
self.sock_on = paths is not None and fetch is None
You can’t perform that action at this time.