Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2391 lines (2250 loc) · 111 KB
/
Copy pathmain.py
File metadata and controls
2391 lines (2250 loc) · 111 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
"""BoneCast — backend Twitch (OAuth device flow + titre/catégorie Helix + overlay chat).
Incrément 1 : login, titre, catégorie, overlay. Le streaming RTMP arrive à l'incrément 2.
Config PAR COMPTE Steam : ~/.config/bonecast-<accountid>.json (tokens = secrets, chmod 600)."""
import os
import sys
from json import load, dump
from pathlib import Path
from asyncio import Lock, create_task, current_task as _current_task
from time import time
from decky import logger, DECKY_PLUGIN_DIR # type: ignore
sys.path.append(DECKY_PLUGIN_DIR)
import bonecast_env as bcenv # noqa: E402
import ssl as _ssl
# plugin_loader est un binaire PyInstaller figé : son python n'expose pas les CA
# du système par défaut → toute requête HTTPS échoue avec « Cannot connect to host
# X:443 ssl:default [certificate verify failed] ». On construit un contexte SSL
# pointant explicitement sur le bundle CA système (même astuce que Steamcord/updater.py).
_SSL_CTX = None
def _ssl_context():
global _SSL_CTX
if _SSL_CTX is not None:
return _SSL_CTX
for ca in ("/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/certs/ca-certificates.crt",
"/etc/ssl/cert.pem"):
try:
if os.path.exists(ca):
_SSL_CTX = _ssl.create_default_context(cafile=ca)
return _SSL_CTX
except Exception:
pass
_SSL_CTX = _ssl.create_default_context()
return _SSL_CTX
def sys_python():
"""Python SYSTÈME (pour les bindings gi/Gst de gst_camera.py).
/usr/bin/python n'existe pas sur Debian/Ubuntu (sauf python-is-python3) →
résoudre python3 du PATH d'abord."""
import shutil as _sh
return _sh.which("python3") or _sh.which("python") or "/usr/bin/python"
async def stream_watcher(stream, is_err=False, prefix="[bonecast]"):
"""Recopie stdout/stderr d'un sous-process dans le journal Decky."""
if stream is None:
return
while True:
line = await stream.readline()
if not line:
break
msg = line.decode(errors="ignore").rstrip()
if msg:
(logger.warning if is_err else logger.info)(f"{prefix} {msg}")
# Decky enregistre son PROPRE module `updater` dans sys.modules → un simple
# `import updater` renverrait celui-là (sans is_autoupdate_enabled). On charge
# notre fichier par chemin sous un nom unique pour éviter la collision. Depuis
# defaults/ (toujours dans le zip + synchronisé par le deploy).
import importlib.util as _ilu # noqa: E402
_upath = Path(DECKY_PLUGIN_DIR) / "defaults" / "updater.py"
if not _upath.exists():
_upath = Path(DECKY_PLUGIN_DIR) / "updater.py"
try:
_uspec = _ilu.spec_from_file_location("bc_updater", str(_upath))
updater = _ilu.module_from_spec(_uspec)
_uspec.loader.exec_module(updater)
except Exception as _e: # best-effort : le plugin survit sans updater
logger.warning(f"[updater] indisponible : {_e!r}")
updater = None
# Nombre de vérifications de release et délai entre deux. La vérif part quelques
# secondes après le backend, c'est-à-dire souvent AVANT que le réseau soit
# joignable : les journaux de la machine de test montrent trois démarrages sur
# quatre qui meurent sur « Temporary failure in name resolution ». Rien ne
# réessayait, donc le plugin restait sur sa version jusqu'au démarrage
# suivant — qui échouait de la même façon.
UPDATE_CHECK_TRIES = 10
UPDATE_CHECK_DELAY_S = 30
async def _recheck(updater):
"""`updater.check()`, réessayé tant que c'est le réseau qui manque."""
from asyncio import sleep as _sleep
info = await updater.check()
for _ in range(UPDATE_CHECK_TRIES - 1):
if not info.get("error"):
break
await _sleep(UPDATE_CHECK_DELAY_S)
info = await updater.check()
return info
class Plugin:
# ── OAuth Twitch (device code flow, client public — pas de secret) ───────
_TWITCH_CLIENT_ID = "idbnwqbkqyrzesxct1ztkejyf5aj6z"
# clips:edit = bouton « Clip » ; user:write:chat = envoi de messages chat ;
# user:read:follows = liste des chaînes suivies actuellement en direct.
# moderator:read:followers = nouveaux followers affichés dans l'overlay.
# Les logins existants n'ont PAS ces scopes → les endpoints renvoient 401 et
# le front invite à se reconnecter (device flow re-demande tout).
_TWITCH_SCOPES = ("channel:read:stream_key channel:manage:broadcast "
"clips:edit user:write:chat user:read:follows")
# moderator:read:followers (follows dans l overlay) : code prêt mais PAS
# encore demandé — à ajouter ici quand la fonction sera testée et livrée.
_TWITCH_JUST_CHATTING = "509658" # game_id « Just Chatting »
_tw_device = None # état transitoire du device flow
_overlay_proc = None
_overlay_platform = None # "twitch" | "youtube" (un overlay à la fois)
_watch_proc = None # helper GTK : lives Twitch par-dessus le jeu
_watch_start_lock = None # évite deux starts QAM simultanés
_start_stream_lock = None # un seul lancement de live à la fois
_start_overlay_lock = None # un seul lancement d'overlay à la fois
_stream_proc = None # ffmpeg RTMP (live Twitch ou YouTube)
_stream_platform = None # "twitch" | "youtube" | "record" (un seul à la fois)
_camera_feeder = None # gst_camera.py --stdout → tuyau → ffmpeg
# Reprise du live (BoneCast #1, demandé par dreemur-e) : réseau coupé, ffmpeg
# mort, « Arrêter » par erreur ou redémarrage de la machine → pendant
# `resume_window` secondes le live peut reprendre SANS en créer un nouveau
# (même live YouTube, même lien pour les spectateurs).
_RESUME_CHOICES = (0, 15, 30, 60, 120)
_resume = None # {"platform", "until"} : reconnexion auto en cours
_yt_end_task = None # fin YouTube différée (arrêt manuel / reboot)
_stream_started = 0.0
_TWITCH_INGEST = "rtmp://ingest.global-contribute.live-video.net/app"
_OVERLAY_DEFAULTS = {"opacity": 62, "fontSize": 13, "width": 360,
"height": 460, "pos": "tr", "badges": True, "thirdParty": True}
_WATCH_DEFAULTS = {"streams": [], "layout": "corner_br", "scale": 1.0,
"opacity": 0.5, "max_fps": 30, "audio": "", "volume": 1.0}
# ── Réglages du stream (par compte Steam) ────────────────────────────────
_RES_PRESETS = {"720p": (1280, 720), "800p": (1280, 800),
"1080p": (1920, 1080), "source": (0, 0)}
_STREAM_DEFAULTS = {"resolution": "720p", "fps": 30, "bitrate": 4500,
"audio_bitrate": 160, "keyframe": 2,
"encoder": "auto", "mic": False, "discord_audio": False,
"record": False, "effort": "balanced"}
# Effort de l'encodeur LOGICIEL (x264) : moins d'effort = moins de CPU (le jeu
# garde ses images sur un Deck), plus d'effort = image plus nette au même débit.
# Idée de dreemur-e (BoneCast #1).
_X264_PRESETS = {"light": "superfast", "balanced": "veryfast", "quality": "faster"}
_vaapi_ok = None # cache détection VAAPI (AMD/Intel)
_nvenc_ok = None # cache détection NVENC (Nvidia)
_x264_ok = None # cache détection libx264 (ffmpeg-free Fedora = absent)
_gst_py_ok = False # cache : bindings gi/Gst du python système OK
# ── Mute micro à la volée (n'affecte QUE le stream, pas le vocal Discord) ──
_mic_active = False # micro inclus dans le stream courant ?
_mic_so_idx = None # source-output ffmpeg qui capte le micro
_mic_muted = False # micro coupé sur le stream (live)
# ── BRB (pause à l'antenne) + enregistrement local ────────────────────────
_brb_on = False # écran pause affiché par le feeder (SIGUSR1/2)
_brb_restore_mic = False # micro auto-muté par le BRB → à rétablir
_record_path = None # fichier mkv du live/enregistrement courant
_record_only = False # session sans RTMP (enregistrement seul)
# ── Pont audio Discord (activable si Steamcord présent) ───────────────────
_DISCORD_SINK = "bonecast_discord" # sink dédié à la voix Discord
_ba_modules = [] # modules pactl chargés (null-sink+loopback)
_ba_watch = None # tâche watcher (re-déplace Vesktop)
_ba_real_sink = None # vraie sortie (l'user entend Discord)
# ── Config par compte Steam ─────────────────────────────────────────────
@classmethod
def _cfg_path(cls):
try:
acc = bcenv.steam_account_id()
except Exception:
acc = "default"
return os.path.expanduser(f"~/.config/bonecast-{acc}.json")
@classmethod
def _load_cfg(cls):
try:
with open(cls._cfg_path()) as f:
return load(f)
except Exception:
return {}
@classmethod
def _save_cfg(cls, cfg):
p = cls._cfg_path()
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w") as f:
dump(cfg, f)
os.chmod(p, 0o600) # tokens + clé = secrets
@classmethod
async def get_config(cls):
"""État exposé au frontend — JAMAIS de token/clé en clair."""
cfg = cls._load_cfg()
oauth = cfg.get("oauth") or {}
yt = cfg.get("youtube") or {}
ov = cls._overlay_proc
ov_on = ov is not None and ov.returncode is None
ov_pf = cls._overlay_platform if ov_on else None
return {
"logged_in": bool(oauth.get("access_token")),
"login": oauth.get("login", ""),
"key_set": bool(cfg.get("key")),
"title": cfg.get("title", ""),
"game_name": cfg.get("game_name", ""),
# Chaîne de l'overlay : override manuel sinon = ta propre chaîne (login OAuth).
"channel": cfg.get("channel") or oauth.get("login", ""),
"overlay_on": ov_pf == "twitch",
"overlay_platform": ov_pf,
"overlay": {**cls._OVERLAY_DEFAULTS, **(cfg.get("overlay") or {})},
"watching": cls._watch_proc is not None and cls._watch_proc.returncode is None,
"watch": {**cls._WATCH_DEFAULTS, **(cfg.get("watch") or {})},
"streaming": cls._stream_proc is not None
and cls._stream_proc.returncode is None,
"stream": {**cls._STREAM_DEFAULTS, **(cfg.get("stream") or {})},
"steamcord": cls._steamcord_present(),
"platform": cls._stream_platform if (cls._stream_proc is not None
and cls._stream_proc.returncode is None) else None,
"youtube": {
"login_available": cls._yt_login_available(),
"logged_in": bool((yt.get("oauth") or {}).get("access_token")),
"channel": yt.get("channel_title", ""),
"key_set": bool(yt.get("key")),
"title": yt.get("title", ""),
"privacy": yt.get("privacy") if yt.get("privacy") in cls._YT_PRIVACY else "public",
"latency": yt.get("latency") if yt.get("latency") in cls._YT_LATENCY else "normal",
"stream": {**cls._STREAM_DEFAULTS, **(yt.get("stream") or {})},
"chat_channel": yt.get("chat_channel", ""),
"chat_source": cls._yt_chat_source(cfg),
"can_send": bool((yt.get("oauth") or {}).get("access_token")),
"overlay_on": ov_pf == "youtube",
"overlay": {**cls._OVERLAY_DEFAULTS, **(yt.get("overlay") or {})},
},
}
@staticmethod
def _steamcord_present():
"""Steamcord installé ? → active l'option « son Discord dans le stream »."""
return os.path.isdir(os.path.expanduser("~/homebrew/plugins/Steamcord"))
# ── HTTP ────────────────────────────────────────────────────────────────
@classmethod
async def _http(cls, method, url, *, headers=None, data=None,
params=None, json_body=None):
import aiohttp
from json import loads
conn = aiohttp.TCPConnector(ssl=_ssl_context())
async with aiohttp.ClientSession(connector=conn) as s:
async with s.request(method, url, headers=headers, data=data,
params=params, json=json_body) as r:
txt = await r.text()
try:
body = loads(txt) if txt else {}
except Exception:
body = {"raw": txt}
return r.status, body
# ── OAuth device flow ───────────────────────────────────────────────────
@classmethod
async def _store_tokens(cls, tok):
cfg = cls._load_cfg()
oauth = cfg.get("oauth") or {}
oauth["access_token"] = tok["access_token"]
if tok.get("refresh_token"):
oauth["refresh_token"] = tok["refresh_token"]
oauth["expires_at"] = time() + int(tok.get("expires_in", 3600))
st, v = await cls._http(
"GET", "https://id.twitch.tv/oauth2/validate",
headers={"Authorization": f"Bearer {tok['access_token']}"})
if st == 200:
oauth["user_id"] = v.get("user_id", "")
oauth["login"] = v.get("login", "")
oauth["scopes"] = v.get("scopes", [])
cfg["oauth"] = oauth
cls._save_cfg(cfg)
try:
await cls.fetch_stream_key()
except Exception as e:
logger.warning(f"[twitch] fetch key: {e!r}")
@classmethod
async def auth_start(cls):
"""Démarre le device flow → code à saisir sur twitch.tv/activate."""
try:
st, body = await cls._http(
"POST", "https://id.twitch.tv/oauth2/device",
data={"client_id": cls._TWITCH_CLIENT_ID, "scopes": cls._TWITCH_SCOPES})
if st != 200 or "device_code" not in body:
return {"ok": False, "error": body.get("message") or f"http {st}"}
cls._tw_device = {
"device_code": body["device_code"],
"interval": int(body.get("interval", 5)),
"expires_at": time() + int(body.get("expires_in", 1800)),
}
return {"ok": True, "user_code": body["user_code"],
"verification_uri": body.get("verification_uri")
or "https://www.twitch.tv/activate",
"interval": int(body.get("interval", 5))}
except Exception as e:
return {"ok": False, "error": str(e)}
@classmethod
async def auth_poll(cls):
"""Poll-é par le frontend : 'pending' jusqu'à l'autorisation, puis 'ok'."""
dev = cls._tw_device
if not dev:
return {"status": "idle"}
if time() > dev["expires_at"]:
cls._tw_device = None
return {"status": "expired"}
try:
st, body = await cls._http(
"POST", "https://id.twitch.tv/oauth2/token",
data={"client_id": cls._TWITCH_CLIENT_ID,
"scopes": cls._TWITCH_SCOPES,
"device_code": dev["device_code"],
"grant_type": "urn:ietf:params:oauth:grant-type:device_code"})
if st == 200 and body.get("access_token"):
cls._tw_device = None
await cls._store_tokens(body)
cfg = cls._load_cfg()
return {"status": "ok", "login": (cfg.get("oauth") or {}).get("login", "")}
msg = str(body.get("message", "")).lower()
if "expired" in msg:
cls._tw_device = None
return {"status": "expired"}
if "denied" in msg:
cls._tw_device = None
return {"status": "denied"}
return {"status": "pending"}
except Exception as e:
return {"status": "error", "error": str(e)}
@classmethod
async def logout(cls):
try:
cfg = cls._load_cfg()
cfg.pop("oauth", None)
cfg.pop("key", None)
cls._save_cfg(cfg)
return {"ok": True}
except Exception as e:
return {"ok": False, "error": str(e)}
# ── Helix ────────────────────────────────────────────────────────────────
@classmethod
async def _bearer(cls):
cfg = cls._load_cfg()
oauth = cfg.get("oauth") or {}
at = oauth.get("access_token")
if not at:
return None
if time() < oauth.get("expires_at", 0) - 60:
return at
rt = oauth.get("refresh_token")
if not rt:
return None
st, body = await cls._http(
"POST", "https://id.twitch.tv/oauth2/token",
data={"client_id": cls._TWITCH_CLIENT_ID,
"grant_type": "refresh_token", "refresh_token": rt})
if st == 200 and body.get("access_token"):
await cls._store_tokens(body)
return body["access_token"]
return None
@classmethod
async def _api(cls, method, path, *, params=None, json_body=None):
at = await cls._bearer()
if not at:
return None, {"error": "not_logged_in"}
headers = {"Authorization": f"Bearer {at}", "Client-Id": cls._TWITCH_CLIENT_ID}
return await cls._http(method, "https://api.twitch.tv/helix/" + path,
headers=headers, params=params, json_body=json_body)
@classmethod
def _broadcaster_id(cls):
return (cls._load_cfg().get("oauth") or {}).get("user_id", "")
@classmethod
async def get_followed_live(cls):
"""Retourne les lives des chaînes suivies, rafraîchis à la demande.
L'endpoint Helix est paginé : on le parcourt entièrement plutôt que de
masquer les lives au-delà de la première centaine. Seules les données
utiles au QAM sont renvoyées, jamais le token OAuth.
"""
cfg = cls._load_cfg()
oauth = cfg.get("oauth") or {}
if not oauth.get("access_token") or not oauth.get("user_id"):
return {"ok": False, "error": "not_logged_in"}
if "user:read:follows" not in (oauth.get("scopes") or []):
return {"ok": False, "error": "missing_follow_scope"}
lives, after = [], None
# Une limite haute protège le QAM d'une réponse anormalement paginée,
# tout en couvrant largement plus que les lives suivis usuels.
for _page in range(20):
params = {"user_id": oauth["user_id"], "first": 100}
if after:
params["after"] = after
status, body = await cls._api("GET", "streams/followed", params=params)
if status != 200:
logger.warning(f"[watch] followed lives failed: http {status} {body!r}")
if status in (401, 403):
return {"ok": False, "error": "missing_follow_scope"}
return {"ok": False, "error": "followed_live_failed"}
for stream in (body or {}).get("data") or []:
login = str(stream.get("user_login") or "").lower()
if login:
lives.append({
"login": login,
"name": stream.get("user_name") or login,
"title": stream.get("title") or "",
"game": stream.get("game_name") or "",
"viewers": int(stream.get("viewer_count") or 0),
# URL modèle Twitch ({width}×{height}), rendue par le
# frontend à une taille légère adaptée au QAM.
"thumbnail": stream.get("thumbnail_url") or "",
})
after = ((body or {}).get("pagination") or {}).get("cursor")
if not after:
break
return {"ok": True, "streams": lives}
@classmethod
async def fetch_stream_key(cls):
"""Récupère la clé de stream via l'API → cfg['key'] (jamais renvoyée au front)."""
bid = cls._broadcaster_id()
if not bid:
return None
st, body = await cls._api("GET", "streams/key", params={"broadcaster_id": bid})
data = (body or {}).get("data") or []
if st == 200 and data and data[0].get("stream_key"):
cfg = cls._load_cfg()
cfg["key"] = data[0]["stream_key"]
cls._save_cfg(cfg)
return cfg["key"]
return None
@classmethod
async def _resolve_game(cls, name):
name = (name or "").strip()
if not name:
return cls._TWITCH_JUST_CHATTING
st, body = await cls._api("GET", "games", params={"name": name})
data = (body or {}).get("data") or []
return data[0].get("id") if data else None
@classmethod
async def update_channel(cls, title=None, game_name=None):
"""MAJ titre et/ou catégorie (PATCH /helix/channels) — marche en direct."""
bid = cls._broadcaster_id()
if not bid:
return {"ok": False, "error": "not_logged_in"}
cfg = cls._load_cfg()
payload = {}
if title is not None:
payload["title"] = str(title)[:140]
cfg["title"] = payload["title"]
if game_name is not None:
gid = await cls._resolve_game(game_name)
cfg["game_name"] = game_name
if gid:
payload["game_id"] = gid # sinon jeu absent du catalogue → on garde l'ancienne
cls._save_cfg(cfg)
if not payload:
return {"ok": True, "no_change": True}
st, body = await cls._api("PATCH", "channels",
params={"broadcaster_id": bid}, json_body=payload)
if st in (200, 204):
return {"ok": True, "game_matched": "game_id" in payload}
return {"ok": False, "error": (body or {}).get("message") or f"http {st}"}
@classmethod
async def set_title(cls, title: str = ""):
return await cls.update_channel(title=title)
@classmethod
async def set_game(cls, game_name: str = ""):
return await cls.update_channel(game_name=game_name)
# ── YouTube ──────────────────────────────────────────────────────────────
# Même modèle que Twitch : connexion par code (google.com/device), puis la
# clé de stream et le live sont créés par l'API. La clé MANUELLE reste en
# secours : tant que Google n'a pas vérifié l'appli, la connexion est
# plafonnée (comptes de test) et les jetons expirent au bout de 7 jours.
#
# Client « TV et appareils à saisie limitée » : Google exige le secret dans
# ce flux, mais le déclare lui-même non confidentiel pour ce type de client
# (il est embarqué dans chaque appli de TV). Vide = connexion masquée.
_YT_CLIENT_ID = "617671992109-u15vhd4phh25qgjnnp0j20ej42i39b1h.apps.googleusercontent.com"
_YT_CLIENT_SECRET = "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"
_YT_SCOPE = "https://www.googleapis.com/auth/youtube"
_YT_INGEST = "rtmp://a.rtmp.youtube.com/live2"
_YT_API = "https://www.googleapis.com/youtube/v3/"
_YT_GAMING = "20" # catégorie « Jeux vidéo »
_YT_PRIVACY = ("public", "unlisted", "private")
# contentDetails.latencyPreference de liveBroadcasts. « normal » ≈ 20 s de
# retard (mesuré par dreemur-e, #1) ; ultraLow ≈ 5 s mais YouTube y coupe
# certaines options (sous-titres, 1440p et plus). Défaut YouTube = normal.
_YT_LATENCY = ("normal", "low", "ultraLow")
_yt_device = None
@classmethod
def _yt_cfg(cls, cfg=None):
cfg = cfg if cfg is not None else cls._load_cfg()
return cfg.setdefault("youtube", {})
@classmethod
def _yt_login_available(cls):
return bool(cls._YT_CLIENT_ID and cls._YT_CLIENT_SECRET)
@classmethod
async def yt_auth_start(cls):
if not cls._yt_login_available():
return {"ok": False, "error": "login_unavailable"}
try:
st, body = await cls._http(
"POST", "https://oauth2.googleapis.com/device/code",
data={"client_id": cls._YT_CLIENT_ID, "scope": cls._YT_SCOPE})
if st != 200 or "device_code" not in body:
return {"ok": False, "error": body.get("error_description")
or body.get("error") or f"http {st}"}
cls._yt_device = {
"device_code": body["device_code"],
"interval": int(body.get("interval", 5)),
"expires_at": time() + int(body.get("expires_in", 1800)),
}
return {"ok": True, "user_code": body["user_code"],
"verification_uri": body.get("verification_url")
or "https://www.google.com/device"}
except Exception as e:
return {"ok": False, "error": str(e)}
@classmethod
async def yt_auth_poll(cls):
dev = cls._yt_device
if not dev:
return {"status": "idle"}
if time() > dev["expires_at"]:
cls._yt_device = None
return {"status": "expired"}
try:
st, body = await cls._http(
"POST", "https://oauth2.googleapis.com/token",
data={"client_id": cls._YT_CLIENT_ID,
"client_secret": cls._YT_CLIENT_SECRET,
"device_code": dev["device_code"],
"grant_type": "urn:ietf:params:oauth:grant-type:device_code"})
if st == 200 and body.get("access_token"):
cls._yt_device = None
await cls._yt_store_tokens(body)
return {"status": "ok", "login": cls._yt_cfg().get("channel_title", "")}
err = str(body.get("error", ""))
if err == "expired_token":
cls._yt_device = None
return {"status": "expired"}
if err == "access_denied":
cls._yt_device = None
return {"status": "denied"}
return {"status": "pending"} # authorization_pending / slow_down
except Exception as e:
return {"status": "error", "error": str(e)}
@classmethod
async def _yt_store_tokens(cls, tok):
cfg = cls._load_cfg()
yt = cls._yt_cfg(cfg)
oauth = yt.get("oauth") or {}
oauth["access_token"] = tok["access_token"]
if tok.get("refresh_token"):
oauth["refresh_token"] = tok["refresh_token"]
oauth["expires_at"] = time() + int(tok.get("expires_in", 3600))
yt["oauth"] = oauth
cls._save_cfg(cfg)
# Nom de la chaîne, pour l'afficher comme « @login » côté Twitch.
st, body = await cls._yt_api("GET", "channels",
params={"part": "snippet", "mine": "true"})
items = (body or {}).get("items") or []
if st == 200 and items:
sn = items[0].get("snippet") or {}
cfg = cls._load_cfg()
yt = cls._yt_cfg(cfg)
yt["channel_title"] = sn.get("title", "")
yt["channel_id"] = items[0].get("id", "")
yt["channel_handle"] = sn.get("customUrl", "")
cls._save_cfg(cfg)
@classmethod
async def yt_logout(cls):
cfg = cls._load_cfg()
yt = cls._yt_cfg(cfg)
for k in ("oauth", "channel_title", "channel_handle", "channel_id", "stream_id",
"api_key", "api_ingest", "broadcast_id", "live_chat_id"):
yt.pop(k, None)
cls._save_cfg(cfg)
return {"ok": True}
@classmethod
async def _yt_bearer(cls):
oauth = cls._yt_cfg().get("oauth") or {}
at = oauth.get("access_token")
if not at:
return None
if time() < oauth.get("expires_at", 0) - 60:
return at
rt = oauth.get("refresh_token")
if not rt:
return None
st, body = await cls._http(
"POST", "https://oauth2.googleapis.com/token",
data={"client_id": cls._YT_CLIENT_ID,
"client_secret": cls._YT_CLIENT_SECRET,
"grant_type": "refresh_token", "refresh_token": rt})
if st == 200 and body.get("access_token"):
cfg = cls._load_cfg()
o = cls._yt_cfg(cfg).setdefault("oauth", {})
o["access_token"] = body["access_token"]
o["expires_at"] = time() + int(body.get("expires_in", 3600))
cls._save_cfg(cfg)
return body["access_token"]
if (body or {}).get("error") == "invalid_grant":
# Jeton révoqué ou expiré (7 jours en mode test chez Google) :
# on se déconnecte proprement plutôt que d'échouer à chaque live.
logger.info("[youtube] refresh refusé (invalid_grant) — déconnexion")
await cls.yt_logout()
return None
@classmethod
async def _yt_api(cls, method, path, *, params=None, json_body=None):
at = await cls._yt_bearer()
if not at:
return None, {"error": "not_logged_in"}
return await cls._http(method, cls._YT_API + path,
headers={"Authorization": f"Bearer {at}"},
params=params, json_body=json_body)
@staticmethod
def _yt_error(body, st):
err = (body or {}).get("error")
if isinstance(err, dict):
reason = ((err.get("errors") or [{}])[0]).get("reason") or ""
return reason or err.get("message") or f"http {st}"
return str(err or f"http {st}")
@classmethod
async def _yt_ensure_stream(cls):
"""Flux d'ingestion réutilisable → (clé, url d'ingestion), créé une fois."""
yt = cls._yt_cfg()
sid = yt.get("stream_id")
if sid:
st, body = await cls._yt_api("GET", "liveStreams",
params={"part": "cdn", "id": sid})
items = (body or {}).get("items") or []
if st == 200 and items:
ing = (items[0].get("cdn") or {}).get("ingestionInfo") or {}
if ing.get("streamName"):
return ing["streamName"], ing.get("ingestionAddress") or cls._YT_INGEST
st, body = await cls._yt_api(
"POST", "liveStreams", params={"part": "snippet,cdn,contentDetails"},
json_body={"snippet": {"title": "BoneCast"},
"cdn": {"ingestionType": "rtmp", "resolution": "variable",
"frameRate": "variable"},
"contentDetails": {"isReusable": True}})
if st not in (200, 201):
raise RuntimeError(cls._yt_error(body, st))
ing = (body.get("cdn") or {}).get("ingestionInfo") or {}
cfg = cls._load_cfg()
y = cls._yt_cfg(cfg)
y["stream_id"] = body.get("id")
cls._save_cfg(cfg)
return ing.get("streamName"), ing.get("ingestionAddress") or cls._YT_INGEST
@classmethod
async def _yt_create_broadcast(cls):
"""Crée le live (titre, visibilité), démarrage/arrêt auto, lié au flux."""
cfg = cls._load_cfg()
yt = cls._yt_cfg(cfg)
title = (yt.get("title") or "").strip() or "BoneCast live"
privacy = yt.get("privacy") if yt.get("privacy") in cls._YT_PRIVACY else "public"
latency = yt.get("latency") if yt.get("latency") in cls._YT_LATENCY else "normal"
from datetime import datetime, timezone
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
st, body = await cls._yt_api(
"POST", "liveBroadcasts", params={"part": "snippet,status,contentDetails"},
json_body={"snippet": {"title": title[:100], "scheduledStartTime": now},
"status": {"privacyStatus": privacy,
"selfDeclaredMadeForKids": False},
# autoStart : YouTube passe le live à l'antenne dès que
# le flux arrive ; pas de phase « test » sans moniteur.
"contentDetails": {"latencyPreference": latency,
"enableAutoStart": True,
"enableAutoStop": cls._resume_window() < 60,
"monitorStream": {"enableMonitorStream": False}}})
if st not in (200, 201):
raise RuntimeError(cls._yt_error(body, st))
bid = body.get("id")
sid = yt.get("stream_id")
st, b2 = await cls._yt_api("POST", "liveBroadcasts/bind",
params={"part": "id", "id": bid, "streamId": sid})
if st != 200:
raise RuntimeError(cls._yt_error(b2, st))
cfg = cls._load_cfg()
y = cls._yt_cfg(cfg)
y["broadcast_id"] = bid
y["live_chat_id"] = (body.get("snippet") or {}).get("liveChatId", "")
cls._save_cfg(cfg)
cls._yt_write_live_hint(y.get("channel_id", ""), bid)
# Catégorie « Jeux vidéo » : l'API ne permet pas de choisir le jeu.
await cls._yt_api("PUT", "videos", params={"part": "snippet"},
json_body={"id": bid, "snippet": {"title": title[:100],
"categoryId": cls._YT_GAMING}})
return bid
@classmethod
def _yt_schedule_end(cls, delay):
"""Termine le live YouTube dans `delay` s, sauf reprise d'ici là. L'échéance
est aussi écrite dans la config : après un redémarrage, _main la reprend."""
from asyncio import sleep
if cls._yt_end_task is not None:
cls._yt_end_task.cancel()
cfg = cls._load_cfg()
if not cls._yt_cfg(cfg).get("broadcast_id"):
return
cls._yt_cfg(cfg)["broadcast_end_at"] = int(time() + delay)
cls._save_cfg(cfg)
async def _later():
await sleep(delay)
cls._yt_end_task = None
if cls._stream_platform == "youtube" or (cls._resume or {}).get("platform") == "youtube":
return # repris entre-temps
logger.info("[youtube] pas de reprise → live terminé")
await cls._yt_end_broadcast()
cls._yt_end_task = create_task(_later())
@classmethod
async def _yt_reuse_broadcast(cls):
"""Un live YouTube de cette session est encore ouvert (coupure, Arrêter par
erreur, redémarrage) → on le reprend au lieu d'en créer un nouveau."""
bid = cls._yt_cfg().get("broadcast_id")
if not bid:
return False
try:
st, body = await cls._yt_api("GET", "liveBroadcasts",
params={"part": "status", "id": bid})
items = (body or {}).get("items") or [] if st == 200 else []
life = ((items[0].get("status") or {}).get("lifeCycleStatus") if items else None)
except Exception as e:
logger.warning(f"[youtube] état du live précédent: {e!r}")
life = None
if life in ("ready", "testStarting", "testing", "liveStarting", "live"):
if cls._yt_end_task is not None:
cls._yt_end_task.cancel()
cls._yt_end_task = None
cfg = cls._load_cfg()
cls._yt_cfg(cfg).pop("broadcast_end_at", None)
cls._save_cfg(cfg)
logger.info(f"[youtube] reprise du live {bid} ({life})")
return True
logger.info(f"[youtube] live précédent {bid} non repris ({life})")
await cls._yt_end_broadcast() # range broadcast_id / indice du chat
return False
@classmethod
async def _yt_end_broadcast(cls):
"""Termine le live côté YouTube (l'arrêt auto prend sinon ~1 min)."""
if cls._yt_end_task is not None and cls._yt_end_task is not _current_task():
cls._yt_end_task.cancel()
cls._yt_end_task = None
bid = cls._yt_cfg().get("broadcast_id")
if not bid:
return
try:
await cls._yt_api("POST", "liveBroadcasts/transition",
params={"part": "id", "id": bid, "broadcastStatus": "complete"})
except Exception:
pass
cfg = cls._load_cfg()
cls._yt_cfg(cfg).pop("broadcast_id", None)
cls._yt_cfg(cfg).pop("broadcast_end_at", None)
cls._save_cfg(cfg)
cls._yt_write_live_hint("", "")
# Un live privé ou non répertorié n'apparaît PAS sur /channel/<id>/live :
# l'overlay attendait à l'infini (test 29/09). On lui donne l'ID de la vidéo
# qu'on vient de créer ; yt_chat.py relit ce fichier à chaque tentative, donc
# un overlay ouvert avant le live le trouve aussi. Vide = plus de live.
_YT_LIVE_HINT = "/tmp/bonecast-yt-live.json"
@classmethod
def _yt_write_live_hint(cls, channel_id, video_id):
try:
if not video_id:
if os.path.exists(cls._YT_LIVE_HINT):
os.remove(cls._YT_LIVE_HINT)
return
with open(cls._YT_LIVE_HINT, "w") as f:
dump({"channel": channel_id, "video": video_id}, f)
except Exception as e:
logger.warning(f"[youtube] live hint: {e!r}")
@classmethod
def _yt_chat_source(cls, cfg=None):
"""Chaîne dont l'overlay lit le chat : saisie manuelle, sinon sa propre
chaîne quand on est connecté (comme pour Twitch)."""
yt = (cfg if cfg is not None else cls._load_cfg()).get("youtube") or {}
return (yt.get("chat_channel") or yt.get("channel_id") or "").strip()
@classmethod
async def yt_send_chat(cls, message: str = ""):
"""Message dans le chat de SON live YouTube (connexion requise)."""
message = (message or "").strip()
if not message:
return {"ok": False, "error": "empty"}
yt = cls._yt_cfg()
if not (yt.get("oauth") or {}).get("access_token"):
return {"ok": False, "error": "not_logged_in"}
chat_id = yt.get("live_chat_id")
if not chat_id or cls._stream_platform != "youtube":
return {"ok": False, "error": "not_live"}
st, body = await cls._yt_api(
"POST", "liveChat/messages", params={"part": "snippet"},
json_body={"snippet": {"liveChatId": chat_id, "type": "textMessageEvent",
"textMessageDetails": {"messageText": message[:200]}}})
if st in (200, 201):
return {"ok": True}
return {"ok": False, "error": cls._yt_error(body, st)}
@classmethod
async def yt_set_settings(cls, settings=None):
"""Titre, visibilité, clé manuelle (chaîne vide = effacer la clé)."""
cfg = cls._load_cfg()
yt = cls._yt_cfg(cfg)
s = settings if isinstance(settings, dict) else {}
if isinstance(s.get("title"), str):
yt["title"] = s["title"].strip()[:100]
if s.get("privacy") in cls._YT_PRIVACY:
yt["privacy"] = s["privacy"]
if s.get("latency") in cls._YT_LATENCY:
yt["latency"] = s["latency"]
if isinstance(s.get("chat_channel"), str):
yt["chat_channel"] = s["chat_channel"].strip()
if isinstance(s.get("key"), str):
k = s["key"].strip()
if k:
yt["key"] = k
else:
yt.pop("key", None)
cls._save_cfg(cfg)
title_live = False
# En direct : le titre part aussi sur le live en cours.
if "title" in s and cls._stream_platform == "youtube" and yt.get("broadcast_id") \
and (yt.get("oauth") or {}).get("access_token"):
st, _ = await cls._yt_api(
"PUT", "videos", params={"part": "snippet"},
json_body={"id": yt["broadcast_id"],
"snippet": {"title": yt.get("title") or "BoneCast live",
"categoryId": cls._YT_GAMING}})
title_live = st == 200
return {"ok": True, "title_live": title_live}
# ── Overlay chat ─────────────────────────────────────────────────────────
@classmethod
def _overlay_state_dir(cls, platform="twitch"):
try:
acc = bcenv.steam_account_id()
except Exception:
acc = "default"
sub = "youtube_overlay" if platform == "youtube" else "twitch_overlay"
return os.path.expanduser(f"~/.local/share/bonecast/{sub}/{acc}")
@classmethod
def _overlay_holder(cls, cfg, platform):
"""Réglages d'apparence : ceux de Twitch à la racine, ceux de YouTube à part."""
return cls._yt_cfg(cfg) if platform == "youtube" else cfg
@classmethod
def _write_overlay_state(cls, cfg=None, platform="twitch"):
cfg = cls._load_cfg() if cfg is None else cfg
d = cls._overlay_state_dir(platform)
os.makedirs(d, exist_ok=True)
st = {**cls._OVERLAY_DEFAULTS, **(cls._overlay_holder(cfg, platform).get("overlay") or {})}
with open(os.path.join(d, "overlay_state.json"), "w") as f:
dump(st, f)
@staticmethod
def _scope_error(st, body):
"""401/403 Helix = token sans le scope (login antérieur à l'ajout) →
le front invite à se reconnecter (le device flow re-demande tout)."""
if st in (401, 403):
return {"ok": False, "error": "missing_scope",
"detail": (body or {}).get("message", "")}
return None
@classmethod
async def create_clip(cls):
"""Clip des ~30 dernières secondes du live (POST /helix/clips)."""
bid = cls._broadcaster_id()
if not bid:
return {"ok": False, "error": "not_logged_in"}
st, body = await cls._api("POST", "clips", params={"broadcaster_id": bid})
if err := cls._scope_error(st, body):
return err
data = (body or {}).get("data") or []
if st == 202 and data and data[0].get("id"):
logger.info(f"[clip] créé: {data[0]['id']}")
return {"ok": True, "id": data[0]["id"],
"edit_url": data[0].get("edit_url", "")}
# 404 = pas en live (Twitch ne peut clipper qu'un stream actif)
if st == 404:
return {"ok": False, "error": "not_live"}
return {"ok": False, "error": (body or {}).get("message") or f"http {st}"}
@classmethod
async def send_chat(cls, message: str = ""):
"""Envoie un message dans SON chat (POST /helix/chat/messages)."""
message = (message or "").strip()
if not message:
return {"ok": False, "error": "empty"}
bid = cls._broadcaster_id()
if not bid:
return {"ok": False, "error": "not_logged_in"}
st, body = await cls._api(
"POST", "chat/messages",
json_body={"broadcaster_id": bid, "sender_id": bid,
"message": message[:500]})
if err := cls._scope_error(st, body):
return err
data = (body or {}).get("data") or []
if st == 200 and data and data[0].get("is_sent"):
return {"ok": True}
drop = (data[0].get("drop_reason") or {}) if data else {}
return {"ok": False,
"error": drop.get("message") or (body or {}).get("message")
or f"http {st}"}
@classmethod
async def set_channel(cls, channel: str = ""):
try:
cfg = cls._load_cfg()
cfg["channel"] = (channel or "").strip().lstrip("#").lower()
cls._save_cfg(cfg)
return {"ok": True, "channel": cfg["channel"]}
except Exception as e:
return {"ok": False, "error": str(e)}
@classmethod
async def set_overlay_settings(cls, settings=None, platform="twitch"):
try:
cfg = cls._load_cfg()
holder = cls._overlay_holder(cfg, platform)
ov = {**cls._OVERLAY_DEFAULTS, **(holder.get("overlay") or {})}
for k in cls._OVERLAY_DEFAULTS:
if isinstance(settings, dict) and settings.get(k) is not None:
ov[k] = settings[k]
holder["overlay"] = ov
cls._save_cfg(cfg)
cls._write_overlay_state(cfg, platform) # poll live par chat.html
return {"ok": True, "overlay": ov}
except Exception as e:
return {"ok": False, "error": str(e)}
@classmethod
async def start_overlay(cls, platform="twitch"):
# Même course que start_stream (le processus n'existe qu'après l'await
# de create_subprocess_exec) : un seul overlay, Twitch OU YouTube.
if cls._start_overlay_lock is None:
cls._start_overlay_lock = Lock()
async with cls._start_overlay_lock:
return await cls._start_overlay_unlocked(platform)
@classmethod
async def _start_overlay_unlocked(cls, platform="twitch"):
platform = "youtube" if platform == "youtube" else "twitch"
if cls._overlay_proc is not None and cls._overlay_proc.returncode is None:
if cls._overlay_platform == platform:
return {"ok": True, "already": True}
return {"ok": False, "error": "busy", "platform": cls._overlay_platform}
cfg = cls._load_cfg()
if platform == "youtube":
channel = cls._yt_chat_source(cfg)
extra = ["--platform", "youtube", "--yt-source", channel]
else:
# Override manuel sinon = ta propre chaîne (login OAuth) → aucun pseudo à saisir.
channel = (cfg.get("channel") or (cfg.get("oauth") or {}).get("login") or "").strip()
extra = ["--channel", channel]
if not channel:
return {"ok": False, "error": "no_channel"}
from asyncio import create_subprocess_exec
from subprocess import PIPE
script = Path(DECKY_PLUGIN_DIR) / "twitch_overlay" / "overlay.py"
if not script.exists():
script = Path(DECKY_PLUGIN_DIR) / "defaults" / "twitch_overlay" / "overlay.py"
d = cls._overlay_state_dir(platform)
cls._write_overlay_state(cfg, platform)
try:
# Base = user_env() DIRECTEMENT (pas de .update() sur os.environ :
# update ne peut pas RETIRER le LD_LIBRARY_PATH PyInstaller, et ce