Example #1
0
    def handle_input(call):
        command_string = call.data.get("command").strip().lower()

        if not command_string:
            _LOGGER.warning(localize["no_call"])
            return

        chromecasts = get_chromecasts()
        for chromecast in chromecasts:
            PA.devices[chromecast.device.friendly_name] = chromecast

        PA.clients = PA.server.clients()
        PA.client_names = [client.title for client in PA.clients]
        PA.client_ids = [client.machineIdentifier for client in PA.clients]

        if localize["controls"]["update_sensor"] in command_string:
            update_sensor()
            return

        cast = None
        alias = ["", 0]
        client = False
        speech_error = False

        command = process_speech(command_string, localize, default_cast, PA)

        if not command["control"]:
            _LOGGER.debug({i: command[i] for i in command if i != 'library'})

        if PA.lib["updated"] < PA.plex.search(sort="addedAt:desc",
                                              limit=1)[0].addedAt:
            PA.lib = get_libraries(PA.plex)

        PA.device_names = list(PA.devices.keys())
        devices = PA.device_names + PA.client_names + PA.client_ids
        device = fuzzy(command["device"] or default_cast, devices)
        if aliases:
            alias = fuzzy(command["device"] or default_cast, PA.alias_names)

        if alias[1] < 60 and device[1] < 60:
            _LOGGER.warning("{0} {1}: \"{2}\"".format(
                localize["cast_device"].capitalize(), localize["not_found"],
                command["device"].title()))
            _LOGGER.debug("Device Score: %s", device[1])
            _LOGGER.debug("Devices: %s", str(devices))

            if aliases:
                _LOGGER.debug("Alias Score: %s", alias[1])
                _LOGGER.debug("Aliases: %s", str(PA.alias_names))
            return

        name = aliases[alias[0]] if alias[1] > device[1] else device[0]
        cast = PA.devices[name] if name in PA.device_names else name
        client = isinstance(cast, str)
        if client:
            client_device = next(
                c for c in PA.clients
                if c.title == cast or c.machineIdentifier == cast)
            cast = client_device

        if command["control"]:
            control = command["control"]
            if client:
                cast.proxyThroughServer()
                plex_c = PA.server.client(cast.title)
            else:
                plex_c = PlexController()
                cast.wait()
                cast.register_handler(plex_c)
            if control == "play":
                plex_c.play()
            elif control == "pause":
                plex_c.pause()
            elif control == "stop":
                plex_c.stop()
            elif control == "jump_forward":
                plex_c.stepForward()
            elif control == "jump_back":
                plex_c.stepBack()
            return

        try:
            result = find_media(command, command["media"], PA.lib)
            media = video_selection(command, result["media"],
                                    result["library"])
        except Exception:
            error = media_error(command, localize)
            if tts_error:
                tts = gTTS(error, lang=lang)
                tts.save(directory + 'error.mp3')
                speech_error = True
            _LOGGER.warning(error)

        if speech_error and not client:
            cast.wait()
            med_con = cast.media_controller
            mp3 = get_url(hass) + "/local/plex_assist_tts/error.mp3"
            med_con.play_media(mp3, 'audio/mpeg')
            med_con.block_until_active()
            return

        _LOGGER.debug("Media: %s", str(media))

        if client:
            _LOGGER.debug("Client: %s", cast)
            cast.proxyThroughServer()
            plex_c = cast
            plex_c.playMedia(media)
        else:
            _LOGGER.debug("Cast: %s", cast.name)
            delay = 6
            if call.data.get("cast_delay") or call.data.get("cast_delay") == 0:
                delay = call.data.get("cast_delay")
            elif cast.name in cast_delay.keys():
                delay = cast_delay[cast.name]
            plex_c = PlexController()
            plex_c.namespace = 'urn:x-cast:com.google.cast.media'
            cast.register_handler(plex_c)
            cast.wait()
            play_media(float(delay), cast, plex_c, media)

        update_sensor()
