476 lines
14 KiB
Python
476 lines
14 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import socket
|
|
import threading
|
|
import uuid
|
|
from urllib.parse import urlencode
|
|
|
|
import requests
|
|
|
|
from .bridge import (
|
|
STATUS_LOADING,
|
|
STATUS_PLAYING,
|
|
STATUS_PAUSED,
|
|
STATUS_STOPPED,
|
|
bridge,
|
|
)
|
|
from .command_parser import CommandParser
|
|
from .templates import announcement
|
|
|
|
logger = logging.getLogger("kronic.cast.youtube")
|
|
|
|
MAX_SEND_RETRIES = 3
|
|
|
|
|
|
class CastState:
|
|
def __init__(self):
|
|
self.ctt = None
|
|
self.playlist_id = None
|
|
self.playlist = None
|
|
self.playlist_index = None
|
|
|
|
@property
|
|
def video_id(self):
|
|
if not self.has_playlist:
|
|
return None
|
|
return self.playlist[self.playlist_index]
|
|
|
|
@property
|
|
def has_playlist(self):
|
|
return bool(self.playlist)
|
|
|
|
def handle_set_playlist(self, data):
|
|
if "ctt" in data:
|
|
self.ctt = data["ctt"]
|
|
|
|
self.playlist_id = data.get("listId")
|
|
self.playlist = str(data.get("videoIds") or "").split(",")
|
|
self.playlist = [item for item in self.playlist if item]
|
|
self.playlist_index = int(data.get("currentIndex") or 0)
|
|
if self.playlist:
|
|
self.playlist_index = max(
|
|
0,
|
|
min(self.playlist_index, len(self.playlist) - 1),
|
|
)
|
|
|
|
def handle_update_playlist(self, data):
|
|
video_ids = data.get("videoIds")
|
|
if not video_ids:
|
|
self.playlist = None
|
|
self.playlist_index = None
|
|
return
|
|
|
|
self.playlist = [item for item in str(video_ids).split(",") if item]
|
|
if (
|
|
self.playlist_index is not None
|
|
and self.playlist_index >= len(self.playlist)
|
|
):
|
|
self.playlist_index = len(self.playlist) - 1
|
|
|
|
def _change_playlist_index(self, change):
|
|
if not self.has_playlist:
|
|
return False
|
|
next_index = self.playlist_index + change
|
|
if not 0 <= next_index < len(self.playlist):
|
|
return False
|
|
self.playlist_index = next_index
|
|
return True
|
|
|
|
def playlist_next(self):
|
|
return self._change_playlist_index(1)
|
|
|
|
def playlist_prev(self):
|
|
return self._change_playlist_index(-1)
|
|
|
|
def create_state_data(self):
|
|
if not self.has_playlist:
|
|
return {}
|
|
return {
|
|
"videoId": self.video_id,
|
|
"ctt": self.ctt,
|
|
"listId": self.playlist_id,
|
|
"currentIndex": self.playlist_index,
|
|
}
|
|
|
|
|
|
class YoutubeCastReceiver:
|
|
def __init__(self, friendly_name):
|
|
self.base_url = os.getenv(
|
|
"KRONIC_CAST_YOUTUBE_BASE_URL",
|
|
"https://www.youtube.com",
|
|
).rstrip("/")
|
|
self.verify_ssl = os.getenv(
|
|
"KRONIC_CAST_VERIFY_SSL",
|
|
"true",
|
|
).lower() not in {"0", "false", "no", "off"}
|
|
|
|
self.default_screen_name = friendly_name
|
|
self.default_screen_app = os.getenv(
|
|
"KRONIC_CAST_SCREEN_APP",
|
|
"kronic-tubecast",
|
|
)
|
|
self.screen_uid = str(
|
|
uuid.uuid5(
|
|
uuid.NAMESPACE_DNS,
|
|
f"kronic.youtube.screen.{friendly_name}",
|
|
)
|
|
)
|
|
|
|
self.session = requests.Session()
|
|
self.session.headers.update({
|
|
"User-Agent": (
|
|
"Mozilla/5.0 (CrKey - 0.9.3) "
|
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
"Chrome/30.0.1573.2 Safari/537.36"
|
|
)
|
|
})
|
|
|
|
self.listener = None
|
|
self._lock = threading.RLock()
|
|
self._initial_app_state()
|
|
|
|
bridge.set_state_reporter(self._browser_state_changed)
|
|
|
|
def _initial_app_state(self):
|
|
with self._lock:
|
|
self.screen_id = None
|
|
self.lounge_token = None
|
|
self.ofs = 0
|
|
self.has_client = False
|
|
self.connected_client = None
|
|
self.code = -1
|
|
self.bind_vals = announcement(
|
|
self.screen_uid,
|
|
self.default_screen_name,
|
|
self.default_screen_app,
|
|
)
|
|
self.state = CastState()
|
|
|
|
self._replace_listener(None)
|
|
|
|
def _replace_listener(self, listener):
|
|
previous = self.listener
|
|
if previous is not None:
|
|
previous.force_stop()
|
|
if previous is not threading.current_thread():
|
|
previous.join(timeout=3)
|
|
|
|
self.listener = listener
|
|
if listener is not None:
|
|
listener.start()
|
|
|
|
def state_xml_connected(self):
|
|
return bool(self.has_client)
|
|
|
|
def dial_launch(self, pairing_code):
|
|
self.has_client = True
|
|
self._pair(pairing_code)
|
|
|
|
def dial_stop(self):
|
|
bridge.publish("stop")
|
|
self._initial_app_state()
|
|
|
|
def _pair(self, pairing_code):
|
|
logger.info("Pairing Kronic Cast with YouTube sender")
|
|
self._generate_screen_id()
|
|
self._get_lounge_token_batch()
|
|
self._bind()
|
|
if pairing_code:
|
|
self._register_pairing_code(pairing_code)
|
|
self._replace_listener(YoutubeListener(app=self, ssdp=True))
|
|
|
|
def _generate_screen_id(self):
|
|
response = self.session.get(
|
|
f"{self.base_url}/api/lounge/pairing/generate_screen_id",
|
|
verify=self.verify_ssl,
|
|
timeout=15,
|
|
)
|
|
response.raise_for_status()
|
|
self.screen_id = response.text.strip()
|
|
return self.screen_id
|
|
|
|
def _get_lounge_token_batch(self):
|
|
response = self.session.post(
|
|
f"{self.base_url}/api/lounge/pairing/get_lounge_token_batch",
|
|
data={"screen_ids": self.screen_id},
|
|
verify=self.verify_ssl,
|
|
timeout=15,
|
|
)
|
|
response.raise_for_status()
|
|
token_info = response.json()
|
|
self.lounge_token = token_info["screens"][0]["loungeToken"]
|
|
self.bind_vals["loungeIdToken"] = self.lounge_token
|
|
return self.lounge_token
|
|
|
|
def _bind(self):
|
|
self.ofs += 1
|
|
self.bind_vals["CVER"] = "1"
|
|
response = self.session.post(
|
|
f"{self.base_url}/api/lounge/bc/bind?{urlencode(self.bind_vals)}",
|
|
data={"count": "0"},
|
|
verify=self.verify_ssl,
|
|
timeout=20,
|
|
)
|
|
response.raise_for_status()
|
|
for cmd in CommandParser(response.text):
|
|
self.handle_cmd(cmd)
|
|
|
|
def _register_pairing_code(self, pairing_code):
|
|
response = self.session.post(
|
|
f"{self.base_url}/api/lounge/pairing/register_pairing_code",
|
|
data={
|
|
"access_type": "permanent",
|
|
"app": self.default_screen_app,
|
|
"pairing_code": pairing_code,
|
|
"screen_id": self.screen_id,
|
|
"screen_name": self.default_screen_name,
|
|
"device_id": self.default_screen_name,
|
|
},
|
|
verify=self.verify_ssl,
|
|
timeout=15,
|
|
)
|
|
logger.info(
|
|
"YouTube pairing registration returned HTTP %s",
|
|
response.status_code,
|
|
)
|
|
|
|
def handle_cmd(self, cmd):
|
|
code, name, data = cmd
|
|
|
|
if code <= self.code:
|
|
return
|
|
self.code = code
|
|
|
|
logger.info("YouTube cast command: %s", name)
|
|
|
|
if name == "c":
|
|
self.bind_vals["SID"] = data[0]
|
|
|
|
elif name == "S":
|
|
self.bind_vals["gsessionid"] = data
|
|
|
|
elif name == "remoteConnected":
|
|
self.has_client = True
|
|
self.connected_client = data
|
|
self._disable_autoplay()
|
|
|
|
elif name == "remoteDisconnected":
|
|
bridge.publish("stop")
|
|
self._initial_app_state()
|
|
|
|
elif name == "getNowPlaying":
|
|
self.report_now_playing()
|
|
|
|
elif name == "setPlaylist":
|
|
self.state.handle_set_playlist(data or {})
|
|
bridge.publish(
|
|
"play",
|
|
video_id=self.state.video_id,
|
|
position=float((data or {}).get("currentTime") or 0),
|
|
playlist_id=self.state.playlist_id,
|
|
playlist=list(self.state.playlist or []),
|
|
playlist_index=self.state.playlist_index,
|
|
)
|
|
|
|
elif name == "updatePlaylist":
|
|
self.state.handle_update_playlist(data or {})
|
|
if not self.state.has_playlist:
|
|
bridge.publish("stop")
|
|
|
|
elif name == "next":
|
|
if self.state.playlist_next():
|
|
bridge.publish(
|
|
"play",
|
|
video_id=self.state.video_id,
|
|
position=0,
|
|
playlist_index=self.state.playlist_index,
|
|
)
|
|
|
|
elif name == "previous":
|
|
if self.state.playlist_prev():
|
|
bridge.publish(
|
|
"play",
|
|
video_id=self.state.video_id,
|
|
position=0,
|
|
playlist_index=self.state.playlist_index,
|
|
)
|
|
|
|
elif name == "pause":
|
|
bridge.publish("pause")
|
|
|
|
elif name == "stopVideo":
|
|
bridge.publish("stop")
|
|
|
|
elif name == "seekTo":
|
|
new_time = round(float((data or {}).get("newTime") or 0))
|
|
current = bridge.player_state()
|
|
self.report_state_change(
|
|
STATUS_LOADING,
|
|
new_time,
|
|
current.get("duration") or 0,
|
|
)
|
|
bridge.publish("seek", position=new_time)
|
|
|
|
elif name == "getVolume":
|
|
current = bridge.player_state()
|
|
self.report_volume(current.get("volume") or 100)
|
|
|
|
elif name == "setVolume":
|
|
bridge.publish(
|
|
"volume",
|
|
volume=max(0, min(100, int((data or {}).get("volume") or 0))),
|
|
)
|
|
|
|
elif name == "play":
|
|
bridge.publish("resume")
|
|
|
|
def _disable_autoplay(self):
|
|
self._post_bind(
|
|
"onAutoplayModeChanged",
|
|
{"autoplayMode": "DISABLED"},
|
|
)
|
|
|
|
def _browser_state_changed(self, state):
|
|
if not self.has_client:
|
|
return
|
|
self.report_state_change(
|
|
int(state.get("status") or STATUS_STOPPED),
|
|
int(float(state.get("position") or 0)),
|
|
int(float(state.get("duration") or 0)),
|
|
)
|
|
|
|
def report_now_playing(self):
|
|
data = self.state.create_state_data()
|
|
state = bridge.player_state()
|
|
if state.get("video_id"):
|
|
data.update(
|
|
currentTime=str(int(float(state.get("position") or 0))),
|
|
state=str(int(state.get("status") or STATUS_STOPPED)),
|
|
)
|
|
self._post_bind("nowPlaying", data)
|
|
|
|
def report_volume(self, volume):
|
|
self._post_bind(
|
|
"onVolumeChanged",
|
|
{"volume": str(int(volume)), "muted": "false"},
|
|
)
|
|
|
|
def report_state_change(self, status_code, current_time, duration):
|
|
self._post_bind(
|
|
"onStateChange",
|
|
{
|
|
"currentTime": str(int(current_time)),
|
|
"state": str(int(status_code)),
|
|
"duration": str(int(duration)),
|
|
"cpn": "kronic",
|
|
},
|
|
)
|
|
|
|
def _post_bind(self, sc, postdata):
|
|
if not self.lounge_token:
|
|
return
|
|
|
|
self.ofs += 1
|
|
post_data = {
|
|
"count": "1",
|
|
"ofs": str(self.ofs),
|
|
"req0__sc": sc,
|
|
}
|
|
for key, value in postdata.items():
|
|
post_data["req0_" + key] = value
|
|
|
|
self.bind_vals["RID"] = "1337"
|
|
url = f"{self.base_url}/api/lounge/bc/bind?{urlencode(self.bind_vals)}"
|
|
|
|
last_error = None
|
|
for attempt in range(MAX_SEND_RETRIES):
|
|
try:
|
|
response = self.session.post(
|
|
url,
|
|
data=post_data,
|
|
verify=self.verify_ssl,
|
|
timeout=15,
|
|
)
|
|
response.raise_for_status()
|
|
return
|
|
except requests.RequestException as error:
|
|
last_error = error
|
|
logger.warning(
|
|
"Cast state send failed (%s/%s): %s",
|
|
attempt + 1,
|
|
MAX_SEND_RETRIES,
|
|
error,
|
|
)
|
|
if last_error:
|
|
logger.error("Unable to send cast state: %s", last_error)
|
|
|
|
|
|
class YoutubeListener(threading.Thread):
|
|
def __init__(self, app, ssdp=True):
|
|
super().__init__(name="KronicYoutubeListener", daemon=True)
|
|
self.app = app
|
|
self.stop_event = threading.Event()
|
|
self.ssdp = ssdp
|
|
self.response = None
|
|
|
|
def _read_cmd_chunks(self, url):
|
|
with self.app.session.get(
|
|
url,
|
|
stream=True,
|
|
verify=self.app.verify_ssl,
|
|
timeout=(15, 90),
|
|
) as self.response:
|
|
self.response.raise_for_status()
|
|
for chunk in self.response.iter_content(chunk_size=None):
|
|
if self.stop_event.is_set():
|
|
break
|
|
if chunk:
|
|
yield chunk
|
|
|
|
def _listen(self):
|
|
self.app.ofs += 1
|
|
bind_vals = self.app.bind_vals.copy()
|
|
bind_vals["RID"] = "rpc"
|
|
bind_vals["CI"] = "0"
|
|
bind_vals["TYPE"] = "xmlhttp"
|
|
bind_vals["AID"] = "3"
|
|
url = (
|
|
f"{self.app.base_url}/api/lounge/bc/bind?"
|
|
f"{urlencode(bind_vals)}"
|
|
)
|
|
|
|
parser = CommandParser()
|
|
for chunk in self._read_cmd_chunks(url):
|
|
parser.write(chunk.decode("utf-8", "replace"))
|
|
for cmd in parser.get_commands():
|
|
self.app.handle_cmd(cmd)
|
|
|
|
def run(self):
|
|
while (
|
|
not self.stop_event.is_set()
|
|
and (not self.ssdp or self.app.has_client)
|
|
):
|
|
try:
|
|
self._listen()
|
|
except requests.RequestException as error:
|
|
if self.stop_event.is_set():
|
|
break
|
|
logger.warning("YouTube listener reconnecting after: %s", error)
|
|
self.stop_event.wait(1.0)
|
|
except Exception:
|
|
if self.stop_event.is_set():
|
|
break
|
|
logger.exception("YouTube cast listener error")
|
|
self.stop_event.wait(1.0)
|
|
|
|
def force_stop(self):
|
|
self.stop_event.set()
|
|
response = self.response
|
|
if response is not None:
|
|
try:
|
|
response.close()
|
|
except Exception:
|
|
pass
|