db: request-path library functions use the request's connection

Library functions an API request reaches now take the request's Session (first argument) instead of
opening their own session or cursor, so a request needs one SQLite connection.  Raw SQL runs through the
new `wrolpi.db.session_curs(session)`, a cursor on the Session's connection; `RequestDB.curs()` uses it.

- Search: files, videos, archives, flasher, and docs search share the request connection for the total,
  the page of ids, and the page's models (3 connections -> 1).
- Zim search, including tag-filtered search and estimates (2 -> 1).
- Channel detail (`Channel.get_statistics` reads on the Channel's own Session) and the channel list.
- Video detail, edit, description, captions, comments and transcode.  `get_video_for_app` and
  `update_video` no longer commit; their handlers use `request.ctx.db.write()`, so editing a Video and
  reading it back is one transaction.
- Tags (list, overlaps, recent), file statistics and estimates, other estimates, bulk tag preview, the
  download list, retry, kill and the status summary, and docs/videos/archive statistics.

Not converted: file operations that refresh files inside the request (delete, rename, upload, channel
and collection tag/move) commit page by page in code shared with the file worker; the cached zim entry
lookup; config import.

The connection-count tests now assert one connection for every endpoint they cover (no xfails left), and
cover the videos and archive statistics endpoints, which had no API test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-04 10:10:38 -06:00
parent a2bef48c6c
commit 24c5796fc6
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
34 changed files with 545 additions and 422 deletions

View file

@ -27,8 +27,8 @@ logger = logger.getChild(__name__)
@archive_bp.get('/statistics')
@openapi.response(HTTPStatus.OK, schema.ArchiveStatisticsResponse)
async def statistics(_: Request):
ret = await lib.get_statistics()
async def statistics(request: Request):
ret = await lib.get_statistics(request.ctx.session)
return json_response(ret, HTTPStatus.OK)
@ -55,14 +55,14 @@ archive_limit_limiter = api_param_limiter(100)
@openapi.response(HTTPStatus.OK, schema.ArchiveSearchResponse)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@validate(schema.ArchiveSearchRequest)
async def search_archives(_: Request, body: schema.ArchiveSearchRequest):
async def search_archives(request: Request, body: schema.ArchiveSearchRequest):
search_str = body.search_str
domain = body.domain
limit = archive_limit_limiter(body.limit)
offset = body.offset or 0
file_groups, total = await asyncio.to_thread(
lib.search_archives, search_str, domain, limit, offset, body.order_by, body.tag_names,
lib.search_archives, request.ctx.session, search_str, domain, limit, offset, body.order_by, body.tag_names,
body.headline, body.deep)
ret = dict(file_groups=file_groups, totals=dict(file_groups=total))
return json_response(ret)

View file

@ -27,7 +27,7 @@ from wrolpi.common import get_media_directory, get_relative_to_media_directory,
escape_file_name, aiohttp_post, format_html_string, split_lines_by_length, get_html_soup, get_title_from_html, \
get_wrolpi_config, html_screenshot, html_file_screenshot, ConfigFile, trim_file_name
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.db import get_db_session, get_db_curs, session_curs
from wrolpi.errors import UnknownArchive, InvalidOrderBy, InvalidDatetime
from wrolpi.events import Events
from wrolpi.files.lib import handle_file_group_search_results, cached_search_total, \
@ -1390,8 +1390,8 @@ NO_NULL_ORDERS = {
}
def search_archives(search_str: str, domain: str, limit: int, offset: int, order: str, tag_names: List[str],
headline: bool = False, deep: bool = False) \
def search_archives(session: Session, search_str: str, domain: str, limit: int, offset: int, order: str,
tag_names: List[str], headline: bool = False, deep: bool = False) \
-> Tuple[List[dict], int]:
# Always filter FileGroups to Archives.
wheres = []
@ -1479,7 +1479,7 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
if unfiltered:
total = cached_search_total(
search_filter_cache_key('archives'),
lambda: count_file_groups('SELECT COUNT(*) AS total FROM archive', dict()),
lambda: count_file_groups(session, 'SELECT COUNT(*) AS total FROM archive', dict()),
)
else:
if file_group_search:
@ -1499,9 +1499,9 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
'archives', search_str=search_str, domain=domain, tag_names=tag_names,
deep=deep, null_filter=null_filter,
)
total = cached_search_total(cache_key, lambda: count_file_groups(count_stmt, params))
total = cached_search_total(cache_key, lambda: count_file_groups(session, count_stmt, params))
results, total = handle_file_group_search_results(stmt, params, total=total)
results, total = handle_file_group_search_results(session, stmt, params, total=total)
if file_group_search and headline and results:
# Highlight the plain titles like the FTS snippets above (Postgres used ts_headline).
@ -1657,9 +1657,9 @@ async def singlefile_to_archive(singlefile: bytes, destination: pathlib.Path = N
return archive
async def get_statistics():
async def get_statistics(session: Session):
"""Get statistics about Archives and Domain Collections."""
with get_db_curs() as curs:
with session_curs(session) as curs:
curs.execute('''
SELECT
-- total archives

View file

@ -1071,6 +1071,7 @@ def test_search_archives_by_domain(test_directory, test_session, archive_factory
# Search for archives in searchtest.com
file_groups, total = search_archives(
test_session,
search_str=None,
domain='searchtest.com',
limit=10,
@ -1085,6 +1086,7 @@ def test_search_archives_by_domain(test_directory, test_session, archive_factory
# Search for other.com
file_groups, total = search_archives(
test_session,
search_str=None,
domain='other.com',
limit=10,
@ -1375,7 +1377,7 @@ async def test_get_statistics(test_session, archive_factory):
from modules.archive.lib import get_statistics
# Can get statistics in empty DB.
result = await get_statistics()
result = await get_statistics(test_session)
assert 'statistics' in result
assert 'archives' in result['statistics']
assert 'domains' in result['statistics']
@ -1393,7 +1395,7 @@ async def test_get_statistics(test_session, archive_factory):
archive4 = archive_factory() # No domain
test_session.commit()
result = await get_statistics()
result = await get_statistics(test_session)
stats = result['statistics']
# Should count all 4 archives.

View file

@ -20,8 +20,8 @@ logger = logger.getChild(__name__)
@docs_bp.get('/statistics')
@openapi.response(HTTPStatus.OK, schema.DocStatisticsResponse)
async def statistics(_: Request):
ret = get_statistics()
async def statistics(request: Request):
ret = get_statistics(request.ctx.session)
return json_response(ret, HTTPStatus.OK)
@ -44,11 +44,12 @@ doc_limit_limiter = api_param_limiter(100)
)
@openapi.response(HTTPStatus.OK, schema.DocSearchResponse)
@validate(schema.DocSearchRequest)
async def search_docs(_: Request, body: schema.DocSearchRequest):
async def search_docs(request: Request, body: schema.DocSearchRequest):
limit = doc_limit_limiter(body.limit)
offset = body.offset or 0
file_groups, total = await asyncio.to_thread(
_search_docs,
request.ctx.session,
search_str=body.search_str,
author=body.author,
subject=body.subject,

View file

@ -10,7 +10,6 @@ from sqlalchemy.orm import Session
from wrolpi import fts
from wrolpi.collections.models import Collection
from wrolpi.collections.types import collection_type_registry
from wrolpi.db import get_db_session
from wrolpi.errors import ValidationError
from wrolpi.files.lib import split_path_stem_and_suffix, get_mimetype, cached_search_total, \
search_filter_cache_key
@ -293,24 +292,23 @@ def discover_calibre_cover(ebook_path: pathlib.Path):
return cover
def get_statistics() -> dict:
def get_statistics(session: Session) -> dict:
"""Get doc statistics."""
from .models import Doc
from wrolpi.files.models import FileGroup
with get_db_session() as session:
total = session.query(func.count(Doc.id)).scalar() or 0
total_size = session.query(func.sum(Doc.size)).scalar() or 0
total = session.query(func.count(Doc.id)).scalar() or 0
total_size = session.query(func.sum(Doc.size)).scalar() or 0
epub_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
FileGroup.mimetype.startswith('application/epub')).scalar() or 0
pdf_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
FileGroup.mimetype == 'application/pdf').scalar() or 0
epub_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
FileGroup.mimetype.startswith('application/epub')).scalar() or 0
pdf_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
FileGroup.mimetype == 'application/pdf').scalar() or 0
author_count = session.query(func.count(Collection.id)).filter(
Collection.kind == 'author').scalar() or 0
subject_count = session.query(func.count(Collection.id)).filter(
Collection.kind == 'subject').scalar() or 0
author_count = session.query(func.count(Collection.id)).filter(
Collection.kind == 'author').scalar() or 0
subject_count = session.query(func.count(Collection.id)).filter(
Collection.kind == 'subject').scalar() or 0
return dict(statistics=dict(
doc_count=total,
@ -368,7 +366,7 @@ def _doc_browse_sql(order_by: str) -> Optional[str]:
ORDER BY {order} LIMIT :limit OFFSET :offset'''
def _search_docs(search_str=None, author=None, subject=None, language=None, mimetype=None,
def _search_docs(session: Session, search_str=None, author=None, subject=None, language=None, mimetype=None,
limit=20, offset=0, order_by='published_datetime', tag_names=None, deep=False):
from .models import Doc
from wrolpi.files.models import FileGroup
@ -377,86 +375,85 @@ def _search_docs(search_str=None, author=None, subject=None, language=None, mime
# the much smaller a/b/c columns.
match = fts.translate_websearch(search_str, None if deep else fts.ABC_COLUMNS) if search_str else None
with get_db_session() as session:
query = session.query(FileGroup).join(Doc, Doc.file_group_id == FileGroup.id)
query = session.query(FileGroup).join(Doc, Doc.file_group_id == FileGroup.id)
fts_sq = None
if match is not None:
fts_sq = text('SELECT rowid AS id, -rank AS ts_rank'
' FROM file_group_fts WHERE file_group_fts MATCH :fts_match') \
.bindparams(fts_match=match) \
.columns(column('id', Integer), column('ts_rank', Float)) \
.alias('fts')
query = query.join(fts_sq, fts_sq.c.id == FileGroup.id)
fts_sq = None
if match is not None:
fts_sq = text('SELECT rowid AS id, -rank AS ts_rank'
' FROM file_group_fts WHERE file_group_fts MATCH :fts_match') \
.bindparams(fts_match=match) \
.columns(column('id', Integer), column('ts_rank', Float)) \
.alias('fts')
query = query.join(fts_sq, fts_sq.c.id == FileGroup.id)
if author:
query = query.filter(FileGroup.b_text.ilike(f'%{author}%'))
if author:
query = query.filter(FileGroup.b_text.ilike(f'%{author}%'))
if subject:
query = query.filter(Doc.subject.ilike(f'%{subject}%'))
if subject:
query = query.filter(Doc.subject.ilike(f'%{subject}%'))
if language:
query = query.filter(Doc.language == language)
if language:
query = query.filter(Doc.language == language)
if mimetype:
query = query.filter(FileGroup.mimetype.startswith(mimetype))
if mimetype:
query = query.filter(FileGroup.mimetype.startswith(mimetype))
if tag_names:
from wrolpi.tags import Tag, TagFile
tagged_fg_ids = session.query(TagFile.file_group_id) \
.join(Tag, Tag.id == TagFile.tag_id) \
.filter(Tag.name.in_(tag_names)) \
.subquery()
query = query.filter(FileGroup.id.in_(tagged_fg_ids))
if tag_names:
from wrolpi.tags import Tag, TagFile
tagged_fg_ids = session.query(TagFile.file_group_id) \
.join(Tag, Tag.id == TagFile.tag_id) \
.filter(Tag.name.in_(tag_names)) \
.subquery()
query = query.filter(FileGroup.id.in_(tagged_fg_ids))
unfiltered = not (search_str or author or subject or language or mimetype or tag_names)
if unfiltered:
total = cached_search_total(
search_filter_cache_key('docs'),
lambda: session.query(func.count(Doc.id)).scalar() or 0,
)
else:
cache_key = search_filter_cache_key(
'docs', search_str=search_str, author=author, subject=subject,
language=language, mimetype=mimetype, tag_names=tag_names, deep=deep,
)
# Count before ORDER BY / LIMIT; cache by filters not page.
total = cached_search_total(cache_key, lambda q=query: q.count())
unfiltered = not (search_str or author or subject or language or mimetype or tag_names)
if unfiltered:
total = cached_search_total(
search_filter_cache_key('docs'),
lambda: session.query(func.count(Doc.id)).scalar() or 0,
)
else:
cache_key = search_filter_cache_key(
'docs', search_str=search_str, author=author, subject=subject,
language=language, mimetype=mimetype, tag_names=tag_names, deep=deep,
)
# Count before ORDER BY / LIMIT; cache by filters not page.
total = cached_search_total(cache_key, lambda q=query: q.count())
# Ordering.
if order_by == 'rank' and fts_sq is not None:
query = query.order_by(
desc(fts_sq.c.ts_rank),
desc(FileGroup.id),
)
elif order_by == 'published_datetime':
query = query.order_by(nullslast(desc(FileGroup.published_datetime)), desc(FileGroup.id))
elif order_by == 'size':
query = query.order_by(nullslast(desc(Doc.size)))
elif order_by == 'title':
query = query.order_by(nullslast(asc(FileGroup.a_text)))
else:
query = query.order_by(desc(FileGroup.id))
# Ordering.
if order_by == 'rank' and fts_sq is not None:
query = query.order_by(
desc(fts_sq.c.ts_rank),
desc(FileGroup.id),
)
elif order_by == 'published_datetime':
query = query.order_by(nullslast(desc(FileGroup.published_datetime)), desc(FileGroup.id))
elif order_by == 'size':
query = query.order_by(nullslast(desc(Doc.size)))
elif order_by == 'title':
query = query.order_by(nullslast(asc(FileGroup.a_text)))
else:
query = query.order_by(desc(FileGroup.id))
# `size` sorts on a doc column and `title` has no file_group index, so neither may fall back to `id`.
browse_sql = None
if unfiltered and order_by not in ('size', 'title'):
browse_sql = _doc_browse_sql(order_by if order_by in DOC_BROWSE_ORDERS else 'id')
if browse_sql:
fg_ids = [i for i, in session.execute(text(browse_sql), dict(limit=limit, offset=offset)).fetchall()]
by_id = {fg.id: fg for fg in session.query(FileGroup).filter(FileGroup.id.in_(fg_ids))} if fg_ids else {}
file_groups = [by_id[i] for i in fg_ids]
else:
file_groups = query.offset(offset).limit(limit).all()
fg_ids = [fg.id for fg in file_groups]
results = [fg.__json__() for fg in file_groups]
# `size` sorts on a doc column and `title` has no file_group index, so neither may fall back to `id`.
browse_sql = None
if unfiltered and order_by not in ('size', 'title'):
browse_sql = _doc_browse_sql(order_by if order_by in DOC_BROWSE_ORDERS else 'id')
if browse_sql:
fg_ids = [i for i, in session.execute(text(browse_sql), dict(limit=limit, offset=offset)).fetchall()]
by_id = {fg.id: fg for fg in session.query(FileGroup).filter(FileGroup.id.in_(fg_ids))} if fg_ids else {}
file_groups = [by_id[i] for i in fg_ids]
else:
file_groups = query.offset(offset).limit(limit).all()
fg_ids = [fg.id for fg in file_groups]
results = [fg.__json__() for fg in file_groups]
if search_str and fg_ids:
hints = _fetch_section_hints(session, fg_ids, search_str)
for r in results:
hint = hints.get(r['id'])
if hint:
r['section_hint'] = hint
if search_str and fg_ids:
hints = _fetch_section_hints(session, fg_ids, search_str)
for r in results:
hint = hints.get(r['id'])
if hint:
r['section_hint'] = hint
return results, total

View file

@ -293,10 +293,10 @@ async def test_search_docs_attaches_section_hint_epub(test_session, test_directo
])
# "mullen" is only in the document body (d_text), so a deep search is required to match it.
results, total = _search_docs(search_str='mullen', mimetype='application/epub')
results, total = _search_docs(test_session, search_str='mullen', mimetype='application/epub')
assert total == 0, 'Document contents are not searched unless deep=True'
results, total = _search_docs(search_str='mullen', mimetype='application/epub', deep=True)
results, total = _search_docs(test_session, search_str='mullen', mimetype='application/epub', deep=True)
assert total == 1
assert results[0]['id'] == fg.id
hint = results[0]['section_hint']
@ -318,7 +318,7 @@ async def test_search_docs_attaches_section_hint_pdf(test_session, test_director
(3, 'Page 3', 'here is where mullen shows up'),
])
results, total = _search_docs(search_str='mullen', mimetype='application/pdf', deep=True)
results, total = _search_docs(test_session, search_str='mullen', mimetype='application/pdf', deep=True)
assert total == 1
assert results[0]['id'] == fg.id
hint = results[0]['section_hint']
@ -334,7 +334,7 @@ async def test_search_docs_no_hint_when_no_query(test_session, test_directory):
'gamma.pdf', 'application/pdf', [
(1, 'Page 1', 'whatever'),
])
results, _ = _search_docs(mimetype='application/pdf')
results, _ = _search_docs(test_session, mimetype='application/pdf')
assert results and results[0]['id'] == fg.id
assert 'section_hint' not in results[0]
@ -360,15 +360,15 @@ async def test_search_docs_browse_walks_file_group_date_index(test_session, test
assert 'TEMP B-TREE' not in plan, plan
# Newest first, NULL published dates last, same as the filtered ORM path.
results, total = _search_docs()
results, total = _search_docs(test_session, )
assert total == 3
assert [i['id'] for i in results] == [docs[2].file_group_id, docs[1].file_group_id, docs[0].file_group_id]
# Paging still works on the fast path.
results, total = _search_docs(limit=1, offset=1)
results, total = _search_docs(test_session, limit=1, offset=1)
assert total == 3
assert [i['id'] for i in results] == [docs[1].file_group_id]
# Filtered searches are unaffected.
results, total = _search_docs(mimetype='application/pdf')
results, total = _search_docs(test_session, mimetype='application/pdf')
assert total == 3

View file

@ -19,10 +19,10 @@ flasher_bp = Blueprint('Flasher', '/api/flasher')
body=schema.FlasherSearchRequest,
)
@validate(schema.FlasherSearchRequest)
async def post_flasher_search(_: Request, body: schema.FlasherSearchRequest):
async def post_flasher_search(request: Request, body: schema.FlasherSearchRequest):
# Reading many firmware headers touches the disk; run off the event loop.
file_groups, total = await asyncio.to_thread(
lib.search_esp_firmware, body.chip, body.path, body.limit)
lib.search_esp_firmware, request.ctx.session, body.chip, body.path, body.limit)
return json_response(dict(file_groups=file_groups, totals=dict(file_groups=total)), HTTPStatus.OK)