Example #2
0
    def handle_input(call):
        if not call.data.get("command").strip():
            _LOGGER.warning(localize["no_call"])
            return

        command_string = call.data.get("command").strip().lower()
        _LOGGER.debug("Command: %s", command_string)

        PA.client_update = True
        get_chromecasts(blocking=False,
                        callback=cc_callback,
                        zeroconf_instance=zc)

        if localize["controls"]["update_sensor"] in command_string:
            update_sensor(hass)
            return

        cast = None
        alias = ["", 0]
        client = False
        speech_error = False

        command = process_speech(command_string, localize, default_cast, PA)
        PA.device_names = list(PA.devices.keys())

        if not command["control"]:
            _LOGGER.debug({i: command[i] for i in command if i != "library"})

        if PA.lib["updated"] < PA.plex.search(sort="addedAt:desc",
                                              limit=1)[0].addedAt:
            PA.lib = get_libraries(PA.plex)

        devices = PA.device_names + PA.client_names + PA.client_ids
        device = fuzzy(command["device"] or default_cast, devices)

        if aliases:
            alias = fuzzy(command["device"] or default_cast, PA.alias_names)

        if alias[1] < 60 and device[1] < 60:
            _LOGGER.warning('{0} {1}: "{2}"'.format(
                localize["cast_device"].capitalize(),
                localize["not_found"],
                command["device"].title(),
            ))
            _LOGGER.debug("Device Score: %s", device[1])
            _LOGGER.debug("Devices: %s", str(devices))

            if aliases:
                _LOGGER.debug("Alias Score: %s", alias[1])
                _LOGGER.debug("Aliases: %s", str(PA.alias_names))
            return

        name = aliases[alias[0]] if alias[1] > device[1] else device[0]
        cast = PA.devices[name] if name in PA.device_names else name
        client = isinstance(cast, str)

        if client:
            client_device = next(
                c for c in PA.clients
                if c.title == cast or c.machineIdentifier == cast)
            cast = client_device

        if command["control"]:
            control = command["control"]
            if client:
                try:
                    if "127.0.0.1" in cast.url("/"):
                        cast.proxyThroughServer()
                except plexapi.exceptions.BadRequest:
                    cast.proxyThroughServer()
                plex_c = cast
            else:
                plex_c = PlexController()
                cast.wait()
                cast.register_handler(plex_c)
            if control == "play":
                plex_c.play()
            elif control == "pause":
                plex_c.pause()
            elif control == "stop":
                plex_c.stop()
            elif control == "jump_forward":
                plex_c.stepForward()
            elif control == "jump_back":
                plex_c.stepBack()
            return

        try:
            result = find_media(command, command["media"], PA.lib)
            media = video_selection(command, result["media"],
                                    result["library"])
        except Exception:
            error = media_error(command, localize)
            if tts_error:
                tts = gTTS(error, lang=lang)
                tts.save(directory + "error.mp3")
                speech_error = True

        if speech_error and not client:
            cast.wait()
            med_con = cast.media_controller
            mp3 = get_url(hass) + "/local/plex_assist_tts/error.mp3"
            med_con.play_media(mp3, "audio/mpeg")
            med_con.block_until_active()
            return

        _LOGGER.debug("Media: %s", str(media))

        if client:
            _LOGGER.debug("Client: %s", cast)
            try:
                if "127.0.0.1" in cast.url("/"):
                    cast.proxyThroughServer()
            except plexapi.exceptions.BadRequest:
                cast.proxyThroughServer()
            plex_c = cast
            plex_c.playMedia(media)
        else:
            _LOGGER.debug("Cast: %s", cast.name)
            plex_c = PlexController()
            cast.register_handler(plex_c)
            cast.wait()
            plex_c.block_until_playing(media)

        update_sensor(hass)
