async def test_wanted(aresponses): """Test queue method is handled correctly.""" aresponses.add( MATCH_HOST, "/api/wanted/missing?sortKey=airDateUtc&page=1&pageSize=10&sortDir=desc", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("wanted-missing.json"), ), match_querystring=True, ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client.wanted() assert response assert isinstance(response, models.WantedResults) assert response.page == 1 assert response.per_page == 10 assert response.total == 2 assert response.sort_key == "airDateUtc" assert response.sort_dir == "descending" assert response.episodes assert isinstance(response.episodes, List) assert len(response.episodes) == 2 assert response.episodes[0] assert isinstance(response.episodes[0], models.Episode)
async def test_series(aresponses): """Test series method is handled correctly.""" aresponses.add( MATCH_HOST, "/api/series", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("series.json"), ), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client.series() assert response assert isinstance(response, List) assert response[0] assert isinstance(response[0], models.SeriesItem) assert response[0].series assert isinstance(response[0].series, models.Series) assert response[0].seasons assert isinstance(response[0].seasons, List) assert response[0].seasons[0] assert isinstance(response[0].seasons[0], models.Season)
async def test_app(aresponses): """Test app property is handled correctly.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("system-status.json"), ), ) aresponses.add( MATCH_HOST, "/api/diskspace", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("diskspace.json"), ), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) await client.update() assert client.app assert isinstance(client.app, models.Application)
async def test_post_request(aresponses): """Test POST requests are handled correctly.""" aresponses.add(MATCH_HOST, "/api/post", "POST", aresponses.Response(status=200, text="OK")) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client._request("post", method="POST") assert response == "OK"
async def test_text_request(aresponses): """Test non JSON response is handled correctly.""" aresponses.add( MATCH_HOST, "/api/text", "GET", aresponses.Response(status=200, text="OK"), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client._request("text") assert response == "OK"
async def test_http_error500(aresponses): """Test HTTP 500 response handling.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response(text="Internal Server Error", status=500), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) with pytest.raises(SonarrError): assert await client._request("system/status")
async def test_http_error404(aresponses): """Test HTTP 404 response handling.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response(text="Not Found!", status=404), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) with pytest.raises(SonarrError): assert await client._request("system/status")
async def test_http_error403(aresponses): """Test HTTP 403 response handling.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response(text="Forbidden", status=403), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) with pytest.raises(SonarrAccessRestricted): assert await client._request("system/status")
async def test_request_base_path(aresponses): """Test API running on different base path.""" aresponses.add( MATCH_HOST, "/api/v3/system/status", "GET", aresponses.Response(text="GOTCHA!", status=200), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, base_path="/api/v3", session=session) response = await client._request("system/status") assert response == "GOTCHA!"
async def test_timeout(aresponses): """Test request timeout from the API.""" # Faking a timeout by sleeping async def response_handler(_): await asyncio.sleep(2) return aresponses.Response(body="Timeout!") aresponses.add(MATCH_HOST, "/api/system/status", "GET", response_handler) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session, request_timeout=1) with pytest.raises(SonarrConnectionError): assert await client._request("system/status")
async def test_update(aresponses): """Test update method is handled correctly.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("system-status.json"), ), ) aresponses.add( MATCH_HOST, "/api/diskspace", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("diskspace.json"), ), ) aresponses.add( MATCH_HOST, "/api/diskspace", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("diskspace.json"), ), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client.update() assert response assert isinstance(response.info, models.Info) assert isinstance(response.disks, List) response = await client.update() assert response assert isinstance(response.info, models.Info) assert isinstance(response.disks, List)
async def test_internal_session(aresponses): """Test JSON response is handled correctly with internal session.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text='{"status": "OK"}', ), ) async with Sonarr(HOST, API_KEY) as client: response = await client._request("system/status") assert response["status"] == "OK"
async def validate_input(hass: HomeAssistant, data: dict) -> None: """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(hass) sonarr = Sonarr( host=data[CONF_HOST], port=data[CONF_PORT], api_key=data[CONF_API_KEY], base_path=data[CONF_BASE_PATH], tls=data[CONF_SSL], verify_ssl=data[CONF_VERIFY_SSL], session=session, ) await sonarr.update()
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Sonarr from a config entry.""" if not entry.options: options = { CONF_UPCOMING_DAYS: entry.data.get( CONF_UPCOMING_DAYS, DEFAULT_UPCOMING_DAYS ), CONF_WANTED_MAX_ITEMS: entry.data.get( CONF_WANTED_MAX_ITEMS, DEFAULT_WANTED_MAX_ITEMS ), } hass.config_entries.async_update_entry(entry, options=options) sonarr = Sonarr( host=entry.data[CONF_HOST], port=entry.data[CONF_PORT], api_key=entry.data[CONF_API_KEY], base_path=entry.data[CONF_BASE_PATH], session=async_get_clientsession(hass), tls=entry.data[CONF_SSL], verify_ssl=entry.data[CONF_VERIFY_SSL], ) try: await sonarr.update() except SonarrAccessRestricted: _async_start_reauth(hass, entry) return False except SonarrError as err: raise ConfigEntryNotReady from err undo_listener = entry.add_update_listener(_async_update_listener) hass.data[DOMAIN][entry.entry_id] = { DATA_SONARR: sonarr, DATA_UNDO_UPDATE_LISTENER: undo_listener, } for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
async def test_http_error500_json(aresponses): """Test HTTP 500 json response handling.""" aresponses.add( MATCH_HOST, "/api/system/status", "GET", aresponses.Response( status=500, headers={"Content-Type": "application/json"}, body='{"status": "NOK"}', ), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) with pytest.raises(SonarrError): response = await client._request("system/status") assert response assert response["status"] == "NOK"
async def test_command_status(aresponses): """Test command_status method is handled correctly.""" aresponses.add( MATCH_HOST, "/api/command/368630", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("command-id.json"), ), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client.command_status(368630) assert response assert isinstance(response, models.CommandItem)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Sonarr from a config entry.""" if not entry.options: options = { CONF_UPCOMING_DAYS: entry.data.get( CONF_UPCOMING_DAYS, DEFAULT_UPCOMING_DAYS ), CONF_WANTED_MAX_ITEMS: entry.data.get( CONF_WANTED_MAX_ITEMS, DEFAULT_WANTED_MAX_ITEMS ), } hass.config_entries.async_update_entry(entry, options=options) sonarr = Sonarr( host=entry.data[CONF_HOST], port=entry.data[CONF_PORT], api_key=entry.data[CONF_API_KEY], base_path=entry.data[CONF_BASE_PATH], session=async_get_clientsession(hass), tls=entry.data[CONF_SSL], verify_ssl=entry.data[CONF_VERIFY_SSL], ) try: await sonarr.update() except SonarrAccessRestricted as err: raise ConfigEntryAuthFailed( "API Key is no longer valid. Please reauthenticate" ) from err except SonarrError as err: raise ConfigEntryNotReady from err undo_listener = entry.add_update_listener(_async_update_listener) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_SONARR: sonarr, DATA_UNDO_UPDATE_LISTENER: undo_listener, } hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def validate_input(opp: OpenPeerPower, data: dict) -> dict[str, Any]: """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(opp) sonarr = Sonarr( host=data[CONF_HOST], port=data[CONF_PORT], api_key=data[CONF_API_KEY], base_path=data[CONF_BASE_PATH], tls=data[CONF_SSL], verify_ssl=data[CONF_VERIFY_SSL], session=session, ) await sonarr.update() return True
async def test_request_port(aresponses): """Test the handling of non-standard API port.""" aresponses.add( f"{HOST}:{NON_STANDARD_PORT}", "/api/system/status", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text='{"status": "OK"}', ), ) async with ClientSession() as session: client = Sonarr(host=HOST, api_key=API_KEY, port=NON_STANDARD_PORT, session=session) response = await client._request("system/status") assert response["status"] == "OK"
async def test_calendar(aresponses): """Test calendar method is handled correctly.""" aresponses.add( MATCH_HOST, "/api/calendar?start=2014-01-26&end=2014-01-27", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("calendar.json"), ), match_querystring=True, ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client.calendar("2014-01-26", "2014-01-27") assert response assert isinstance(response, List) assert response[0] assert isinstance(response[0], models.Episode)
async def test_queue(aresponses): """Test queue method is handled correctly.""" aresponses.add( MATCH_HOST, "/api/queue", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("queue.json"), ), ) async with ClientSession() as session: client = Sonarr(HOST, API_KEY, session=session) response = await client.queue() assert response assert isinstance(response, List) assert response[0] assert isinstance(response[0], models.QueueItem) assert response[0].episode assert isinstance(response[0].episode, models.Episode)
import yaml import json from loguru import logger from config import load_config from sonarr import Sonarr from elk import ELK from flask import Flask, render_template config = load_config("m0nitor.yml") content = dict() #print(config) s = Sonarr(config['sonarr']['URL'], config['sonarr']['API_KEY']) e = ELK(config['elk']['URL'], config['elk']['PORT']) services = config['elk']['SERVICES'] #logger.debug("Configured services: {}", services) for service in services: logs = e.getLogs(service) content[service] = logs #logger.debug("Sonarr - {}", episode) content['sonarr'] = s.getLastEpisodes() content['diskspace'] = s.getDiskSpace() #logger.debug(content) #pretty(content) app = Flask(__name__) @app.route('/') def hello_world():
async def test_client_error(): """Test HTTP client error.""" async with ClientSession() as session: client = Sonarr("#", API_KEY, session=session) with pytest.raises(SonarrConnectionError): assert await client._request("system/status")
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackQueryHandler) import logging from imdb import IMDb import os import random if os.path.isfile('.env'): from dotenv import load_dotenv load_dotenv() radarrApiKey = os.environ.get('RADARR_API_KEY') sonarrApiKey = os.environ.get('SONARR_API_KEY') telegram_bot_token = os.environ.get('TELEGRAM_BOT_TOKEN') raddar = Radarr(radarrApiKey) sonarr = Sonarr(sonarrApiKey) seasons_to_add_global = {} manager_id = os.environ.get('MANAGER_ID', '') # Telegram manager id gf_id = os.environ.get('GF_ID', '') guests_id = os.environ.get('GUESTS_ID', '') logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) if manager_id != '': managers = list(map(int, manager_id.split(','))) manager_id = managers[0] if gf_id != '': gf_list = list(map(int, gf_id.split(',')))