Ejemplo n.º 1
0
    def start_casting(call):
        """service called."""

        from pychromecast.controllers.spotify import SpotifyController
        import spotipy

        uri = call.data.get(CONF_SPOTIFY_URI)
        if call.data.get(CONF_DEVICE_NAME) is None:
            device_name = hass.states.get(
                call.data.get(CONF_ENTITY_ID)).attributes.get('friendly_name')
        else:
            device_name = call.data.get(CONF_DEVICE_NAME)

        _LOGGER.debug('Starting spotify on %s', device_name)

        # Find chromecast device
        cast = get_chromcast_device(device_name)
        cast.wait()

        account = call.data.get(CONF_SPOTIFY_ACCOUNT)
        user = username
        pwd = password
        if account is not None:
            _LOGGER.debug('setting up with different account than default %s',
                          account)
            user = accounts.get(account).get(CONF_USERNAME)
            pwd = accounts.get(account).get(CONF_PASSWORD)

        # login as real browser to get powerful token
        access_token, expires = get_spotify_token(username=user, password=pwd)

        client = spotipy.Spotify(auth=access_token)

        # launch the app on chromecast
        sp = SpotifyController(access_token, expires)
        cast.register_handler(sp)
        sp.launch_app()

        if not sp.is_launched and not sp.credential_error:
            raise HomeAssistantError(
                'Failed to launch spotify controller due to timeout')
        if not sp.is_launched and sp.credential_error:
            raise HomeAssistantError(
                'Failed to launch spotify controller due to credentials error')

        spotify_device_id = None
        devices_available = client.devices()
        for device in devices_available['devices']:
            if device['id'] == sp.device:
                spotify_device_id = device['id']
                break

        if not spotify_device_id:
            _LOGGER.error('No device with id "{}" known by Spotify'.format(
                sp.device))
            _LOGGER.error('Known devices: {}'.format(
                devices_available['devices']))
            return

        play(client, spotify_device_id, uri)
Ejemplo n.º 2
0
    def startSpotifyController(self, access_token, expires):
        sp = SpotifyController(access_token, expires)
        self.castDevice.register_handler(sp)
        sp.launch_app()

        if not sp.is_launched and not sp.credential_error:
            raise HomeAssistantError(
                "Failed to launch spotify controller due to timeout")
        if not sp.is_launched and sp.credential_error:
            raise HomeAssistantError(
                "Failed to launch spotify controller due to credentials error")

        self.spotifyController = sp
Ejemplo n.º 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
Ejemplo n.º 4
0
def launch_spotify_app():
    global shared_options
    global shared_chromecast
    global shared_spotify_client
    global shared_spotify_device_id
    try:
        if shared_chromecast == False:
            init_chromecast(shared_options)
        shared_spotify_client = False
        shared_spotify_client = spotipy.Spotify(
            auth=shared_options['spotify_token_info']["access_token"])
        sp = SpotifyController(
            shared_options['spotify_token_info']["access_token"],
            shared_options['spotify_token_info']["seconds_left"])
        shared_chromecast.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 = shared_spotify_client.devices()
        #shared_spotify_device_id = False
        print("Available Devices ==")
        print(devices_available['devices'])
        for device in devices_available['devices']:
            if device['is_active'] == True:
                # if device[ 'name' ] == "Attic TV":
                # 	shared_spotify_device_id = device['id']
                # 	break
                if device['type'] == "CastVideo":
                    shared_spotify_device_id = device['id']
                    break
            if device['id'] == sp.device:
                shared_spotify_device_id = device['id']
                break
        if not shared_spotify_device_id:
            print('No device with id "{}" known by Spotify'.format(sp.device))
            print('Known devices: {}'.format(devices_available['devices']))
            return False
        return True
    except Exception as e:
        print(e)
        shared_spotify_client = False
        shared_spotify_device_id = False
        return False
