async def async_step_oauth(self, user_input=None): """Handle a flow start.""" global AUTH_URL errors = {} description_placeholders = {"error_info": ""} data_schema = vol.Schema({vol.Required(CONF_OAUTH_JSON): str}) if user_input is not None: json_from_user = user_input.get(CONF_OAUTH_JSON) oauth_json = {} try: oauth_json = json.loads(json_from_user) except ValueError as e: errors = {CONF_OAUTH_JSON: "oauth_error"} description_placeholders = {"error_info": str(e)} if errors == {}: try: ais_cloud_ws = ais_cloud.AisCloudWS(self.hass) ws_ret = ais_cloud_ws.gh_ais_add_device(oauth_json) response = ws_ret.json() AUTH_URL = response["message"] except Exception as e: errors = {CONF_OAUTH_JSON: "oauth_error"} description_placeholders = {"error_info": str(e)} if errors == {}: return await self.async_step_token(user_input=None) return self.async_show_form( step_id="oauth", errors=errors, data_schema=data_schema, description_placeholders=description_placeholders, )
async def async_setup(hass, config): """Register the service.""" global aisCloud aisCloud = ais_cloud.AisCloudWS(hass) await async_get_key(hass) async def async_ask(service): """ask service about info""" query = service.data[ATTR_TEXT] await async_process_ask(hass, query) async def async_ask_wiki(service): """ask wikipedia service about info""" query = service.data[ATTR_TEXT] await async_process_ask_wiki(hass, query) # register services hass.services.async_register( DOMAIN, SERVICE_ASK, async_ask, schema=SERVICE_ASK_SCHEMA ) hass.services.async_register( DOMAIN, SERVICE_ASK_WIKI, async_ask_wiki, schema=SERVICE_ASK_SCHEMA ) return True
async def async_step_obtain_token(self, user_input=None): """Obtain token after external auth completed.""" # get token to call SUPLA API ais_dom = ais_cloud.AisCloudWS(self.hass) json_ws_resp = await ais_dom.async_key("supla_mqtt_bridge_code") code = json_ws_resp["key"] json_ws_resp = await ais_dom.async_key("supla_mqtt_prod_secret") client_secret = json_ws_resp["key"] data = { "grant_type": "authorization_code", "client_id": self.client_id, "client_secret": client_secret, "redirect_uri": REDIRECT_URL.replace("AIS_HOST", ais_global.AIS_HOST), "code": code, } web_session = self.hass.helpers.aiohttp_client.async_get_clientsession() token_response = await web_session.post(TOKEN_URL, json=data) result = await token_response.json(content_type=None) # get mqtt connection info from cloud access_token = result["access_token"] target_url = result["target_url"] bearer_token = f"Bearer {access_token}" supla_mqtt_settings_response = await web_session.post( f"{target_url}{API_ENDPOINT}", headers={"Authorization": bearer_token}, ) self.bridge_config_answer_status = supla_mqtt_settings_response.status self.bridge_config = await supla_mqtt_settings_response.json() return self.async_external_step_done(next_step_id="use_bridge_settings")
async def async_setup(hass, config): """Register the service.""" global aisCloudWS async def command(service): """ask service about info""" await _process_command(hass, service) hass.services.async_register(DOMAIN, "command", command) aisCloudWS = ais_cloud.AisCloudWS(hass) return True
def ais_dom_api(self): # aid-dom part if self._api_key == "use_ais_dom_api_key": try: from homeassistant.components import ais_cloud aiscloud = ais_cloud.AisCloudWS() ws_resp = aiscloud.key("darksky_sensor") json_ws_resp = ws_resp.json() self._api_key = json_ws_resp["key"] except Exception as error: _LOGGER.error( "Unable to get the API Key to OpenWeatherMap from AIS dom. %s", error)
async def async_load_all(self, hass): """Load all the folders and files.""" from homeassistant.components import ais_cloud aisCloud = ais_cloud.AisCloudWS(hass) self.display_root_items(False) global G_DRIVE_SECRET, G_DRIVE_CLIENT_ID # set client and secret try: json_ws_resp = await aisCloud.async_key("gdrive_client_id") G_DRIVE_CLIENT_ID = json_ws_resp["key"] json_ws_resp = await aisCloud.async_key("gdrive_secret") G_DRIVE_SECRET = json_ws_resp["key"] except Exception as e: _LOGGER.error("Error ais_drives_service async_load_all: " + str(e))
async def async_step_oauth(self, user_input=None): request = current_request.get() url_host = yarl.URL(request.url).host """Handle flow external step.""" ais_dom = ais_cloud.AisCloudWS(self.hass) json_ws_resp = ais_dom.key("google_calendar_web_client_id") client_id = json_ws_resp["key"] gate_id = ais_global.get_sercure_android_id_dom() auth_url = ( "https://accounts.google.com/o/oauth2/auth/oauthchooseaccount?client_id=" + client_id + "&redirect_uri=https://" + ais_global.AIS_HOST + "/ords/dom/auth/google_calendar_callback" + "&response_type=code&scope=https://www.googleapis.com/auth/calendar" + "&access_type=offline" + "&state=" + gate_id + "ais0dom" + url_host + "ais0domgoogle-calendar-" + self.flow_id) return self.async_external_step(step_id="obtain_token", url=auth_url)
def ais_dom_api(self): # aid-dom part if not self.owm: import pyowm try: from homeassistant.components import ais_cloud aiscloud = ais_cloud.AisCloudWS() ws_resp = aiscloud.key("openweathermap_weather") json_ws_resp = ws_resp.json() try: self.owm = pyowm.OWM(json_ws_resp["key"]) except pyowm.exceptions.api_call_error.APICallError: _LOGGER.error("Error while connecting to OpenWeatherMap") except Exception as error: _LOGGER.error( "Unable to get the API Key to OpenWeatherMap from AIS dom. %s", error)
async def async_unload_entry(hass, config_entry): # remove token from ais from homeassistant.components import ais_cloud ais_dom = ais_cloud.AisCloudWS(hass) j_ret = await ais_dom.async_delete_oauth("google_calendar_callback") _LOGGER.info(str(j_ret)) # delete token and calendar file if os.path.isfile(hass.config.path(YAML_DEVICES)): await hass.async_add_executor_job(os.remove, hass.config.path(YAML_DEVICES)) if os.path.isfile(hass.config.path(TOKEN_FILE)): await hass.async_add_executor_job(os.remove, hass.config.path(TOKEN_FILE)) hass.components.frontend.async_remove_panel("calendar") return False
async def async_step_authentication(self, user_input=None): """authentication""" if user_input is not None: ais_cloud_ws = ais_cloud.AisCloudWS(self.hass) broker_config = await ais_cloud_ws.async_get_mqtt_settings( user_input["username"], user_input["password"] ) if "server" not in broker_config: error = "error" if "error" in broker_config: error = broker_config["error"] return self.async_abort( reason="abort_by_error", description_placeholders={"error_info": f"Exception: {error}."}, ) """Continue bridge configuration with broker settings.""" return self.async_create_entry(title="AIS MQTT Bridge", data=broker_config) return self.async_show_form(step_id="authentication")
async def async_step_oauth(self, user_input=None): if user_input is not None: self.hass.http.register_view(AuthorizationCallbackView) request = current_request.get() url_host = yarl.URL(request.url).host """Handle flow external step.""" ais_dom = ais_cloud.AisCloudWS(self.hass) json_ws_resp = ais_dom.key("supla_mqtt_prod_client_id") self.client_id = json_ws_resp["key"] gate_id = ais_global.get_sercure_android_id_dom() redirect_uri = REDIRECT_URL.replace("AIS_HOST", ais_global.AIS_HOST) auth_url = ( f"{OAUTH_URL}?client_id={self.client_id}&redirect_uri={redirect_uri}&scope={AUTH_SCOPE}&response_type" f"=code&state={gate_id}ais0dom{url_host}ais0domsupla-mqtt-{self.flow_id}" ) return self.async_external_step(step_id="obtain_token", url=auth_url) return self.async_show_form(step_id="oauth")
def __init__(self, owm, latitude, longitude, mode, hass): """Initialize the data object.""" self._mode = mode self.owm = owm self.latitude = latitude self.longitude = longitude self.data = None self.forecast_data = None self.hass = hass # AIS dom fix if not self.owm: from homeassistant.components import ais_cloud import pyowm aiscloud = ais_cloud.AisCloudWS(hass) json_ws_resp = aiscloud.key("openweathermap_weather") try: self.owm = pyowm.OWM(json_ws_resp["key"]) except pyowm.exceptions.api_call_error.APICallError: _LOGGER.error("Error while connecting to OpenWeatherMap")
async def async_setup(hass, config): global aisCloud aisCloud = ais_cloud.AisCloudWS(hass) """Register the service.""" data = hass.data[DOMAIN] = YouTubeData(hass) await data.async_get_key(hass) async def async_search(service): """search service about audio""" await data.async_process_search(service) def select_track_uri(service): """select track uri""" data.process_select_track_uri(service) # register services hass.services.async_register(DOMAIN, SERVICE_SEARCH, async_search) hass.services.async_register(DOMAIN, "select_track_uri", select_track_uri) return True
async def async_step_obtain_token(self, user_input=None): """Obtain token after external auth completed.""" # get token from cloud try: ais_dom = ais_cloud.AisCloudWS(self.hass) json_ws_resp = await ais_dom.async_key("google_calendar_user_token" ) calendar_token = json_ws_resp["key"] json_ws_resp = await ais_dom.async_key( "google_calendar_web_client_id") client_id = json_ws_resp["key"] json_ws_resp = await ais_dom.async_key("google_calendar_web_secret" ) client_secret = json_ws_resp["key"] token_response = json.loads(calendar_token) json_token = json.loads(calendar_token) json_token["token_response"] = token_response json_token["_module"] = "oauth2client.client" json_token["_class"] = "OAuth2Credentials" json_token["client_id"] = client_id json_token["client_secret"] = client_secret delta = datetime.timedelta(seconds=token_response["expires_in"]) now = datetime.datetime.utcnow() json_token["token_expiry"] = str(now + delta) json_token[ "token_uri"] = "https://www.googleapis.com/oauth2/v4/token" json_token["user_agent"] = None json_token["invalid"] = False with open(self.hass.config.path(TOKEN_FILE), "w") as json_file: json.dump(json_token, json_file) except Exception as e: return self.async_abort( reason="abort_by_error", description_placeholders={"error_info": str(e)}) return self.async_external_step_done(next_step_id="use_external_token")
def __init__(self, api_key, latitude, longitude, units, language, interval, hass): """Initialize the data object.""" self._api_key = api_key self.latitude = latitude self.longitude = longitude self.units = units self.language = language self._connect_error = False self.data = None self.unit_system = None self.data_currently = None self.data_minutely = None self.data_hourly = None self.data_daily = None self.data_alerts = None # Apply throttling to methods using configured interval self.update = Throttle(interval)(self._update) self.update_currently = Throttle(interval)(self._update_currently) self.update_minutely = Throttle(interval)(self._update_minutely) self.update_hourly = Throttle(interval)(self._update_hourly) self.update_daily = Throttle(interval)(self._update_daily) self.update_alerts = Throttle(interval)(self._update_alerts) # aid-dom part if self._api_key == "use_ais_dom_api_key": try: from homeassistant.components import ais_cloud aiscloud = ais_cloud.AisCloudWS(hass) json_ws_resp = aiscloud.key("darksky_sensor") self._api_key = json_ws_resp["key"] except Exception as error: _LOGGER.error( "Unable to get the API Key to DarkSky from AIS dom. %s", error, )
async def async_step_token(self, user_input=None): """Handle a flow start.""" global AUTH_URL description_placeholders = {"error_info": "", "auth_url": AUTH_URL} errors = {} data_schema = vol.Schema({vol.Required(CONF_ACCESS_TOKEN): str}) if user_input is not None and CONF_ACCESS_TOKEN in user_input: # save token ais_cloud_ws = ais_cloud.AisCloudWS(self.hass) ws_ret = ais_cloud_ws.gh_ais_add_token(user_input[CONF_ACCESS_TOKEN]) try: response = ws_ret.json() ret = response["message"] return self.async_create_entry(title="Google Home", data=user_input) except Exception as e: errors = {CONF_ACCESS_TOKEN: "token_error"} description_placeholders = {"auth_url": AUTH_URL, "error_info": str(e)} return self.async_show_form( step_id="token", errors=errors, description_placeholders=description_placeholders, data_schema=data_schema, )
async def async_load_all(self, hass): """Load all the folders and files.""" from homeassistant.components import ais_cloud aisCloud = ais_cloud.AisCloudWS(hass) self.display_root_items(False) global G_DRIVE_SECRET, G_DRIVE_CLIENT_ID # version 0.105 config migration - to allow backup to AIS cloud if os.path.isfile(G_RCLONE_OLD_CONF_FILE): if not os.path.isfile(G_RCLONE_CONF_FILE): subprocess.call( f"mv {G_RCLONE_OLD_CONF_FILE} {G_RCLONE_CONF_FILE}", shell=True, # nosec ) # set client and secret try: json_ws_resp = await aisCloud.async_key("gdrive_client_id") G_DRIVE_CLIENT_ID = json_ws_resp["key"] json_ws_resp = await aisCloud.async_key("gdrive_secret") G_DRIVE_SECRET = json_ws_resp["key"] except Exception as e: _LOGGER.error("Error ais_drives_service async_load_all: " + str(e))
For more details about this component, please refer to the documentation at https://www.ai-speaker.com """ import asyncio import logging import os import signal import json import mimetypes import subprocess import time from homeassistant.components import ais_cloud from homeassistant.components.ais_dom import ais_global from .config_flow import configured_drivers aisCloud = ais_cloud.AisCloudWS() DOMAIN = "ais_drives_service" G_LOCAL_FILES_ROOT = "/data/data/pl.sviete.dom/files/home/dom" G_CLOUD_PREFIX = "dyski-zdalne:" G_RCLONE_CONF_FILE = "/data/data/pl.sviete.dom/files/home/dom/rclone.conf" G_RCLONE_CONF = "--config=" + G_RCLONE_CONF_FILE G_RCLONE_URL_TO_STREAM = "http://127.0.0.1:8080/" G_DRIVE_CLIENT_ID = None G_DRIVE_SECRET = None G_COVER_FILE = "/data/data/pl.sviete.dom/files/home/AIS/www/cover.jpg" G_RCLONE_REMOTES_LONG = [] _LOGGER = logging.getLogger(__name__) TYPE_DRIVE = "drive" TYPE_MEGA = "mega"
async def get(self, request): global G_SPOTIFY_AUTH_URL hass = request.app["hass"] flow_id = request.query["flow_id"] try: step_ip = request.query["step_ip"] except Exception: step_ip = 0 # add the REAL_IP and FLOW_ID to Spotify Auth URL and redirect to Spotify for authentication if step_ip == "1": real_ip = request.url.host # if G_SPOTIFY_AUTH_URL is None: try: import json import spotipy.oauth2 from homeassistant.components import ais_cloud from homeassistant.components.ais_dom import ais_global from . import DEFAULT_CACHE_PATH aisCloud = ais_cloud.AisCloudWS(hass) json_ws_resp = await aisCloud.async_key("spotify_oauth") spotify_redirect_url = json_ws_resp["SPOTIFY_REDIRECT_URL"] spotify_client_id = json_ws_resp["SPOTIFY_CLIENT_ID"] spotify_client_secret = json_ws_resp["SPOTIFY_CLIENT_SECRET"] if "SPOTIFY_SCOPE_FULL" in json_ws_resp: spotify_scope = json_ws_resp["SPOTIFY_SCOPE_FULL"] else: spotify_scope = json_ws_resp["SPOTIFY_SCOPE"] except Exception as e: _LOGGER.error("No spotify oauth info: " + str(e)) return True cache = hass.config.path(DEFAULT_CACHE_PATH) gate_id = ais_global.get_sercure_android_id_dom() j_state = json.dumps( { "gate_id": gate_id, "real_ip": "real_ip_place", "flow_id": "flow_id_place", } ) oauth = spotipy.oauth2.SpotifyOAuth( spotify_client_id, spotify_client_secret, spotify_redirect_url, scope=spotify_scope, cache_path=cache, state=j_state, ) setUrl(oauth.get_authorize_url()) G_SPOTIFY_AUTH_URL = G_SPOTIFY_AUTH_URL.replace("real_ip_place", real_ip) G_SPOTIFY_AUTH_URL = G_SPOTIFY_AUTH_URL.replace("flow_id_place", flow_id) js_text = ( "<script>window.location.href='" + G_SPOTIFY_AUTH_URL + "'</script>" ) return aiohttp.web_response.Response( headers={"content-type": "text/html"}, text=js_text ) # the call was from ais-dom finish the integration hass.async_create_task( hass.config_entries.flow.async_configure(flow_id=flow_id, user_input="ok") ) # js_text = "<script>window.close()</script>" js_text = ( "<script>window.location.href='/config/integrations/dashboard'</script>" ) return aiohttp.web_response.Response( headers={"content-type": "text/html"}, text=js_text )
async def async_setup(hass, config): """Set up the Spotify platform.""" global aisCloud aisCloud = ais_cloud.AisCloudWS(hass) import json import spotipy.oauth2 global AIS_SPOTIFY_TOKEN # info about discovery async def do_the_spotify_disco(service): """ Called when a Spotify integration has been discovered. """ await hass.config_entries.flow.async_init( "ais_spotify_service", context={"source": "discovery"}, data={}) await hass.async_block_till_done() try: json_ws_resp = await aisCloud.async_key("spotify_oauth") spotify_redirect_url = json_ws_resp["SPOTIFY_REDIRECT_URL"] spotify_client_id = json_ws_resp["SPOTIFY_CLIENT_ID"] spotify_client_secret = json_ws_resp["SPOTIFY_CLIENT_SECRET"] if "SPOTIFY_SCOPE_FULL" in json_ws_resp: spotify_scope = json_ws_resp["SPOTIFY_SCOPE_FULL"] else: spotify_scope = json_ws_resp["SPOTIFY_SCOPE"] try: json_ws_resp = await aisCloud.async_key("spotify_token") key = json_ws_resp["key"] AIS_SPOTIFY_TOKEN = json.loads(key) except: AIS_SPOTIFY_TOKEN = None _LOGGER.info("No AIS_SPOTIFY_TOKEN") except Exception as e: _LOGGER.error("No spotify oauth info: " + str(e)) return True cache = hass.config.path(DEFAULT_CACHE_PATH) gate_id = ais_global.get_sercure_android_id_dom() j_state = json.dumps({ "gate_id": gate_id, "real_ip": "real_ip_place", "flow_id": "flow_id_place" }) oauth = spotipy.oauth2.SpotifyOAuth( spotify_client_id, spotify_client_secret, spotify_redirect_url, scope=spotify_scope, cache_path=cache, state=j_state, ) setUrl(oauth.get_authorize_url()) token_info = oauth.get_cached_token() if not token_info: _LOGGER.info("no spotify token in cache;") if AIS_SPOTIFY_TOKEN is not None: with open(cache, "w") as outfile: json.dump(AIS_SPOTIFY_TOKEN, outfile) token_info = oauth.get_cached_token() # register services if not token_info: _LOGGER.info("no spotify token exit") hass.async_add_job(do_the_spotify_disco(hass)) return True data = hass.data[DOMAIN] = SpotifyData(hass, oauth) async def async_search(call): _LOGGER.info("search " + str(call)) await data.async_process_search(call) async def async_get_favorites(call): await data.async_process_get_favorites(call) def select_search_uri(call): _LOGGER.info("select_search_uri") data.select_search_uri(call) def select_track_uri(call): _LOGGER.info("select_track_uri") data.select_track_uri(call) def change_play_queue(call): _LOGGER.info("change_play_queue") data.change_play_queue(call) hass.services.async_register(DOMAIN, "search", async_search) hass.services.async_register(DOMAIN, "get_favorites", async_get_favorites) hass.services.async_register(DOMAIN, "select_search_uri", select_search_uri) hass.services.async_register(DOMAIN, "select_track_uri", select_track_uri) hass.services.async_register(DOMAIN, "change_play_queue", change_play_queue) return True
async def ais_podcast_library(hass, media_content_id) -> BrowseMedia: ais_cloud_ws = ais_cloud.AisCloudWS(hass) if media_content_id == "ais_podcast": # get podcast types ws_resp = ais_cloud_ws.audio_type(ais_global.G_AN_PODCAST) json_ws_resp = ws_resp.json() ais_podcast_types = [] for item in json_ws_resp["data"]: media_class = MEDIA_CLASS_PODCAST if item == "Biznes": media_class = "podcastbuisnes" elif item == "Edukacja": media_class = "podcasteducation" elif item == "Familijne": media_class = "podcastfamily" elif item == "Gry i Hobby": media_class = "podcastgames" elif item == "Humor": media_class = "podcastsmile" elif item == "nformacyjne": media_class = "podcastinfo" elif item == "Komedia": media_class = "podcastcomedy" elif item == "Książki": media_class = "podcastbooks" elif item == "Kuchnia": media_class = "podcastcook" elif item == "Marketing": media_class = "podcastmarket" elif item == "Sport i rekreacja": media_class = "podcastsport" elif item == "Sztuka": media_class = "podcastart" elif item == "TV i film": media_class = "podcasttv" elif item == "Technologia": media_class = "podcasttechno" elif item == "Tyflopodcast": media_class = "podcasttyflo" elif item == "Zdrowie": media_class = "podcastdoctor" ais_podcast_types.append( BrowseMedia( title=item, media_class=media_class, media_content_id="ais_podcast/" + item, media_content_type=MEDIA_TYPE_APP, can_play=False, can_expand=True, )) root = BrowseMedia( title="Podcasty", media_class=MEDIA_CLASS_PODCAST, media_content_id="ais_podcast", media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_podcast_types, ) return root elif media_content_id.count("/") == 1: # get podcasts for types ws_resp = ais_cloud_ws.audio_name( ais_global.G_AN_PODCAST, media_content_id.replace("ais_podcast/", "")) json_ws_resp = ws_resp.json() ais_radio_stations = [] for item in json_ws_resp["data"]: ais_radio_stations.append( BrowseMedia( title=item["NAME"], media_class=MEDIA_CLASS_PODCAST, media_content_id=media_content_id + "/" + item["NAME"] + "/" + item["LOOKUP_URL"], media_content_type=MEDIA_TYPE_CHANNELS, can_play=False, can_expand=True, thumbnail=item["IMAGE_URL"], )) root = BrowseMedia( title=media_content_id.replace("ais_podcast/", ""), media_class=MEDIA_CLASS_DIRECTORY, media_content_id=media_content_id, media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_radio_stations, ) return root else: # get podcast tracks try: lookup_url = media_content_id.split("/", 3)[3] web_session = aiohttp_client.async_get_clientsession(hass) import feedparser # 5 sec should be enough with async_timeout.timeout(7): ws_resp = await web_session.get(lookup_url) response_text = await ws_resp.text() d = feedparser.parse(response_text) ais_podcast_episodes = [] for e in d.entries: try: thumbnail = d.feed.image.href except Exception: thumbnail = "" ais_podcast_episodes.append( BrowseMedia( title=e.title, media_class=MEDIA_CLASS_MUSIC, media_content_id=e.enclosures[0]["url"], media_content_type=MEDIA_TYPE_MUSIC, can_play=True, can_expand=False, thumbnail=thumbnail, )) root = BrowseMedia( title=media_content_id.split("/", 3)[2], media_class=MEDIA_CLASS_PODCAST, media_content_id=media_content_id, media_content_type=MEDIA_TYPE_CHANNELS, can_expand=True, can_play=False, children=ais_podcast_episodes, ) return root except Exception as e: _LOGGER.warning("Timeout when reading RSS %s", lookup_url) raise BrowseError("Timeout when reading RSS %s", lookup_url)
async def ais_audio_books_library(hass, media_content_id) -> BrowseMedia: ais_cloud_ws = ais_cloud.AisCloudWS(hass) # get all books all_books = await get_books_lib(hass) if media_content_id == "ais_audio_books": # get authors authors = [] for item in all_books: if item["author"] not in authors: authors.append(item["author"]) ais_authors = [] for author in authors: ais_authors.append( BrowseMedia( title=author, media_class=MEDIA_CLASS_DIRECTORY, media_content_id="ais_audio_books/" + author, media_content_type=MEDIA_TYPE_APP, can_play=False, can_expand=True, )) root = BrowseMedia( title="Autorzy", media_class=MEDIA_CLASS_DIRECTORY, media_content_id="ais_audio_books", media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_authors, ) return root elif media_content_id.count("/") == 1: # get books for author ais_books = [] for item in all_books: if item["author"] == media_content_id.replace( "ais_audio_books/", ""): try: thumbnail = "https://wolnelektury.pl/media/" + item[ "cover_thumb"] except Exception: thumbnail = item["simple_thumb"] ais_books.append( BrowseMedia( title=item["title"], media_class=MEDIA_CLASS_DIRECTORY, media_content_id=media_content_id + "/" + item["title"] + "/" + item["href"], media_content_type=MEDIA_TYPE_APP, can_play=False, can_expand=True, thumbnail=thumbnail, )) root = BrowseMedia( title=media_content_id.replace("ais_audio_books/", ""), media_class=MEDIA_CLASS_DIRECTORY, media_content_id=media_content_id, media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_books, ) return root else: # get book chapters lookup_url = media_content_id.split("/", 3)[3] web_session = aiohttp_client.async_get_clientsession(hass) # 5 sec should be enough try: with async_timeout.timeout(7): ws_resp = await web_session.get(lookup_url + "?format=json") data = await ws_resp.json() ais_book_chapters = [] for item in data["media"]: if item["type"] == "ogg": try: thumbnail = data["cover"] except Exception: thumbnail = data["simple_cover"] ais_book_chapters.append( BrowseMedia( title=item["name"], media_class=MEDIA_CLASS_DIRECTORY, media_content_id=item["url"], media_content_type=MEDIA_TYPE_APP, can_play=True, can_expand=False, thumbnail=thumbnail, )) root = BrowseMedia( title=media_content_id.split("/", 3)[2], media_class=MEDIA_CLASS_DIRECTORY, media_content_id=media_content_id, media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_book_chapters, ) return root except Exception as e: _LOGGER.error("Can't load chapters: " + str(e)) hass.services.call("ais_ai_service", "say_it", {"text": "Nie można pobrać rozdziałów"}) raise BrowseError("Can't load chapters: " + str(e))
def ais_radio_library(hass, media_content_id) -> BrowseMedia: ais_cloud_ws = ais_cloud.AisCloudWS(hass) if media_content_id == "ais_radio": # get ws_resp = ais_cloud_ws.audio_type(ais_global.G_AN_RADIO) json_ws_resp = ws_resp.json() # ais_radio_types = [ais_global.G_FAVORITE_OPTION] ais_radio_types = [] for item in json_ws_resp["data"]: media_class = MEDIA_CLASS_DIRECTORY if item == "Dzieci": media_class = "radiokids" elif item == "Filmowe": media_class = "radiofils" elif item == "Historyczne": media_class = "radiohistory" elif item == "Informacyjne": media_class = "radionews" elif item == "Inne": media_class = "radioothers" elif item == "Katolickie": media_class = "radiochurch" elif item == "Klasyczne": media_class = "radioclasic" elif item == "Muzyczne": media_class = "radiomusic" elif item == "Muzyczne - Rock": media_class = "radiomusicrock" elif item == "Naukowe": media_class = "radioschool" elif item == "Regionalne": media_class = "radiolocal" elif item == "Publiczne": media_class = "radiopublic" elif item == "Sportowe": media_class = "radiosport" elif item == "Słowo": media_class = "radiopen" elif item == "Trendy TuneIn": media_class = "radiotuneintrend" ais_radio_types.append( BrowseMedia( title=item, media_class=media_class, media_content_id="ais_radio/" + item, media_content_type=MEDIA_TYPE_APP, can_play=False, can_expand=True, )) root = BrowseMedia( title="Radio", media_class=MEDIA_CLASS_DIRECTORY, media_content_id="ais_radio", media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_radio_types, ) return root else: # get radio station for type ws_resp = ais_cloud_ws.audio_name( ais_global.G_AN_RADIO, media_content_id.replace("ais_radio/", "")) json_ws_resp = ws_resp.json() ais_radio_stations = [] for item in json_ws_resp["data"]: ais_radio_stations.append( BrowseMedia( title=item["NAME"], media_class=MEDIA_CLASS_DIRECTORY, media_content_id=item["STREAM_URL"], media_content_type=MEDIA_TYPE_APP, can_play=True, can_expand=False, thumbnail=item["IMAGE_URL"], )) root = BrowseMedia( title=media_content_id.replace("ais_radio/", ""), media_class=MEDIA_CLASS_DIRECTORY, media_content_id=media_content_id, media_content_type=MEDIA_TYPE_APP, can_expand=True, can_play=False, children=ais_radio_stations, ) return root
def __init__(self): """Initialize google home configuration flow.""" global aisCloudWS aisCloudWS = ais_cloud.AisCloudWS(self.hass)