示例#1
0
def Play():
    """
    Endpoint to play media.
    """
    Log.Debug('Recieved a call to play media.')
    params = ['Clienturi', 'Contentid', 'Contenttype', 'Serverid', 'Serveruri',
              'Username', 'Transienttoken', 'Queueid', 'Version']
    values = sort_headers(params, False)
    status = "Missing required headers"
    msg = status
    if values is not False:
        Log.Debug("Holy crap, we have all the headers we need.")
        client_uri = values['Clienturi'].split(":")
        host = client_uri[0]
        port = int(client_uri[1])
        pc = False
        servers = fetch_servers()
        for server in servers:
            if server['id'] == values['Serverid']:
                Log.Debug("Found a matching server!")
                values['Serveruri'] = server['uri']
                values['Version'] = server['version']

        msg = "No message received"
        try:
            cast = pychromecast.Chromecast(host, port)
            cast.wait()
            values['Type'] = cast.cast_type
            pc = PlexController(cast)
            cast.register_handler(pc)
            pc.play_media(values, log_data)
        except pychromecast.LaunchError, pychromecast.PyChromecastError:
            Log.Debug('Error connecting to host.')
            status = "Error"
        finally:
示例#2
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)
示例#3
0
def cast_media_to(cast, media):
    try:
        cast.wait()
        pc = PlexController()
        cast.register_handler(pc)
        pc.play_media(media)
    except Exception as e:
        logging.error(e)
示例#4
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)
    def play_media(self, media_type, media_id, **kwargs):
        """Play media from a URL."""
        extra = kwargs.get(ATTR_MEDIA_EXTRA, {})
        metadata = extra.get("metadata")

        # We do not want this to be forwarded to a group
        if media_type == CAST_DOMAIN:
            try:
                app_data = json.loads(media_id)
                if metadata is not None:
                    app_data["metadata"] = extra.get("metadata")
            except json.JSONDecodeError:
                _LOGGER.error("Invalid JSON in media_content_id")
                raise

            # Special handling for passed `app_id` parameter. This will only launch
            # an arbitrary cast app, generally for UX.
            if "app_id" in app_data:
                app_id = app_data.pop("app_id")
                _LOGGER.info("Starting Cast app by ID %s", app_id)
                self._chromecast.start_app(app_id)
                if app_data:
                    _LOGGER.warning(
                        "Extra keys %s were ignored. Please use app_name to cast media",
                        app_data.keys(),
                    )
                return

            app_name = app_data.pop("app_name")
            try:
                quick_play(self._chromecast, app_name, app_data)
            except NotImplementedError:
                _LOGGER.error("App %s not supported", app_name)
        # Handle plex
        elif media_id and media_id.startswith(PLEX_URI_SCHEME):
            media_id = media_id[len(PLEX_URI_SCHEME):]
            media, _ = lookup_plex_media(self.hass, media_type, media_id)
            if media is None:
                return
            controller = PlexController()
            self._chromecast.register_handler(controller)
            controller.play_media(media)
        else:
            app_data = {
                "media_id": media_id,
                "media_type": media_type,
                **extra
            }
            quick_play(self._chromecast, "default_media_receiver", app_data)
示例#6
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)

        client_update = True
        get_chromecasts(blocking=False, callback=cc_callback)

        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)
        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:
                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 = media_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))

        offset = 0

        if media.type == "track":
            offset = media.viewOffset

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

        update_sensor()