Ejemplo n.º 5
0
    def start_casting(call):
        """service called."""

        from pychromecast.controllers.spotify import SpotifyController
        import spotipy

        uri = call.data.get(CONF_SPOTIFY_URI)
        device_name = call.data.get(CONF_DEVICE_NAME)

        _LOGGER.info('Starting spotify on %s', device_name)

        # Find chromecast device
        cast = get_chromcase_device(device_name)
        cast.wait()

        account = call.data.get(CONF_SPOTIFY_ACCOUNT)
        user = username
        pwd = password
        if account is not None:
            _LOGGER.info('setting up with different account than default %s',
                         account)
            user = accounts.get(account).get(CONF_USERNAME)
            pwd = accounts.get(account).get(CONF_PASSWORD)

        # login as real browser to get powerful token
        access_token, expires = get_spotify_token(username=username,
                                                  password=password)

        client = spotipy.Spotify(auth=access_token)

        # launch the app on chromecast
        sp = SpotifyController(access_token, expires)
        cast.register_handler(sp)
        sp.launch_app()

        spotify_device_id = None
        devices_available = client.devices()
        for device in devices_available['devices']:
            if device['name'] == device_name:
                spotify_device_id = device['id']
                break

        play(client, spotify_device_id, uri)
Ejemplo n.º 6
0
    def startSpotifyController(self, access_token, expires):
        from pychromecast.controllers.spotify import SpotifyController
        # get the volume so we can remove the bloink
        # volume = self.castDevice.status.volume_level
        # self.castDevice.set_volume(0)

        sp = SpotifyController(access_token, expires)
        self.castDevice.register_handler(sp)
        sp.launch_app()

        # reset the volume
        # self.castDevice.set_volume(volume)

        if not sp.is_launched and not sp.credential_error:
            raise HomeAssistantError('Failed to launch spotify controller due to timeout')
        if not sp.is_launched and sp.credential_error:
            raise HomeAssistantError('Failed to launch spotify controller due to credentials error')

        self.spotifyController = sp
Ejemplo n.º 7
0
def play_music(song_uri):
    devices = pychromecast.get_chromecasts()
    speaker = next(cc for cc in devices
                   if cc.device.friendly_name == CAST_NAME)
    speaker.wait()
    data = st.start_session("little_wang", "Jumbobean123")
    access_token = data[0]
    expires = data[1] - int(time.time())

    client = spotipy.Spotify(auth=access_token)
    sp = SpotifyController(access_token, expires)
    speaker.register_handler(sp)
    sp.launch_app()
    devices_available = client.devices()
    for device in devices_available['devices']:
        if device['name'] == CAST_NAME:
            device_id = device['id']
            break
    speaker.set_volume(0.5)
    client.start_playback(device_id=device_id, uris=[song_uri])
Ejemplo n.º 8
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
Ejemplo n.º 9
0
def _getSpotifyChromecastController():
    try:
        spotifyUserUsername = os.environ['SPOTIFY_USER_USERNAME']
        spotifyUserPassword = os.environ['SPOTIFY_USER_PASSWORD']
    except KeyError:
        raise SpotifyPlaybackError(
            'Missing Spotify user credentials in env vars '
            '`SPOTIFY_USER_USERNAME` and/or `SPOTIFY_USER_PASSWORD`')
    (spotifyControllerAccessToken,
     spotifyControllerExpiresAt) = spotify_token.start_session(
         spotifyUserUsername, spotifyUserPassword)
    spotifyControllerExpiresIn = spotifyControllerExpiresAt - int(time())

    return SpotifyController(spotifyControllerAccessToken,
                             spotifyControllerExpiresIn)
Ejemplo n.º 10
0
    def initialize(self):
        self.sp_key = sp_key
        self.sp_dc = sp_dc
        token, expires = spotify_token.start_session(sp_dc, sp_key)
        self.spotify_controller = SpotifyController(token, expires)

        username = self.settings.get('username')
        password = self.settings.get('password')
        self.log.info("Settings:" + str(self.settings))
        self.log.info("Username:"******"Password:"******"Init device")
        self.log.info("Init spotify cast skill")
        thread = threading.Thread(target=self.update_chromecasts)
        thread.start()
