コード例 #1
0
ファイル: cast.py プロジェクト: jbouwh/core
def _play_media(hass: HomeAssistant, chromecast: Chromecast, media_type: str,
                media_id: str) -> None:
    """Play media."""
    result = process_plex_payload(hass, media_type, media_id)
    controller = PlexController()
    chromecast.register_handler(controller)
    offset_in_s = result.offset / 1000
    controller.play_media(result.media, offset=offset_in_s)
コード例 #2
0
def _play_media(hass: HomeAssistant, chromecast: Chromecast, media_type: str,
                media_id: str) -> None:
    """Play media."""
    media_id = media_id[len(PLEX_URI_SCHEME):]
    media = lookup_plex_media(hass, media_type, media_id)
    if media is None:
        return
    controller = PlexController()
    chromecast.register_handler(controller)
    controller.play_media(media)
コード例 #3
0
def play():
    try:
        output_chromecast_ip = sys.argv[1]
        uri_to_play = sys.argv[2]
        shuffle = sys.argv[3]
        if type(shuffle != bool):
            shuffle = string_to_bool(shuffle)
        redis_connection = try_to_connect_to_redis()
        spotify_token_info = RefreshSpotifyTokenIfNecessary(redis_connection)
        cast = Chromecast(output_chromecast_ip)
        cast.wait()
        client = spotipy.Spotify(auth=spotify_token_info["access_token"])
        sp = SpotifyController(spotify_token_info["access_token"],
                               spotify_token_info["seconds_left"])
        cast.register_handler(sp)
        sp.launch_app()
        if not sp.is_launched and not sp.credential_error:
            print('Failed to launch spotify controller due to timeout')
            sys.exit(1)
        if not sp.is_launched and sp.credential_error:
            print(
                'Failed to launch spotify controller due to credential error')
            sys.exit(1)

        devices_available = client.devices()
        spotify_device_id = None
        for device in devices_available['devices']:
            if device['id'] == sp.device:
                spotify_device_id = device['id']
                break
        if not spotify_device_id:
            print('No device with id "{}" known by Spotify'.format(sp.device))
            print('Known devices: {}'.format(devices_available['devices']))
            sys.exit(1)

        # # Start playback
        if uri_to_play.find('track') > 0:
            client.start_playback(device_id=spotify_device_id,
                                  uris=[uri_to_play])
        else:
            client.start_playback(device_id=spotify_device_id,
                                  context_uri=[uri_to_play])

        time.sleep(2)
        client.shuffle(shuffle)
        return True
    except Exception as e:
        print("Couldn't Load URI and Play Spotify")
        print(e)
        return False
コード例 #4
0
ファイル: app.py プロジェクト: chrisgilmerproj/echo-nest
def enable_chromecast():
    """
    Turn on the chromecast
    """
    cast = Chromecast('192.168.1.104')
    cast_name = cast.device.friendly_name
    print("Turning on the '{}' chromecast".format(cast_name))
    if cast:
        media = MediaController()
        cast.register_handler(media)
        time.sleep(1)
        print("Attempting to play media")
        media.play_media('http://upload.wikimedia.org/wikipedia/commons/7/7f/Pug_portrait.jpg', 'jpg')  # nopep8
        time.sleep(30)
        cast.quit_app()
コード例 #5
0
def enable_chromecast():
    """
    Turn on the chromecast
    """
    cast = Chromecast('192.168.1.104')
    cast_name = cast.device.friendly_name
    print("Turning on the '{}' chromecast".format(cast_name))
    if cast:
        media = MediaController()
        cast.register_handler(media)
        time.sleep(1)
        print("Attempting to play media")
        media.play_media(
            'http://upload.wikimedia.org/wikipedia/commons/7/7f/Pug_portrait.jpg',
            'jpg')  # nopep8
        time.sleep(30)
        cast.quit_app()
