Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
import asyncio
|
2026-05-02 14:31:54 -06:00
|
|
|
import json
|
2024-03-09 16:27:34 -07:00
|
|
|
import pathlib
|
2021-11-01 16:42:52 -06:00
|
|
|
import re
|
|
|
|
|
from http import HTTPStatus
|
2026-03-13 15:03:13 -06:00
|
|
|
from zoneinfo import ZoneInfo
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2023-06-11 12:31:56 -06:00
|
|
|
import vininfo.exceptions
|
2024-05-02 10:56:43 -06:00
|
|
|
from sanic import response, Blueprint, __version__ as sanic_version
|
2021-11-01 16:42:52 -06:00
|
|
|
from sanic.request import Request
|
2022-01-13 09:29:58 -07:00
|
|
|
from sanic_ext import validate
|
|
|
|
|
from sanic_ext.extensions.openapi import openapi
|
2023-06-11 12:31:56 -06:00
|
|
|
from vininfo import Vin
|
|
|
|
|
from vininfo.details._base import VinDetails
|
2021-11-01 16:42:52 -06:00
|
|
|
|
ai: add the /api/ai blueprint, the read-only LLM tool catalog
Lean, flat, LLM-shaped read-only endpoints over the library: global,
video, archive, and doc search; paged captions, archive text, and zim
entries; collections, inventories, and a media-directory text reader.
Links are server-computed; big content is paged, never truncated.
This ports the formatting layer from wrolpi_mcp (untouched for now)
into tested code. First phase of ai.md.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 21:03:11 -06:00
|
|
|
from modules.ai.api import ai_bp
|
ai: the /api/chat agent loop — SSE streaming, modes, tool execution
Tool definitions are generated in-process from the /api/ai blueprint's
own OpenAPI operations (operationId = tool name, description = tool
description, dataclass bodies + declared parameters = one flat JSON
schema) — the spec IS the catalog, nothing to drift. Manage endpoints
never become tools. A mode is a server-enforced system prompt + tool
allowlist (Help / Research / System per ai.md); the executor can only
reach allowlisted /api/ai endpoints, path parameters are encoded and
traversal-rejected so a crafted argument cannot escape an endpoint.
POST /api/chat streams SSE (status/token/tool_call/tool_result/done/
error), starts llama-server on demand, validates tool args server-side
with instructive errors the model can retry on, caps tool results with
a paging hint, and bounds the loop by ai.yaml max_tool_calls plus a
hard timeout. Caddy passes the stream unbuffered (flush_interval -1)
in both deployments.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 21:47:50 -06:00
|
|
|
from modules.ai.chat import chat_bp
|
2024-07-30 19:28:53 -06:00
|
|
|
from modules.archive.api import archive_bp
|
2026-03-17 18:35:57 -06:00
|
|
|
from modules.docs.api import docs_bp
|
Add ESP32 firmware flasher
Browser-based ESP32/ESP8266 flasher (esptool-js + Web Serial); nothing is
uploaded to WROLPi, the flash is written straight to the device over USB.
Firmware sources (themed, tabbed): a saved set, the WROLPi media directory,
or a local file. Local files can be dropped anywhere on the page, which jumps
to the "Add from computer" dropzone. The media picker searches .bin files by
path and can detect the connected chip to filter firmware to matching images.
- Indexed file_group.suffix + path filter for fast .bin search (alembic
migration backfills via split_path_stem_and_suffix)
- modules/flasher: chip detection from ESP image headers, /search endpoint,
and flasher.yaml saved configurations (/configs CRUD)
- Flash progress modal with ETA, connect timeout, boot-mode hint, auto-
scrolling logs
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 18:24:21 -06:00
|
|
|
from modules.flasher.api import flasher_bp
|
2024-04-17 11:25:26 -06:00
|
|
|
from modules.inventory import inventory_bp
|
|
|
|
|
from modules.map.api import map_bp
|
|
|
|
|
from modules.videos.api import videos_bp
|
|
|
|
|
from modules.zim.api import zim_bp
|
2025-12-19 17:40:43 -07:00
|
|
|
from wrolpi import flags, schema, dates
|
2023-03-24 08:58:18 -06:00
|
|
|
from wrolpi import tags
|
2024-09-28 17:28:33 -06:00
|
|
|
from wrolpi.api_utils import json_response, api_app
|
2025-10-29 22:16:33 -06:00
|
|
|
from wrolpi.collections.api import collection_bp
|
2024-04-17 11:25:26 -06:00
|
|
|
from wrolpi.common import logger, get_wrolpi_config, wrol_mode_enabled, get_media_directory, \
|
|
|
|
|
wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode, get_global_statistics, url_strip_host, \
|
2026-03-13 15:56:21 -06:00
|
|
|
set_global_log_level, get_relative_to_media_directory, search_other_estimates, set_system_timezone
|
2024-12-03 22:30:12 -07:00
|
|
|
from wrolpi.config_api import config_bp
|
2023-10-20 18:53:26 -06:00
|
|
|
from wrolpi.dates import now
|
db: write intent is the opt-in, not a second session helper
Three "database is locked" failures on the docker WROLPi, one cause each:
* `INSERT INTO download` from POST /api/download -- a user creating a
video download while a refresh ran (2026-08-06 14:06:46);
* six `INSERT INTO file_group` from `upsert_file`, uploads landing in
the same three-minute window;
* `UPDATE download SET status` from `renew_recurring_downloads`.
All three are the deferred read-then-write trap: a transaction that
begins as a reader and upgrades at its first write is refused
*instantly* when another connection wrote in between, because
busy_timeout is skipped for lock upgrades. `get_immediate_db_session`
existed to avoid it, but an opt-in helper only works if every author
remembers, and read-then-write is the ordinary shape of a write. So it
is gone: `get_db_session(commit=True)` -- the existing declaration of
write intent -- now begins IMMEDIATE. Rails 7.1 and Django 5.1 made the
same call, defaulting SQLite transactions to IMMEDIATE rather than
asking application code to opt in.
That default is only safe if write transactions stay short, and one did
not. `video_cleanup` ran its whole Channel-claiming join --
`UPDATE video ... FROM channel ... LEFT JOIN file_group`, O(channels x
file_groups) -- inside one write transaction: 110 to 130 seconds each of
the eight times it appears in the log, on a library with ~1500 channels.
While it ran, *every* writer on the box failed, including ones that
began IMMEDIATE, because the hold far exceeds the 30s busy_timeout. The
14:04-14:06 failures above sit inside its 130-second window. The join
is now a read -- WAL readers never block writers -- and only the
resulting UPDATEs take the lock, 500 rows per transaction.
`claim_videos_for_channels` had the same join and the same fix; channel
import calls it with every channel in channels.yaml.
Also here:
* `renew_recurring_downloads` was a read session with an inner commit;
it is a write session now. Its computed `next_download` values now
persist even when nothing was renewed -- that is the point of
computing them.
* POST /api/download no longer writes through `request.ctx.session`.
That session is committed by the response middleware, so a writer
would hold the lock across the whole request; a write session
commits before the handler returns, ahead of the background dispatch
it fires.
* `_immediate_txn` is a ContextVar, not a threading.local. The
writers that set it include coroutines, and one asyncio thread runs
many of them interleaved.
* `write_lock_held_briefly` moved from the move tests into conftest,
since two suites now need it.
Both regression tests were verified by mutation: reverting either site
alone fails its own test, and the API one fails with the production
error verbatim.
Sources: fractaledmind.com/2023/12/11/sqlite-on-rails-improving-concurrency,
tenthousandmeters.com/blog/sqlite-concurrent-writes-and-database-is-locked-errors,
berthub.eu/articles/posts/a-brief-post-on-sqlite3-database-locked-despite-timeout
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 19:40:41 -06:00
|
|
|
from wrolpi.db import get_db_session
|
2024-05-01 17:42:26 -06:00
|
|
|
from wrolpi.downloader import download_manager
|
2025-12-19 17:40:43 -07:00
|
|
|
from wrolpi.errors import WROLModeEnabled, InvalidConfig, ValidationError
|
2023-04-01 15:34:46 -06:00
|
|
|
from wrolpi.events import get_events, Events
|
2024-04-17 11:25:26 -06:00
|
|
|
from wrolpi.files import files_bp
|
2024-02-10 19:42:29 -07:00
|
|
|
from wrolpi.files.lib import get_file_statistics, search_file_suggestion_count
|
2026-01-23 15:11:12 -07:00
|
|
|
from wrolpi.log_levels import int_to_name
|
2024-08-15 19:32:01 -06:00
|
|
|
from wrolpi.tags import Tag
|
2024-05-02 10:56:43 -06:00
|
|
|
from wrolpi.vars import DOCKERIZED, IS_RPI, IS_RPI4, IS_RPI5, API_HOST, API_PORT, API_WORKERS, API_DEBUG, \
|
|
|
|
|
API_ACCESS_LOG, truthy_arg, API_AUTO_RELOAD
|
2022-01-30 16:59:26 -07:00
|
|
|
from wrolpi.version import __version__
|
2021-11-01 16:42:52 -06:00
|
|
|
|
|
|
|
|
logger = logger.getChild(__name__)
|
|
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
api_app.config.FALLBACK_ERROR_FORMAT = 'json'
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
api_bp = Blueprint('RootAPI', url_prefix='/api')
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2024-04-17 11:25:26 -06:00
|
|
|
# Blueprints order here defines what order they are displayed in OpenAPI Docs.
|
|
|
|
|
api_app.blueprint(api_bp)
|
ai: add the /api/ai blueprint, the read-only LLM tool catalog
Lean, flat, LLM-shaped read-only endpoints over the library: global,
video, archive, and doc search; paged captions, archive text, and zim
entries; collections, inventories, and a media-directory text reader.
Links are server-computed; big content is paged, never truncated.
This ports the formatting layer from wrolpi_mcp (untouched for now)
into tested code. First phase of ai.md.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 21:03:11 -06:00
|
|
|
api_app.blueprint(ai_bp)
|
ai: the /api/chat agent loop — SSE streaming, modes, tool execution
Tool definitions are generated in-process from the /api/ai blueprint's
own OpenAPI operations (operationId = tool name, description = tool
description, dataclass bodies + declared parameters = one flat JSON
schema) — the spec IS the catalog, nothing to drift. Manage endpoints
never become tools. A mode is a server-enforced system prompt + tool
allowlist (Help / Research / System per ai.md); the executor can only
reach allowlisted /api/ai endpoints, path parameters are encoded and
traversal-rejected so a crafted argument cannot escape an endpoint.
POST /api/chat streams SSE (status/token/tool_call/tool_result/done/
error), starts llama-server on demand, validates tool args server-side
with instructive errors the model can retry on, caps tool results with
a paging hint, and bounds the loop by ai.yaml max_tool_calls plus a
hard timeout. Caddy passes the stream unbuffered (flush_interval -1)
in both deployments.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 21:47:50 -06:00
|
|
|
api_app.blueprint(chat_bp)
|
2024-04-17 11:25:26 -06:00
|
|
|
api_app.blueprint(archive_bp)
|
2025-10-29 22:16:33 -06:00
|
|
|
api_app.blueprint(collection_bp) # Unified collection endpoints
|
2024-12-03 22:30:12 -07:00
|
|
|
api_app.blueprint(config_bp)
|
2026-03-17 18:35:57 -06:00
|
|
|
api_app.blueprint(docs_bp)
|
2024-04-17 11:25:26 -06:00
|
|
|
api_app.blueprint(files_bp)
|
Add ESP32 firmware flasher
Browser-based ESP32/ESP8266 flasher (esptool-js + Web Serial); nothing is
uploaded to WROLPi, the flash is written straight to the device over USB.
Firmware sources (themed, tabbed): a saved set, the WROLPi media directory,
or a local file. Local files can be dropped anywhere on the page, which jumps
to the "Add from computer" dropzone. The media picker searches .bin files by
path and can detect the connected chip to filter firmware to matching images.
- Indexed file_group.suffix + path filter for fast .bin search (alembic
migration backfills via split_path_stem_and_suffix)
- modules/flasher: chip detection from ESP image headers, /search endpoint,
and flasher.yaml saved configurations (/configs CRUD)
- Flash progress modal with ETA, connect timeout, boot-mode hint, auto-
scrolling logs
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 18:24:21 -06:00
|
|
|
api_app.blueprint(flasher_bp)
|
2024-04-17 11:25:26 -06:00
|
|
|
api_app.blueprint(inventory_bp)
|
|
|
|
|
api_app.blueprint(map_bp)
|
|
|
|
|
api_app.blueprint(videos_bp)
|
|
|
|
|
api_app.blueprint(zim_bp)
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2024-05-02 10:56:43 -06:00
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
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,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2021-11-01 16:42:52 -06:00
|
|
|
index_html = '''
|
|
|
|
|
<html>
|
|
|
|
|
<body>
|
|
|
|
|
<p>
|
|
|
|
|
This is a WROLPi API.
|
|
|
|
|
<ul>
|
|
|
|
|
<li>You can test it at this endpoint <a href="/api/echo">/api/echo</a></li>
|
2022-02-03 10:07:04 -07:00
|
|
|
<li>You can view the docs at <a href="/docs">/docs</a></li>
|
2021-11-01 16:42:52 -06:00
|
|
|
</ul>
|
|
|
|
|
</p>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|
|
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
|
2023-06-09 16:16:43 -06:00
|
|
|
@api_app.get('/')
|
2023-06-09 16:09:56 -06:00
|
|
|
@api_bp.get('/')
|
|
|
|
|
async def index(_):
|
2021-11-01 16:42:52 -06:00
|
|
|
return response.html(index_html)
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.route('/echo', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'])
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Echo whatever is sent to this.',
|
|
|
|
|
response=schema.EchoResponse,
|
|
|
|
|
)
|
2021-11-01 16:42:52 -06:00
|
|
|
async def echo(request: Request):
|
2024-08-15 19:32:01 -06:00
|
|
|
try:
|
|
|
|
|
request_json = request.json
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error('Failed to parse request JSON', exc_info=e)
|
|
|
|
|
request_json = None
|
|
|
|
|
request_headers = dict(request.headers)
|
2021-11-01 16:42:52 -06:00
|
|
|
ret = dict(
|
|
|
|
|
form=request.form,
|
2024-08-15 19:32:01 -06:00
|
|
|
headers=request_headers,
|
|
|
|
|
json=request_json,
|
2021-11-01 16:42:52 -06:00
|
|
|
method=request.method,
|
|
|
|
|
args=request.args,
|
|
|
|
|
)
|
|
|
|
|
return response.json(ret)
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.route('/settings', methods=['GET', 'OPTIONS'])
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Get WROLPi settings',
|
|
|
|
|
response=schema.SettingsResponse,
|
|
|
|
|
)
|
2021-11-01 16:42:52 -06:00
|
|
|
def get_settings(_: Request):
|
2024-09-26 09:13:29 -06:00
|
|
|
wrolpi_config = get_wrolpi_config()
|
2022-02-16 21:57:27 -07:00
|
|
|
|
2026-07-19 13:19:30 -06:00
|
|
|
# Drop special directories (e.g. zims) that must never be ignored, if present from older configs.
|
|
|
|
|
from wrolpi.files.lib import sanitize_ignored_directories
|
|
|
|
|
sanitize_ignored_directories()
|
|
|
|
|
|
2024-09-26 09:13:29 -06:00
|
|
|
ignored_directories = [get_relative_to_media_directory(i) for i in wrolpi_config.ignored_directories]
|
2024-02-19 13:45:41 -07:00
|
|
|
|
2022-02-16 21:57:27 -07:00
|
|
|
settings = {
|
2024-09-26 09:13:29 -06:00
|
|
|
'archive_destination': wrolpi_config.archive_destination,
|
2024-05-01 17:42:26 -06:00
|
|
|
'download_manager_disabled': download_manager.is_disabled,
|
|
|
|
|
'download_manager_stopped': download_manager.is_stopped,
|
2026-06-28 16:51:21 -06:00
|
|
|
'download_daily_limit_global': wrolpi_config.download_daily_limit_global,
|
|
|
|
|
'download_daily_limit_per_domain': wrolpi_config.download_daily_limit_per_domain,
|
2024-09-26 09:13:29 -06:00
|
|
|
'download_on_startup': wrolpi_config.download_on_startup,
|
|
|
|
|
'download_timeout': wrolpi_config.download_timeout,
|
2026-02-20 14:37:58 -07:00
|
|
|
'download_wait': wrolpi_config.download_wait,
|
2026-03-12 20:10:57 -06:00
|
|
|
'download_window_start': wrolpi_config.download_window_start,
|
|
|
|
|
'download_window_end': wrolpi_config.download_window_end,
|
2024-09-26 09:13:29 -06:00
|
|
|
'hotspot_device': wrolpi_config.hotspot_device,
|
|
|
|
|
'hotspot_on_startup': wrolpi_config.hotspot_on_startup,
|
|
|
|
|
'hotspot_password': wrolpi_config.hotspot_password,
|
|
|
|
|
'hotspot_ssid': wrolpi_config.hotspot_ssid,
|
2025-12-19 17:40:43 -07:00
|
|
|
# Hotspot/throttle status now from Controller (/controller/api/hotspot/status, /controller/api/throttle/status)
|
2025-12-06 14:47:52 -07:00
|
|
|
'check_for_upgrades': wrolpi_config.check_for_upgrades,
|
2024-09-26 09:13:29 -06:00
|
|
|
'ignore_outdated_zims': wrolpi_config.ignore_outdated_zims,
|
2024-02-19 13:45:41 -07:00
|
|
|
'ignored_directories': ignored_directories,
|
2024-04-17 11:25:26 -06:00
|
|
|
'log_level': api_app.shared_ctx.log_level.value,
|
2026-04-04 14:56:25 -06:00
|
|
|
'map_default_location': wrolpi_config.map_default_location,
|
2024-09-26 09:13:29 -06:00
|
|
|
'map_destination': wrolpi_config.map_destination,
|
|
|
|
|
'nav_color': wrolpi_config.nav_color,
|
2022-08-06 05:22:07 +00:00
|
|
|
'media_directory': str(get_media_directory()), # Convert to string to avoid conversion to relative.
|
Add ordered collections (playlists): polymorphic items + item API (#475)
* Add Playlists: ordered, mixed-type collections
A playlist (Collection kind='playlist') is a manually-curated, ordered list that
mixes item types. Squash of the playlists feature branch (24 commits).
Data model & API:
- CollectionItem is polymorphic via item_kind: 'file' (FileGroup), 'zim'
(zim_id + zim_entry), or 'url' (link to anything the WROLPi browser opens,
e.g. /map?lat=&lon=&z=). CHECK constraint enforces exactly one kind; per-kind
unique constraints; migration a7b1c2d3e4f5.
- Endpoints: create playlist; add/remove/reorder items (idempotent adds: 201 new,
200 existing); GET returns the ordered items. All mutations wrol_mode_check'd.
Config (source of truth):
- playlists.yaml (PlaylistsConfig) stores each playlist's metadata AND ordered
items (file by relative path, zim by path+entry, url inline); round-trips a
DB wipe. Supports backup import (DB_CONFIG_FILE_NAMES).
- The redundant generic CollectionsConfig (collections.yaml) is deleted:
channels/domains own their configs, authors/subjects are re-derived.
On-disk sync (sync_playlists_directory switch):
- Each playlist materializes into the configurable Playlists Directory
(playlists_destination, Settings UI input, excluded from indexing) with
position-prefixed entries: NNNN_<file> hard links (copy fallback across
filesystems) and NNNN_<title>.html stubs for zim/url items.
- Tagged playlists are namespaced like channels: <playlists>/<tag>/<name>;
a tag change moves the directory and prunes the empty old tag dir.
- Deletion safety: managed files are only removed when they are our marked
stubs or still have another hard link (st_nlink > 1) -- never a last copy.
Stray loose files at the playlists root are removed; stub URLs are
scheme-allowlisted (no javascript:/data:).
Frontend:
- /playlists list page (CollectionTable, name filter, New Playlist modal, Tag
column) between Files and Zim in the nav.
- View-only detail page (Name link) and edit page (Edit button): themed table
with model icons/colors + poster thumbnails, items link to their model page
(video/archive/doc) or preview, up/down reorder, remove, add-URL form,
single-tag selector; all editing disabled in WROL Mode.
- Reusable green "Add to Playlist" button on Video/Archive/Doc detail pages,
the FilePreview toolbar, Zim search results, and Map pins (added as a /map
URL item with a map-marker icon).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Playlist edit page parity: rename, custom directory, tag modal move suggestion
Match the ChannelEditPage/DomainEditPage UX on the playlist edit page:
Back/View buttons, an edit form (name, description, directory), and the
shared CollectionTagModal with the violet "Tag" button. The tag modal now
suggests moving the playlist to its managed tag location
(playlists/<tag>/<name>); accepting the suggestion stores directory=None so
the sync keeps auto-managing the location. Tag buttons on the Channel and
Domain edit pages are now violet to match.
Backend: update_collection learns rename (with per-kind validation and
duplicate checks) and playlist custom directories (cleanup of the abandoned
directory, config round-trip, commit-before-switch to avoid the background
sync racing pre-commit state). tag_collection's duplicated untag/tag
branches are merged, and the per-kind config-save dispatch is consolidated
into _activate_config_save().
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Deduplicate Collection error handling and Tag creation
Delete the duplicate UnknownCollection in wrolpi/collections/errors.py and
re-export the canonical one from wrolpi/errors.py, which carries
status_code=NOT_FOUND (the local copy inherited 500). Replace the repeated
query/raise pattern in reorganize.py with Collection.find_by_id.
Add Tag.get_or_create_tag and use it for collection tagging; flush the new
Tag before returning so callers can read .id immediately -- previously
tagging a collection with a brand-new tag name set tag_id=None. Regression
test included.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:37:34 -06:00
|
|
|
'playlists_destination': wrolpi_config.playlists_destination,
|
2026-01-31 12:54:27 -07:00
|
|
|
'tags_directory': wrolpi_config.tags_directory,
|
2024-09-26 09:13:29 -06:00
|
|
|
'throttle_on_startup': wrolpi_config.throttle_on_startup,
|
2022-02-16 21:57:27 -07:00
|
|
|
'version': __version__,
|
2024-09-26 09:13:29 -06:00
|
|
|
'videos_destination': wrolpi_config.videos_destination,
|
|
|
|
|
'wrol_mode': wrolpi_config.wrol_mode,
|
|
|
|
|
'zims_destination': wrolpi_config.zims_destination,
|
2026-03-14 12:08:23 -06:00
|
|
|
'require_cookies_unlocked': wrolpi_config.require_cookies_unlocked,
|
2026-05-14 15:51:32 -06:00
|
|
|
'require_media_mounted': wrolpi_config.require_media_mounted,
|
2026-02-07 18:40:56 -07:00
|
|
|
'save_ffprobe_json': wrolpi_config.save_ffprobe_json,
|
2026-03-13 15:03:13 -06:00
|
|
|
'timezone': wrolpi_config.timezone,
|
2022-02-16 21:57:27 -07:00
|
|
|
}
|
|
|
|
|
return json_response(settings)
|
2021-11-01 16:42:52 -06:00
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.patch('/settings')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Update WROLPi settings',
|
|
|
|
|
body=schema.SettingsRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2024-04-17 11:25:26 -06:00
|
|
|
async def update_settings(_: Request, body: schema.SettingsRequest):
|
2022-02-16 21:57:27 -07:00
|
|
|
if wrol_mode_enabled() and body.wrol_mode is None:
|
2021-11-01 16:42:52 -06:00
|
|
|
# Cannot update settings while WROL Mode is enabled, unless you want to disable WROL Mode.
|
|
|
|
|
raise WROLModeEnabled()
|
|
|
|
|
|
2022-02-16 21:57:27 -07:00
|
|
|
if body.wrol_mode is False:
|
|
|
|
|
# Disable WROL Mode
|
2024-04-17 11:25:26 -06:00
|
|
|
await disable_wrol_mode()
|
2022-02-16 21:57:27 -07:00
|
|
|
return response.empty()
|
|
|
|
|
elif body.wrol_mode is True:
|
|
|
|
|
# Enable WROL Mode
|
2022-08-06 05:22:07 +00:00
|
|
|
enable_wrol_mode()
|
2022-02-16 21:57:27 -07:00
|
|
|
return response.empty()
|
|
|
|
|
|
2023-07-17 14:21:27 -06:00
|
|
|
if body.hotspot_password and len(body.hotspot_password) < 8:
|
2025-12-19 17:40:43 -07:00
|
|
|
raise InvalidConfig('Hotspot password must be at least 8 characters')
|
2023-07-17 14:21:27 -06:00
|
|
|
|
2022-02-16 21:57:27 -07:00
|
|
|
# Remove any keys with None values, then save the config.
|
2024-09-26 09:13:29 -06:00
|
|
|
new_config = {k: v for k, v in body.__dict__.items() if v is not None}
|
2024-03-09 16:27:34 -07:00
|
|
|
wrolpi_config = get_wrolpi_config()
|
2026-07-20 18:24:03 -06:00
|
|
|
old_zims_destination = wrolpi_config.zims_destination
|
2023-09-08 17:10:15 -06:00
|
|
|
|
2024-09-26 09:13:29 -06:00
|
|
|
if not new_config:
|
2023-09-08 17:10:15 -06:00
|
|
|
raise InvalidConfig()
|
|
|
|
|
|
2024-08-06 18:13:21 -06:00
|
|
|
if body.archive_destination and pathlib.Path(body.archive_destination).is_absolute():
|
2024-03-09 16:27:34 -07:00
|
|
|
raise InvalidConfig('Archive directory must be relative to media directory')
|
2024-08-06 18:13:21 -06:00
|
|
|
elif not body.archive_destination:
|
2024-09-26 09:13:29 -06:00
|
|
|
new_config['archive_destination'] = wrolpi_config.default_config['archive_destination']
|
2024-03-09 16:27:34 -07:00
|
|
|
|
2024-08-06 18:13:21 -06:00
|
|
|
if body.videos_destination and pathlib.Path(body.videos_destination).is_absolute():
|
2024-03-09 16:27:34 -07:00
|
|
|
raise InvalidConfig('Videos directory must be relative to media directory')
|
2024-08-06 18:13:21 -06:00
|
|
|
elif not body.videos_destination:
|
2024-09-26 09:13:29 -06:00
|
|
|
new_config['videos_destination'] = wrolpi_config.default_config['videos_destination']
|
2024-03-09 16:27:34 -07:00
|
|
|
|
2024-08-06 18:13:21 -06:00
|
|
|
if body.map_destination and pathlib.Path(body.map_destination).is_absolute():
|
2024-03-09 16:27:34 -07:00
|
|
|
raise InvalidConfig('Map directory must be relative to media directory')
|
2024-08-06 18:13:21 -06:00
|
|
|
elif not body.map_destination:
|
2024-09-26 09:13:29 -06:00
|
|
|
new_config['map_destination'] = wrolpi_config.default_config['map_destination']
|
2024-03-09 16:27:34 -07:00
|
|
|
|
2024-08-06 18:13:21 -06:00
|
|
|
if body.zims_destination and pathlib.Path(body.zims_destination).is_absolute():
|
2024-03-09 16:27:34 -07:00
|
|
|
raise InvalidConfig('Zims directory must be relative to media directory')
|
2026-07-20 18:44:19 -06:00
|
|
|
elif body.zims_destination and '..' in pathlib.Path(body.zims_destination).parts:
|
|
|
|
|
# Kiwix serves and rebuilds library.xml in this directory; traversal must not escape media.
|
|
|
|
|
raise InvalidConfig('Zims directory must not contain ".."')
|
2024-08-06 18:13:21 -06:00
|
|
|
elif not body.zims_destination:
|
2024-09-26 09:13:29 -06:00
|
|
|
new_config['zims_destination'] = wrolpi_config.default_config['zims_destination']
|
2024-03-09 16:27:34 -07:00
|
|
|
|
Add ordered collections (playlists): polymorphic items + item API (#475)
* Add Playlists: ordered, mixed-type collections
A playlist (Collection kind='playlist') is a manually-curated, ordered list that
mixes item types. Squash of the playlists feature branch (24 commits).
Data model & API:
- CollectionItem is polymorphic via item_kind: 'file' (FileGroup), 'zim'
(zim_id + zim_entry), or 'url' (link to anything the WROLPi browser opens,
e.g. /map?lat=&lon=&z=). CHECK constraint enforces exactly one kind; per-kind
unique constraints; migration a7b1c2d3e4f5.
- Endpoints: create playlist; add/remove/reorder items (idempotent adds: 201 new,
200 existing); GET returns the ordered items. All mutations wrol_mode_check'd.
Config (source of truth):
- playlists.yaml (PlaylistsConfig) stores each playlist's metadata AND ordered
items (file by relative path, zim by path+entry, url inline); round-trips a
DB wipe. Supports backup import (DB_CONFIG_FILE_NAMES).
- The redundant generic CollectionsConfig (collections.yaml) is deleted:
channels/domains own their configs, authors/subjects are re-derived.
On-disk sync (sync_playlists_directory switch):
- Each playlist materializes into the configurable Playlists Directory
(playlists_destination, Settings UI input, excluded from indexing) with
position-prefixed entries: NNNN_<file> hard links (copy fallback across
filesystems) and NNNN_<title>.html stubs for zim/url items.
- Tagged playlists are namespaced like channels: <playlists>/<tag>/<name>;
a tag change moves the directory and prunes the empty old tag dir.
- Deletion safety: managed files are only removed when they are our marked
stubs or still have another hard link (st_nlink > 1) -- never a last copy.
Stray loose files at the playlists root are removed; stub URLs are
scheme-allowlisted (no javascript:/data:).
Frontend:
- /playlists list page (CollectionTable, name filter, New Playlist modal, Tag
column) between Files and Zim in the nav.
- View-only detail page (Name link) and edit page (Edit button): themed table
with model icons/colors + poster thumbnails, items link to their model page
(video/archive/doc) or preview, up/down reorder, remove, add-URL form,
single-tag selector; all editing disabled in WROL Mode.
- Reusable green "Add to Playlist" button on Video/Archive/Doc detail pages,
the FilePreview toolbar, Zim search results, and Map pins (added as a /map
URL item with a map-marker icon).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Playlist edit page parity: rename, custom directory, tag modal move suggestion
Match the ChannelEditPage/DomainEditPage UX on the playlist edit page:
Back/View buttons, an edit form (name, description, directory), and the
shared CollectionTagModal with the violet "Tag" button. The tag modal now
suggests moving the playlist to its managed tag location
(playlists/<tag>/<name>); accepting the suggestion stores directory=None so
the sync keeps auto-managing the location. Tag buttons on the Channel and
Domain edit pages are now violet to match.
Backend: update_collection learns rename (with per-kind validation and
duplicate checks) and playlist custom directories (cleanup of the abandoned
directory, config round-trip, commit-before-switch to avoid the background
sync racing pre-commit state). tag_collection's duplicated untag/tag
branches are merged, and the per-kind config-save dispatch is consolidated
into _activate_config_save().
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Deduplicate Collection error handling and Tag creation
Delete the duplicate UnknownCollection in wrolpi/collections/errors.py and
re-export the canonical one from wrolpi/errors.py, which carries
status_code=NOT_FOUND (the local copy inherited 500). Replace the repeated
query/raise pattern in reorganize.py with Collection.find_by_id.
Add Tag.get_or_create_tag and use it for collection tagging; flush the new
Tag before returning so callers can read .id immediately -- previously
tagging a collection with a brand-new tag name set tag_id=None. Regression
test included.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:37:34 -06:00
|
|
|
if body.playlists_destination:
|
|
|
|
|
# The playlists sync deletes files in its directory, so this destination gets stricter
|
|
|
|
|
# validation: no traversal, and no overlap with the other content destinations. Compare
|
|
|
|
|
# against the destinations in this same request when provided.
|
|
|
|
|
from types import SimpleNamespace
|
|
|
|
|
from wrolpi.collections.sync import validate_playlists_destination
|
|
|
|
|
effective = SimpleNamespace(
|
|
|
|
|
videos_destination=body.videos_destination or wrolpi_config.videos_destination,
|
|
|
|
|
archive_destination=body.archive_destination or wrolpi_config.archive_destination,
|
|
|
|
|
map_destination=body.map_destination or wrolpi_config.map_destination,
|
|
|
|
|
zims_destination=body.zims_destination or wrolpi_config.zims_destination,
|
|
|
|
|
)
|
|
|
|
|
if error := validate_playlists_destination(body.playlists_destination, effective):
|
|
|
|
|
raise InvalidConfig(error)
|
|
|
|
|
else:
|
|
|
|
|
new_config['playlists_destination'] = wrolpi_config.default_config['playlists_destination']
|
|
|
|
|
|
2026-03-13 15:03:13 -06:00
|
|
|
# Validate timezone if provided; empty string clears it.
|
|
|
|
|
if body.timezone is not None:
|
|
|
|
|
if body.timezone == '':
|
|
|
|
|
new_config['timezone'] = None
|
|
|
|
|
else:
|
|
|
|
|
try:
|
|
|
|
|
ZoneInfo(body.timezone)
|
|
|
|
|
except (KeyError, Exception):
|
|
|
|
|
raise InvalidConfig(f'Invalid timezone: {body.timezone}')
|
|
|
|
|
|
2026-06-28 16:51:21 -06:00
|
|
|
# Daily download limits must be non-negative integers. 0 (or null) means unlimited.
|
|
|
|
|
for field_name in ('download_daily_limit_global', 'download_daily_limit_per_domain'):
|
|
|
|
|
value = getattr(body, field_name, None)
|
|
|
|
|
if value is not None and value < 0:
|
|
|
|
|
raise InvalidConfig(f'{field_name} must be a non-negative integer')
|
|
|
|
|
|
2026-03-12 20:10:57 -06:00
|
|
|
# Handle download window fields: empty string clears the value.
|
|
|
|
|
for field_name in ('download_window_start', 'download_window_end'):
|
|
|
|
|
value = getattr(body, field_name, None)
|
|
|
|
|
if value is not None:
|
|
|
|
|
if value == '':
|
|
|
|
|
new_config[field_name] = None
|
|
|
|
|
else:
|
|
|
|
|
if not re.match(r'^\d{2}:\d{2}$', value):
|
|
|
|
|
raise InvalidConfig(f'{field_name} must be in HH:MM format')
|
|
|
|
|
new_config[field_name] = value
|
|
|
|
|
|
2024-09-26 09:13:29 -06:00
|
|
|
log_level = new_config.pop('log_level', None)
|
2023-09-08 17:10:15 -06:00
|
|
|
if isinstance(log_level, int):
|
|
|
|
|
set_global_log_level(log_level)
|
2025-12-16 19:20:04 -07:00
|
|
|
# Persist log level to config
|
2026-01-23 15:11:12 -07:00
|
|
|
wrolpi_config.log_level = int_to_name(log_level)
|
2023-09-08 17:10:15 -06:00
|
|
|
|
2025-12-19 17:40:43 -07:00
|
|
|
# Save config settings (hotspot control is now through Controller endpoints)
|
2024-09-26 09:13:29 -06:00
|
|
|
wrolpi_config.update(new_config)
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2026-07-20 18:24:03 -06:00
|
|
|
# If the Zim directory changed, restart Kiwix so it serves the new directory
|
|
|
|
|
# without waiting for a reboot. Local import avoids a circular import
|
|
|
|
|
# (modules depend on wrolpi, not the reverse).
|
|
|
|
|
if wrolpi_config.zims_destination != old_zims_destination:
|
2026-07-20 18:44:19 -06:00
|
|
|
# Persist synchronously first: update() only queues an async background_save,
|
|
|
|
|
# and that switch has no ordering guarantee against the restart switch below.
|
|
|
|
|
# start_kiwix_serve.sh reads zims_destination from disk, so the file must be
|
|
|
|
|
# current before Kiwix restarts. A save failure is non-fatal (background_save
|
|
|
|
|
# still runs); log and continue.
|
|
|
|
|
try:
|
|
|
|
|
wrolpi_config.save()
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.warning(f'Could not synchronously save config before restarting Kiwix: {e}')
|
2026-07-20 18:24:03 -06:00
|
|
|
from modules.zim.lib import restart_kiwix_handler
|
|
|
|
|
restart_kiwix_handler.activate_switch()
|
|
|
|
|
|
2026-03-13 15:56:21 -06:00
|
|
|
# Apply timezone to the system via Controller (native deployments only).
|
|
|
|
|
if body.timezone is not None and not DOCKERIZED:
|
|
|
|
|
timezone_value = new_config.get('timezone')
|
|
|
|
|
if timezone_value:
|
|
|
|
|
await set_system_timezone(timezone_value)
|
|
|
|
|
|
2022-02-16 21:57:27 -07:00
|
|
|
return response.empty()
|
2021-11-01 16:42:52 -06:00
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/valid_regex')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Check if the regex is valid.',
|
|
|
|
|
body=schema.RegexRequest,
|
|
|
|
|
response=schema.RegexResponse,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2023-03-27 20:46:31 -06:00
|
|
|
def valid_regex(_: Request, body: schema.RegexRequest):
|
2021-11-01 16:42:52 -06:00
|
|
|
try:
|
2022-01-13 09:29:58 -07:00
|
|
|
re.compile(body.regex)
|
|
|
|
|
return response.json({'valid': True, 'regex': body.regex})
|
2021-11-01 16:42:52 -06:00
|
|
|
except re.error:
|
2022-01-13 09:29:58 -07:00
|
|
|
return response.json({'valid': False, 'regex': body.regex}, HTTPStatus.BAD_REQUEST)
|
2021-11-01 16:42:52 -06:00
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/download')
|
2024-12-03 12:44:38 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Download all the URLs that are provided.',
|
|
|
|
|
body=schema.DownloadRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2021-12-20 16:08:13 -07:00
|
|
|
@wrol_mode_check
|
2025-12-10 21:16:10 -07:00
|
|
|
async def post_download(request: Request, body: schema.DownloadRequest):
|
2024-12-03 12:44:38 -07:00
|
|
|
# Raises an InvalidDownload if the Downloader cannot be found.
|
|
|
|
|
download_manager.find_downloader_by_name(body.downloader)
|
2023-04-01 15:34:46 -06:00
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
kwargs = dict(downloader_name=body.downloader,
|
|
|
|
|
sub_downloader_name=body.sub_downloader, reset_attempts=True,
|
|
|
|
|
destination=body.destination, tag_names=body.tag_names,
|
2026-03-29 18:58:31 -06:00
|
|
|
settings=body.settings, override_skip=True)
|
db: write intent is the opt-in, not a second session helper
Three "database is locked" failures on the docker WROLPi, one cause each:
* `INSERT INTO download` from POST /api/download -- a user creating a
video download while a refresh ran (2026-08-06 14:06:46);
* six `INSERT INTO file_group` from `upsert_file`, uploads landing in
the same three-minute window;
* `UPDATE download SET status` from `renew_recurring_downloads`.
All three are the deferred read-then-write trap: a transaction that
begins as a reader and upgrades at its first write is refused
*instantly* when another connection wrote in between, because
busy_timeout is skipped for lock upgrades. `get_immediate_db_session`
existed to avoid it, but an opt-in helper only works if every author
remembers, and read-then-write is the ordinary shape of a write. So it
is gone: `get_db_session(commit=True)` -- the existing declaration of
write intent -- now begins IMMEDIATE. Rails 7.1 and Django 5.1 made the
same call, defaulting SQLite transactions to IMMEDIATE rather than
asking application code to opt in.
That default is only safe if write transactions stay short, and one did
not. `video_cleanup` ran its whole Channel-claiming join --
`UPDATE video ... FROM channel ... LEFT JOIN file_group`, O(channels x
file_groups) -- inside one write transaction: 110 to 130 seconds each of
the eight times it appears in the log, on a library with ~1500 channels.
While it ran, *every* writer on the box failed, including ones that
began IMMEDIATE, because the hold far exceeds the 30s busy_timeout. The
14:04-14:06 failures above sit inside its 130-second window. The join
is now a read -- WAL readers never block writers -- and only the
resulting UPDATEs take the lock, 500 rows per transaction.
`claim_videos_for_channels` had the same join and the same fix; channel
import calls it with every channel in channels.yaml.
Also here:
* `renew_recurring_downloads` was a read session with an inner commit;
it is a write session now. Its computed `next_download` values now
persist even when nothing was renewed -- that is the point of
computing them.
* POST /api/download no longer writes through `request.ctx.session`.
That session is committed by the response middleware, so a writer
would hold the lock across the whole request; a write session
commits before the handler returns, ahead of the background dispatch
it fires.
* `_immediate_txn` is a ContextVar, not a threading.local. The
writers that set it include coroutines, and one asyncio thread runs
many of them interleaved.
* `write_lock_held_briefly` moved from the move tests into conftest,
since two suites now need it.
Both regression tests were verified by mutation: reverting either site
alone fails its own test, and the API one fails with the production
error verbatim.
Sources: fractaledmind.com/2023/12/11/sqlite-on-rails-improving-concurrency,
tenthousandmeters.com/blog/sqlite-concurrent-writes-and-database-is-locked-errors,
berthub.eu/articles/posts/a-brief-post-on-sqlite3-database-locked-despite-timeout
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 19:40:41 -06:00
|
|
|
# Not `request.ctx.session`: creating a Download reads (the Tags, then any existing Download for
|
|
|
|
|
# each URL) before it INSERTs, and a deferred transaction fails that lock upgrade *instantly*
|
|
|
|
|
# with "database is locked" if anything else wrote in between -- which is what a user creating a
|
|
|
|
|
# download during a refresh hit. This session also commits before the handler returns, so the
|
|
|
|
|
# background dispatch `create_downloads` fires does not wait on a lock this request still holds.
|
|
|
|
|
with get_db_session(commit=True) as session:
|
|
|
|
|
if body.frequency:
|
|
|
|
|
download_manager.recurring_download(session, body.urls[0], body.frequency,
|
|
|
|
|
collection_id=body.collection_id, **kwargs)
|
|
|
|
|
else:
|
|
|
|
|
download_manager.create_downloads(session, body.urls, **kwargs)
|
2024-06-25 22:12:13 -06:00
|
|
|
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
|
|
|
|
|
# Downloads are disabled, warn the user.
|
|
|
|
|
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
|
|
|
|
|
|
2024-12-03 12:44:38 -07:00
|
|
|
return response.empty(status=HTTPStatus.CREATED)
|
2024-06-25 22:12:13 -06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.put('/download/<download_id:int>')
|
2024-12-03 12:44:38 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Update properties of the Download',
|
|
|
|
|
body=schema.DownloadRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2024-06-25 22:12:13 -06:00
|
|
|
@wrol_mode_check
|
2025-12-10 21:16:10 -07:00
|
|
|
async def put_download(request: Request, download_id: int, body: schema.DownloadRequest):
|
2024-12-03 12:44:38 -07:00
|
|
|
# Raises an InvalidDownload if the Downloader cannot be found.
|
|
|
|
|
download_manager.find_downloader_by_name(body.downloader)
|
|
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
if len(body.urls) != 1:
|
|
|
|
|
raise ValidationError('Only one URL can be specified when updating a Download')
|
|
|
|
|
|
2025-12-10 21:16:10 -07:00
|
|
|
session = request.ctx.session
|
|
|
|
|
download_manager.update_download(
|
|
|
|
|
session,
|
|
|
|
|
id_=download_id,
|
|
|
|
|
url=body.urls[0],
|
|
|
|
|
downloader=body.downloader,
|
|
|
|
|
destination=body.destination,
|
|
|
|
|
frequency=body.frequency,
|
|
|
|
|
tag_names=body.tag_names,
|
|
|
|
|
sub_downloader=body.sub_downloader,
|
|
|
|
|
settings=body.settings,
|
|
|
|
|
collection_id=body.collection_id,
|
|
|
|
|
)
|
2023-04-01 15:50:11 -06:00
|
|
|
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
|
2023-04-01 15:34:46 -06:00
|
|
|
# Downloads are disabled, warn the user.
|
|
|
|
|
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
|
|
|
|
|
|
2021-12-20 16:08:13 -07:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2024-06-25 22:12:13 -06:00
|
|
|
@api_bp.delete('/download/<download_id:int>')
|
|
|
|
|
@openapi.description('Delete a download')
|
|
|
|
|
@wrol_mode_check
|
2025-12-10 21:16:10 -07:00
|
|
|
async def delete_download(request: Request, download_id: int):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
deleted = download_manager.delete_download(session, download_id)
|
2024-06-25 22:12:13 -06:00
|
|
|
return response.empty(HTTPStatus.NO_CONTENT if deleted else HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
|
|
|
|
|
2023-09-07 21:38:19 -06:00
|
|
|
@api_bp.post('/download/<download_id:int>/restart')
|
|
|
|
|
@openapi.description('Restart a download.')
|
2025-12-10 21:16:10 -07:00
|
|
|
async def restart_download(request: Request, download_id: int):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
download_manager.restart_download(session, download_id)
|
2023-09-07 21:38:19 -06:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.get('/download')
|
2024-11-02 15:14:02 -06:00
|
|
|
@openapi.description('Get all Downloads so they can be displayed to the User.')
|
2022-01-13 09:29:58 -07:00
|
|
|
async def get_downloads(_: Request):
|
2022-01-07 14:13:48 -07:00
|
|
|
data = download_manager.get_fe_downloads()
|
2024-11-02 15:14:02 -06:00
|
|
|
|
|
|
|
|
# Convert `destination` to relative.
|
|
|
|
|
for download in data['once_downloads']:
|
|
|
|
|
download['destination'] = get_relative_to_media_directory(download['destination']) \
|
|
|
|
|
if download['destination'] else None
|
|
|
|
|
for download in data['recurring_downloads']:
|
|
|
|
|
download['destination'] = get_relative_to_media_directory(download['destination']) \
|
|
|
|
|
if download['destination'] else None
|
|
|
|
|
|
2021-12-20 16:08:13 -07:00
|
|
|
return json_response(data)
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/download/<download_id:int>/kill')
|
2022-01-13 09:29:58 -07:00
|
|
|
@openapi.description('Kill a download. It will be stopped if it is pending.')
|
|
|
|
|
async def kill_download(_: Request, download_id: int):
|
2021-12-20 16:08:13 -07:00
|
|
|
download_manager.kill_download(download_id)
|
|
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/download/kill')
|
2022-01-13 09:29:58 -07:00
|
|
|
@openapi.description('Kill all downloads. Disable downloading.')
|
|
|
|
|
async def kill_downloads(_: Request):
|
2024-04-17 11:25:26 -06:00
|
|
|
logger.warning('Disabled downloads')
|
2022-08-06 05:22:07 +00:00
|
|
|
download_manager.disable()
|
2022-01-11 10:08:47 -07:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/download/enable')
|
2022-01-13 09:29:58 -07:00
|
|
|
@openapi.description('Enable and start downloading.')
|
|
|
|
|
async def enable_downloads(_: Request):
|
2024-04-17 11:25:26 -06:00
|
|
|
await download_manager.enable()
|
2022-01-11 10:08:47 -07:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/download/clear_completed')
|
2022-04-01 16:31:49 -06:00
|
|
|
@openapi.description('Clear completed downloads')
|
2025-12-10 21:16:10 -07:00
|
|
|
async def clear_completed(request: Request):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
download_manager.delete_completed(session)
|
2022-04-01 16:31:49 -06:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.post('/download/clear_failed')
|
2022-04-01 16:45:59 -06:00
|
|
|
@openapi.description('Clear failed downloads')
|
2025-12-10 21:16:10 -07:00
|
|
|
async def clear_failed(request: Request):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
download_manager.delete_failed(session)
|
2022-04-01 16:45:59 -06:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2024-05-08 17:02:27 -06:00
|
|
|
@api_bp.post('/download/retry_once')
|
|
|
|
|
@openapi.description('Retry failed once-downloads')
|
|
|
|
|
async def retry_once(_: Request):
|
2024-10-15 08:59:14 -06:00
|
|
|
download_manager.retry_downloads(reset_attempts=True)
|
2024-05-08 17:02:27 -06:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2024-04-17 11:25:26 -06:00
|
|
|
@api_bp.post('/download/delete_once')
|
|
|
|
|
@openapi.description('Delete all once downloads')
|
2025-12-10 21:16:10 -07:00
|
|
|
async def delete_once(request: Request):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
download_manager.delete_once(session)
|
2024-04-17 11:25:26 -06:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
2025-12-26 10:16:12 -07:00
|
|
|
@api_bp.post('/download/batch/delete')
|
|
|
|
|
@openapi.definition(
|
|
|
|
|
description='Delete specific downloads by their IDs',
|
|
|
|
|
body=schema.DownloadBatchRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
|
|
|
|
@wrol_mode_check
|
|
|
|
|
async def batch_delete_downloads(request: Request, body: schema.DownloadBatchRequest):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
deleted_ids = download_manager.delete_downloads_by_ids(session, body.download_ids)
|
|
|
|
|
return json_response({'deleted_ids': deleted_ids})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.post('/download/batch/retry')
|
|
|
|
|
@openapi.definition(
|
|
|
|
|
description='Retry specific downloads by their IDs',
|
|
|
|
|
body=schema.DownloadBatchRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
|
|
|
|
@wrol_mode_check
|
|
|
|
|
async def batch_retry_downloads(request: Request, body: schema.DownloadBatchRequest):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
count = download_manager.retry_downloads_by_ids(session, body.download_ids)
|
|
|
|
|
return json_response({'retried_count': count})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.post('/download/batch/clear')
|
|
|
|
|
@openapi.definition(
|
|
|
|
|
description='Clear specific completed downloads by their IDs',
|
|
|
|
|
body=schema.DownloadBatchRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
|
|
|
|
@wrol_mode_check
|
|
|
|
|
async def batch_clear_downloads(request: Request, body: schema.DownloadBatchRequest):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
deleted_ids = download_manager.clear_completed_by_ids(session, body.download_ids)
|
|
|
|
|
return json_response({'deleted_ids': deleted_ids})
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.get('/downloaders')
|
2022-01-13 09:29:58 -07:00
|
|
|
@openapi.description('List all Downloaders that can be specified by the user.')
|
|
|
|
|
async def get_downloaders(_: Request):
|
2021-12-30 20:45:11 -07:00
|
|
|
downloaders = download_manager.list_downloaders()
|
2022-01-11 10:08:47 -07:00
|
|
|
disabled = download_manager.disabled.is_set()
|
|
|
|
|
ret = dict(downloaders=downloaders, manager_disabled=disabled)
|
2021-12-30 20:45:11 -07:00
|
|
|
return json_response(ret)
|
|
|
|
|
|
|
|
|
|
|
2022-10-09 18:42:23 -06:00
|
|
|
@api_bp.get('/status')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Get the status of CPU/load/etc.',
|
|
|
|
|
response=schema.StatusResponse,
|
|
|
|
|
)
|
2024-11-02 15:14:02 -06:00
|
|
|
async def get_status(request: Request):
|
2023-01-31 17:11:31 -07:00
|
|
|
downloads = dict()
|
|
|
|
|
if flags.db_up.is_set():
|
|
|
|
|
try:
|
|
|
|
|
downloads = download_manager.get_summary()
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.debug('Unable to get download status', exc_info=e)
|
2022-12-23 16:04:09 -07:00
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
sanic_workers = dict()
|
|
|
|
|
if hasattr(request.app, 'multiplexer'):
|
|
|
|
|
# `multiplexer` may be empty while testing.
|
|
|
|
|
sanic_workers = {
|
|
|
|
|
i: {'pid': j['pid'], 'state': j['state']}
|
|
|
|
|
for i, j in request.app.multiplexer.workers.items()
|
|
|
|
|
if i.startswith('Sanic-Server')
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 15:03:13 -06:00
|
|
|
wrolpi_config = get_wrolpi_config()
|
|
|
|
|
if wrolpi_config.timezone:
|
|
|
|
|
tz = ZoneInfo(wrolpi_config.timezone)
|
|
|
|
|
local_time = now().astimezone(tz).isoformat()
|
|
|
|
|
else:
|
|
|
|
|
local_time = now().astimezone().isoformat()
|
|
|
|
|
|
2022-10-16 11:53:44 -06:00
|
|
|
ret = dict(
|
2022-10-22 14:26:59 -06:00
|
|
|
dockerized=DOCKERIZED,
|
2022-10-16 11:53:44 -06:00
|
|
|
downloads=downloads,
|
2023-01-31 17:11:31 -07:00
|
|
|
flags=flags.get_flags(),
|
2025-12-19 17:40:43 -07:00
|
|
|
# Hotspot and throttle status now come from Controller (/controller/api/stats)
|
2024-11-02 15:14:02 -06:00
|
|
|
is_rpi4=IS_RPI4,
|
|
|
|
|
is_rpi5=IS_RPI5,
|
|
|
|
|
is_rpi=IS_RPI,
|
2026-03-13 15:03:13 -06:00
|
|
|
local_time=local_time,
|
2024-11-02 15:14:02 -06:00
|
|
|
sanic_workers=sanic_workers,
|
2022-10-16 11:53:44 -06:00
|
|
|
version=__version__,
|
|
|
|
|
wrol_mode=wrol_mode_enabled(),
|
2025-10-29 22:16:33 -06:00
|
|
|
# Include all stats from status worker (includes upgrade info and git_branch).
|
2024-08-15 21:45:06 -06:00
|
|
|
**api_app.shared_ctx.status,
|
2022-10-16 11:53:44 -06:00
|
|
|
)
|
2022-06-29 20:07:40 -06:00
|
|
|
return json_response(ret)
|
|
|
|
|
|
|
|
|
|
|
2022-12-16 11:10:01 -07:00
|
|
|
@api_bp.get('/statistics')
|
|
|
|
|
@openapi.definition(
|
2024-12-03 21:32:37 -07:00
|
|
|
description='Get summary statistics of all files',
|
2022-12-16 11:10:01 -07:00
|
|
|
)
|
|
|
|
|
async def get_statistics(_):
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
# Full-table aggregates take many seconds cold on a large library; keep them off the event loop.
|
|
|
|
|
file_statistics = await asyncio.to_thread(get_file_statistics)
|
|
|
|
|
global_statistics = await asyncio.to_thread(get_global_statistics)
|
2022-12-16 11:10:01 -07:00
|
|
|
return json_response({
|
|
|
|
|
'file_statistics': file_statistics,
|
|
|
|
|
'global_statistics': global_statistics,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
2022-12-23 16:04:09 -07:00
|
|
|
@api_bp.get('/events/feed')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.description('Get all events after the provided date.')
|
2023-03-27 20:46:31 -06:00
|
|
|
@validate(query=schema.EventsRequest)
|
2024-04-17 11:25:26 -06:00
|
|
|
async def feed(request: Request, query: schema.EventsRequest):
|
|
|
|
|
# Get the current datetime from the API. The frontend will use this to request any events that happen after it's
|
|
|
|
|
# previous request. The API decides what the time is, just in case the RPi's clock is wrong, or no NTP is
|
|
|
|
|
# available.
|
2022-12-23 16:04:09 -07:00
|
|
|
start = now()
|
2024-04-17 11:25:26 -06:00
|
|
|
|
2026-01-09 14:01:25 -07:00
|
|
|
after = None if query.after in (None, 'None') else dates.strpdate(query.after)
|
2022-12-23 16:04:09 -07:00
|
|
|
events = get_events(after)
|
|
|
|
|
return json_response(dict(events=events, now=start))
|
|
|
|
|
|
|
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
@api_bp.get('/tag')
|
2023-03-27 20:46:31 -06:00
|
|
|
@openapi.definition(
|
2024-12-03 21:32:37 -07:00
|
|
|
description='Get a list of all Tags',
|
2023-03-27 20:46:31 -06:00
|
|
|
)
|
2026-03-07 15:43:11 -07:00
|
|
|
async def get_tags_request(request: Request):
|
2023-03-24 08:58:18 -06:00
|
|
|
tags_ = tags.get_tags()
|
2026-03-07 15:43:11 -07:00
|
|
|
tag_names = request.args.getlist('tag_names')
|
|
|
|
|
result = dict(tags=tags_)
|
|
|
|
|
if tag_names:
|
|
|
|
|
limit = request.args.get('limit')
|
|
|
|
|
limit = int(limit) if limit is not None else None
|
|
|
|
|
result['overlapping_tag_names'] = tags.get_overlapping_tags(tag_names, limit=limit)
|
|
|
|
|
return json_response(result)
|
2023-03-24 08:58:18 -06:00
|
|
|
|
|
|
|
|
|
2026-03-07 10:29:05 -07:00
|
|
|
@api_bp.get('/tag/recent')
|
|
|
|
|
@openapi.definition(
|
|
|
|
|
description='Get the most recently used tags',
|
|
|
|
|
)
|
|
|
|
|
async def get_recent_tags_request(_: Request):
|
|
|
|
|
tag_names = tags.get_recent_tags()
|
|
|
|
|
return json_response(dict(tag_names=tag_names))
|
|
|
|
|
|
|
|
|
|
|
2024-04-17 11:25:26 -06:00
|
|
|
@api_bp.post('/tag', name='tag_crate')
|
|
|
|
|
@api_bp.post('/tag/<tag_id:int>', name='tag_update')
|
2023-03-27 16:17:33 -06:00
|
|
|
@openapi.definition(
|
2024-12-03 21:32:37 -07:00
|
|
|
description='Create or update a Tag',
|
|
|
|
|
body=schema.TagRequest,
|
|
|
|
|
validate=True,
|
2023-03-27 16:17:33 -06:00
|
|
|
)
|
2025-12-10 21:16:10 -07:00
|
|
|
async def post_tag(request: Request, body: schema.TagRequest, tag_id: int = None):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
await tags.upsert_tag(session, body.name, body.color, tag_id)
|
2023-03-27 16:17:33 -06:00
|
|
|
if tag_id:
|
|
|
|
|
return response.empty(HTTPStatus.OK)
|
|
|
|
|
else:
|
|
|
|
|
return response.empty(HTTPStatus.CREATED)
|
2023-03-24 08:58:18 -06:00
|
|
|
|
|
|
|
|
|
2023-03-27 16:17:33 -06:00
|
|
|
@api_bp.delete('/tag/<tag_id:int>')
|
2025-12-10 21:16:10 -07:00
|
|
|
async def delete_tag_request(request: Request, tag_id: int):
|
|
|
|
|
session = request.ctx.session
|
|
|
|
|
Tag.find_by_id(session, tag_id).delete()
|
2023-04-10 13:15:34 -06:00
|
|
|
return response.empty()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.post('/notify')
|
|
|
|
|
@validate(schema.NotifyRequest)
|
|
|
|
|
async def post_notify(_: Request, body: schema.NotifyRequest):
|
|
|
|
|
"""Sends a notify Event"""
|
|
|
|
|
url = url_strip_host(body.url)
|
|
|
|
|
Events.send_user_notify(body.message, url)
|
|
|
|
|
return response.empty(HTTPStatus.CREATED)
|
2023-03-24 08:58:18 -06:00
|
|
|
|
|
|
|
|
|
2023-06-11 12:31:56 -06:00
|
|
|
@api_bp.post('/vin_number_decoder')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Decode a VIN number',
|
|
|
|
|
body=schema.VINDecoderRequest,
|
|
|
|
|
response=schema.VINDecoderResponse,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2023-06-11 12:31:56 -06:00
|
|
|
async def post_vin_number_decoder(_: Request, body: schema.VINDecoderRequest):
|
|
|
|
|
try:
|
|
|
|
|
vin = Vin(body.vin_number)
|
|
|
|
|
except vininfo.exceptions.VininfoException:
|
|
|
|
|
return json_response({}, HTTPStatus.BAD_REQUEST)
|
|
|
|
|
|
|
|
|
|
def detail_to_json(details: VinDetails, key: str):
|
|
|
|
|
if details:
|
|
|
|
|
attr = getattr(details, key)
|
|
|
|
|
if attr and attr.name:
|
|
|
|
|
name = attr.name
|
|
|
|
|
if isinstance(name, list):
|
|
|
|
|
return ', '.join(str(i) for i in name)
|
|
|
|
|
else:
|
|
|
|
|
return name
|
|
|
|
|
|
|
|
|
|
vin = schema.VIN(
|
|
|
|
|
country=vin.country,
|
|
|
|
|
manufacturer=vin.manufacturer,
|
|
|
|
|
region=vin.region,
|
|
|
|
|
years=','.join(map(str, vin.years)),
|
|
|
|
|
body=detail_to_json(vin.details, 'body'),
|
|
|
|
|
engine=detail_to_json(vin.details, 'engine'),
|
|
|
|
|
model=detail_to_json(vin.details, 'model'),
|
|
|
|
|
plant=detail_to_json(vin.details, 'plant'),
|
|
|
|
|
transmission=detail_to_json(vin.details, 'transmission'),
|
|
|
|
|
serial=detail_to_json(vin.details, 'serial'),
|
|
|
|
|
)
|
|
|
|
|
return json_response(dict(vin=vin))
|
|
|
|
|
|
|
|
|
|
|
2025-10-29 22:16:33 -06:00
|
|
|
@api_bp.get('/upgrade/check')
|
|
|
|
|
@openapi.definition(description='Check for available WROLPi updates')
|
|
|
|
|
@native_only
|
|
|
|
|
async def get_upgrade_check(request: Request):
|
|
|
|
|
"""
|
|
|
|
|
Check if an update is available by comparing local git HEAD with origin/{branch}.
|
|
|
|
|
|
|
|
|
|
Query params:
|
|
|
|
|
force: If 'true', force a fresh git fetch before checking.
|
|
|
|
|
"""
|
|
|
|
|
from wrolpi.upgrade import check_for_update
|
|
|
|
|
|
|
|
|
|
force = request.args.get('force', 'false').lower() == 'true'
|
|
|
|
|
result = check_for_update(fetch=force)
|
|
|
|
|
|
|
|
|
|
# Update shared_ctx.status so /api/status returns the latest info.
|
|
|
|
|
# Using shared_ctx.status (a manager.dict) ensures info is shared across all workers.
|
|
|
|
|
api_app.shared_ctx.status['update_available'] = result.get('update_available', False)
|
|
|
|
|
api_app.shared_ctx.status['latest_commit'] = result.get('latest_commit')
|
|
|
|
|
api_app.shared_ctx.status['current_commit'] = result.get('current_commit')
|
|
|
|
|
api_app.shared_ctx.status['commits_behind'] = result.get('commits_behind', 0)
|
|
|
|
|
|
|
|
|
|
return json_response(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.post('/upgrade/start')
|
|
|
|
|
@openapi.definition(description='Start WROLPi upgrade')
|
|
|
|
|
@native_only
|
|
|
|
|
@wrol_mode_check
|
|
|
|
|
async def post_upgrade_start(_: Request):
|
|
|
|
|
"""
|
|
|
|
|
Trigger the WROLPi upgrade process.
|
|
|
|
|
|
|
|
|
|
This executes /opt/wrolpi/upgrade.sh which will:
|
|
|
|
|
1. Stop the API and app services
|
|
|
|
|
2. Fetch latest code from git
|
|
|
|
|
3. Run upgrade scripts
|
|
|
|
|
4. Restart services
|
|
|
|
|
|
|
|
|
|
The frontend should redirect to the maintenance page after calling this.
|
|
|
|
|
Returns 202 Accepted as the upgrade runs asynchronously.
|
|
|
|
|
"""
|
|
|
|
|
from wrolpi.upgrade import start_upgrade
|
|
|
|
|
|
|
|
|
|
await start_upgrade()
|
|
|
|
|
return response.empty(HTTPStatus.ACCEPTED)
|
|
|
|
|
|
|
|
|
|
|
2023-11-20 11:01:46 -07:00
|
|
|
@api_bp.post('/search_suggestions')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Suggest related Channels/Domains/etc. to the user.',
|
|
|
|
|
body=schema.SearchSuggestionsRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2025-12-10 21:16:10 -07:00
|
|
|
async def post_search_suggestions(request: Request, body: schema.SearchSuggestionsRequest):
|
2023-11-20 11:01:46 -07:00
|
|
|
from modules.videos.channel.lib import search_channels_by_name
|
|
|
|
|
from modules.archive.lib import search_domains_by_name
|
2026-03-17 18:35:57 -06:00
|
|
|
from modules.docs.lib import search_authors_by_name, search_subjects_by_name
|
2023-11-20 11:01:46 -07:00
|
|
|
|
2025-12-10 21:16:10 -07:00
|
|
|
session = request.ctx.session
|
2026-08-11 18:45:05 -06:00
|
|
|
# Run sequentially: a SQLAlchemy Session is not safe for concurrent use, and
|
|
|
|
|
# asyncio.gather on the same session has caused intermittent empty results under
|
|
|
|
|
# pytest-xdist load even when the coroutines themselves do not await.
|
|
|
|
|
channels = await search_channels_by_name(
|
|
|
|
|
session, body.search_str, order_by_video_count=body.order_by_video_count)
|
|
|
|
|
domains = await search_domains_by_name(session, body.search_str)
|
|
|
|
|
authors = await search_authors_by_name(session, body.search_str)
|
|
|
|
|
subjects = await search_subjects_by_name(session, body.search_str)
|
2024-04-16 09:39:29 -06:00
|
|
|
|
|
|
|
|
ret = dict(
|
|
|
|
|
channels=channels,
|
|
|
|
|
domains=domains,
|
2026-03-17 18:35:57 -06:00
|
|
|
authors=authors,
|
|
|
|
|
subjects=subjects,
|
2024-04-16 09:39:29 -06:00
|
|
|
)
|
|
|
|
|
return json_response(ret)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.post('/search_file_estimates')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Get a count of FileGroup suggestions.',
|
|
|
|
|
body=schema.SearchFileEstimateRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2024-04-16 09:39:29 -06:00
|
|
|
async def post_search_file_estimates(_: Request, body: schema.SearchFileEstimateRequest):
|
|
|
|
|
"""Used by the Global search to suggest FileGroup count to the user."""
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
counts = await search_file_suggestion_count(
|
2024-03-06 17:41:04 -07:00
|
|
|
body.search_str,
|
|
|
|
|
body.tag_names,
|
|
|
|
|
body.mimetypes,
|
|
|
|
|
body.months,
|
|
|
|
|
body.from_year,
|
|
|
|
|
body.to_year,
|
2024-07-22 16:36:57 -06:00
|
|
|
body.any_tag,
|
2023-11-21 13:01:52 -07:00
|
|
|
)
|
2023-11-21 14:46:55 -07:00
|
|
|
|
2023-11-26 20:49:36 -07:00
|
|
|
ret = dict(
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
file_groups=counts['file_groups'],
|
|
|
|
|
file_groups_deep=counts['file_groups_deep'],
|
2023-11-26 20:49:36 -07:00
|
|
|
)
|
|
|
|
|
return json_response(ret)
|
|
|
|
|
|
|
|
|
|
|
2024-08-15 19:32:01 -06:00
|
|
|
@api_bp.post('/search_other_estimates')
|
2024-12-03 21:32:37 -07:00
|
|
|
@openapi.definition(
|
|
|
|
|
description='Get a count of other suggestions.',
|
|
|
|
|
body=schema.SearchOtherEstimateRequest,
|
|
|
|
|
validate=True,
|
|
|
|
|
)
|
2024-08-15 19:32:01 -06:00
|
|
|
async def post_search_other_estimates(_: Request, body: schema.SearchOtherEstimateRequest):
|
|
|
|
|
"""Used by the Global search to suggest FileGroup count to the user."""
|
|
|
|
|
others = await search_other_estimates(body.tag_names)
|
|
|
|
|
ret = dict(others=others)
|
|
|
|
|
return json_response(ret)
|
2026-05-02 14:31:54 -06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# Browser extension distribution.
|
|
|
|
|
# Files are committed to wrolpi/static/extensions/ and served as binary
|
|
|
|
|
# downloads. The whitelist prevents path traversal and limits exposure to
|
|
|
|
|
# only the two filenames the install page knows about.
|
|
|
|
|
EXTENSION_DIR = pathlib.Path(__file__).parent / 'static' / 'extensions'
|
|
|
|
|
|
|
|
|
|
EXTENSION_FILES = {
|
|
|
|
|
'wrolpi-chrome.zip': 'application/zip',
|
|
|
|
|
# Firefox click-to-install requires this exact Content-Type.
|
|
|
|
|
'wrolpi-firefox.xpi': 'application/x-xpinstall',
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.get('/extensions')
|
|
|
|
|
@openapi.description('Metadata for the WROLPi browser extension binaries.')
|
|
|
|
|
async def get_extensions_metadata(_: Request):
|
|
|
|
|
versions = {}
|
|
|
|
|
versions_path = EXTENSION_DIR / 'versions.json'
|
|
|
|
|
if versions_path.is_file():
|
|
|
|
|
try:
|
|
|
|
|
versions = json.loads(versions_path.read_text())
|
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
|
logger.warning(f'Could not parse {versions_path}')
|
|
|
|
|
files = {}
|
|
|
|
|
for name in EXTENSION_FILES:
|
|
|
|
|
path = EXTENSION_DIR / name
|
|
|
|
|
files[name] = {
|
|
|
|
|
'available': path.is_file(),
|
|
|
|
|
'size_bytes': path.stat().st_size if path.is_file() else None,
|
|
|
|
|
}
|
|
|
|
|
return json_response(dict(files=files, versions=versions))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@api_bp.get('/extensions/<filename:str>')
|
|
|
|
|
@openapi.description('Download a WROLPi browser extension binary.')
|
|
|
|
|
async def get_extension_file(_: Request, filename: str):
|
|
|
|
|
if filename not in EXTENSION_FILES:
|
|
|
|
|
return response.json({'error': f'Unknown extension file: {filename}'}, status=HTTPStatus.NOT_FOUND)
|
|
|
|
|
path = EXTENSION_DIR / filename
|
|
|
|
|
if not path.is_file():
|
|
|
|
|
return response.json({'error': f'Extension file not installed: {filename}'},
|
|
|
|
|
status=HTTPStatus.NOT_FOUND)
|
|
|
|
|
mime_type = EXTENSION_FILES[filename]
|
|
|
|
|
headers = {}
|
|
|
|
|
# Firefox click-to-install requires application/x-xpinstall AND that we do
|
|
|
|
|
# NOT send Content-Disposition: attachment — the latter forces the browser
|
|
|
|
|
# into "save file" mode, bypassing the add-on install handler. The Chrome
|
|
|
|
|
# zip still wants attachment so the browser writes a file instead of
|
|
|
|
|
# navigating away from the page.
|
|
|
|
|
if mime_type != 'application/x-xpinstall':
|
|
|
|
|
headers['Content-Disposition'] = f'attachment; filename="{filename}"'
|
|
|
|
|
return await response.file(str(path), mime_type=mime_type, headers=headers)
|