Ejemplo n.º 11
0
def play_spotify(user,
                 password,
                 uri=["spotify:track:3Zwu2K0Qa5sT6teCCHPShP"],
                 show_debug=False,
                 cast="Sadie's TV"):
    if show_debug:
        logging.basicConfig(level=logging.DEBUG)
        # Uncomment to enable http.client debug log
        #http_client.HTTPConnection.debuglevel = 1

    # Store the ip in a txt file
    # Open File
    cast_ip = None

    with open('cast.txt', 'r+') as f:
        print("This is the file pointer", f)
        if len(f.read(1)) == 0:
            cast = discover_casts(cast)
        else:
            f.seek(0)
            cast_ip = [line for line in f][0]
            cast = get_cast(cast_ip, cast)

        if (cast.host != cast_ip):
            f.write(cast.host)

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(user, password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    # Create a spotify client
    client = spotipy.Spotify(auth=access_token)
    if show_debug:
        spotipy.trace = True
        spotipy.trace_out = True

    # Launch the spotify app on the cast we want to cast to
    sp = SpotifyController(access_token, expires)
    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:
            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[0].find('track') > 0:
        client.start_playback(device_id=spotify_device_id, uris=uri)
    else:
        client.start_playback(device_id=spotify_device_id, context_uri=uri[0])
Ejemplo n.º 12
0
def launch_spotify(target, user, password, uri):

    chromecasts = pychromecast.get_listed_chromecasts(friendly_names=target)
    cast = None
    for _cast in chromecasts:
        if _cast.name == target:
            cast = _cast
            break

    if not cast:
        print('No chromecast with name "{}" discovered'.format(target))
        print("Discovered casts: {}".format(chromecasts))
        sys.exit(1)

    print("cast {}".format(cast))

    class ConnListener:
        def __init__(self, mz):
            self._mz = mz

        def new_connection_status(self, connection_status):
            """Handle reception of a new ConnectionStatus."""
            if connection_status.status == "CONNECTED":
                self._mz.update_members()

    class MzListener:
        def __init__(self):
            self.got_members = False

        def multizone_member_added(self, uuid):
            pass

        def multizone_member_removed(self, uuid):
            pass

        def multizone_status_received(self):
            self.got_members = True

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(user, password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    #Create spotify client
    client = spotipy.Spotify(auth=access_token)

    # Launch the spotify app on cast device
    sp = SpotifyController(access_token, expires)
    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:
            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
    client.start_playback(device_id=spotify_device_id, context_uri=uri)
Ejemplo n.º 13
0
    logging.basicConfig(level=logging.DEBUG)

chromecasts = pychromecast.get_chromecasts()
cast = None
for _cast in chromecasts:
    if _cast.name == CAST_NAME:
        cast = _cast
        break

if cast:
    cast.wait()
    device_id = None

    data = st.start_session("SPOTIFY_USERNAME", "SPOTIFY_PASSWORD")
    access_token = data[0]

    client = spotipy.Spotify(auth=access_token)

    sp = SpotifyController(access_token)
    cast.register_handler(sp)
    sp.launch_app()

    devices_available = client.devices()

    for device in devices_available['devices']:
        if device['name'] == CAST_NAME:
            device_id = device['id']
            break

    client.start_playback(device_id=device_id,
                          uris=["spotify:track:3Zwu2K0Qa5sT6teCCHPShP"])
Ejemplo n.º 14
0
def play(args):
    cast.wait()
    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(
        'AQCNDwe7-v4N1F0SLn_HbosHFppfrYvUW-RON3cq-l17dFWIxNEItMSC_Ydm3kN1sBnz8lIucTzx9XC0B-fYAdTi_tODOmqf0mR2LNVJ9Q',
        '03439c8c-2dc1-45c4-85e1-55726b431177')
    access_token = data[0]
    expires = data[1] - int(time.time())

    # Create a spotify client
    client = spotipy.Spotify(auth=access_token)

    # Launch the spotify app on the cast we want to cast to
    sp = SpotifyController(access_token, expires)
    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:
            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)

    def getTracks(uri):
        split = uri.split(":")

        def doAlbum(_id):
            tracks = client.album_tracks(_id)
            return tracks['total'], uri

        if split[1] == "playlist":
            playlist = client.playlist(split[2])

            num_tracks = playlist['tracks']['total']
            return num_tracks, uri
        elif split[1] == "artist":
            # Turn it into one of their albums
            raw = client.artist_albums(split[2])
            albums = raw['items']
            uri = random.choice(albums)['uri']
            return doAlbum(uri.split(":")[2])
        elif split[1] == "album":
            return doAlbum(split[2])

    def getName(str):
        ttype = str.split(":")[1]
        item = client.track(str) if ttype == 'track' \
            else client.album(str) if ttype == 'album' \
            else client.artist(str) if ttype == 'artist' \
            else client.playlist(str)
        return item['name']

    # Start playback
    def playMusic():
        if args.uri[0] == 'unset':
            dat = client.user_playlists("12144944831")['items']
            # Get the playlists for my account
            dd = [o['id'] for o in dat]
            dd2 = [o['name'] for o in dat]
            choice = random.choice(dd)

            uuri = "spotify:playlist:{}".format(choice)
            num_tracks, uri = getTracks(uuri)

            print("♫ Playing " + dd2[dd.index(choice)] + " ♫")
            client.start_playback(
                device_id=spotify_device_id,
                context_uri=uuri,
                offset={"position": random.randint(0, num_tracks - 1)})
            cast.wait()
            volume.setVolume(volume.MUSIC_VOLUME, "Spotify")
            client.shuffle(True, device_id=spotify_device_id)
        else:
            name = getName(args.uri[0])
            print("♫ Playing: " + name + " ♫")
            if args.uri[0].find("track") > 0:
                client.start_playback(device_id=spotify_device_id,
                                      uris=args.uri)
            else:
                num_tracks, uri = getTracks(args.uri[0])
                client.start_playback(
                    device_id=spotify_device_id,
                    context_uri=uri,
                    offset={"position": random.randint(0, num_tracks - 1)})
            volume.setVolume(volume.MUSIC_VOLUME, "Spotify")
            client.shuffle(True, device_id=spotify_device_id)

    playMusic()
Ejemplo n.º 15
0
def run_spotify():
    """
	Example on how to use the Spotify Controller.
	NOTE: You need to install the spotipy and spotify-token dependencies.
	
	This can be done by running the following:
	pip install spotify-token
	pip install git+https://github.com/plamere/spotipy.git
	"""
    import argparse
    import logging
    import time
    import sys

    import pychromecast
    from pychromecast.controllers.spotify import SpotifyController
    import spotify_token as st
    import spotipy

    CAST_NAME = "My Chromecast"

    parser = argparse.ArgumentParser(
        description="Example on how to use the Spotify Controller.")
    parser.add_argument("--show-debug",
                        help="Enable debug log",
                        action="store_true")
    parser.add_argument("--cast",
                        help='Name of cast device (default: "%(default)s")',
                        default=CAST_NAME)
    parser.add_argument("--user", help="Spotify username", required=True)
    parser.add_argument("--password", help="Spotify password", required=True)
    parser.add_argument(
        "--uri",
        help='Spotify uri(s) (default: "%(default)s")',
        default=["spotify:track:3Zwu2K0Qa5sT6teCCHPShP"],
        nargs="+",
    )
    args = parser.parse_args()

    if args.show_debug:
        logging.basicConfig(level=logging.DEBUG)
        # Uncomment to enable http.client debug log
        # http_client.HTTPConnection.debuglevel = 1

    chromecasts = pychromecast.get_listed_chromecasts(
        friendly_names=[args.cast])
    cast = None
    for _cast in chromecasts:
        if _cast.name == args.cast:
            cast = _cast
            break

    if not cast:
        print('No chromecast with name "{}" discovered'.format(args.cast))
        print("Discovered casts: {}".format(chromecasts))
        sys.exit(1)

    print("cast {}".format(cast))

    class ConnListener:
        def __init__(self, mz):
            self._mz = mz

        def new_connection_status(self, connection_status):
            """Handle reception of a new ConnectionStatus."""
            if connection_status.status == "CONNECTED":
                self._mz.update_members()

    class MzListener:
        def __init__(self):
            self.got_members = False

        def multizone_member_added(self, uuid):
            pass

        def multizone_member_removed(self, uuid):
            pass

        def multizone_status_received(self):
            self.got_members = True

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(args.user, args.password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    # Create a spotify client
    client = spotipy.Spotify(auth=access_token)
    if args.show_debug:
        spotipy.trace = True
        spotipy.trace_out = True

    # Launch the spotify app on the cast we want to cast to
    sp = SpotifyController(access_token, expires)
    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:
            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 args.uri[0].find("track") > 0:
        client.start_playback(device_id=spotify_device_id, uris=args.uri)
    else:
        client.start_playback(device_id=spotify_device_id,
                              context_uri=args.uri[0])
Ejemplo n.º 16
0
spotify_device_id = None

# Create a spotify token
data = st.start_session(args.user, args.password)
access_token = data[0]
expires = data[1] - int(time.time())

# Create a spotify client
client = spotipy.Spotify(auth=access_token)
if args.show_debug:
    spotipy.trace = True
    spotipy.trace_out = True

# Launch the spotify app on the cast we want to cast to
sp = SpotifyController(access_token, expires)
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']:
Ejemplo n.º 17
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']:
Ejemplo n.º 18
0
    def start_casting(call):
        """service called."""

        from pychromecast.controllers.spotify import SpotifyController
        import spotipy
        transfer_playback = False

        uri = call.data.get(CONF_SPOTIFY_URI)
        random_song = call.data.get(CONF_RANDOM, False)
        repeat = call.data.get(CONF_REPEAT)

        # Get device name from tiehr device_name or entity_id
        device_name = None
        if call.data.get(CONF_DEVICE_NAME) is None:
            entity_id = call.data.get(CONF_ENTITY_ID)
            if entity_id is None:
                raise HomeAssistantError(
                    'Either entity_id or device_name must be specified')
            entity_states = hass.states.get(entity_id)
            if entity_states is None:
                _LOGGER.error('Could not find entity_id: %s', entity_id)
            else:
                device_name = entity_states.attributes.get('friendly_name')
        else:
            device_name = call.data.get(CONF_DEVICE_NAME)

        if device_name is None or device_name.strip() == '':
            raise HomeAssistantError('device_name is empty')

        # Find chromecast device
        cast = get_chromecast_device(device_name)
        _LOGGER.debug('Found cast device: %s', cast)
        cast.wait()

        account = call.data.get(CONF_SPOTIFY_ACCOUNT)
        user = username
        pwd = password
        if account is not None:
            _LOGGER.debug('setting up with different account than default %s',
                          account)
            user = accounts.get(account).get(CONF_USERNAME)
            pwd = accounts.get(account).get(CONF_PASSWORD)

        # login as real browser to get powerful token
        access_token, expires = get_spotify_token(username=user, password=pwd)

        # get the spotify web api client
        client = spotipy.Spotify(auth=access_token)

        # Check if something is playing

        if uri is None or uri.strip() == '' or call.data.get(
                CONF_TRANSFER_PLAYBACK):
            current_playback = client.current_playback()
            if current_playback is not None:
                _LOGGER.debug('current_playback from spotipy: %s',
                              current_playback)
                transfer_playback = True

        # launch the app on chromecast
        sp = SpotifyController(access_token, expires)
        cast.register_handler(sp)
        sp.launch_app()

        if not sp.is_launched and not sp.credential_error:
            raise HomeAssistantError(
                'Failed to launch spotify controller due to timeout')
        if not sp.is_launched and sp.credential_error:
            raise HomeAssistantError(
                'Failed to launch spotify controller due to credentials error')

        spotify_device_id = None
        devices_available = client.devices()
        for device in devices_available['devices']:
            if device['id'] == sp.device:
                spotify_device_id = device['id']
                break

        if not spotify_device_id:
            _LOGGER.error('No device with id "{}" known by Spotify'.format(
                sp.device))
            _LOGGER.error('Known devices: {}'.format(
                devices_available['devices']))
            return

        if transfer_playback == True:
            transfer_pb(client, spotify_device_id)
        else:
            play(client, spotify_device_id, uri, random_song, repeat)
Ejemplo n.º 19
0
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()
Ejemplo n.º 20
0
spotify_device_id = None

# Create a spotify token
data = st.start_session(args.user, args.password)
access_token = data[0]
expires = data[1] - int(time.time())

# Create a spotify client
client = spotipy.Spotify(auth=access_token)
if args.show_debug:
    spotipy.trace = True
    spotipy.trace_out = True

# Launch the spotify app on the cast we want to cast to
sp = SpotifyController(access_token, expires)
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']:
Ejemplo n.º 21
0
def RestartSpotify(q,uri,TrackId = None,ContextUri = None,seektime=0,ContextType = None,Offset = None):
	global _plugin
	try:

		#Get the latest played music from Spotify if not given as parameters
		TrackInfo = _plugin.SpotifyClient.current_user_recently_played(limit=1)
		if TrackId == None and ContextUri == None:
			if TrackInfo['items'][0]['context'] != None:
				ContextUri 		= TrackInfo['items'][0]['context']['uri']
				ContextType 	= TrackInfo['items'][0]['context']['type']
				Offset 			= {"uri": TrackInfo['items'][0]['track']['uri']}
			else:
				TrackId 		= [TrackInfo['items'][0]['track']['uri']]
		elif ContextUri != None:
				Offset 			= {"uri": TrackId}
				TrackId 		= None
		elif TrackId != None and ContextUri == None:
			TrackId 			= [TrackId]

		#Connect to chromecast
		ip 		= uri.split(":")[0]
		port 	= int(uri.split(":")[1])
		cc 		= pychromecast.Chromecast(ip,port)
		cc.start()
		cc.wait()
		sp 		= SpotifyController(_plugin.SpotifyAccessToken, _plugin.SpotifyExpiryTime)
		cc.register_handler(sp)

		#Launch spotify app on chromecast and find device id
		device_id = None
		sp.launch_app()
		if _plugin.Debug == True:
			q.put("Spotify started.")
		devices_available = _plugin.SpotifyClient.devices()
		for device in devices_available['devices']:
		    if device['name'] == cc.name:
		        device_id = device['id']
		        break


		if ContextUri != None:
			if _plugin.Debug == True:
				q.put("Spotify user id is " + str(_plugin.SpotifyUserId) + " contexturi is " + str(ContextUri) + " Offset is " + str(Offset))
			
			if ContextType == 'artist':
				Name = _plugin.SpotifyClient.artist(ContextUri)["name"]
				Offset = None
			elif ContextType == "album":
				Name = _plugin.SpotifyClient.album("spotify:album:3KHPqtzQKRPKup29xEQWtg")["name"]
			else:
				Name = _plugin.SpotifyClient.user_playlist(_plugin.SpotifyUserId,ContextUri,"name")["name"]
		
		if Offset != None:
			q.put("Restarted playback of " + str(ContextType) + " with the name '" + str(Name) + "' and track '" + TrackInfo['items'][0]['track']['name'] + "'" )
		elif ContextUri != None:
			q.put("Restarted playback of " + str(ContextType) + " with the name '"+ str(Name) + "'")
		else:
			q.put('Restarted playback of track "' + TrackInfo['items'][0]['track']['name'] +'"' )


		if _plugin.Debug == True:
			q.put("Spotify arguments are: uris "+str(TrackId) + " context uri " + str(ContextUri) + " offset " + str(Offset))
		try:
			_plugin.SpotifyClient.start_playback(device_id=device_id, uris=TrackId, context_uri=ContextUri, offset=Offset)
		except:
			try:
				_plugin.SpotifyClient.start_playback(device_id=device_id, uris=TrackId, context_uri=ContextUri)
			except Exception as e:
				q.put('Error on line {}'.format(sys.exc_info()[-1].tb_lineno)+" Error is: " +str(e))

		if seektime != 0:
			_plugin.SpotifyClient.seek_track(seektime)
			q.put("Searched in track to previous position")

		cc.disconnect()
		if _plugin.Debug == True:
			q.put("Restarting Spotify is done")
	except Exception as e:
		if "Could not connect to" in str(e):
			q.put("Could not start Spotify as the chrmecast is not connected.")
		else:
			q.put('Error on line {}'.format(sys.exc_info()[-1].tb_lineno)+" Error is: " +str(e))