import json import json import re from datetime import datetime, date from decimal import Decimal from functools import wraps from http import HTTPStatus from pathlib import Path from typing import Union from pytz import UnknownTimeZoneError from sanic import Sanic, response, Blueprint, __version__ as sanic_version from sanic.blueprint_group import BlueprintGroup from sanic.request import Request from sanic.response import HTTPResponse from sanic_ext import validate from sanic_ext.extensions.openapi import openapi from wrolpi import admin, status from wrolpi.admin import HotspotStatus from wrolpi.common import logger, get_config, wrol_mode_enabled, Base, get_media_directory, \ wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode from wrolpi.dates import set_timezone from wrolpi.downloader import download_manager from wrolpi.errors import WROLModeEnabled, InvalidTimezone, API_ERRORS, APIError, ValidationError, HotspotError from wrolpi.schema import RegexRequest, RegexResponse, SettingsRequest, SettingsResponse, DownloadRequest, EchoResponse from wrolpi.vars import API_HOST, API_PORT, DOCKERIZED, API_DEBUG, API_ACCESS_LOG, API_WORKERS, API_AUTO_RELOAD, \ truthy_arg from wrolpi.version import __version__ logger = logger.getChild(__name__) api_app = Sanic(name='api_app') api_bp = Blueprint('RootAPI', url_prefix='/api') BLUEPRINTS = [api_bp, ] def get_blueprint(name: str, url_prefix: str) -> Blueprint: """ Create a new Sanic blueprint. This will be attached to the app just before run. See `root_api.run_webserver`. """ bp = Blueprint(name, url_prefix) add_blueprint(bp) return bp def add_blueprint(bp: Union[Blueprint, BlueprintGroup]): BLUEPRINTS.append(bp) def run_webserver( host: str = API_HOST, port: int = API_PORT, workers: int = API_WORKERS, api_debug: bool = API_DEBUG, access_log: bool = API_ACCESS_LOG, ): # Attach all blueprints after they have been defined. for bp in BLUEPRINTS: api_app.blueprint(bp) kwargs = dict( host=host, port=port, workers=workers, debug=api_debug, access_log=access_log, auto_reload=DOCKERIZED, ) logger.warning(f'Running Sanic {sanic_version} with kwargs {kwargs}') return api_app.run(**kwargs) def init_parser(parser): # Called by WROLPI's main() function parser.add_argument('-H', '--host', default=API_HOST, help='What network interface to connect webserver') parser.add_argument('-p', '--port', default=API_PORT, type=int, help='What port to connect webserver') parser.add_argument('-w', '--workers', default=API_WORKERS, type=int, help='How many web workers to run') parser.add_argument('--access-log', default=API_ACCESS_LOG, type=truthy_arg, help='Enable Sanic access log') parser.add_argument('--api-debug', default=API_DEBUG, type=truthy_arg, help='Enable Sanic debug log') parser.add_argument('--api-auto-reload', default=API_AUTO_RELOAD, type=truthy_arg, help='Enable Sanic auto reload') def main(args): return run_webserver( host=args.host, port=args.port, workers=args.workers, api_debug=args.api_debug, access_log=args.access_log, ) index_html = '''
This is a WROLPi API.
''' @api_app.get('/') def index(_): return response.html(index_html) @api_bp.route('/echo', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']) @openapi.description('Echo whatever is sent to this.') @openapi.response(HTTPStatus.OK, EchoResponse) async def echo(request: Request): ret = dict( form=request.form, headers=dict(request.headers), json=request.json, method=request.method, args=request.args, ) return response.json(ret) @api_bp.route('/settings', methods=['GET', 'OPTIONS']) @openapi.description('Get WROLPi settings') @openapi.response(HTTPStatus.OK, SettingsResponse) def get_settings(_: Request): config = get_config() settings = { 'download_manager_disabled': download_manager.disabled.is_set(), 'download_manager_stopped': download_manager.stopped.is_set(), 'download_on_startup': config.download_on_startup, 'download_timeout': config.download_timeout, 'hotspot_device': config.hotspot_device, 'hotspot_on_startup': config.hotspot_on_startup, 'hotspot_password': config.hotspot_password, 'hotspot_ssid': config.hotspot_ssid, 'hotspot_status': admin.hotspot_status().name, 'media_directory': str(get_media_directory()), # Convert to string to avoid conversion to relative. 'throttle_on_startup': config.throttle_on_startup, 'throttle_status': admin.throttle_status().name, 'timezone': config.timezone, 'version': __version__, 'wrol_mode': config.wrol_mode, } return json_response(settings) @api_bp.patch('/settings') @openapi.description('Update WROLPi settings') @validate(json=SettingsRequest) def update_settings(_: Request, body: SettingsRequest): if wrol_mode_enabled() and body.wrol_mode is None: # Cannot update settings while WROL Mode is enabled, unless you want to disable WROL Mode. raise WROLModeEnabled() if body.wrol_mode is False: # Disable WROL Mode disable_wrol_mode() return response.empty() elif body.wrol_mode is True: # Enable WROL Mode enable_wrol_mode() return response.empty() try: if body.timezone: set_timezone(body.timezone) except UnknownTimeZoneError: raise InvalidTimezone(f'Invalid timezone: {body.timezone}') # Remove any keys with None values, then save the config. config = {k: v for k, v in body.__dict__.items() if v is not None} wrolpi_config = get_config() old_password = wrolpi_config.hotspot_password wrolpi_config.update(config) # If the password was changed, we need to restart the hotspot. password_changed = (new_password := config.get('hotspot_password')) and old_password != new_password if body.hotspot_status is True or (password_changed and admin.hotspot_status() == HotspotStatus.connected): # Turn on Hotspot if admin.enable_hotspot() is False: raise HotspotError('Could not turn on hotspot') elif body.hotspot_status is False: # Turn off Hotspot if admin.disable_hotspot() is False: raise HotspotError('Could not turn off hotspot') return response.empty() @api_bp.post('/valid_regex') @openapi.description('Check if the regex is valid.') @openapi.response(HTTPStatus.OK, RegexResponse) @openapi.response(HTTPStatus.BAD_REQUEST, RegexResponse) @validate(RegexRequest) def valid_regex(_: Request, body: RegexRequest): try: re.compile(body.regex) return response.json({'valid': True, 'regex': body.regex}) except re.error: return response.json({'valid': False, 'regex': body.regex}, HTTPStatus.BAD_REQUEST) @api_bp.post('/download') @openapi.description('Download the many URLs that are provided.') @validate(DownloadRequest) @wrol_mode_check async def post_download(_: Request, body: DownloadRequest): # URLs are provided in a textarea, lets split all lines. urls = [i.strip() for i in str(body.urls).strip().splitlines()] excluded_urls = [i.strip() for i in body.excluded_urls.split(',')] if body.excluded_urls else None downloader = body.downloader if not downloader or downloader in ('auto', 'None', 'null'): downloader = None if body.frequency: download_manager.recurring_download(urls[0], body.frequency, downloader=downloader, sub_downloader=body.sub_downloader, reset_attempts=True, excluded_urls=excluded_urls) else: download_manager.create_downloads(urls, downloader=downloader, sub_downloader=body.sub_downloader, reset_attempts=True, excluded_urls=excluded_urls) return response.empty() @api_bp.get('/download') @openapi.description('Get all Downloads that need to be processed.') async def get_downloads(_: Request): data = download_manager.get_fe_downloads() return json_response(data) @api_bp.post('/download/