コード例 #6
0
def play_currated_uris(spotify_token_info, chromecast_output_ip, uris):
    try:
        cast = Chromecast(chromecast_output_ip)
        cast.wait()
        cast.media_controller.stop()
        #client = spotipy.Spotify( auth=spotify_token_info[ "access_token" ] )
        client = spotipy.Spotify(auth=spotify_token_info["access_token"])
        sp = SpotifyController(spotify_token_info["access_token"],
                               spotify_token_info["seconds_left"])
        cast.register_handler(sp)
        sp.launch_app()
        if not sp.is_launched and not sp.credential_error:
            print('Failed to launch spotify controller due to timeout')
            return False
        if not sp.is_launched and sp.credential_error:
            print(
                'Failed to launch spotify controller due to credential error')
            return False

        devices_available = client.devices()
        spotify_device_id = None
        for device in devices_available['devices']:
            if device['id'] == sp.device:
                spotify_device_id = device['id']
                break
        if not spotify_device_id:
            print('No device with id "{}" known by Spotify'.format(sp.device))
            print('Known devices: {}'.format(devices_available['devices']))
            return False

        client.start_playback(device_id=spotify_device_id, uris=uris)
        time.sleep(2)
        client.volume(99)
        time.sleep(2)
        client.volume(100)
        client.shuffle(False)
        return True
    except Exception as e:
        print("Couldn't Load Spotify Chromecast App")
        print(e)
        return False
コード例 #7
0
RefreshSpotifyTokenIfNecessary()

cast = Chromecast( OurPersonalDB.self[ "chromecast_ip" ] )
print('cast {}'.format(cast))
cast.wait()

spotify_device_id = None

# Create a spotify client
client = spotipy.Spotify( auth=OurSpotifyTokenDB.self[ "access_token" ] )
spotipy.trace = True
spotipy.trace_out = True

# Launch the spotify app on the cast we want to cast to
sp = SpotifyController( OurSpotifyTokenDB.self[ "access_token" ] , OurSpotifyTokenDB.self[ "seconds_left" ] )
cast.register_handler(sp)
sp.launch_app()

if not sp.is_launched and not sp.credential_error:
	print('Failed to launch spotify controller due to timeout')
	sys.exit(1)
if not sp.is_launched and sp.credential_error:
	print('Failed to launch spotify controller due to credential error')
	sys.exit(1)

# Query spotify for active devices
devices_available = client.devices()

# Match active spotify devices with the spotify controller's device id
for device in devices_available['devices']:
	if device['id'] == sp.device:
