openlive 0.1.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openlive/__init__.py +1 -0
- openlive/__main__.py +5 -0
- openlive/channels.py +53 -0
- openlive/chat.py +418 -0
- openlive/chatview.py +456 -0
- openlive/cli.py +43 -0
- openlive/common.py +64 -0
- openlive/config.py +187 -0
- openlive/demo.py +80 -0
- openlive/google.py +186 -0
- openlive/i18n.py +248 -0
- openlive/kick.py +100 -0
- openlive/mpv/openlive.lua +167 -0
- openlive/mpv/openlive_ui.lua +576 -0
- openlive/net.py +46 -0
- openlive/onboard.py +602 -0
- openlive/player.py +466 -0
- openlive/settings.py +169 -0
- openlive/text.py +56 -0
- openlive/tui.py +955 -0
- openlive/twitch.py +200 -0
- openlive/updater.py +120 -0
- openlive/youtube.py +221 -0
- openlive-0.1.3.dist-info/METADATA +203 -0
- openlive-0.1.3.dist-info/RECORD +28 -0
- openlive-0.1.3.dist-info/WHEEL +4 -0
- openlive-0.1.3.dist-info/entry_points.txt +2 -0
- openlive-0.1.3.dist-info/licenses/LICENSE +21 -0
openlive/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.3"
|
openlive/__main__.py
ADDED
openlive/channels.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Platforms and the user's own channel lists (Kick and YouTube have no 'channels you follow' openlive can read)."""
|
|
2
|
+
from . import config
|
|
3
|
+
|
|
4
|
+
# key, label, colour (soft version of the brand), toggle key
|
|
5
|
+
PLATFORMS = (
|
|
6
|
+
("twitch", "Twitch", "#b39ddb", "t"),
|
|
7
|
+
("kick", "Kick", "#7be36a", "k"),
|
|
8
|
+
("youtube", "YouTube", "#f47c7c", "y"),
|
|
9
|
+
)
|
|
10
|
+
ALL = tuple(p[0] for p in PLATFORMS)
|
|
11
|
+
LABEL = {p[0]: p[1] for p in PLATFORMS}
|
|
12
|
+
COLOR = {p[0]: p[2] for p in PLATFORMS}
|
|
13
|
+
KEY = {p[0]: p[3] for p in PLATFORMS}
|
|
14
|
+
LISTED = ("kick", "youtube") # platforms whose channels live in channels.json
|
|
15
|
+
FILE = "channels.json"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def row_key(r):
|
|
19
|
+
"""Unique id of a row. Twitch keeps the bare login so favourites from 0.1 still match."""
|
|
20
|
+
p = r.get("platform", "twitch")
|
|
21
|
+
return r["login"] if p == "twitch" else f"{p}:{r['login']}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load():
|
|
25
|
+
d = config.read_json(FILE, {}) or {}
|
|
26
|
+
return {p: list(d.get(p) or []) for p in LISTED}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def save(d):
|
|
30
|
+
config.write_json(FILE, {p: d.get(p, []) for p in LISTED})
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def add(d, platform, rec):
|
|
34
|
+
"""Add {'id', 'name', ...} unless it is already there. Returns True when added."""
|
|
35
|
+
lst = d.setdefault(platform, [])
|
|
36
|
+
if any(c["id"].lower() == rec["id"].lower() or (rec.get("channel_id") and c.get("channel_id") == rec["channel_id"]) for c in lst):
|
|
37
|
+
return False
|
|
38
|
+
lst.append(rec)
|
|
39
|
+
return True
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def remove(d, platform, cid):
|
|
43
|
+
before = len(d.get(platform, []))
|
|
44
|
+
d[platform] = [c for c in d.get(platform, []) if c["id"].lower() != cid.lower()]
|
|
45
|
+
return len(d[platform]) < before
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def guess_platform(text):
|
|
49
|
+
s = text.lower()
|
|
50
|
+
for p, host in (("kick", "kick.com"), ("youtube", "youtube.com"), ("youtube", "youtu.be"), ("twitch", "twitch.tv")):
|
|
51
|
+
if host in s:
|
|
52
|
+
return p
|
|
53
|
+
return None
|
openlive/chat.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Twitch chat for openlive's mpv sidebar. It reads the channel's chat anonymously, draws the sidebar as an
|
|
2
|
+
image (chatview.py: emoji, Twitch emotes, scrollback, pause) and hands it to mpv over its IPC socket. It also
|
|
3
|
+
sends what you write, with your openlive Twitch sign-in. openlive starts it next to mpv; it ends when mpv closes.
|
|
4
|
+
|
|
5
|
+
python -m openlive.chat <mpv-ipc-path> <channel> [<channel-id>]
|
|
6
|
+
|
|
7
|
+
mpv → bridge: openlive_ui.lua sends "script-message openlive-chat-ui <what> …" (click x y, scroll n, send text,
|
|
8
|
+
toggle) and sets user-data/openlive-ui/chat when the sidebar is shown or hidden.
|
|
9
|
+
"""
|
|
10
|
+
import json
|
|
11
|
+
import queue
|
|
12
|
+
import random
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
15
|
+
import ssl
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
|
|
22
|
+
IRC = ("irc.chat.twitch.tv", 6697)
|
|
23
|
+
EMOTE_URL = "https://static-cdn.jtvnw.net/emoticons/v2/{id}/default/dark/2.0"
|
|
24
|
+
WRITE_SCOPE = "user:write:chat"
|
|
25
|
+
FPS = 10
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _unescape_tag(v):
|
|
29
|
+
return v.replace(r"\s", " ").replace(r"\:", ";").replace(r"\\", "\\").replace(r"\r", "").replace(r"\n", "")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse(line):
|
|
33
|
+
"""A PRIVMSG line → {"n": name, "c": "#rrggbb" or "", "t": text, "e": emotes tag[, "me": True]}; None otherwise."""
|
|
34
|
+
tags = {}
|
|
35
|
+
if line.startswith("@"):
|
|
36
|
+
raw, _, line = line.partition(" ")
|
|
37
|
+
for kv in raw[1:].split(";"):
|
|
38
|
+
k, _, v = kv.partition("=")
|
|
39
|
+
tags[k] = _unescape_tag(v)
|
|
40
|
+
parts = line.split(" ", 3)
|
|
41
|
+
if len(parts) < 4 or parts[1] != "PRIVMSG":
|
|
42
|
+
return None
|
|
43
|
+
nick = parts[0].lstrip(":").split("!")[0]
|
|
44
|
+
text = parts[3][1:] if parts[3].startswith(":") else parts[3]
|
|
45
|
+
m = {"n": tags.get("display-name") or nick, "c": tags.get("color", ""), "t": text, "e": tags.get("emotes", "")}
|
|
46
|
+
if text.startswith("\x01ACTION ") and text.endswith("\x01"):
|
|
47
|
+
m.update(t=text[8:-1], me=True)
|
|
48
|
+
return m
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ───────────────────────── mpv ─────────────────────────
|
|
52
|
+
|
|
53
|
+
class Mpv:
|
|
54
|
+
"""mpv's JSON IPC (a Unix socket, or a named pipe on Windows). Events go to `events` from a reader thread."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, path, events, wait=30):
|
|
57
|
+
self.events, self.lock = events, threading.Lock()
|
|
58
|
+
deadline = time.time() + wait
|
|
59
|
+
while True:
|
|
60
|
+
try:
|
|
61
|
+
if sys.platform == "win32": # one handle to write, another to read: a pipe can't do both at once
|
|
62
|
+
self.w = open(path, "r+b", buffering=0) # noqa: SIM115
|
|
63
|
+
self.r = open(path, "rb", buffering=0) # noqa: SIM115
|
|
64
|
+
self.s = None
|
|
65
|
+
else:
|
|
66
|
+
self.s = socket.socket(socket.AF_UNIX)
|
|
67
|
+
self.s.connect(path)
|
|
68
|
+
self.r = self.s.makefile("rb")
|
|
69
|
+
break
|
|
70
|
+
except OSError:
|
|
71
|
+
if time.time() > deadline:
|
|
72
|
+
raise
|
|
73
|
+
time.sleep(0.3)
|
|
74
|
+
threading.Thread(target=self._read, daemon=True).start()
|
|
75
|
+
|
|
76
|
+
def _read(self):
|
|
77
|
+
try:
|
|
78
|
+
for raw in self.r:
|
|
79
|
+
try:
|
|
80
|
+
ev = json.loads(raw)
|
|
81
|
+
except ValueError:
|
|
82
|
+
continue
|
|
83
|
+
if "event" in ev:
|
|
84
|
+
self.events.put(("mpv", ev))
|
|
85
|
+
except OSError:
|
|
86
|
+
pass
|
|
87
|
+
self.events.put(("quit", None))
|
|
88
|
+
|
|
89
|
+
def send(self, command):
|
|
90
|
+
data = (json.dumps({"command": command}) + "\n").encode()
|
|
91
|
+
with self.lock:
|
|
92
|
+
if self.s is None:
|
|
93
|
+
self.w.write(data)
|
|
94
|
+
else:
|
|
95
|
+
self.s.sendall(data)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ───────────────────────── Twitch ─────────────────────────
|
|
99
|
+
|
|
100
|
+
def _irc(channel):
|
|
101
|
+
raw = socket.create_connection(IRC, timeout=15)
|
|
102
|
+
s = ssl.create_default_context().wrap_socket(raw, server_hostname=IRC[0])
|
|
103
|
+
nick = f"justinfan{random.randint(10000, 99999)}" # Twitch's anonymous, read-only login
|
|
104
|
+
s.sendall(f"CAP REQ :twitch.tv/tags\r\nNICK {nick}\r\nJOIN #{channel.lower()}\r\n".encode())
|
|
105
|
+
s.settimeout(30)
|
|
106
|
+
return s
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def irc_loop(channel, events):
|
|
110
|
+
backoff = 2
|
|
111
|
+
while True:
|
|
112
|
+
try:
|
|
113
|
+
irc = _irc(channel)
|
|
114
|
+
except OSError:
|
|
115
|
+
events.put(("status", "offline"))
|
|
116
|
+
time.sleep(backoff)
|
|
117
|
+
backoff = min(backoff * 2, 60)
|
|
118
|
+
continue
|
|
119
|
+
events.put(("status", "joined"))
|
|
120
|
+
backoff, buf = 2, b""
|
|
121
|
+
while True:
|
|
122
|
+
try:
|
|
123
|
+
chunk = irc.recv(65536)
|
|
124
|
+
except TimeoutError:
|
|
125
|
+
continue
|
|
126
|
+
except OSError:
|
|
127
|
+
break
|
|
128
|
+
if not chunk:
|
|
129
|
+
break
|
|
130
|
+
buf += chunk
|
|
131
|
+
*lines, buf = buf.split(b"\r\n")
|
|
132
|
+
for raw in lines:
|
|
133
|
+
line = raw.decode("utf-8", "replace")
|
|
134
|
+
if line.startswith("PING"):
|
|
135
|
+
irc.sendall(("PONG" + line[4:] + "\r\n").encode())
|
|
136
|
+
elif m := parse(line):
|
|
137
|
+
events.put(("msg", m))
|
|
138
|
+
try:
|
|
139
|
+
irc.close()
|
|
140
|
+
except OSError:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Emotes:
|
|
145
|
+
"""Twitch emote images, fetched once from Twitch's CDN and kept in openlive's data folder."""
|
|
146
|
+
|
|
147
|
+
def __init__(self, events, folder=None):
|
|
148
|
+
self.events, self.folder = events, folder
|
|
149
|
+
self.images, self.pending = {}, set()
|
|
150
|
+
self.lock = threading.Lock()
|
|
151
|
+
|
|
152
|
+
def get(self, eid):
|
|
153
|
+
if eid in self.images:
|
|
154
|
+
return self.images[eid]
|
|
155
|
+
with self.lock:
|
|
156
|
+
if eid not in self.pending and re.fullmatch(r"[A-Za-z0-9_]+", eid):
|
|
157
|
+
self.pending.add(eid)
|
|
158
|
+
threading.Thread(target=self._fetch, args=(eid,), daemon=True).start()
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
def _fetch(self, eid):
|
|
162
|
+
from io import BytesIO
|
|
163
|
+
|
|
164
|
+
from PIL import Image
|
|
165
|
+
data = None
|
|
166
|
+
path = self.folder / f"{eid}.png" if self.folder else None
|
|
167
|
+
try:
|
|
168
|
+
if path and path.exists():
|
|
169
|
+
data = path.read_bytes()
|
|
170
|
+
else:
|
|
171
|
+
req = urllib.request.Request(EMOTE_URL.format(id=eid), headers={"User-Agent": "openlive"})
|
|
172
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
173
|
+
data = r.read(2_000_000)
|
|
174
|
+
if path:
|
|
175
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
176
|
+
path.write_bytes(data)
|
|
177
|
+
img = Image.open(BytesIO(data))
|
|
178
|
+
img.seek(0) # animated emotes: the first frame
|
|
179
|
+
self.images[eid] = img.convert("RGBA")
|
|
180
|
+
except (OSError, ValueError, urllib.error.URLError):
|
|
181
|
+
self.images[eid] = None
|
|
182
|
+
self.events.put(("emote", eid))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class Sender:
|
|
186
|
+
"""Sends chat messages with the openlive Twitch sign-in (Helix chat/messages, scope user:write:chat)."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, channel, channel_id=""):
|
|
189
|
+
self.channel, self.channel_id = channel, channel_id
|
|
190
|
+
self.scopes = None
|
|
191
|
+
|
|
192
|
+
def ready(self):
|
|
193
|
+
"""None when it can write, else the reason: "signin" (not signed in) or "rescope" (old sign-in)."""
|
|
194
|
+
from . import twitch
|
|
195
|
+
rec = twitch.load_auth()
|
|
196
|
+
if not rec:
|
|
197
|
+
return "signin"
|
|
198
|
+
if self.scopes is None:
|
|
199
|
+
try:
|
|
200
|
+
if rec.get("expires_at") and rec["expires_at"] - time.time() < 60:
|
|
201
|
+
rec = twitch.refresh(rec)
|
|
202
|
+
self.scopes = twitch.validate(rec["access_token"]).get("scopes") or []
|
|
203
|
+
except twitch.TwitchError:
|
|
204
|
+
return "signin"
|
|
205
|
+
return None if WRITE_SCOPE in self.scopes else "rescope"
|
|
206
|
+
|
|
207
|
+
def send(self, text):
|
|
208
|
+
"""Returns None when sent, else a short reason."""
|
|
209
|
+
from . import twitch
|
|
210
|
+
rec = twitch.load_auth()
|
|
211
|
+
if not rec:
|
|
212
|
+
return "signin"
|
|
213
|
+
try:
|
|
214
|
+
if rec.get("expires_at") and rec["expires_at"] - time.time() < 60:
|
|
215
|
+
rec = twitch.refresh(rec)
|
|
216
|
+
hdr = {"Client-Id": rec["client_id"], "Authorization": f"Bearer {rec['access_token']}"}
|
|
217
|
+
if not self.channel_id:
|
|
218
|
+
users = _helix("GET", f"users?login={self.channel}", hdr)
|
|
219
|
+
self.channel_id = (users.get("data") or [{}])[0].get("id", "")
|
|
220
|
+
res = _helix("POST", "chat/messages", hdr, {"broadcaster_id": self.channel_id, "sender_id": rec["user_id"],
|
|
221
|
+
"message": text[:500]})
|
|
222
|
+
except twitch.TwitchError as e:
|
|
223
|
+
return "rescope" if e.status in (401, 403) else str(e)
|
|
224
|
+
d = (res.get("data") or [{}])[0]
|
|
225
|
+
if d.get("is_sent") is False:
|
|
226
|
+
return (d.get("drop_reason") or {}).get("message") or "not sent"
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _helix(method, path, headers, body=None):
|
|
231
|
+
from . import twitch
|
|
232
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
233
|
+
req = urllib.request.Request(f"{twitch.API_URL}/{path}", data=data, method=method,
|
|
234
|
+
headers={"User-Agent": twitch.UA, "Content-Type": "application/json", **headers})
|
|
235
|
+
try:
|
|
236
|
+
with urllib.request.urlopen(req, timeout=15) as r:
|
|
237
|
+
return json.loads(r.read() or b"{}")
|
|
238
|
+
except urllib.error.HTTPError as e:
|
|
239
|
+
try:
|
|
240
|
+
msg = json.loads(e.read() or b"{}").get("message")
|
|
241
|
+
except ValueError:
|
|
242
|
+
msg = None
|
|
243
|
+
raise twitch.TwitchError(msg or f"HTTP {e.code}", e.code) from None
|
|
244
|
+
except (urllib.error.URLError, OSError) as e:
|
|
245
|
+
raise twitch.TwitchError(f"network: {getattr(e, 'reason', e)}") from None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# ───────────────────────── the bridge ─────────────────────────
|
|
249
|
+
|
|
250
|
+
class Bridge:
|
|
251
|
+
def __init__(self, mpv, view, sender, folder):
|
|
252
|
+
self.mpv, self.view, self.sender, self.folder = mpv, view, sender, folder
|
|
253
|
+
self.size = (0, 0)
|
|
254
|
+
self.shown = True
|
|
255
|
+
self.dirty, self.last = True, 0.0
|
|
256
|
+
self.frame = 0
|
|
257
|
+
self.overlay = False
|
|
258
|
+
|
|
259
|
+
def handle(self, kind, val):
|
|
260
|
+
v = self.view
|
|
261
|
+
if kind == "msg":
|
|
262
|
+
v.add(val)
|
|
263
|
+
elif kind == "status":
|
|
264
|
+
v.status = val
|
|
265
|
+
elif kind == "emote":
|
|
266
|
+
v.forget_layouts()
|
|
267
|
+
elif kind == "note":
|
|
268
|
+
v.add({"note": val})
|
|
269
|
+
elif kind == "mpv":
|
|
270
|
+
self.mpv_event(val)
|
|
271
|
+
return
|
|
272
|
+
self.dirty = True
|
|
273
|
+
|
|
274
|
+
def note(self, key, fallback, **kw):
|
|
275
|
+
s = self.view.tr(key, fallback)
|
|
276
|
+
for k, x in kw.items():
|
|
277
|
+
s = s.replace("{" + k + "}", str(x))
|
|
278
|
+
self.view.add({"note": s})
|
|
279
|
+
|
|
280
|
+
def mpv_event(self, ev):
|
|
281
|
+
v = self.view
|
|
282
|
+
if ev.get("event") == "property-change":
|
|
283
|
+
name, data = ev.get("name"), ev.get("data")
|
|
284
|
+
if name == "osd-dimensions" and isinstance(data, dict):
|
|
285
|
+
self.size = (int(data.get("w") or 0), int(data.get("h") or 0))
|
|
286
|
+
elif name == "user-data/openlive" and isinstance(data, dict):
|
|
287
|
+
v.text = data.get("text") or {}
|
|
288
|
+
v.channel = data.get("channel") or self.sender.channel
|
|
289
|
+
elif name == "user-data/openlive-ui" and isinstance(data, dict):
|
|
290
|
+
self.shown = bool(data.get("chat"))
|
|
291
|
+
self.dirty = True
|
|
292
|
+
elif ev.get("event") == "client-message":
|
|
293
|
+
args = ev.get("args") or []
|
|
294
|
+
if not args or args[0] != "openlive-chat-ui":
|
|
295
|
+
return
|
|
296
|
+
what = args[1] if len(args) > 1 else ""
|
|
297
|
+
if what == "click" and len(args) >= 4:
|
|
298
|
+
self.action(v.click(float(args[2]), float(args[3])))
|
|
299
|
+
elif what == "scroll" and len(args) >= 3:
|
|
300
|
+
v.scroll_by(float(args[2]))
|
|
301
|
+
elif what == "write":
|
|
302
|
+
self.action("write")
|
|
303
|
+
elif what == "pause":
|
|
304
|
+
v.toggle_pause()
|
|
305
|
+
elif what == "send" and len(args) >= 3 and args[2].strip():
|
|
306
|
+
self.send(args[2].strip())
|
|
307
|
+
self.dirty = True
|
|
308
|
+
|
|
309
|
+
def action(self, what):
|
|
310
|
+
v = self.view
|
|
311
|
+
if what == "hide":
|
|
312
|
+
self.mpv.send(["script-message", "openlive-chat-hide"])
|
|
313
|
+
elif what == "pause":
|
|
314
|
+
v.toggle_pause()
|
|
315
|
+
elif what == "resume":
|
|
316
|
+
v.resume()
|
|
317
|
+
elif what == "write":
|
|
318
|
+
why = self.sender.ready()
|
|
319
|
+
v.can_write = why is None
|
|
320
|
+
if why is None:
|
|
321
|
+
self.mpv.send(["script-message", "openlive-chat-prompt"])
|
|
322
|
+
elif why == "rescope":
|
|
323
|
+
self.note("chat_rescope", "To write, sign in to Twitch again in openlive (press l there).")
|
|
324
|
+
else:
|
|
325
|
+
self.note("chat_signin", "To write, sign in to Twitch in openlive (press l there).")
|
|
326
|
+
self.dirty = True
|
|
327
|
+
|
|
328
|
+
def send(self, text):
|
|
329
|
+
def run():
|
|
330
|
+
why = self.sender.send(text)
|
|
331
|
+
if why == "rescope":
|
|
332
|
+
self.sender.scopes = None
|
|
333
|
+
self.mpv.events.put(("note", self.view.tr("chat_rescope", "To write, sign in to Twitch again in openlive (press l there).")))
|
|
334
|
+
elif why == "signin":
|
|
335
|
+
self.mpv.events.put(("note", self.view.tr("chat_signin", "To write, sign in to Twitch in openlive (press l there).")))
|
|
336
|
+
elif why:
|
|
337
|
+
self.mpv.events.put(("note", self.view.tr("chat_not_sent", "Not sent: {why}").replace("{why}", why)))
|
|
338
|
+
if self.view.frozen:
|
|
339
|
+
self.view.resume()
|
|
340
|
+
threading.Thread(target=run, daemon=True).start()
|
|
341
|
+
|
|
342
|
+
def draw(self):
|
|
343
|
+
w, h = self.size
|
|
344
|
+
if not self.shown or w < 200 or h < 150:
|
|
345
|
+
if self.overlay:
|
|
346
|
+
self.mpv.send(["overlay-remove", 0])
|
|
347
|
+
self.overlay = False
|
|
348
|
+
return
|
|
349
|
+
img, x0 = self.view.render(w, h)
|
|
350
|
+
self.frame ^= 1 # two files: mpv may still be reading the previous one
|
|
351
|
+
path = self.folder / f"chat-{id(self)}-{self.frame}.bgra"
|
|
352
|
+
path.write_bytes(img.tobytes("raw", "BGRA"))
|
|
353
|
+
self.mpv.send(["overlay-add", 0, x0, 0, str(path), 0, "bgra", img.width, img.height, img.width * 4])
|
|
354
|
+
self.overlay = True
|
|
355
|
+
|
|
356
|
+
def loop(self, events):
|
|
357
|
+
while True:
|
|
358
|
+
try:
|
|
359
|
+
kind, val = events.get(timeout=1 / FPS)
|
|
360
|
+
if kind == "quit":
|
|
361
|
+
return
|
|
362
|
+
self.handle(kind, val)
|
|
363
|
+
while True: # take everything waiting before drawing
|
|
364
|
+
kind, val = events.get_nowait()
|
|
365
|
+
if kind == "quit":
|
|
366
|
+
return
|
|
367
|
+
self.handle(kind, val)
|
|
368
|
+
except queue.Empty:
|
|
369
|
+
pass
|
|
370
|
+
if self.dirty and time.time() - self.last >= 1 / FPS:
|
|
371
|
+
self.dirty, self.last = False, time.time()
|
|
372
|
+
self.draw()
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def run(ipc_path, channel, channel_id=""):
|
|
376
|
+
from . import config
|
|
377
|
+
from .chatview import ChatView
|
|
378
|
+
events = queue.Queue()
|
|
379
|
+
folder = config.DATA / "mpv"
|
|
380
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
381
|
+
mpv = Mpv(ipc_path, events)
|
|
382
|
+
emotes = Emotes(events, config.DATA / "emotes")
|
|
383
|
+
view = ChatView(emote_image=emotes.get)
|
|
384
|
+
sender = Sender(channel, channel_id)
|
|
385
|
+
view.channel = channel
|
|
386
|
+
|
|
387
|
+
def check_write(): # asks Twitch which permissions the sign-in has: don't hold up the chat for it
|
|
388
|
+
try:
|
|
389
|
+
view.can_write = sender.ready() is None
|
|
390
|
+
except Exception: # noqa: BLE001 — writing is optional
|
|
391
|
+
view.can_write = False
|
|
392
|
+
events.put(("status", view.status))
|
|
393
|
+
threading.Thread(target=check_write, daemon=True).start()
|
|
394
|
+
bridge = Bridge(mpv, view, sender, folder)
|
|
395
|
+
for i, prop in enumerate(("osd-dimensions", "user-data/openlive", "user-data/openlive-ui"), 1):
|
|
396
|
+
mpv.send(["observe_property", i, prop])
|
|
397
|
+
threading.Thread(target=irc_loop, args=(channel, events), daemon=True).start()
|
|
398
|
+
try:
|
|
399
|
+
bridge.loop(events)
|
|
400
|
+
finally:
|
|
401
|
+
for f in folder.glob(f"chat-{id(bridge)}-*.bgra"):
|
|
402
|
+
f.unlink(missing_ok=True)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def main(argv=None):
|
|
406
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
407
|
+
if len(argv) not in (2, 3):
|
|
408
|
+
print(__doc__, file=sys.stderr)
|
|
409
|
+
return 2
|
|
410
|
+
try:
|
|
411
|
+
run(*argv)
|
|
412
|
+
except (OSError, KeyboardInterrupt): # mpv closed
|
|
413
|
+
return 0
|
|
414
|
+
return 0
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
if __name__ == "__main__":
|
|
418
|
+
sys.exit(main())
|