Example #3
0
def Cmd():
    """
    Media control command(s).

    Plex-specific commands use the format:


    Required params:
    Uri
    Cmd
    Vol(If setting volume, otherwise, ignored)

    Where <COMMAND> is one of:
    PLAY (resume)
    PAUSE
    STOP
    STEPFORWARD
    STEPBACKWARD Need to test, not in PHP cast app)
    PREVIOUS
    NEXT
    MUTE
    UNMUTE
    VOLUME - also requires an int representing level from 0-100

    """
    Log.Debug('Recieved a call to control playback')
    params = sort_headers(['Uri', 'Cmd', 'Val'], False)
    status = "Missing paramaters"
    response = "Error"

    if params is not False:
        uri = params['Uri'].split(":")
        cast = pychromecast.Chromecast(uri[0], int(uri[1]))
        cast.wait()
        pc = PlexController(cast)
        Log.Debug("Handler namespace is %s" % pc.namespace)
        cast.register_handler(pc)

        Log.Debug("Handler namespace is %s" % pc.namespace)

        cmd = params['Cmd']
        Log.Debug("Command is " + cmd)

        if cmd == "play":
            pc.play()
        if cmd == "pause":
            pc.pause()
        if cmd == "stop":
            pc.stop()
        if cmd == "next":
            pc.next()
        if (cmd == "offset") & ('Val' in params):
            pc.seek(params["Val"])
        if cmd == "previous":
            pc.previous()
        if cmd == "volume.mute":
            pc.mute(True)
        if cmd == "volume.unmute":
            pc.mute(False)
        if (cmd == "volume") & ('Val' in params):
            pc.set_volume(params["Val"])
        if cmd == "volume.down":
            pc.volume_down()
        if cmd == "volume.up":
            pc.volume_up()

        cast.disconnect()
        response = "Command successful"

    oc = ObjectContainer(
        title1=response,
        title2=status,
        no_cache=True,
        no_history=True)
    return oc
Example #4
0
    def handle_input(call):
        """Handle the service call."""
        if not call.data.get("command").strip():
            _LOGGER.warning(localize["no_call"])
            return

        cast = None
        client = False
        speech_error = False

        get_chromecasts(blocking=False, callback=cc_callback)
        for client in PA.server.clients():
            if client.title not in PA.client_names:
                PA.client_names.append(client.title)

        command = process_speech(
            call.data.get("command").lower(),
            localize,
            default_cast,
            PA
        )

        if not command["control"]:
            _LOGGER.debug({i: command[i] for i in command if i != 'library'})

        if PA.lib["updated"] < PA.plex.search(sort="addedAt:desc")[0].addedAt:
            PA.lib = get_libraries(PA.plex)

        try:
            devices = PA.device_names + PA.client_names
            device = fuzzy(command["device"] or default_cast, devices)
            alias = fuzzy(command["device"] or default_cast, PA.alias_names)
            name = aliases[alias[0]] if alias[1] > device[1] else device[0]
            cast = PA.devices[name] if name in PA.device_names else name
        except Exception:
            error = "{0} {1}.".format(localize["cast_device"].capitalize(),
                                      localize["not_found"])
            _LOGGER.warning(error)
            return

        client = isinstance(cast, str)

        if command["control"]:
            control = command["control"]
            if client:
                PA.server.client(cast).proxyThroughServer()
                plex_c = PA.server.client(cast)
            else:
                plex_c = PlexController()
                cast.wait()
                cast.register_handler(plex_c)
            if control == "play":
                plex_c.play()
            elif control == "pause":
                plex_c.pause()
            elif control == "stop":
                plex_c.stop()
            elif control == "jump_forward":
                plex_c.stepForward()
            elif control == "jump_back":
                plex_c.stepBack()
            return

        try:
            result = find_media(command, command["media"], PA.lib)
            media = video_selection(command, result["media"],
                                    result["library"])
        except Exception:
            error = media_error(command, localize)
            if tts_error:
                tts = gTTS(error, lang=lang)
                tts.save(directory + 'error.mp3')
                speech_error = True
            _LOGGER.warning(error)

        if speech_error and not client:
            cast.wait()
            med_con = cast.media_controller
            mp3 = hass.config.api.base_url + "/local/plex_assist_tts/error.mp3"
            med_con.play_media(mp3, 'audio/mpeg')
            med_con.block_until_active()
            return

        _LOGGER.debug("Media: %s", str(media))

        if client:
            _LOGGER.debug("Client: %s", cast)
            PA.server.client(cast).proxyThroughServer()
            plex_c = PA.server.client(cast)
            plex_c.playMedia(media)
        else:
            _LOGGER.debug("Cast: %s", cast.name)
            plex_c = PlexController()
            cast.wait()
            cast.register_handler(plex_c)
            play_media(cast, plex_c, media)