コード例 #8
0
class TwitchCastController(BaseController):
    """Controller used to send TwitchCast streams to a Chromecast."""
    def __init__(self,
                 chromecast_name: str = None,
                 chromecast_host: str = None) -> None:
        """Take care of some house keeping on init."""
        super(TwitchCastController,
              self).__init__('urn:x-cast:com.google.cast.media', 'DAC1CD8C')
        self._cast = None  # type: Chromecast
        self._chromecast_host = chromecast_host
        self._chromecast_name = chromecast_name
        self._expected_app_id = 'DAC1CD8C'
        self._setup_valid = False
        self._headers = {
            'User-Agent':
            "Home-Assistant-TwitchCast-Service {}".format(__version__)
        }
        self._location = "https://hls-us-west.nightdev.com"

    def _setup(self) -> bool:
        self._setup_valid = self._setup_chromecast()
        if self._setup_valid:
            _LOGGER.info("setup completed successfully")
        else:
            _LOGGER.error("setup failed")
            if not self._cast:
                _LOGGER.error("no cast device")
            return False
        return True

    def _setup_chromecast(self) -> bool:
        if self._chromecast_host:
            try:
                self._cast = Chromecast(host=self._chromecast_host)
                self._cast.register_handler(self)
                self._cast.wait()
                return True
            except pychromecast.error.ChromecastConnectionError:
                _LOGGER.error("cannot find {}".format(self._chromecast_host))
        elif self._chromecast_name:
            try:
                self._cast = next(
                    cc for cc in get_chromecasts()
                    if cc.device.friendly_name == self._chromecast_name)
                self._cast.register_handler(self)
                self._cast.wait()
                return True
            except StopIteration:
                _LOGGER.error("cannot find {}".format(self._chromecast_name))
        else:
            _LOGGER.error("no chromecast host or name defined.")
        return False

    @property
    def cast(self) -> Chromecast:
        """Get chromecast object or set one up if needed."""
        if not self._setup_valid:
            self._setup()
        return self._cast

    def _get_content_id(self, channel: str) -> str:
        _LOGGER.debug("getting content_id for {}".format(channel))
        r = requests.get(
            'https://nightdev.com/api/1/twitchcast/token?channel={}'.format(
                requests.utils.quote(channel)),
            headers=self._headers)
        token, sig = "", ""
        if r.status_code == 200:
            try:
                parsed_text = json.loads(r.text)
                token = parsed_text['token']
                sig = parsed_text['sig']
            except (ValueError, KeyError):
                _LOGGER.error(
                    "error parsing token and sig for {}".format(channel))
                return ""
        else:
            _LOGGER.error("status {} during token and sig for {}".format(
                r.status_code, channel))
        playlist = []  # type: List[dict]
        if token and sig:
            url = '{}/get/playlist?channel={}&token={}&sig={}&callback=?'.\
                format(
                    self._location,
                    requests.utils.quote(channel),
                    requests.utils.quote(token),
                    requests.utils.quote(sig))
            r = requests.get(url, headers=self._headers)
            if r.status_code == 200:
                try:
                    playlist = json.loads(r.text[2:-2])['playlist']
                except ValueError:
                    _LOGGER.error(
                        "error parsing playlist for {}".format(channel))
                    return ""
            else:
                _LOGGER.error("status {} during playlist for {}".format(
                    r.status_code, channel))
        else:
            return ""
        if playlist:
            return playlist[0]['url']
        else:
            return ""

    def _check_app_id(self, timeout: int = 10) -> bool:
        if not self.cast:
            return False
        if self.cast.app_id != self._expected_app_id:
            self.launch()
        for t in range(timeout * 5):
            if self.cast.app_id != self._expected_app_id:
                time.sleep(t / 5)
            else:
                return True
        return False

    def _stream_channel_callback(self, channel: str, layout: str,
                                 content_id: str) -> None:
        msg = {
            'type': 'LOAD',
            'media': {
                'contentId': content_id,
                'contentType': 'video/mp4',
                'streamType': 'LIVE',
                'metadata': self.channel_details(channel)
            },
            'mediaSessionId': None,
            'customData': {
                'channel': channel,
                'layout': layout,
            },
        }
        _LOGGER.debug("sending chromecast message {}".format(msg))
        self.send_message(msg)

    def channel_details(self, channel: str) -> dict:
        """Get stream title & details from Twitch Kraken API."""
        _LOGGER.debug("getting steam details for {}".format(channel))
        metadata = {
            'metadataType': 1,
            'title': channel,
            'subtitle': channel,
            'images': []
        }
        r = requests.get('https://api.twitch.tv/kraken/streams/{}?client_id'
                         '=apbhlybpld3ybc6grv5c118xqpoz01c'.format(
                             requests.utils.quote(channel)),
                         headers=self._headers)
        if r.status_code == 200:
            try:
                parsed_text = json.loads(r.text)['stream']['channel']
                metadata['title'] = parsed_text['display_name']
                metadata['subtitle'] = parsed_text['status']
                metadata['images'].append({
                    'url': parsed_text['logo'],
                    'width': 0,
                    'height': 0,
                })
            except (ValueError, KeyError):
                _LOGGER.error(
                    "error parsing channel details for {}".format(channel))
        else:
            _LOGGER.error("status {} during token and sig for {}".format(
                r.status_code, channel))
        return metadata

    def stream_channel(self, channel: str, layout: str) -> None:
        """Stream a channel for a given layout on the Chromecast."""
        _LOGGER.debug("trying to stream {} - {}".format(channel, layout))
        content_id = self._get_content_id(channel)
        self._launched = False
        if content_id:
            _LOGGER.debug("launching {} - {}".format(channel, layout))
            if self._check_app_id():
                self.launch(
                    callback_function=partial(self._stream_channel_callback,
                                              channel=channel,
                                              layout=layout,
                                              content_id=content_id))
            else:
                _LOGGER.error("timed out waiting on chromecast")
        else:
            _LOGGER.error("couldn't get content_id for {}".format(channel))
コード例 #9
0
ファイル: spotify.py プロジェクト: heholek/honeycast
from pychromecast import Chromecast
from pychromecast.controllers.spotify import SpotifyController
import spotify_token

username = input("Spotify username: "******"Spotify password: "******"Honeycast url: ") or "localhost"

session = spotify_token.start_session(username, password)
token = session[0]

cast = Chromecast(cast_address)
controller = SpotifyController(token)
cast.register_handler(controller)
controller.launch_app()