View file

@ -8,6 +8,8 @@ import functools
import pathlib
from typing import List, Optional, Tuple
from sqlalchemy.orm import Session
from wrolpi.common import get_media_directory, logger
logger = logger.getChild(__name__)
@ -100,7 +102,7 @@ def _resolve_media_path(primary_path) -> pathlib.Path:
return path if path.is_absolute() else get_media_directory() / path
def search_esp_firmware(chip: Optional[str] = None, path: Optional[str] = None,
def search_esp_firmware(session: Session, chip: Optional[str] = None, path: Optional[str] = None,
limit: int = 1000) -> Tuple[List[dict], int]:
"""Search for ``.bin`` firmware, annotated with each file's detected chip/kind.
@ -114,7 +116,7 @@ def search_esp_firmware(chip: Optional[str] = None, path: Optional[str] = None,
"""
from wrolpi.files.lib import search_files
file_groups, _ = search_files(None, limit, 0, suffix='.bin', path=path)
file_groups, _ = search_files(session, None, limit, 0, suffix='.bin', path=path)
results = []
for file_group in file_groups:

View file

@ -59,20 +59,20 @@ async def test_search_esp_firmware_filters_by_chip(async_client, test_session, m
return sorted(pathlib.Path(r['primary_path']).name for r in results)
# Filter to ESP32-S3: only the two S3 images, never the non-ESP file.
s3, total = search_esp_firmware(chip='ESP32-S3')
s3, total = search_esp_firmware(test_session, chip='ESP32-S3')
assert total == 2
assert names(s3) == ['s3-app.bin', 's3-factory.bin']
assert {r['esp_chip'] for r in s3} == {'ESP32-S3'}
assert {r['esp_kind'] for r in s3} == {'app', 'factory'}
# Filter to ESP32-S2: just the one.
s2, total = search_esp_firmware(chip='ESP32-S2')
s2, total = search_esp_firmware(test_session, chip='ESP32-S2')
assert total == 1
assert names(s2) == ['s2-app.bin']
# No chip: every .bin, including non-ESP parts (partition tables, littlefs, boot_app0) annotated with a null
# chip so a full flash set can still be assembled from the picker.
all_bin, total = search_esp_firmware()
all_bin, total = search_esp_firmware(test_session)
assert total == 5
assert 'littlefs.bin' in names(all_bin)
littlefs = next(r for r in all_bin if pathlib.Path(r['primary_path']).name == 'littlefs.bin')
@ -80,7 +80,7 @@ async def test_search_esp_firmware_filters_by_chip(async_client, test_session, m
assert littlefs['esp_kind'] == 'not_esp_image'
# Filtering to a specific chip still returns only that chip's ESP images (non-ESP parts are shown unfiltered).
_, total = search_esp_firmware(chip='ESP32-H2')
_, total = search_esp_firmware(test_session, chip='ESP32-H2')
assert total == 0

View file

@ -27,8 +27,8 @@ logger = logger.getChild(__name__)
@content_bp.get('/statistics')
@openapi.response(HTTPStatus.OK, schema.VideosStatisticsResponse)
async def statistics(_: Request):
ret = await lib.get_statistics()
async def statistics(request: Request):
ret = await lib.get_statistics(request.ctx.session)
return json_response(ret, HTTPStatus.OK)

View file

@ -26,8 +26,8 @@ logger = logger.getChild(__name__)
@channel_bp.get('/')
@openapi.description('Get a list of all Channels')
@openapi.response(HTTPStatus.OK, schema.ChannelsResponse)
async def get_channels(_: Request):
channels = await lib.get_minimal_channels()
async def get_channels(request: Request):
channels = await lib.get_minimal_channels(request.ctx.session)
return json_response({'channels': channels})

View file

@ -9,7 +9,7 @@ from wrolpi import flags
from wrolpi.collections import Collection
from wrolpi.common import logger, \
get_media_directory, wrol_mode_check, background_task
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.db import get_db_session, session_curs
from wrolpi.downloader import save_downloads_config, download_manager, Download
from wrolpi.errors import APIError, ValidationError, FileWorkerConflict
from wrolpi.events import Events
@ -23,11 +23,11 @@ from ..models import Channel, Video
logger = logger.getChild(__name__)
async def get_minimal_channels() -> List[dict]:
async def get_minimal_channels(session: Session) -> List[dict]:
"""
Get the minimum amount of information necessary about all channels.
"""
with get_db_curs() as curs:
with session_curs(session) as curs:
# Get all channels, even if they don't have videos. Also get the minimum frequency download because this is the
# one that will consume the most resources.
stmt = '''

View file

@ -19,7 +19,7 @@ from wrolpi.captions import extract_captions
from wrolpi.common import ConfigFile, extract_domain, logger, \
escape_file_name, get_media_directory, background_task, Base, get_wrolpi_config, trim_file_name
from wrolpi.dates import Seconds, from_timestamp
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.db import get_db_curs, get_db_session, session_curs
from wrolpi.downloader import Download, download_manager
from wrolpi.errors import UnknownDirectory
from wrolpi.events import Events
@ -1029,8 +1029,8 @@ def get_channel_source_id(url: str) -> str:
return channel_info.get('channel_id') or channel_info['uploader_id']
async def get_statistics():
with get_db_curs() as curs:
async def get_statistics(session: Session):
with session_curs(session) as curs:
curs.execute('''
SELECT
-- total videos

View file

@ -10,7 +10,7 @@ from modules.videos.errors import UnknownVideo, UnknownChannel
from wrolpi.captions import read_captions, read_captions_with_timestamps
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, get_relative_to_media_directory, \
background_task
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.db import get_db_curs, get_db_session, session_curs
from wrolpi.downloader import Download
from wrolpi.files.lib import split_path_stem_and_suffix
from wrolpi.files.worker import file_worker
@ -177,7 +177,7 @@ class Video(ModelHelper, Base):
"""
session = Session.object_session(self)
with get_db_curs() as curs:
with session_curs(session) as curs:
if self.file_group.published_datetime:
# Get videos next to this Video's upload date.
stmt = '''
@ -964,9 +964,14 @@ class Channel(ModelHelper, Base):
d['downloads'] = self.downloads
return d
def get_statistics(self):
"""Get statistics about this channel."""
with get_db_curs() as curs:
def get_statistics(self) -> dict:
"""Get statistics about this channel.
Read on the Channel's own Session, so during a request this uses the request's connection."""
session = Session.object_session(self)
if session is None:
raise RuntimeError(f'{self} is not in a session!')
with session_curs(session) as curs:
stmt = '''
SELECT SUM(size) AS "size",
MAX(size) AS "largest_video",

View file

@ -680,7 +680,7 @@ async def test_search_videos_default_page_pagination(test_session, video_factory
# The fast path must return exactly what the generic query returns for the same request:
# same rows, same order (NULL placement, id tiebreaker, interleaved mimetypes), same paging.
def ids(order, limit, offset):
results, total = lib.search_videos(order=order, limit=limit, offset=offset)
results, total = lib.search_videos(test_session, order=order, limit=limit, offset=offset)
return [i['id'] for i in results], total
for order in lib.INDEXED_DATE_ORDERS:

View file

@ -167,7 +167,7 @@ def test_validate_video_directory_beats_info_json_channel(test_session, test_dir
@pytest.mark.asyncio
async def test_get_statistics(test_session, video_factory, channel_factory):
# Can get statistics in empty DB.
await get_statistics()
await get_statistics(test_session)
channel1 = channel_factory()
channel2 = channel_factory()
@ -176,7 +176,7 @@ async def test_get_statistics(test_session, video_factory, channel_factory):
video_factory(channel_id=channel2.id)
video_factory()
result = await get_statistics()
result = await get_statistics(test_session)
assert 'statistics' in result
assert 'videos' in result['statistics']
assert 'channels' in result['statistics']

View file

@ -20,7 +20,8 @@ def test_update_video_title(test_session, test_directory, video_factory):
test_session.commit()
assert video.file_group.title == 'Old Title'
update_video(video.file_group_id, ' New Title ')
update_video(test_session, video.file_group_id, ' New Title ')
test_session.commit()
test_session.expire_all()
video = Video.find_by_file_group_id(test_session, video.file_group_id)
@ -39,7 +40,8 @@ def test_update_video_title_creates_info_json(test_session, test_directory, vide
test_session.commit()
assert video.info_json_path is None
update_video(video.file_group_id, 'Brand New')
update_video(test_session, video.file_group_id, 'Brand New')
test_session.commit()
test_session.expire_all()
video = Video.find_by_file_group_id(test_session, video.file_group_id)
@ -57,7 +59,8 @@ def test_update_video_description(test_session, test_directory, video_factory):
test_session.commit()
assert video.file_group.c_text == 'old words'
update_video(video.file_group_id, description='new words\nsecond line')
update_video(test_session, video.file_group_id, description='new words\nsecond line')
test_session.commit()
test_session.expire_all()
video = Video.find_by_file_group_id(test_session, video.file_group_id)
@ -68,7 +71,8 @@ def test_update_video_description(test_session, test_directory, video_factory):
assert info_json['description'] == 'old words', 'The original is kept'
assert info_json['wrolpi']['custom_description'] == 'new words\nsecond line'
update_video(video.file_group_id, description='')
update_video(test_session, video.file_group_id, description='')
test_session.commit()
test_session.expire_all()
video = Video.find_by_file_group_id(test_session, video.file_group_id)
assert video.get_description() is None
@ -80,14 +84,14 @@ def test_update_video_nothing(test_session, video_factory):
video = video_factory(with_info_json={'title': 'Old'})
test_session.commit()
with pytest.raises(ValidationError):
update_video(video.file_group_id)
update_video(test_session, video.file_group_id)
def test_update_video_title_empty(test_session, video_factory):
video = video_factory(with_info_json={'title': 'Old'})
test_session.commit()
with pytest.raises(ValidationError):
update_video(video.file_group_id, ' ')
update_video(test_session, video.file_group_id, ' ')
test_session.expire_all()
assert Video.find_by_file_group_id(test_session, video.file_group_id).file_group.title == 'Old'
@ -108,7 +112,8 @@ async def test_custom_title_survives_refresh(test_session, test_directory, async
video = video_factory(with_info_json={'title': 'Original'})
test_session.commit()
update_video(video.file_group_id, title='Custom', description='custom words')
update_video(test_session, video.file_group_id, title='Custom', description='custom words')
test_session.commit()
video_path = video.video_path
file_group_id = video.file_group_id
@ -174,7 +179,7 @@ async def test_update_video_wrol_mode(test_session, video_factory, wrol_mode_fix
await wrol_mode_fixture(True)
try:
with pytest.raises(WROLModeEnabled):
update_video(video.file_group_id, title='Nope')
update_video(test_session, video.file_group_id, title='Nope')
finally:
await wrol_mode_fixture(False)
@ -194,7 +199,8 @@ async def test_edit_creates_info_json_that_survives_refresh(test_session, test_d
video_path = video.video_path
file_group_id = video.file_group_id
update_video(file_group_id, title='Custom', description='my words')
update_video(test_session, file_group_id, title='Custom', description='my words')
test_session.commit()
test_session.expire_all()
video = Video.find_by_file_group_id(test_session, file_group_id)
assert video.info_json_path and video.info_json_path.is_file()

View file

@ -25,7 +25,9 @@ logger = logger.getChild(__name__)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
def video_get(request: Request, file_group_id: int):
skip_viewed = request.args.get('skip_viewed', '').lower() == 'true'
video, previous_video, next_video = lib.get_video_for_app(file_group_id, skip_viewed=skip_viewed)
# Marking the Video viewed is a write.
with request.ctx.db.write() as session:
video, previous_video, next_video = lib.get_video_for_app(session, file_group_id, skip_viewed=skip_viewed)
return json_response({'file_group': video, 'prev': previous_video, 'next': next_video})
@ -37,9 +39,10 @@ def video_get(request: Request, file_group_id: int):
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@validate(schema.VideoUpdateRequest)
@wrol_mode_check
async def video_update(_: Request, file_group_id: int, body: schema.VideoUpdateRequest):
lib.update_video(file_group_id, title=body.title, description=body.description)
video, previous_video, next_video = lib.get_video_for_app(file_group_id)
async def video_update(request: Request, file_group_id: int, body: schema.VideoUpdateRequest):
with request.ctx.db.write() as session:
lib.update_video(session, file_group_id, title=body.title, description=body.description)
video, previous_video, next_video = lib.get_video_for_app(session, file_group_id)
return json_response({'file_group': video, 'prev': previous_video, 'next': next_video})
@ -47,8 +50,8 @@ async def video_update(_: Request, file_group_id: int, body: schema.VideoUpdateR
@openapi.description('Get Video comments')
@openapi.response(HTTPStatus.OK, schema.VideoCommentsResponse)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
def video_get_comments(_: Request, file_group_id: int):
video = lib.get_video(file_group_id)
def video_get_comments(request: Request, file_group_id: int):
video = lib.get_video(request.ctx.session, file_group_id)
return json_response({'comments': video.get_comments()})
@ -56,8 +59,8 @@ def video_get_comments(_: Request, file_group_id: int):
@openapi.description('Get Video description')
@openapi.response(HTTPStatus.OK, schema.VideoDescriptionResponse)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
def video_get_description(_: Request, file_group_id: int):
video = lib.get_video(file_group_id)
def video_get_description(request: Request, file_group_id: int):
video = lib.get_video(request.ctx.session, file_group_id)
return json_response({'description': video.get_description()})
@ -65,8 +68,8 @@ def video_get_description(_: Request, file_group_id: int):
@openapi.description('Get Video captions')
@openapi.response(HTTPStatus.OK, schema.VideoCaptionsResponse)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
def video_get_captions(_: Request, file_group_id: int):
video = lib.get_video(file_group_id)
def video_get_captions(request: Request, file_group_id: int):
video = lib.get_video(request.ctx.session, file_group_id)
return json_response({'captions': video.get_caption_chunks()})
@ -78,13 +81,13 @@ def video_get_captions(_: Request, file_group_id: int):
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@validate(schema.VideoTranscodeRequest)
@wrol_mode_check
async def video_transcode(_: Request, file_group_id: int, body: schema.VideoTranscodeRequest):
async def video_transcode(request: Request, file_group_id: int, body: schema.VideoTranscodeRequest):
try:
validate_transcode_request(body.video_codec, body.audio_codec, body.container, body.fragmented)
except ValueError as e:
raise InvalidJob(str(e))
# Raises UnknownVideo (404) before anything is queued.
video = lib.get_video(file_group_id)
video = lib.get_video(request.ctx.session, file_group_id)
is_audio = (video.file_group.mimetype or '').startswith('audio/')
if is_audio and body.video_codec and body.video_codec != REMOVE_VIDEO:
raise InvalidJob(f'This is an audio file; it has no video stream to transcode to {body.video_codec}')
@ -117,13 +120,14 @@ async def video_transcode(_: Request, file_group_id: int, body: schema.VideoTran
@openapi.response(HTTPStatus.OK, schema.VideoSearchResponse)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@validate(schema.VideoSearchRequest)
async def search_videos(_: Request, body: schema.VideoSearchRequest):
async def search_videos(request: Request, body: schema.VideoSearchRequest):
if body.order_by not in lib.VIDEO_ORDERS:
raise InvalidOrderBy('Invalid order by')
# Synchronous SQLite query; keep it off the event loop.
file_groups, videos_total = await asyncio.to_thread(
lib.search_videos,
request.ctx.session,
body.search_str,
body.offset,
body.limit,

View file

@ -11,7 +11,7 @@ from modules.videos.models import Video, Channel
from wrolpi import fts
from wrolpi.common import logger, limit_concurrent, wrol_mode_check
from wrolpi.dates import now
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.db import get_db_session, session_curs
from wrolpi.downloader import download_manager
from wrolpi.files.lib import handle_file_group_search_results, cached_search_total, \
search_filter_cache_key, count_file_groups
@ -24,34 +24,32 @@ from ..lib import get_yt_dlp_http_headers, get_yt_dlp_sleep_opts
logger.getChild(__name__)
def get_video_for_app(file_group_id: int, skip_viewed: bool = False) -> Tuple[dict, Optional[dict], Optional[dict]]:
def get_video_for_app(session: Session, file_group_id: int, skip_viewed: bool = False) \
-> Tuple[dict, Optional[dict], Optional[dict]]:
"""
Get a Video by its FileGroup ID, with its prev/next videos. Mark the Video as viewed.
Get a Video by its FileGroup ID, with its prev/next videos. Mark the Video as viewed (a write; the
caller commits).
"""
with get_db_session(commit=True) as session:
video = Video.find_by_file_group_id(session, file_group_id)
if not skip_viewed:
video.file_group.set_viewed()
previous_video, next_video = video.get_surrounding_videos()
video = video.__json__()
previous_video = previous_video.__json__() if previous_video and previous_video.file_group else None
next_video = next_video.__json__() if next_video and next_video.file_group else None
video = Video.find_by_file_group_id(session, file_group_id)
if not skip_viewed:
video.file_group.set_viewed()
previous_video, next_video = video.get_surrounding_videos()
video = video.__json__()
previous_video = previous_video.__json__() if previous_video and previous_video.file_group else None
next_video = next_video.__json__() if next_video and next_video.file_group else None
return video, previous_video, next_video
def get_video(file_group_id: int) -> Video:
def get_video(session: Session, file_group_id: int) -> Video:
"""
Get a Video by its FileGroup ID.
"""
with get_db_session() as session:
video = Video.find_by_file_group_id(session, file_group_id)
return video
return Video.find_by_file_group_id(session, file_group_id)
@wrol_mode_check
def update_video(file_group_id: int, title: str = None, description: str = None) -> Video:
def update_video(session: Session, file_group_id: int, title: str = None, description: str = None) -> Video:
"""Edit a Video's details. The files are the source of truth, so the change is written to the
Video's .info.json (created if missing) and the Video is validated again from it. Only the
fields given (not None) are changed; an empty description clears it.
@ -60,6 +58,8 @@ def update_video(file_group_id: int, title: str = None, description: str = None)
over yt-dlp's own keys: the original title and description stay in the file, and a metadata
re-download carries the section over.
The caller commits.
@raise UnknownVideo: if the Video can not be found
@raise ValidationError: when nothing is given, or the title is empty
"""
@ -77,17 +77,16 @@ def update_video(file_group_id: int, title: str = None, description: str = None)
if description is not None:
changes['custom_description'] = description
with get_db_session(commit=True) as session:
video = Video.find_by_file_group_id(session, file_group_id)
if video.info_json_path is None or not video.info_json_path.is_file():
# No info json yet: create one holding only the wrolpi section.
video.replace_info_json({'wrolpi': changes}, clean=False)
else:
video.file_group.update_wrolpi_json(changes)
# Re-derive the title (and search text) from the file just written.
video.validate(session)
video.flush()
return video
video = Video.find_by_file_group_id(session, file_group_id)
if video.info_json_path is None or not video.info_json_path.is_file():
# No info json yet: create one holding only the wrolpi section.
video.replace_info_json({'wrolpi': changes}, clean=False)
else:
video.file_group.update_wrolpi_json(changes)
# Re-derive the title (and search text) from the file just written.
video.validate(session)
video.flush()
return video
VIDEO_ORDERS = {
@ -132,10 +131,10 @@ INDEXED_DATE_ORDERS = ('published_datetime', '-published_datetime')
VIDEO_MIMETYPE_PREFIXES = ('video/', 'audio/')
def _video_mimetypes() -> List[str]:
def _video_mimetypes(session: Session) -> List[str]:
"""Every distinct video/* and audio/* mimetype in the library (a handful; served by the mimetype index)."""
mimetypes = []
with get_db_curs() as curs:
with session_curs(session) as curs:
for prefix in VIDEO_MIMETYPE_PREFIXES:
# '0' is the character after '/', so this is the half-open range of the prefix.
curs.execute('SELECT DISTINCT mimetype FROM file_group WHERE mimetype >= ? AND mimetype < ?',
@ -144,17 +143,17 @@ def _video_mimetypes() -> List[str]:
return mimetypes
def _count_videos() -> int:
def _count_videos(session: Session) -> int:
ranges = ' OR '.join(f'(mimetype >= :p{i} AND mimetype < :e{i})' for i in range(len(VIDEO_MIMETYPE_PREFIXES)))
params = dict()
for i, prefix in enumerate(VIDEO_MIMETYPE_PREFIXES):
params[f'p{i}'], params[f'e{i}'] = prefix, prefix[:-1] + '0'
with get_db_curs() as curs:
with session_curs(session) as curs:
curs.execute(f'SELECT COUNT(*) FROM file_group WHERE {ranges}', params)
return curs.fetchone()[0]
def _search_videos_by_date(order: str, limit: int, offset: int) -> Tuple[List[dict], int]:
def _search_videos_by_date(session: Session, order: str, limit: int, offset: int) -> Tuple[List[dict], int]:
"""The unfiltered Videos page, ordered by date, without visiting every video.
The generic query (`mimetype LIKE 'video/%' OR ...`) plus a windowed COUNT used to visit every
@ -163,7 +162,7 @@ def _search_videos_by_date(order: str, limit: int, offset: int) -> Tuple[List[di
then merged. Results must be identical to the generic query's (same ORDER BY, including the
id tiebreaker and NULL placement). The total is a separate, cached count."""
order_by = VIDEO_ORDERS[order]
mimetypes = _video_mimetypes()
mimetypes = _video_mimetypes(session)
if not mimetypes:
return [], 0
@ -183,11 +182,12 @@ def _search_videos_by_date(order: str, limit: int, offset: int) -> Tuple[List[di
'''.strip()
logger.debug(f'{stmt} {params}')
total = cached_search_total(search_filter_cache_key('videos'), _count_videos)
return handle_file_group_search_results(stmt, params, total=total)
total = cached_search_total(search_filter_cache_key('videos'), lambda: _count_videos(session))
return handle_file_group_search_results(session, stmt, params, total=total)
def search_videos(
session: Session,
search_str: str = None,
offset: int = None,
limit: int = VIDEO_QUERY_LIMIT,
@ -212,7 +212,7 @@ def search_videos(
offset = int(offset) if offset else 0
if not search_str and not tag_names and not channel_id and not censored and order in INDEXED_DATE_ORDERS:
# The Videos page with no filters, in date order.
return _search_videos_by_date(order, limit, offset)
return _search_videos_by_date(session, order, limit, offset)
params = dict(search_str=search_str, offset=offset)
if channel_id:
@ -280,7 +280,7 @@ def search_videos(
unfiltered = (not search_str and not tag_names and not channel_id and not censored
and not null_filter)
if unfiltered:
total = cached_search_total(search_filter_cache_key('videos'), _count_videos)
total = cached_search_total(search_filter_cache_key('videos'), lambda: _count_videos(session))
else:
if fts_search:
fts_count = fts.file_group_search(search_str, deep=deep)
@ -303,9 +303,9 @@ def search_videos(
'videos', search_str=search_str, channel_id=channel_id, tag_names=tag_names,
censored=censored, deep=deep, null_filter=null_filter,
)
total = cached_search_total(cache_key, lambda: count_file_groups(count_stmt, count_params))
total = cached_search_total(cache_key, lambda: count_file_groups(session, count_stmt, count_params))
results, total = handle_file_group_search_results(stmt, params, total=total)
results, total = handle_file_group_search_results(session, stmt, params, total=total)
return results, total

View file

@ -22,7 +22,7 @@ from wrolpi.common import register_modeler, logger, extract_html_text, extract_h
from wrolpi.switches import register_switch_handler
from wrolpi.dates import Seconds
from wrolpi.events import Events
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.db import get_db_session, session_curs
from wrolpi.downloader import DownloadFrequency
from wrolpi.files.lib import split_file_name_words
from wrolpi.files.modeler import run_modeler_loop, skip_clause
@ -112,7 +112,7 @@ async def zim_modeler(progress_callback: Callable[[int], None] = None):
)
def get_all_entries_tags():
def get_all_entries_tags(session: Session):
"""Returns a dict of dicts which contain the names of all Tags of each Entry's path.
Example:
@ -130,7 +130,7 @@ def get_all_entries_tags():
LEFT JOIN tag_zim tz on t.id = tz.tag_id
GROUP BY 1, 2 \
'''
with get_db_curs() as curs:
with session_curs(session) as curs:
curs.execute(stmt)
entries = dict()
for zim_id, zim_entry, tag_names in curs.fetchall():
@ -144,8 +144,8 @@ def get_all_entries_tags():
return entries
def get_entries_tags(paths: List[str], zim_id: int):
all_entries_tags = get_all_entries_tags()
def get_entries_tags(session: Session, paths: List[str], zim_id: int):
all_entries_tags = get_all_entries_tags(session)
entries = dict()
for path in paths:
zim_tag_entries = all_entries_tags.get(zim_id, dict())
@ -187,7 +187,7 @@ def headline_zim(session: Session, search_str: str, zim_id: int, tag_names: List
articles = [bytes(i.get_item().content).decode('UTF-8') for i in entries]
articles = [extract_html_text(i) for i in articles]
entries_tag_names = get_entries_tags([i.path for i in entries], zim_id)
entries_tag_names = get_entries_tags(session, [i.path for i in entries], zim_id)
# Always get headlines even if there is no search_str. Non-matches get the leading text of each article.
headlines = extract_headlines(articles, search_str)

View file

@ -14,7 +14,7 @@ from modules.zim.errors import UnknownZimEntry, UnknownZimTagEntry, UnknownZim
from wrolpi import dates, tags
from wrolpi.common import Base, logger, get_relative_to_media_directory, ModelHelper
from wrolpi.dates import TZDateTime
from wrolpi.db import get_db_curs
from wrolpi.db import session_curs
from wrolpi.downloader import Download, download_manager
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
@ -249,7 +249,7 @@ class Zim(Base, ModelHelper):
@staticmethod
def _entries_with_tags_process(limit: int, offset: int, params: dict, session: Session, tags_sub_select: str):
with get_db_curs() as curs:
with session_curs(session) as curs:
curs.execute(tags_sub_select, params)
# sqlite3.Row is not a tuple; convert for the `tuple_(...).in_()` below.
zim_ids_entries: List[Tuple[int, str]] = [tuple(row) for row in curs.fetchall()]

View file

@ -64,7 +64,7 @@ async def test_zim_get_entries_tags(async_client, test_session, test_zim, tag_fa
test_zim.tag_entry(test_session, tag1.name, 'two')
test_session.commit()
assert lib.get_entries_tags(['one', 'two', 'home'], 1) \
assert lib.get_entries_tags(test_session, ['one', 'two', 'home'], 1) \
== dict(one=['tag1', 'tag2'], two=['tag1'], home=[])