Removing optional_session, passing session down from request middleware. Moving session param to the front of functions.
Some checks failed
CodeQL / Analyze (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled

This commit is contained in:
Roland 2025-12-10 21:16:10 -07:00
parent 1747442db3
commit 344fe9035f
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
70 changed files with 1035 additions and 1110 deletions

View file

@ -11,7 +11,7 @@ from wrolpi.cmd import SINGLE_FILE_BIN, CHROMIUM
from wrolpi.collections import Collection
from wrolpi.common import logger, register_modeler, register_refresh_cleanup, limit_concurrent, split_lines_by_length, \
slow_logger, get_title_from_html
from wrolpi.db import optional_session, get_db_session
from wrolpi.db import get_db_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from wrolpi.files.models import FileGroup
@ -36,8 +36,7 @@ class ArchiveDownloader(Downloader, ABC):
def __repr__(self):
return f'<ArchiveDownloader>'
@optional_session
def already_downloaded(self, *urls: List[str], session: Session = None) -> List:
def already_downloaded(self, session: Session, *urls: List[str]) -> List:
file_groups = list(session.query(FileGroup).filter(FileGroup.url.in_(urls), FileGroup.model == 'archive'))
return file_groups
@ -57,7 +56,7 @@ class ArchiveDownloader(Downloader, ABC):
archive_id = archive.id
with get_db_session() as session:
archive = Archive.find_by_id(archive_id, session)
archive = Archive.find_by_id(session, archive_id)
need_commit = False
if tag_names := download.tag_names:
for name in tag_names:
@ -107,7 +106,7 @@ class ArchiveDownloader(Downloader, ABC):
archive_downloader = ArchiveDownloader()
def model_archive(file_group: FileGroup, session: Session = None) -> Archive:
def model_archive(session: Session, file_group: FileGroup) -> Archive:
"""
Models an Archive from a given FileGroup.
@ -117,8 +116,8 @@ def model_archive(file_group: FileGroup, session: Session = None) -> Archive:
(title, contents) from either the JSON or text readability files.
Args:
session: Database session.
file_group: The FileGroup to model as an Archive.
session: An optional database session for committing changes.
Returns:
An Archive object representing the modeled archive.
@ -289,7 +288,7 @@ async def archive_modeler():
raise
else:
try:
model_archive(file_group, session=session)
model_archive(session, file_group)
# Successfully modeled, mark as indexed
file_group.indexed = True
except InvalidArchive:

View file

@ -5,10 +5,10 @@ from http import HTTPStatus
from sanic import response, Request, Blueprint
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from sqlalchemy.orm import Session
from wrolpi.api_utils import json_response, api_app
from wrolpi.common import logger, wrol_mode_check, api_param_limiter, TRACE_LEVEL
from wrolpi.db import get_db_session
from wrolpi.errors import ValidationError
from wrolpi.events import Events
from wrolpi.schema import JSONErrorResponse
@ -25,8 +25,9 @@ logger = logger.getChild(__name__)
@archive_bp.get('/<archive_id:int>')
@openapi.description('Get an archive')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
async def get_archive(_: Request, archive_id: int):
archive = lib.get_archive(archive_id=archive_id)
async def get_archive(request: Request, archive_id: int):
session = request.ctx.session
archive = lib.get_archive(session, archive_id)
archive_file_group = archive.file_group.__json__()
history = [i.file_group.__json__() for i in archive.history]
return json_response({'file_group': archive_file_group, 'history': history})
@ -115,12 +116,12 @@ async def singlefile_upload_switch_handler(url=None):
logger.info(f'Created Archive from upload ({q_size}): {archive}')
Events.send_archive_uploaded(f'Created Archive from upload: {name}', url=archive.location)
url = archive.file_group.url
if url and (download := Download.get_by_url(url)):
if (download.is_failed or download.is_deferred) and download.downloader == ArchiveDownloader.name:
# Download was attempted and failed, user manually archived the URL.
download.complete()
download.location = archive.location
Session.object_session(download).commit()
with get_db_session(commit=True) as session:
if url and (download := Download.get_by_url(session, url)):
if (download.is_failed or download.is_deferred) and download.downloader == ArchiveDownloader.name:
# Download was attempted and failed, user manually archived the URL.
download.complete()
download.location = archive.location
# Call this function again so any new singlefiles can be archived.
singlefile_upload_switch_handler.activate_switch()
@ -154,9 +155,10 @@ async def generate_screenshot_switch_handler(archive_id=None):
try:
await lib.generate_archive_screenshot(archive_id)
# Always send success event since exceptions are raised on failure
archive = lib.get_archive(archive_id=archive_id)
location = archive.location
name = archive.file_group.title or archive.file_group.url
with get_db_session() as session:
archive = lib.get_archive(session, archive_id)
location = archive.location
name = archive.file_group.title or archive.file_group.url
logger.info(f'Generated screenshot for Archive ({q_size}): {archive_id}')
Events.send_screenshot_generated(f'Generated screenshot for: {name}', url=location)
except Exception as e:
@ -196,11 +198,12 @@ async def post_upload_singlefile(request: Request):
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
@wrol_mode_check
async def post_generate_screenshot(_: Request, archive_id: int):
async def post_generate_screenshot(request: Request, archive_id: int):
"""Queue a screenshot generation request for an Archive."""
session = request.ctx.session
# Verify archive exists
try:
archive = lib.get_archive(archive_id=archive_id)
archive = lib.get_archive(session, archive_id)
except Exception:
return json_response({'error': f'Archive {archive_id} not found'}, status=HTTPStatus.NOT_FOUND)

View file

@ -93,7 +93,7 @@ def archive_factory(test_session, archive_directory, make_files_structure, image
archive.validate()
for tag_name in tag_names:
archive.add_tag(tag_name, test_session)
archive.add_tag(test_session, tag_name)
return archive

View file

@ -24,7 +24,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, ConfigFile
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs, optional_session
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import UnknownArchive, InvalidOrderBy, InvalidDatetime
from wrolpi.events import Events
from wrolpi.files.lib import handle_file_group_search_results
@ -143,7 +143,7 @@ class DomainsConfig(ConfigFile):
# Batch create/update collections
imported_domains = set()
if valid_data_list:
collections = Collection.batch_from_config(valid_data_list, session=session)
collections = Collection.batch_from_config(session, valid_data_list)
imported_domains = {c.name for c in collections}
# Delete domain collections that are no longer in config
@ -453,7 +453,7 @@ async def model_archive_result(url: str, singlefile: str, readability: dict, scr
return archive
def detect_domain_directory(collection: Collection, session: Session) -> Optional[pathlib.Path]:
def detect_domain_directory(session: Session, collection: Collection) -> Optional[pathlib.Path]:
"""
Detect if all archives for a domain collection share a common directory.
@ -546,7 +546,7 @@ def update_domain_directories(session: Session = None) -> int:
updated_count = 0
for collection in collections:
detected_dir = detect_domain_directory(collection, session)
detected_dir = detect_domain_directory(session, collection)
if detected_dir:
collection.directory = detected_dir
session.flush([collection])
@ -598,7 +598,7 @@ def get_or_create_domain_collection(session: Session, url, directory: pathlib.Pa
# Auto-detect directory if not explicitly set and collection doesn't have one
if not directory and not collection.directory:
detected_dir = detect_domain_directory(collection, session)
detected_dir = detect_domain_directory(session, collection)
if detected_dir:
collection.directory = detected_dir
session.flush()
@ -810,10 +810,9 @@ def parse_article_html_metadata(html: Union[bytes, str], assume_utc: bool = True
return metadata
@optional_session
def get_archive(session, archive_id: int) -> Archive:
def get_archive(session: Session, archive_id: int) -> Archive:
"""Get an Archive."""
archive = Archive.find_by_id(archive_id, session=session)
archive = Archive.find_by_id(session, archive_id)
archive.file_group.set_viewed()
return archive
@ -907,17 +906,18 @@ def get_domain(domain_id: int) -> dict:
Raises UnknownArchive if domain not found.
"""
# Get the collection using find_by_id
try:
collection = Collection.find_by_id(domain_id)
except Exception:
# Collection.find_by_id raises UnknownCollection, but we want UnknownArchive
raise UnknownArchive(f"Domain collection with ID {domain_id} not found")
with get_db_session() as session:
try:
collection = Collection.find_by_id(session, domain_id)
except Exception:
# Collection.find_by_id raises UnknownCollection, but we want UnknownArchive
raise UnknownArchive(f"Domain collection with ID {domain_id} not found")
if collection.kind != 'domain':
raise UnknownArchive(f"Collection {domain_id} is not a domain")
if collection.kind != 'domain':
raise UnknownArchive(f"Collection {domain_id} is not a domain")
# Get base domain data from __json__()
domain_data = collection.__json__()
# Get base domain data from __json__()
domain_data = collection.__json__()
# Get archive statistics for this domain
with get_db_curs() as curs:
@ -1045,15 +1045,14 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
return results, total
@optional_session
async def search_domains_by_name(name: str, limit: int = 5, session: Session = None) -> List[dict]:
async def search_domains_by_name(session: Session, name: str, limit: int = 5) -> List[dict]:
"""
Search for domain collections by name.
Args:
session: Database session
name: Search string to match against collection names
limit: Maximum number of results to return
session: Database session
Returns:
List of domain dicts matching the search (in old Domain format for backward compatibility)
@ -1163,7 +1162,7 @@ async def generate_archive_screenshot(archive_id: int) -> pathlib.Path:
RuntimeError: If screenshot generation fails
"""
with get_db_session() as session:
archive = Archive.find_by_id(archive_id, session=session)
archive = Archive.find_by_id(session, archive_id)
if not archive.singlefile_path:
raise ValueError(f'Cannot generate screenshot for Archive {archive_id}: no singlefile')
@ -1175,7 +1174,7 @@ async def generate_archive_screenshot(archive_id: int) -> pathlib.Path:
logger.info(f'Archive {archive_id} already has a screenshot, ensuring it is tracked')
# Ensure the screenshot is tracked in FileGroup.files and FileGroup.data
with get_db_session(commit=True) as tracking_session:
archive = Archive.find_by_id(archive_id, session=tracking_session)
archive = Archive.find_by_id(tracking_session, archive_id)
file_group = archive.file_group
# append_files uses unique_by_predicate, so this is safe even if already tracked
file_group.append_files(archive.screenshot_path)
@ -1213,7 +1212,7 @@ async def generate_archive_screenshot(archive_id: int) -> pathlib.Path:
# Update the Archive to include the new screenshot file
with get_db_session(commit=True) as session:
archive = Archive.find_by_id(archive_id, session=session)
archive = Archive.find_by_id(session, archive_id)
archive.set_screenshot(screenshot_path)
session.flush()

View file

@ -11,7 +11,6 @@ from wrolpi import dates
from wrolpi.collections import Collection
from wrolpi.common import ModelHelper, Base, logger, get_title_from_html, get_wrolpi_config, get_media_directory
from wrolpi.dates import now
from wrolpi.db import optional_session
from wrolpi.errors import UnknownArchive
from wrolpi.files.models import FileGroup
from wrolpi.tags import TagFile
@ -62,33 +61,29 @@ class Archive(Base, ModelHelper):
return None
@staticmethod
@optional_session
def get_by_id(id_: int, session: Session = None) -> Optional['Archive']:
def get_by_id(session: Session, id_: int) -> Optional['Archive']:
"""Attempt to find an Archive with the provided id. Returns None if it cannot be found."""
archive = session.query(Archive).filter_by(id=id_).one_or_none()
return archive
@staticmethod
@optional_session
def find_by_id(id_: int, session: Session = None) -> 'Archive':
def find_by_id(session: Session, id_: int) -> 'Archive':
"""Find an Archive with the provided id, raises an exception when no Archive is found.
@raise UnknownArchive: if the Archive can not be found"""
archive = Archive.get_by_id(id_, session=session)
archive = Archive.get_by_id(session, id_)
if not archive:
raise UnknownArchive(f'Cannot find Archive with id {id_}')
return archive
@staticmethod
@optional_session
def get_by_path(path: pathlib.Path | str, session: Session = None) -> Optional['Archive']:
def get_by_path(session: Session, path: pathlib.Path | str) -> Optional['Archive']:
archive = session.query(Archive).join(FileGroup).filter(FileGroup.primary_path == str(path)).one_or_none()
return archive
@staticmethod
@optional_session
def find_by_path(path: pathlib.Path | str, session: Session = None) -> Optional['Archive']:
archive = Archive.get_by_path(path, session)
def find_by_path(session: Session, path: pathlib.Path | str) -> Optional['Archive']:
archive = Archive.get_by_path(session, path)
if archive:
return archive
raise UnknownArchive(f'Cannot find Archive with path: {path}')
@ -102,10 +97,10 @@ class Archive(Base, ModelHelper):
return False
@staticmethod
def do_model(file_group: FileGroup, session: Session) -> 'Archive':
def do_model(session: Session, file_group: FileGroup) -> 'Archive':
# Local import to avoid circular import within archive module
from modules.archive import model_archive
archive = model_archive(file_group, session)
archive = model_archive(session, file_group)
archive.validate()
file_group.indexed = True
return archive
@ -377,7 +372,7 @@ class Archive(Base, ModelHelper):
# Local import to avoid circular import within archive module
from modules.archive import model_archive
file_group = FileGroup.from_paths(session, *paths)
archive = model_archive(file_group, session)
archive = model_archive(session, file_group)
return archive
def add_tag(self, tag_id_or_name: int | str, session: Session = None) -> TagFile:

View file

@ -65,7 +65,7 @@ async def test_model_archive_sets_collection_id(async_client, test_session, test
# Model the archive using the production code path
# This should create an Archive with collection_id set
archive = model_archive(file_group, session=test_session)
archive = model_archive(test_session, file_group)
# The bug: collection_id is None, causing NOT NULL constraint violation
assert archive is not None, "Archive should be created"
@ -126,7 +126,7 @@ async def test_model_archive_extracts_url_from_singlefile(async_client, test_ses
file_group = FileGroup.from_paths(test_session, *file_paths)
# Model the archive - it should extract the URL from the singlefile
archive = model_archive(file_group, session=test_session)
archive = model_archive(test_session, file_group)
assert archive is not None
assert archive.file_group.url == url, \

View file

@ -310,7 +310,7 @@ async def test_tag_domain_without_directory_saves_config(test_session, test_dire
test_session.commit()
# Tag using library function (no directory)
await tag_collection(collection.id, tag_name='News', directory=None, session=test_session)
await tag_collection(test_session, collection.id, tag_name='News', directory=None)
test_session.commit()
# Wait for switches to process
@ -340,7 +340,7 @@ async def test_untag_domain_without_directory_saves_config(test_session, test_di
test_session.commit()
# Untag using library function (tag_name=None)
await tag_collection(collection.id, tag_name=None, directory=None, session=test_session)
await tag_collection(test_session, collection.id, tag_name=None, directory=None)
test_session.commit()
# Wait for switches to process

View file

@ -883,7 +883,7 @@ async def test_detect_domain_directory_single_archive(async_client, test_directo
assert 'example.com' in str(collection.directory)
# Verify detect_domain_directory also returns the same result
detected = detect_domain_directory(collection, test_session)
detected = detect_domain_directory(test_session, collection)
assert detected is not None
assert str(detected) == 'archive/example.com'
@ -904,7 +904,7 @@ async def test_detect_domain_directory_multiple_archives(async_client, test_dire
assert collection.name == 'test.com'
# Detect directory
detected = detect_domain_directory(collection, test_session)
detected = detect_domain_directory(test_session, collection)
assert detected is not None
assert str(detected) == 'archive/test.com'
@ -919,7 +919,7 @@ def test_detect_domain_directory_no_archives(test_directory, test_session):
test_session.flush()
# Detect directory - should return None
detected = detect_domain_directory(collection, test_session)
detected = detect_domain_directory(test_session, collection)
assert detected is None

View file

@ -5,6 +5,37 @@ import pytest
from modules.archive import Archive
from wrolpi.common import get_wrolpi_config
from wrolpi.errors import UnknownArchive
def test_archive_get_by_id(test_session, archive_factory):
"""Archive.get_by_id should accept session as first argument, id as second."""
archive = archive_factory()
test_session.commit()
# Session must be first argument (session-first pattern)
found = Archive.get_by_id(test_session, archive.id)
assert found is not None
assert found.id == archive.id
# Non-existent ID should return None
not_found = Archive.get_by_id(test_session, 99999)
assert not_found is None
def test_archive_find_by_id(test_session, archive_factory):
"""Archive.find_by_id should accept session as first argument, id as second."""
archive = archive_factory()
test_session.commit()
# Session must be first argument (session-first pattern)
found = Archive.find_by_id(test_session, archive.id)
assert found is not None
assert found.id == archive.id
# Non-existent ID should raise UnknownArchive
with pytest.raises(UnknownArchive):
Archive.find_by_id(test_session, 99999)
@pytest.mark.asyncio

View file

@ -28,8 +28,8 @@ def get_brands(_: Request):
@inventory_bp.get('/')
def get_inventories(_: Request):
inventories = inventory.get_inventories()
def get_inventories(request: Request):
inventories = inventory.get_inventories(request.ctx.session)
return json_response(dict(inventories=inventories))

View file

@ -142,8 +142,9 @@ class InventoriesConfig(ConfigFile):
def dump_config(self, file: pathlib.Path = None, send_events=False, overwrite=False):
inventories = []
for inventory in get_inventories():
inventories.append(inventory.dict())
with get_db_session() as session:
for inventory in get_inventories(session):
inventories.append(inventory.dict())
if not inventories:
raise NoInventories('No Inventories are in the database!')

View file

@ -7,7 +7,7 @@ import psycopg2
from sqlalchemy.orm import Session
from wrolpi.common import logger, Base
from wrolpi.db import get_db_session, get_db_curs, optional_session
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import APIError
from .models import Inventory, Item
@ -85,8 +85,7 @@ DEFAULT_INVENTORIES = [
sort_categories = partial(sorted, key=itemgetter(1, 0))
@optional_session
def get_inventories(session: Session = None) -> List[Inventory]:
def get_inventories(session: Session) -> List[Inventory]:
inventories = session.query(Inventory).filter(
Inventory.deleted_at == None, # noqa
).order_by(

View file

@ -81,7 +81,7 @@ class TestInventory(PytestCase):
def test_get_inventories(self, test_session):
self.prepare()
inventories = get_inventories()
inventories = get_inventories(test_session)
dates = extract_items(inventories, {'created_at', 'deleted_at', 'viewed_at'})
self.assertItemsTruthyOrFalsey(dates, [{'created_at': True, 'deleted_at': False, 'viewed_at': False}])
self.assertEqual(inventories[0].id, 1)
@ -290,7 +290,7 @@ async def test_inventories_config(await_switches, test_session, test_directory,
import_inventories_config()
inventories = get_inventories()
inventories = get_inventories(test_session)
assert len(inventories) == 1
# ID has increased because we did not reset the sequence when deleting from the table.
assert inventories[0].id == 2

View file

@ -41,7 +41,7 @@ async def import_pbfs(_: Request, body: schema.ImportPost):
@map_bp.get('/files')
@openapi.description('Find any map files, get their import status')
def get_files_status(request: Request):
paths = lib.get_import_status()
paths = lib.get_import_status(request.ctx.session)
paths = sorted(paths, key=lambda i: str(i.path))
pending = request.app.shared_ctx.map_importing.get('pending')
if pending:

View file

@ -11,7 +11,7 @@ from wrolpi.api_utils import api_app
from wrolpi.cmd import SUDO_BIN, run_command
from wrolpi.common import get_media_directory, walk, logger, get_wrolpi_config
from wrolpi.dates import timedelta_to_timestamp, seconds_to_timestamp, now
from wrolpi.db import optional_session, get_db_session
from wrolpi.db import get_db_session
from wrolpi.events import Events
from wrolpi.vars import PROJECT_DIR, IS_RPI5
@ -208,8 +208,7 @@ async def run_import_command(*paths: Path):
raise ValueError(f'Importing map file failed with return code {result.return_code}')
@optional_session
def get_import_status(session: Session = None) -> List[MapFile]:
def get_import_status(session: Session) -> List[MapFile]:
paths = get_map_paths()
map_paths = []
for path in paths:

View file

@ -37,12 +37,13 @@ async def statistics(_: Request):
body=schema.ChannelTagInfoRequest,
)
@validate(schema.ChannelTagInfoRequest)
async def channel_tag_info(_: Request, body: schema.ChannelTagInfoRequest):
async def channel_tag_info(request: Request, body: schema.ChannelTagInfoRequest):
from wrolpi.tags import Tag
channel = Channel.find_by_id(body.channel_id) if body.channel_id else None
session = request.ctx.session
channel = Channel.find_by_id(session, body.channel_id) if body.channel_id else None
channel_name = channel.name if channel else None
channel_url = channel.url if channel else None
tag_name = Tag.find_by_name(body.tag_name).name if body.tag_name else None
tag_name = Tag.find_by_name(session, body.tag_name).name if body.tag_name else None
videos_destination = format_videos_destination(channel_name, tag_name, channel_url)
ret = dict(videos_destination=videos_destination)
return json_response(ret)

View file

@ -34,8 +34,9 @@ async def get_channels(_: Request):
@channel_bp.get('/<channel_id:int>')
@openapi.description('Get a Channel')
@openapi.response(HTTPStatus.OK, schema.ChannelResponse)
def channel_get(_: Request, channel_id: int = None):
channel = lib.get_channel(channel_id=channel_id, return_dict=True)
def channel_get(request: Request, channel_id: int = None):
session = request.ctx.session
channel = lib.get_channel(session, channel_id=channel_id, return_dict=True)
channel.pop('info_json')
return json_response({'channel': channel})
@ -49,10 +50,11 @@ def channel_get(_: Request, channel_id: int = None):
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
@validate(schema.ChannelPostRequest)
@wrol_mode_check
def channel_post(_: Request, body: schema.ChannelPostRequest):
def channel_post(request: Request, body: schema.ChannelPostRequest):
session = request.ctx.session
body.directory = get_media_directory() / body.directory
channel = lib.create_channel(data=body, return_dict=False)
channel = lib.create_channel(session, data=body, return_dict=False)
# Refresh the videos asynchronously
if not PYTEST:
@ -73,9 +75,10 @@ def channel_post(_: Request, body: schema.ChannelPostRequest):
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
@validate(schema.ChannelPutRequest)
@wrol_mode_check
async def channel_update(_: Request, channel_id: int, body: schema.ChannelPutRequest):
async def channel_update(request: Request, channel_id: int, body: schema.ChannelPutRequest):
session = request.ctx.session
body.directory = pathlib.Path(body.directory) if body.directory else None
channel = await lib.update_channel(data=body, channel_id=channel_id)
channel = await lib.update_channel(session, data=body, channel_id=channel_id)
save_channels_config.activate_switch()
return response.raw('', HTTPStatus.NO_CONTENT,
headers={'Location': f'/api/videos/channels/{channel.id}'})
@ -85,8 +88,9 @@ async def channel_update(_: Request, channel_id: int, body: schema.ChannelPutReq
@openapi.description('Delete a Channel')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
def channel_delete(_: Request, channel_id: int):
channel = lib.delete_channel(channel_id=channel_id)
def channel_delete(request: Request, channel_id: int):
session = request.ctx.session
channel = lib.delete_channel(session, channel_id=channel_id)
Events.send_deleted(f'Deleted Channel: {channel["name"]}')
return response.raw('', HTTPStatus.NO_CONTENT)
@ -95,8 +99,9 @@ def channel_delete(_: Request, channel_id: int):
@openapi.description('Refresh all files in the Channel directory')
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
def channel_refresh(_: Request, channel_id: int):
channel: Channel = lib.get_channel(channel_id=channel_id, return_dict=False)
def channel_refresh(request: Request, channel_id: int):
session = request.ctx.session
channel: Channel = lib.get_channel(session, channel_id=channel_id, return_dict=False)
if not channel:
raise UnknownChannel()
@ -115,13 +120,14 @@ def channel_refresh(_: Request, channel_id: int):
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
@validate(schema.ChannelTagRequest)
@wrol_mode_check
async def channel_tag(_: Request, channel_id: int, body: schema.ChannelTagRequest):
async def channel_tag(request: Request, channel_id: int, body: schema.ChannelTagRequest):
session = request.ctx.session
directory = None
if body.directory:
directory = pathlib.Path(body.directory)
directory = get_media_directory() / directory
await lib.tag_channel(body.tag_name, directory, channel_id)
await lib.tag_channel(session, body.tag_name, directory, channel_id)
return response.raw('', HTTPStatus.NO_CONTENT)
@ -132,8 +138,9 @@ async def channel_tag(_: Request, channel_id: int, body: schema.ChannelTagReques
body=schema.ChannelSearchRequest,
)
@validate(schema.ChannelSearchRequest)
async def channel_search(_: Request, body: schema.ChannelSearchRequest):
channels = await lib.search_channels(body.tag_names)
async def channel_search(request: Request, body: schema.ChannelSearchRequest):
session = request.ctx.session
channels = await lib.search_channels(session, body.tag_names)
ret = dict(
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, optional_session, get_db_session
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.downloader import save_downloads_config, download_manager, Download
from wrolpi.errors import APIError, ValidationError, RefreshConflict
from wrolpi.tags import Tag
@ -53,7 +53,6 @@ async def get_minimal_channels() -> List[dict]:
COD = Union[dict, Channel]
@optional_session
def get_channel(session: Session, *, channel_id: int = None, source_id: str = None, url: str = None,
directory: str = None, name: str = None, return_dict: bool = True) -> COD:
"""
@ -92,10 +91,9 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
return channel
@optional_session
async def update_channel(session: Session, *, data: schema.ChannelPutRequest, channel_id: int) -> Channel:
"""Update a Channel's DB record"""
channel = Channel.find_by_id(channel_id, session)
channel = Channel.find_by_id(session, channel_id)
# Verify that the URL/Name/directory aren't taken
check_for_channel_conflicts(
@ -132,7 +130,6 @@ async def update_channel(session: Session, *, data: schema.ChannelPutRequest, ch
return channel
@optional_session
def create_channel(session: Session, data: schema.ChannelPostRequest, return_dict: bool = True) -> Union[Channel, dict]:
"""
Create a new Channel. Check for conflicts with existing Channels.
@ -176,9 +173,8 @@ def create_channel(session: Session, data: schema.ChannelPostRequest, return_dic
return channel.dict() if return_dict else channel
@optional_session(commit=True)
def delete_channel(session: Session, *, channel_id: int):
channel = Channel.find_by_id(channel_id, session=session)
channel = Channel.find_by_id(session, channel_id)
channel_dict = channel.dict()
channel.delete_with_videos()
@ -188,8 +184,7 @@ def delete_channel(session: Session, *, channel_id: int):
return channel_dict
@optional_session
async def search_channels_by_name(name: str, limit: int = 5, session: Session = None,
async def search_channels_by_name(session: Session, name: str, limit: int = 5,
order_by_video_count: bool = False) -> List[Channel]:
name = name or ''
name_no_spaces = ''.join(name.split(' '))
@ -222,8 +217,8 @@ async def search_channels_by_name(name: str, limit: int = 5, session: Session =
async def create_channel_download(channel_id: int, url: str, frequency: int, settings: dict):
"""Create Download for Channel."""
with get_db_session(commit=True) as session:
channel = Channel.find_by_id(channel_id, session=session)
download = channel.get_or_create_download(url, frequency, session, reset_attempts=True)
channel = Channel.find_by_id(session, channel_id)
download = channel.get_or_create_download(session, url, frequency, reset_attempts=True)
download.settings = settings
save_channels_config.activate_switch()
@ -237,8 +232,8 @@ async def update_channel_download(channel_id: int, download_id: int, url: str, f
"""Fetch Channel's Download, update its properties."""
with get_db_session(commit=True) as session:
# Ensure that the Channel exists.
Channel.find_by_id(channel_id, session=session)
download = Download.find_by_id(download_id, session=session)
Channel.find_by_id(session, channel_id)
download = Download.find_by_id(session, download_id)
download.url = url
download.frequency = frequency
download.settings = settings
@ -253,8 +248,7 @@ async def update_channel_download(channel_id: int, download_id: int, url: str, f
@wrol_mode_check
@optional_session
async def tag_channel(tag_name: str | None, directory: pathlib.Path | None, channel_id: int, session: Session = None):
async def tag_channel(session: Session, tag_name: str | None, directory: pathlib.Path | None, channel_id: int):
"""Add a Tag to a Channel, or remove a Tag from a Channel if no `tag_name` is provided.
Move the Channel to the new directory, if provided."""
@ -262,7 +256,7 @@ async def tag_channel(tag_name: str | None, directory: pathlib.Path | None, chan
if directory and flags.refreshing.is_set():
raise RefreshConflict('Refusing to move channel while file refresh is in progress')
channel = Channel.find_by_id(channel_id, session)
channel = Channel.find_by_id(session, channel_id)
# May also clear the tag if `tag_name` is None.
channel.set_tag(tag_name)
@ -287,8 +281,7 @@ async def tag_channel(tag_name: str | None, directory: pathlib.Path | None, chan
save_channels_config.activate_switch()
@optional_session
async def search_channels(tag_names: List[str], session: Session) -> List[Channel]:
async def search_channels(session: Session, tag_names: List[str]) -> List[Channel]:
"""Search Tagged Channels."""
channels = session.query(Channel).join(Collection).join(Tag).filter(Tag.name.in_(tag_names)).all()
return channels

View file

@ -476,7 +476,7 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
tag = await tag_factory('Tag Name')
v1, v2 = video_factory(title='video1', channel_id=channel.id), video_factory(title='video2', channel_id=channel.id)
# Create recurring download which uses the Channel's directory.
download = test_download_manager.recurring_download('https://example.com/1', 60, test_downloader.name,
download = test_download_manager.recurring_download(test_session, 'https://example.com/1', 60, test_downloader.name,
destination=str(test_directory / 'videos/Channel Name'))
test_session.commit()
save_channels_config()
@ -597,7 +597,7 @@ async def test_move_channel(async_client, test_session, test_directory, channel_
)
request, response = await async_client.put(f'/api/videos/channels/{channel.id}', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content.decode()
channel = Channel.find_by_id(channel.id)
channel = Channel.find_by_id(test_session, channel.id)
assert str(channel.directory) == str(test_directory / 'videos/New Directory')
assert str(vid1.video_path).startswith(str(test_directory / 'videos/New Directory/'))
assert str(vid2.video_path).startswith(str(test_directory / 'videos/New Directory/'))
@ -625,7 +625,7 @@ async def test_move_channel_after_terminal_move(async_client, test_session, test
)
request, response = await async_client.put(f'/api/videos/channels/{channel.id}', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content.decode()
channel = Channel.find_by_id(channel.id)
channel = Channel.find_by_id(test_session, channel.id)
vid1 = test_session.query(Video).one()
assert str(channel.directory) == str(test_directory / 'videos/New Directory')
assert str(vid1.video_path).startswith(str(test_directory / 'videos/New Directory/'))

View file

@ -20,7 +20,7 @@ from modules.videos.models import Channel
def test_get_bad_channel(test_session, test_directory, params):
"""A Channel cannot be found without data."""
with pytest.raises(UnknownChannel):
lib.get_channel(**params)
lib.get_channel(test_session, **params)
def test_get_channel(test_session, test_directory, channel_factory):
@ -38,19 +38,19 @@ def test_get_channel(test_session, test_directory, channel_factory):
test_session.commit()
channel = lib.get_channel(channel_id=channel_id_channel.id, return_dict=False)
channel = lib.get_channel(test_session, channel_id=channel_id_channel.id, return_dict=False)
assert channel == channel_id_channel
channel = lib.get_channel(source_id='the source id', return_dict=False)
channel = lib.get_channel(test_session, source_id='the source id', return_dict=False)
assert channel == source_id_channel
channel = lib.get_channel(url='https://example.com/channel', return_dict=False)
channel = lib.get_channel(test_session, url='https://example.com/channel', return_dict=False)
assert channel == url_channel
# Directory can be relative, or absolute.
channel = lib.get_channel(directory='some directory', return_dict=False)
channel = lib.get_channel(test_session, directory='some directory', return_dict=False)
assert channel == directory_channel
channel = lib.get_channel(directory=f'{test_directory}/some directory', return_dict=False)
channel = lib.get_channel(test_session, directory=f'{test_directory}/some directory', return_dict=False)
assert channel == directory_channel
# Channel is found using the priority of params, incorrect data is ignored.
@ -61,8 +61,8 @@ def test_get_channel(test_session, test_directory, channel_factory):
dict(channel_id=channel_id_channel.id, source_id='the source id'),
]
for p in params:
assert lib.get_channel(**p, return_dict=False) == channel_id_channel
assert lib.get_channel(**p)
assert lib.get_channel(test_session, **p, return_dict=False) == channel_id_channel
assert lib.get_channel(test_session, **p)
@pytest.mark.asyncio
@ -115,7 +115,7 @@ async def test_search_channels_by_name(test_session, channel_factory, video_fact
test_session.commit()
async def assert_search(name: str, channel_names: List[str], order_by_video_count=False):
channels = await lib.search_channels_by_name(name, order_by_video_count=order_by_video_count)
channels = await lib.search_channels_by_name(test_session, name, order_by_video_count=order_by_video_count)
for channel in channels:
channel_name = channel_names.pop(0)
if channel.name != channel_name:
@ -139,7 +139,7 @@ async def test_tag_channel_existing(async_client, test_session, test_directory,
assert str(channel.directory).startswith(f'{test_directory}/videos/one/')
tag = await tag_factory()
await lib.tag_channel(tag.name, channel_directory, channel.id, test_session)
await lib.tag_channel(test_session, tag.name, channel_directory, channel.id)
await await_switches()
# Channel's tag is saved to the config.
@ -161,7 +161,7 @@ async def test_tag_channel_without_directory_saves_config(
tag = await tag_factory(name='Tech')
# Tag without providing directory (directory=None)
await lib.tag_channel(tag.name, None, channel.id, test_session)
await lib.tag_channel(test_session, tag.name, None, channel.id)
test_session.commit()
await await_switches()
@ -189,7 +189,7 @@ async def test_untag_channel_without_directory_saves_config(
assert channel.tag is not None
# Untag without providing directory (tag_name=None, directory=None)
await lib.tag_channel(None, None, channel.id, test_session)
await lib.tag_channel(test_session, None, None, channel.id)
test_session.commit()
await await_switches()

View file

@ -96,7 +96,7 @@ async def test_channel_download_relationships(test_session, download_channel):
assert test_session.query(Channel).one(), 'Channel should not have been deleted.'
# Create a Download again.
download_channel.get_or_create_download('https://example.com/1', 60, test_session, reset_attempts=True)
download_channel.get_or_create_download(test_session, 'https://example.com/1', 60, reset_attempts=True)
assert test_session.query(Download).count() == 1
# Delete the Channel, and any relationships.
download_channel.delete_with_videos()

View file

@ -53,7 +53,7 @@ def channel_factory(test_session, test_directory):
def factory(source_id: str = None, download_frequency: DownloadFrequency = None, url: str = None, name: str = None,
directory: pathlib.Path = None, tag_name: str = None):
name = name or str(uuid4())
tag = Tag.find_by_name(tag_name) if tag_name else None
tag = Tag.find_by_name(test_session, tag_name) if tag_name else None
tag_name = tag.name if tag else None
directory = directory or format_videos_destination(name, tag_name, url or f'https://example.com/{name}')
directory.mkdir(exist_ok=True, parents=True)
@ -79,7 +79,7 @@ def channel_factory(test_session, test_directory):
test_session.add(Directory(path=channel.directory, name=channel.directory.name))
assert channel.id and channel.url
if download_frequency:
download = channel.get_or_create_download(channel.url, download_frequency)
download = channel.get_or_create_download(test_session, channel.url, download_frequency)
assert download.url == channel.url
assert channel.downloads
test_session.commit()
@ -111,7 +111,7 @@ def download_channel(test_session, test_directory, video_download_manager) -> Ch
test_session.add(channel)
test_session.flush([channel])
assert channel and channel.id and channel.url
download = channel.get_or_create_download(channel.url, 60, test_session)
download = channel.get_or_create_download(test_session, channel.url, 60)
assert download.url == channel.url
download.frequency = DownloadFrequency.weekly
test_session.commit()
@ -126,7 +126,7 @@ def simple_video(test_session, test_directory, simple_channel, video_file) -> Vi
video = Video.from_paths(test_session, video_path)
video.channel = simple_channel
test_session.commit()
video = Video.find_by_id(video.id, session=test_session)
video = Video.find_by_id(test_session, video.id)
return video
@ -145,7 +145,7 @@ def video_factory(test_session, test_directory):
path = pathlib.Path(with_video_file) if not isinstance(with_video_file, pathlib.Path) else with_video_file
elif channel_id:
# Put the video in its Channel's directory.
channel = Channel.find_by_id(channel_id)
channel = Channel.find_by_id(test_session, channel_id)
path = (channel.directory or test_directory) / f'{title}.mp4'
path.parent.mkdir(exist_ok=True, parents=True)
else:
@ -182,10 +182,10 @@ def video_factory(test_session, test_directory):
video.channel_id = channel_id
video.source_id = source_id or title
video.file_group.published_datetime = upload_date
video.validate()
video.validate(test_session)
for tag_name in tag_names:
video.add_tag(tag_name)
video.add_tag(test_session, tag_name)
return video

View file

@ -22,7 +22,6 @@ from wrolpi.common import logger, get_media_directory, escape_file_name, resolve
trim_file_name, cached_multiprocessing_result, get_absolute_media_path
from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.db import optional_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from wrolpi.files.lib import glob_shared_stem, split_path_stem_and_suffix
@ -147,7 +146,7 @@ async def fetch_video_duration(url: str) -> int:
otherwise, fetches the duration using yt-dlp."""
with get_db_session() as session:
# Join with Video to get duration; a URL may have other files (such as an Archive).
video = Video.get_by_url(url, session=session)
video = Video.get_by_url(session, url)
if video and (duration := video.file_group.length):
logger.debug(f'Using already-known duration {duration} for {url} from FileGroup')
return duration
@ -199,7 +198,7 @@ class ChannelDownloader(Downloader, ABC):
if not name:
raise ValueError(f'Could not find name')
channel_source_id = info.get('channel_id') or info.get('id')
channel = get_or_create_channel(channel_source_id, download.url, name, channel_tag_name)
channel = get_or_create_channel(session, channel_source_id, download.url, name, channel_tag_name)
channel.dict() # get all attributes while we have the session.
location = f'/videos/channel/{channel.id}/video' if channel and channel.id else None
@ -225,7 +224,7 @@ class ChannelDownloader(Downloader, ABC):
else:
logger.debug('Not updating channel because this is a playlist')
downloads = self.get_missing_videos(download)
downloads = self.get_missing_videos(session, download)
return DownloadResult(
success=True,
location=location,
@ -261,7 +260,7 @@ class ChannelDownloader(Downloader, ABC):
session.refresh(channel)
@staticmethod
def get_missing_videos(download: Download) -> List[str]:
def get_missing_videos(session: Session, download: Download) -> List[str]:
"""
Return all URLs of Videos in the `info_json` which need to be downloaded.
"""
@ -323,7 +322,7 @@ class ChannelDownloader(Downloader, ABC):
downloads = [normalize_video_url(i) for i in downloads]
# Only download those that have not yet been downloaded.
already_downloaded = [i.url for i in video_downloader.already_downloaded(*downloads)]
already_downloaded = [i.url for i in video_downloader.already_downloaded(session, *downloads)]
downloads = [i for i in downloads if i not in already_downloaded]
return downloads
@ -343,65 +342,64 @@ class VideoDownloader(Downloader, ABC):
def __repr__(self):
return f'<VideoDownloader>'
@optional_session
def already_downloaded(self, *urls: str, session: Session = None) -> List:
def already_downloaded(self, session: Session, *urls: str) -> List:
# We only consider a video record with a video file as "downloaded".
file_groups = list(session.query(FileGroup).filter(FileGroup.url.in_(urls), FileGroup.model == 'video'))
return file_groups
async def do_download(self, download: Download) -> DownloadResult:
if download.attempts >= 10:
raise UnrecoverableDownloadError('Max download attempts reached')
url = normalize_video_url(download.url)
# Copy settings into Download (they may be from the ChannelDownloader)
settings = download.settings or dict()
download.destination = download.destination or settings.get('destination')
tag_names = download.tag_names = download.tag_names or settings.get('tag_names')
# Video may have been downloaded previously, get its location for error reporting.
with get_db_session() as session:
video_ = Video.get_by_url(url, session)
if download.attempts >= 10:
raise UnrecoverableDownloadError('Max download attempts reached')
url = normalize_video_url(download.url)
# Copy settings into Download (they may be from the ChannelDownloader)
settings = download.settings or dict()
download.destination = download.destination or settings.get('destination')
tag_names = download.tag_names = download.tag_names or settings.get('tag_names')
# Video may have been downloaded previously, get its location for error reporting.
video_ = Video.get_by_url(session, url)
location = video_.location if video_ else None
try:
download.info_json = download.info_json or extract_info(url)
except yt_dlp.utils.DownloadError as e:
# Video may be private.
try:
raise RuntimeError('Failed to extract_info') from e
except Exception as e:
return DownloadResult(
success=False,
location=location,
error='\n'.join(traceback.format_exception(e)),
)
download.info_json = download.info_json or extract_info(url)
except yt_dlp.utils.DownloadError as e:
# Video may be private.
try:
raise RuntimeError('Failed to extract_info') from e
except Exception as e:
return DownloadResult(
success=False,
location=location,
error='\n'.join(traceback.format_exception(e)),
)
if not download.info_json:
raise ValueError(f'Cannot download video with no info_json.')
if not download.info_json:
raise ValueError(f'Cannot download video with no info_json.')
channel, channel_directory, channel_id, destination, settings = await self._get_channel(download)
channel, channel_directory, channel_id, destination, settings = await self._get_channel(session, download)
if destination:
# Download to the directory specified in the settings.
out_dir = destination
logger.debug(f'Downloading {url} to destination {destination} from settings')
elif channel:
out_dir = channel_directory
logger.debug(f'Downloading {url} to channel directory: {channel_directory}')
else:
# Download to the default directory if this video has no channel.
out_dir = get_no_channel_directory()
logger.debug(f'Downloading {url} to default directory')
if destination:
# Download to the directory specified in the settings.
out_dir = destination
logger.debug(f'Downloading {url} to destination {destination} from settings')
elif channel:
out_dir = channel_directory
logger.debug(f'Downloading {url} to channel directory: {channel_directory}')
else:
# Download to the default directory if this video has no channel.
out_dir = get_no_channel_directory()
logger.debug(f'Downloading {url} to default directory')
# Make output directory. (Maybe string from settings)
out_dir = out_dir if isinstance(out_dir, pathlib.Path) else pathlib.Path(out_dir)
out_dir = get_absolute_media_path(out_dir)
out_dir.mkdir(exist_ok=True, parents=True)
# Make output directory. (Maybe string from settings)
out_dir = out_dir if isinstance(out_dir, pathlib.Path) else pathlib.Path(out_dir)
out_dir = get_absolute_media_path(out_dir)
out_dir.mkdir(exist_ok=True, parents=True)
if tag_names and logger.isEnabledFor(logging.DEBUG):
logger.debug(f'Downloading {url} with {tag_names=}')
if tag_names and logger.isEnabledFor(logging.DEBUG):
logger.debug(f'Downloading {url} with {tag_names=}')
config = get_videos_downloader_config()
@ -526,12 +524,12 @@ class VideoDownloader(Downloader, ABC):
with get_db_session(commit=True) as session:
# Second session is started because SQLAlchemy will forget what we have done.
video = Video.get_by_id(video_id, session)
video = Video.get_by_id(session, video_id)
if tag_names:
existing_names = video.file_group.tag_names
for name in tag_names:
if name not in existing_names:
video.add_tag(name)
video.add_tag(session, name)
location = video.location
await video.get_ffprobe_json()
@ -589,7 +587,7 @@ class VideoDownloader(Downloader, ABC):
return result
@staticmethod
async def _get_channel(download: Download) \
async def _get_channel(session: Session, download: Download) \
-> Tuple[Optional[Channel], Optional[pathlib.Path], Optional[int], Optional[pathlib.Path], dict]:
settings = download.settings or dict()
channel_tag_name = i[0] if (i := settings.get('channel_tag_name')) else None
@ -603,7 +601,8 @@ class VideoDownloader(Downloader, ABC):
if channel_name or channel_source_id or channel_url:
# Try to find the channel via info_json from yt-dlp.
try:
channel = get_or_create_channel(source_id=channel_source_id, url=channel_url, name=channel_name,
channel = get_or_create_channel(session, source_id=channel_source_id, url=channel_url,
name=channel_name,
tag_name=channel_tag_name)
if channel:
found_channel = 'yt_dlp'
@ -615,7 +614,7 @@ class VideoDownloader(Downloader, ABC):
if not channel and destination:
# Destination may find Channel if not already found.
try:
channel = get_channel(directory=destination, return_dict=False)
channel = get_channel(session, directory=destination, return_dict=False)
found_channel = 'download_settings_directory'
logger.debug(f'Found a channel that shares the destination directory {channel=}')
except UnknownChannel:
@ -630,10 +629,9 @@ class VideoDownloader(Downloader, ABC):
try:
# Find Channel by collection_id or URL
if collection_id:
with get_db_session() as session:
channel = session.query(Channel).filter_by(collection_id=collection_id).one_or_none()
channel = session.query(Channel).filter_by(collection_id=collection_id).one_or_none()
if not channel and channel_url:
channel = get_channel(url=channel_url, return_dict=False)
channel = get_channel(session, url=channel_url, return_dict=False)
logger.debug(f'Found channel with collection_id or channel url {channel=}')
except UnknownChannel:
# We do not need a Channel if we have a destination directory.
@ -811,14 +809,15 @@ channel_downloader = ChannelDownloader()
video_downloader = VideoDownloader()
def get_or_create_channel(source_id: str = None, url: str = None, name: str = None, tag_name: str = None) -> Channel:
def get_or_create_channel(session: Session, source_id: str = None, url: str = None, name: str = None,
tag_name: str = None) -> Channel:
"""
Attempt to find a Channel using the provided params. The params are in order of reliability.
Creates a new Channel if one cannot be found.
"""
try:
channel = get_channel(source_id=source_id, url=url, name=name, return_dict=False)
channel = get_channel(session, source_id=source_id, url=url, name=name, return_dict=False)
# Get all properties while we have the session.
channel.dict()
return channel
@ -839,7 +838,7 @@ def get_or_create_channel(source_id: str = None, url: str = None, name: str = No
directory=str(channel_directory.relative_to(get_media_directory())),
tag_name=tag_name,
)
channel = create_channel(data=data, return_dict=False)
channel = create_channel(session, data=data, return_dict=False)
# Create the directory now that the channel is approved.
channel_directory.mkdir(exist_ok=True)
# Get all properties while we have the session.

View file

@ -84,7 +84,7 @@ def extract_video_info_json(video: Video) -> VideoInfoJSON:
EXTRACT_SUBTITLES = False
def validate_video(video: Video, channel_generate_poster: bool):
def validate_video(session: Session, video: Video, channel_generate_poster: bool):
"""
Validate a single video.
@ -116,6 +116,7 @@ def validate_video(video: Video, channel_generate_poster: bool):
from modules.videos.channel.lib import get_channel
try:
if channel := get_channel(
session,
source_id=video_info_json.channel_source_id,
url=video_info_json.channel_url,
directory=video.video_path.parent,
@ -292,7 +293,7 @@ class ChannelsConfig(ConfigFile):
# Batch create/update Collections
from wrolpi.collections import Collection
collections = Collection.batch_from_config(channel_data_list, session=session)
collections = Collection.batch_from_config(session, channel_data_list)
# Pre-fetch existing Channels by collection_id in ONE query
collection_ids = [c.id for c in collections]
@ -624,7 +625,7 @@ async def fetch_channel_source_id(channel_id: int):
try:
with get_db_session() as session:
from modules.videos.channel.lib import get_channel
channel = Channel.find_by_id(channel_id)
channel = Channel.find_by_id(session, channel_id)
channel.source_id = channel.source_id or get_channel_source_id(channel.url)
if not channel.source_id:
channel_import_logger.warning(f'Unable to fetch source_id for {channel.url}')
@ -682,7 +683,7 @@ def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel,
# Associate any Download which shares a Channel's URL.
for download in downloads:
channel = channel_.get_by_url(download.url, session)
channel = channel_.get_by_url(session, download.url)
if channel and not download.collection_id:
download.collection_id = channel.collection_id
need_commit = True

View file

@ -9,7 +9,7 @@ from sqlalchemy.orm.collections import InstrumentedList
from modules.videos.errors import UnknownVideo, UnknownChannel
from wrolpi.captions import read_captions
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task, replace_file
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.downloader import Download
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
@ -99,14 +99,14 @@ class Video(ModelHelper, Base):
return file_group.mimetype.startswith('video/')
@staticmethod
def do_model(file_group: FileGroup, session: Session) -> 'Video':
def do_model(session: Session, file_group: FileGroup) -> 'Video':
# Check if a Video already exists for this FileGroup
video = session.query(Video).filter_by(file_group_id=file_group.id).one_or_none()
if not video:
# Create new Video if it doesn't exist
video = Video(file_group_id=file_group.id, file_group=file_group)
session.add(video)
video.validate()
video.validate(session)
file_group.indexed = True
video.flush()
return video
@ -208,12 +208,12 @@ class Video(ModelHelper, Base):
break
# Fetch the videos by id, if they exist.
previous_video = Video.find_by_id(previous_id, session) if previous_id else None
next_video = Video.find_by_id(next_id, session) if next_id else None
previous_video = Video.find_by_id(session, previous_id) if previous_id else None
next_video = Video.find_by_id(session, next_id) if next_id else None
return previous_video, next_video
def validate(self, session: Session = None):
def validate(self, session: Session):
"""Perform a validation of this video and it's files."""
if not self.file_group.primary_path:
# Can't validate if there is no video file.
@ -222,7 +222,7 @@ class Video(ModelHelper, Base):
logger.debug(f'Validating {self}')
from .lib import validate_video
try:
validate_video(self, self.channel.generate_posters if self.channel else False)
validate_video(session, self, self.channel.generate_posters if self.channel else False)
except Exception as e:
logger.error(f'Failed to validate video {self}', exc_info=e)
if PYTEST:
@ -239,7 +239,7 @@ class Video(ModelHelper, Base):
# If this Video is in a Channel's directory, then it is part of that Channel.
session: Session = session or Session.object_session(self)
if session and (channel := Channel.get_by_path(self.video_path.parent, session)):
if session and (channel := Channel.get_by_path(session, self.video_path.parent)):
self.channel = channel
logger.debug(f'{self} has Channel {channel}')
@ -263,7 +263,7 @@ class Video(ModelHelper, Base):
session.add(video)
session.flush([video, file_group])
video.validate()
video.validate(session)
session.flush([video, ])
return video
@ -322,46 +322,40 @@ class Video(ModelHelper, Base):
return caption_text
@staticmethod
@optional_session
def get_by_path(path, session: Session) -> Optional['Video']:
def get_by_path(session: Session, path) -> Optional['Video']:
video = session.query(Video) \
.join(FileGroup, FileGroup.id == Video.file_group_id) \
.filter(FileGroup.primary_path == path).one_or_none()
return video
@staticmethod
@optional_session
def get_by_url(url: str, session: Session) -> Optional['Video']:
def get_by_url(session: Session, url: str) -> Optional['Video']:
video = session.query(Video) \
.join(FileGroup, FileGroup.id == Video.file_group_id) \
.filter(FileGroup.url == url).one_or_none()
return video
@staticmethod
@optional_session
def get_by_id(id_: int, session: Session = None) -> Optional['Video']:
def get_by_id(session: Session, id_: int) -> Optional['Video']:
"""Attempt to find a Video with the provided id. Returns None if it cannot be found."""
video = session.query(Video).filter(Video.id == id_).one_or_none()
return video
@staticmethod
@optional_session
def find_by_id(id_: int, session: Session = None) -> 'Video':
def find_by_id(session: Session, id_: int) -> 'Video':
"""Find a Video with the provided id, raises an exception if it cannot be found.
@raise UnknownVideo: if the Video can not be found"""
video = Video.get_by_id(id_, session)
video = Video.get_by_id(session, id_)
if not video:
raise UnknownVideo(f'Cannot find Video with id {id_}')
return video
def add_tag(self, tag_id_or_name: int | str, session: Session = None) -> TagFile:
session = session or Session.object_session(self)
return self.file_group.add_tag(tag_id_or_name, session=session)
def add_tag(self, session: Session, tag_id_or_name: int | str) -> TagFile:
return self.file_group.add_tag(session, tag_id_or_name)
def untag(self, tag_id_or_name: int | str, session: Session = None):
session = session or Session.object_session(self)
self.file_group.untag(tag_id_or_name, session)
def untag(self, session: Session, tag_id_or_name: int | str):
self.file_group.untag(session, tag_id_or_name)
async def get_ffprobe_json(self) -> dict:
"""Return the ffprobe json object if previously stored.
@ -468,7 +462,7 @@ class Video(ModelHelper, Base):
largest_video = duplicate_videos.pop(largest_video_idx)
# Delete the video at the destination, if it is not the largest.
existing_video = Video.get_by_path(video_path, session=session)
existing_video = Video.get_by_path(session, video_path)
if existing_video and largest_video != existing_video:
delete_video(existing_video)
for idx, video in enumerate(duplicate_videos):
@ -480,7 +474,7 @@ class Video(ModelHelper, Base):
largest_video.file_group.move(video_path)
for tag_name in tag_names:
if tag_name not in largest_video.file_group.tag_names:
largest_video.add_tag(tag_name, session)
largest_video.add_tag(session, tag_name)
logger.warning(f'Deleting duplicate videos: {duplicate_videos}')
@ -660,7 +654,7 @@ class Channel(ModelHelper, Base):
downloads = data.pop('downloads', [])
if tag_name := data.pop('tag_name', None):
self.tag = Tag.find_by_name(tag_name, session)
self.tag = Tag.find_by_name(session, tag_name)
for key, value in data.items():
setattr(self, key, value)
@ -677,7 +671,7 @@ class Channel(ModelHelper, Base):
if isinstance(download, dict):
url = download['url']
# Use download frequency from downloads config before the channels config.
if existing_download := Download.get_by_url(url, session=session):
if existing_download := Download.get_by_url(session, url):
frequency = existing_download.frequency
else:
frequency = download.get('frequency')
@ -691,7 +685,7 @@ class Channel(ModelHelper, Base):
logger.error(f'Refusing to create Download for Channel without frequency: {url}')
continue
download = self.get_or_create_download(url, frequency, session=session, reset_attempts=True)
download = self.get_or_create_download(session, url, frequency, reset_attempts=True)
download.collection_id = self.collection_id
session.add(download)
@ -754,7 +748,7 @@ class Channel(ModelHelper, Base):
logger.error(f'Refusing to create Download for Channel without frequency: {url}')
continue
download_obj = self.get_or_create_download(url, frequency, session=session, reset_attempts=True)
download_obj = self.get_or_create_download(session, url, frequency, reset_attempts=True)
download_obj.collection_id = self.collection_id
session.add(download_obj)
@ -776,29 +770,25 @@ class Channel(ModelHelper, Base):
return config
@classmethod
def from_config(cls, data: dict, session: Session = None) -> 'Channel':
def from_config(cls, session: Session, data: dict) -> 'Channel':
"""
Create or update a Channel from config data. This also creates/updates the Collection.
Args:
data: Config dict containing channel metadata (name, directory, url, source_id, etc.)
session: Database session
data: Config dict containing channel metadata (name, directory, url, source_id, etc.)
Returns:
The created or updated Channel
"""
from wrolpi.collections import Collection
from wrolpi.db import get_db_session
if session is None:
session = get_db_session()
# Ensure this is treated as a channel collection
data = data.copy()
data['kind'] = 'channel'
# Create or update the Collection first
collection = Collection.from_config(data, session=session)
collection = Collection.from_config(session, data)
# Extract Channel-specific fields
url = data.get('url')
@ -823,7 +813,7 @@ class Channel(ModelHelper, Base):
return channel
@staticmethod
def get_by_path(path: pathlib.Path, session: Session) -> Optional['Channel']:
def get_by_path(session: Session, path: pathlib.Path) -> Optional['Channel']:
if not path:
raise RuntimeError('Must provide path to get Channel')
path = pathlib.Path(path) if isinstance(path, str) else path
@ -883,9 +873,9 @@ class Channel(ModelHelper, Base):
# Clear tag.
self.tag = None
elif isinstance(tag_id_or_name, int):
self.tag = Tag.find_by_id(tag_id_or_name, session)
self.tag = Tag.find_by_id(session, tag_id_or_name)
elif isinstance(tag_id_or_name, str):
self.tag = Tag.find_by_name(tag_id_or_name, session)
self.tag = Tag.find_by_name(session, tag_id_or_name)
# Copy the id in case some code needs the id before flush.
self.tag_id = self.tag.id if self.tag else None
return self.tag
@ -916,19 +906,17 @@ class Channel(ModelHelper, Base):
background_task(_())
@staticmethod
@optional_session
def get_by_id(id_: int, session: Session = None) -> Optional['Channel']:
def get_by_id(session: Session, id_: int) -> Optional['Channel']:
"""Attempt to find a Channel with the provided id. Returns None if it cannot be found."""
channel = session.query(Channel).filter_by(id=id_).one_or_none()
return channel
@staticmethod
@optional_session
def find_by_id(id_: int, session: Session = None) -> 'Channel':
def find_by_id(session: Session, id_: int) -> 'Channel':
"""Find a Channel with the provided id, raises an exception when no Channel is found.
@raise UnknownChannel: if the channel can not be found"""
if channel := Channel.get_by_id(id_, session=session):
if channel := Channel.get_by_id(session, id_):
return channel
raise UnknownChannel(f'Cannot find channel with id {id_}')
@ -941,8 +929,7 @@ class Channel(ModelHelper, Base):
elif len(matching_entries) > 1:
raise RuntimeError(f'More than one info_json entry matches {video_source_id}')
@optional_session
def get_or_create_download(self, url: str, frequency: int, session: Session = None,
def get_or_create_download(self, session: Session, url: str, frequency: int,
reset_attempts: bool = False) -> Download:
"""Get a Download record, if it does not exist, create it. Create a Download if necessary
which goes into this Channel's directory.
@ -952,7 +939,7 @@ class Channel(ModelHelper, Base):
from modules.videos.downloader import ChannelDownloader, VideoDownloader
return self.collection.get_or_create_download(
url, frequency, session=session,
session, url, frequency,
reset_attempts=reset_attempts,
downloader_name=ChannelDownloader.name,
sub_downloader_name=VideoDownloader.name
@ -966,8 +953,7 @@ class Channel(ModelHelper, Base):
return f'https://www.youtube.com/feeds/videos.xml?channel_id={self.source_id}'
@staticmethod
@optional_session
def get_by_url(url: str, session: Session = None) -> Optional['Channel']:
def get_by_url(session: Session, url: str) -> Optional['Channel']:
if not url:
raise RuntimeError('Must provide URL to get Channel')
channel = session.query(Channel).filter_by(url=url).one_or_none()

View file

@ -106,7 +106,7 @@ async def test_refresh_videos(async_client, test_session, test_directory, simple
video1_video_path = str(video1.video_path)
video1.poster_path.unlink()
await async_client.post('/api/files/refresh')
video1 = Video.get_by_path(video1_video_path, test_session)
video1 = Video.get_by_path(test_session, video1_video_path)
assert not video1.poster_path
@ -141,9 +141,9 @@ async def test_channels_with_videos(test_session, async_client, test_directory,
assert {i[0] for i in test_session.query(Collection.name).join(Channel).filter(Collection.kind == 'channel')} == {
'channel1', 'channel2'}, 'Channels were changed.'
vid1 = Video.get_by_path(vid1_path)
vid2 = Video.get_by_path(vid2_path)
vid3 = Video.get_by_path(vid3_path)
vid1 = Video.get_by_path(test_session, vid1_path)
vid2 = Video.get_by_path(test_session, vid2_path)
vid3 = Video.get_by_path(test_session, vid3_path)
assert vid1.channel == channel1
assert vid2.channel == channel2
@ -234,13 +234,13 @@ async def test_search_videos(test_session, video_factory, assert_video_search, s
vid3: Video = video_factory(upload_date='2022-09-18', with_video_file=True, title='vid3')
tag1, tag2 = await tag_factory(), await tag_factory()
vid1.add_tag(tag1.id)
vid1.add_tag(test_session, tag1.id)
# vid2 has two tags
vid2.add_tag(tag1.id)
vid2.add_tag(tag2.id)
vid2.add_tag(test_session, tag1.id)
vid2.add_tag(test_session, tag2.id)
vid3.add_tag(tag2.id)
vid3.add_tag(test_session, tag2.id)
test_session.commit()
assert test_session.query(Video).count() == 3

View file

@ -122,8 +122,10 @@ async def test_update_view_count(test_session, channel_factory, video_factory):
# An outdated view count will be overwritten.
vid = test_session.query(Video).filter_by(id=1).one()
vid.view_count = 8
test_session.commit() # Commit so raw SQL in update_view_counts_and_censored doesn't deadlock
check_view_counts({'vid1': 8, 'vid2': 11, 'vid3': 13, 'vid4': 14})
await update_view_counts_and_censored(channel1.id)
test_session.expire_all() # Expire cached values to see raw SQL changes
check_view_counts({'vid1': 10, 'vid2': 11, 'vid3': 13, 'vid4': 14})
@ -192,15 +194,15 @@ async def test_import_channel_downloads(await_switches, test_session, channel_fa
assert next_download == str(download.next_download)
# Creating Download that matches Channel2's URL means they are related. Delete it and it should be re-created.
channel2.get_or_create_download(channel2.url, 60, test_session)
channel2.get_or_create_download(test_session, channel2.url, 60)
save_channels_config()
Download.find_by_url(channel2.url).delete(add_to_skip_list=False)
Download.find_by_url(test_session, channel2.url).delete(add_to_skip_list=False)
test_session.commit()
await await_switches()
# Missing Download is re-created on import.
import_channels_config()
channel2 = Channel.get_by_id(channel2.id)
channel2 = Channel.get_by_id(test_session, channel2.id)
downloads = test_session.query(Download).all()
assert len(downloads) == 1, downloads
assert len(channel1.downloads) == 1
@ -208,8 +210,8 @@ async def test_import_channel_downloads(await_switches, test_session, channel_fa
assert downloads[0].downloader == 'video_channel'
# Add a Download to Channel2 which does not match Channel.url.
channel2.get_or_create_download('https://example.org', 60, session=test_session)
channel2.get_or_create_download('https://example.com/channel2', 60, session=test_session)
channel2.get_or_create_download(test_session, 'https://example.org', 60)
channel2.get_or_create_download(test_session, 'https://example.com/channel2', 60)
test_session.commit()
save_channels_config()
await await_switches()

View file

@ -98,7 +98,7 @@ async def test_download_no_channel(test_session, video_download_manager, test_di
mock_video_extract_info.return_value = info_json
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name)
video_download_manager.create_download(test_session, url, video_downloader.name)
await video_download_manager.wait_for_all_downloads()
mock_video_process_runner.assert_called_once()
@ -119,7 +119,7 @@ async def test_download_video_tags(test_session, video_download_manager, video_f
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
settings = dict(tag_names=[tag1.name, tag2.name])
video_download_manager.create_download(url, video_downloader.name, settings=settings)
video_download_manager.create_download(test_session, url, video_downloader.name, settings=settings)
await video_download_manager.wait_for_all_downloads()
mock_video_process_runner.assert_called_once()
@ -141,7 +141,7 @@ async def test_download_channel(test_session, test_directory, simple_channel, vi
mock_video_extract_info.return_value = example_channel_json
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
simple_channel.get_or_create_download(url, 60, test_session)
simple_channel.get_or_create_download(test_session, url, 60)
# Download channel.
await video_download_manager.wait_for_all_downloads()
# Download videos.
@ -166,7 +166,7 @@ async def test_download_channel(test_session, test_directory, simple_channel, vi
test_session.commit()
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
download = simple_channel.get_or_create_download(url, 60, test_session)
download = simple_channel.get_or_create_download(test_session, url, 60)
download.frequency = 100
download.settings = {'title_include': '2'}
await video_download_manager.wait_for_all_downloads()
@ -184,7 +184,7 @@ async def test_download_channel(test_session, test_directory, simple_channel, vi
test_session.commit()
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
download = simple_channel.get_or_create_download(url, 60, test_session)
download = simple_channel.get_or_create_download(test_session, url, 60)
download.frequency = 100
download.settings = {'title_exclude': '2'}
await video_download_manager.wait_for_all_downloads()
@ -233,30 +233,30 @@ async def test_get_or_create_channel(async_client, test_session, test_directory,
(dict(name='qux'), c4),
]
for kwargs, expected in tests:
channel = get_or_create_channel(**kwargs)
channel = get_or_create_channel(test_session, **kwargs)
assert expected.id == channel.id, f'Expected {expected} for {kwargs} but got {channel}'
# A new channel is created. It will not be automatically downloaded.
channel = get_or_create_channel(source_id='quux', name='quux', url='https://example.org')
channel = get_or_create_channel(test_session, source_id='quux', name='quux', url='https://example.org')
assert channel.id == 5
assert channel.source_id == 'quux'
assert channel.name == 'quux'
assert channel.url == 'https://example.org'
# New channel can be retrieved.
assert get_or_create_channel(source_id='quux') == channel
assert get_or_create_channel(test_session, source_id='quux') == channel
# A Channel can be created with a tag name.
channel = get_or_create_channel(name='One Channel', tag_name=one.name)
channel = get_or_create_channel(test_session, name='One Channel', tag_name=one.name)
await await_switches()
assert channel.directory == test_directory / f'videos/one/One Channel'
assert channel.tag_name == one.name and channel.tag == one
# Getting the same Channel will not change the tag.
channel = get_or_create_channel(name='One Channel', tag_name=two.name)
channel = get_or_create_channel(test_session, name='One Channel', tag_name=two.name)
assert channel.directory == test_directory / f'videos/one/One Channel'
assert channel.tag_name == one.name and channel.tag == one
channel = get_or_create_channel(name='One Channel')
channel = get_or_create_channel(test_session, name='One Channel')
assert channel.directory == test_directory / f'videos/one/One Channel'
assert channel.directory.is_dir()
assert channel.tag_name == one.name and channel.tag == one
@ -275,7 +275,7 @@ def test_bad_downloader(test_session, video_download_manager):
Attempting to use an unknown downloader should raise an error.
"""
with pytest.raises(InvalidDownload):
video_download_manager.create_download('https://example.com', downloader_name='bad downloader')
video_download_manager.create_download(test_session, 'https://example.com', downloader_name='bad downloader')
@pytest.mark.asyncio
@ -303,7 +303,7 @@ async def test_video_download(test_session, test_directory, mock_video_extract_i
mock_video_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name)
video_download_manager.create_download(test_session, url, video_downloader.name)
await video_download_manager.wait_for_all_downloads()
mock_video_process_runner.assert_called_once()
@ -338,7 +338,7 @@ async def test_download_result(test_session, test_directory, video_download_mana
mock_video_extract_info.return_value = example_video_json
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_prepare_filename.return_value = [video_file, {'id': 'foo'}]
video_download_manager.create_download('https://example.com', video_downloader.name)
video_download_manager.create_download(test_session, 'https://example.com', video_downloader.name)
await video_download_manager.wait_for_all_downloads()
# Sleep to allow background tasks to finish.
await asyncio.sleep(1)
@ -362,7 +362,7 @@ async def test_download_destination(test_session, test_directory, video_download
# This result will be ignored during the test, we just need some value so the download does not fail.
mock_video_prepare_filename.return_value = str(test_directory / 'test video.mp4')
video_download_manager.create_download('https://example.com/1', downloader_name=VideoDownloader.name)
video_download_manager.create_download(test_session, 'https://example.com/1', downloader_name=VideoDownloader.name)
await video_download_manager.wait_for_all_downloads()
# Output directory matches the channel directory.
assert mock_video_prepare_filename.call_args_list[0].kwargs['ydl'].params['outtmpl']['default'] \
@ -370,7 +370,7 @@ async def test_download_destination(test_session, test_directory, video_download
mock_video_prepare_filename.reset_mock()
video_download_manager.create_download('https://example.com/2', downloader_name=VideoDownloader.name,
video_download_manager.create_download(test_session, 'https://example.com/2', downloader_name=VideoDownloader.name,
destination=f'{test_directory}/custom')
await video_download_manager.wait_for_all_downloads()
# Output directory matches the custom directory specified.
@ -446,7 +446,8 @@ async def test_download_playlist(test_session, test_directory, mock_video_extrac
"""All videos in a playlist can be downloaded for it's Channel."""
download = Download(url='https://example.com/playlist-url')
test_session.add(download)
channel = get_or_create_channel(example_playlist_json['channel_id'], download.url, example_channel_json['uploader'])
channel = get_or_create_channel(test_session, source_id=example_playlist_json['channel_id'], url=download.url,
name=example_channel_json['uploader'])
video = Video.from_paths(test_session, video_file)
video.channel_id = channel.id
video.source_id = 'video 1 id'
@ -577,7 +578,7 @@ async def test_video_download_cookies(test_session, test_directory, mock_video_e
mock_video_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name, settings=settings)
video_download_manager.create_download(test_session, url, video_downloader.name, settings=settings)
await video_download_manager.wait_for_all_downloads()
download, cmd, out_dir = mock_video_process_runner.call_args[0]
@ -604,7 +605,7 @@ async def test_video_download_always_use_cookies(test_session, test_directory, m
mock_video_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name)
video_download_manager.create_download(test_session, url, video_downloader.name)
await video_download_manager.wait_for_all_downloads()
download, cmd, out_dir = mock_video_process_runner.call_args[0]

View file

@ -73,7 +73,7 @@ async def test_video_factory(test_session, video_factory, channel_factory):
assert video.source_id == 'some id'
def test_validate_video(test_directory, video_factory, image_bytes_factory, video_file):
def test_validate_video(test_session, test_directory, video_factory, image_bytes_factory, video_file):
"""A video poster will be generated only if the channel permits."""
video_file = video_file.rename(test_directory / 'Channel Name_20050607_1234567890_The Title.mp4')
vid1 = video_factory(with_video_file=video_file, with_info_json=True)
@ -81,7 +81,7 @@ def test_validate_video(test_directory, video_factory, image_bytes_factory, vide
vid1.source_id = None
assert not vid1.poster_path
validate_video(vid1, True)
validate_video(test_session, vid1, True)
assert vid1.video_path == video_file
assert vid1.poster_path, 'Poster was not created'
assert vid1.poster_path.is_file(), 'Poster path does not exist'
@ -108,7 +108,7 @@ def test_validate_video(test_directory, video_factory, image_bytes_factory, vide
'view_count': 406
}
vid1.replace_info_json(info_json)
validate_video(vid1, False)
validate_video(test_session, vid1, False)
assert vid1.file_group.published_datetime and vid1.file_group.published_datetime.year == 2024
assert vid1.file_group.title == 'The full title'
@ -116,7 +116,7 @@ def test_validate_video(test_directory, video_factory, image_bytes_factory, vide
vid2 = video_factory(with_video_file=True, with_poster_ext='.png')
assert vid2.poster_path and vid2.poster_path.suffix == '.png', 'Poster was not initialized'
assert {i.suffix for i in vid2.file_group.my_paths()} == {'.png', '.mp4'}
validate_video(vid2, True)
validate_video(test_session, vid2, True)
assert vid2.poster_path.is_file(), 'New poster was not generated'
assert vid2.poster_path.suffix == '.jpg' and vid2.poster_path.stat().st_size > 0
assert {i.suffix for i in vid2.file_group.my_paths()} == {'.jpg', '.png', '.mp4'}
@ -194,7 +194,7 @@ def test_link_channel_and_downloads(test_session, channel_factory, test_download
assert not any(i.collection_id for i in test_download_manager.get_downloads(test_session))
# `link_channel_and_downloads` links Downloads to Collections.
lib.link_channel_and_downloads(session=test_session)
lib.link_channel_and_downloads(test_session)
assert test_session.query(Download).count() == 3
assert all(i.collection_id for i in test_download_manager.get_recurring_downloads(test_session))
assert not any(i.collection_id for i in test_download_manager.get_once_downloads(test_session))

View file

@ -34,7 +34,7 @@ async def test_delete_video_with_tag(async_client, test_session, video_factory,
"""You cannot delete a video with a tag."""
video = video_factory(with_video_file=True, with_poster_ext='png')
tag = await tag_factory()
video.add_tag(tag.name)
video.add_tag(test_session, tag.name)
test_session.commit()
with pytest.raises(FileGroupIsTagged):
@ -66,8 +66,8 @@ async def test_video_channel_refresh(async_client, test_session, test_directory,
assert test_session.query(Video).count() == 2
# The video is associated with `simple_channel` because its file is in the Channel's directory.
video1: Video = Video.get_by_path(video1_path, test_session)
video2: Video = Video.get_by_path(video2_path, test_session)
video1: Video = Video.get_by_path(test_session, video1_path)
video2: Video = Video.get_by_path(test_session, video2_path)
assert video1.channel == channel
assert not video2.channel
assert video1.__json__()['video']['channel']

View file

@ -78,13 +78,14 @@ async def search_videos(_: Request, body: schema.VideoSearchRequest):
@openapi.response(HTTPStatus.NO_CONTENT)
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
async def video_delete(_: Request, video_ids: str):
async def video_delete(request: Request, video_ids: str):
try:
video_ids = [int(i) for i in str(video_ids).split(',')]
except Exception:
raise ValidationError('Unable to parse video ids')
lib.delete_videos(*video_ids)
session = request.ctx.session
lib.delete_videos(session, *video_ids)
save_channels_config.activate_switch()
Events.send_deleted(f'Deleted {len(video_ids)} videos')

View file

@ -10,7 +10,7 @@ from sqlalchemy.orm import Session
from modules.videos.models import Video, Channel
from wrolpi.common import logger, limit_concurrent, wrol_mode_check
from wrolpi.dates import now
from wrolpi.db import get_db_session, optional_session
from wrolpi.db import get_db_session
from wrolpi.downloader import download_manager
from wrolpi.files.lib import handle_file_group_search_results
from wrolpi.files.models import FileGroup
@ -26,7 +26,7 @@ def get_video_for_app(video_id: int) -> Tuple[dict, Optional[dict], Optional[dic
Get a Video, with it's prev/next videos. Mark the Video as viewed.
"""
with get_db_session(commit=True) as session:
video = Video.find_by_id(video_id, session=session)
video = Video.find_by_id(session, video_id)
video.file_group.set_viewed()
previous_video, next_video = video.get_surrounding_videos()
@ -42,7 +42,7 @@ def get_video(video_id: int) -> Video:
Get a Video, with it's prev/next videos. Mark the Video as viewed.
"""
with get_db_session() as session:
video = Video.find_by_id(video_id, session=session)
video = Video.find_by_id(session, video_id)
return video
@ -159,8 +159,7 @@ def search_videos(
return results, total
@optional_session
def delete_videos(*video_ids: int, session: Session = None):
def delete_videos(session: Session, *video_ids: int):
videos = list(session.query(Video).filter(Video.id.in_(video_ids)))
if not videos:
raise UnknownVideo('Could not find videos to delete')

View file

@ -8,7 +8,6 @@ from sanic_ext.extensions.openapi import openapi
from wrolpi import lang
from wrolpi.api_utils import json_response
from wrolpi.common import logger
from wrolpi.db import get_db_session
from wrolpi.downloader import download_manager
from wrolpi.events import Events
from . import lib, schema
@ -24,12 +23,12 @@ logger = logger.getChild(__name__)
summary='List all known Zim files',
response=schema.GetZimsResponse,
)
async def get_zims(_: Request):
with get_db_session() as session:
zims = lib.get_zims(session=session)
resp = {
'zims': [i.__json__() for i in zims],
}
async def get_zims(request: Request):
session = request.ctx.session
zims = lib.get_zims(session)
resp = {
'zims': [i.__json__() for i in zims],
}
return json_response(resp)
@ -37,9 +36,11 @@ async def get_zims(_: Request):
@openapi.definition(
summary='Delete all Zim files',
)
async def delete_zims(_: Request, zim_ids: str):
async def delete_zims(request: Request, zim_ids: str):
session = request.ctx.session
zim_ids = [int(i) for i in zim_ids.split(',')]
lib.delete_zims(zim_ids)
lib.delete_zims(session, zim_ids)
return response.empty()
@ -49,9 +50,10 @@ async def delete_zims(_: Request, zim_ids: str):
body=schema.ZimAutoSearchRequest,
)
@validate(schema.ZimAutoSearchRequest)
async def post_set_zim_auto_search(_: Request, zim_id: int, body: schema.ZimAutoSearchRequest):
async def post_set_zim_auto_search(request: Request, zim_id: int, body: schema.ZimAutoSearchRequest):
session = request.ctx.session
zim_id = int(zim_id)
lib.set_zim_auto_search(zim_id, body.auto_search)
lib.set_zim_auto_search(session, zim_id, body.auto_search)
return response.empty()
@ -62,8 +64,9 @@ async def post_set_zim_auto_search(_: Request, zim_id: int, body: schema.ZimAuto
response=schema.ZimSearchResponse,
)
@validate(schema.ZimSearchRequest)
async def search_zim(_: Request, zim_id: int, body: schema.ZimSearchRequest):
headlines = lib.headline_zim(body.search_str, zim_id, tag_names=body.tag_names, offset=body.offset,
async def search_zim(request: Request, zim_id: int, body: schema.ZimSearchRequest):
session = request.ctx.session
headlines = lib.headline_zim(session, body.search_str, zim_id, tag_names=body.tag_names, offset=body.offset,
limit=body.limit)
return json_response({'zim': headlines})
@ -92,8 +95,10 @@ async def get_zim_entry(_: Request, zim_id: int, zim_path: str):
body=schema.TagZimEntry,
)
@validate(schema.TagZimEntry)
async def post_zim_tag(_: Request, body: schema.TagZimEntry):
await lib.add_tag(body.tag_name, body.zim_id, body.zim_entry)
async def post_zim_tag(request: Request, body: schema.TagZimEntry):
session = request.ctx.session
await lib.add_tag(session, body.tag_name, body.zim_id, body.zim_entry)
return response.empty(HTTPStatus.CREATED)
@ -103,8 +108,10 @@ async def post_zim_tag(_: Request, body: schema.TagZimEntry):
body=schema.TagZimEntry,
)
@validate(schema.TagZimEntry)
async def post_zim_untag(_: Request, body: schema.TagZimEntry):
await lib.untag(body.tag_name, body.zim_id, body.zim_entry)
async def post_zim_untag(request: Request, body: schema.TagZimEntry):
session = request.ctx.session
await lib.untag(session, body.tag_name, body.zim_id, body.zim_entry)
return response.empty(HTTPStatus.NO_CONTENT)
@ -113,10 +120,10 @@ async def post_zim_untag(_: Request, body: schema.TagZimEntry):
summary='Retrieve Zim subscriptions',
response=schema.ZimSubscriptions,
)
async def get_zim_subscriptions(_: Request):
async def get_zim_subscriptions(request: Request):
catalog = lib.get_kiwix_catalog()
with get_db_session() as session:
subscriptions = {i: j.__json__() for i, j in lib.get_kiwix_subscriptions(session).items()}
session = request.ctx.session
subscriptions = {i: j.__json__() for i, j in lib.get_kiwix_subscriptions(session).items()}
resp = dict(
catalog=catalog,
iso_639_codes=lang.ISO_639_CODES,
@ -131,8 +138,10 @@ async def get_zim_subscriptions(_: Request):
body=schema.ZimSubscribeRequest,
)
@validate(schema.ZimSubscribeRequest)
async def post_zim_subscribe(_: Request, body: schema.ZimSubscribeRequest):
await lib.subscribe(body.name, body.language)
async def post_zim_subscribe(request: Request, body: schema.ZimSubscribeRequest):
session = request.ctx.session
await lib.subscribe(session, body.name, body.language)
if download_manager.disabled or download_manager.stopped:
# Downloads are disabled, warn the user.
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
@ -144,8 +153,10 @@ async def post_zim_subscribe(_: Request, body: schema.ZimSubscribeRequest):
@openapi.definition(
summary='Unsubscribe to a particular Kiwix Zim',
)
async def delete_zim_subscription(_: Request, subscription_id: int):
await lib.unsubscribe(subscription_id)
async def delete_zim_subscription(request: Request, subscription_id: int):
session = request.ctx.session
await lib.unsubscribe(session, subscription_id)
Events.send_deleted(f'Zim subscription deleted')
return response.empty(HTTPStatus.NO_CONTENT)
@ -175,16 +186,18 @@ async def delete_outdated_zims(_: Request):
@zim_bp.post('/search_estimates')
@validate(json=schema.SearchEstimateRequest)
async def post_search_estimates(_: Request, body: schema.SearchEstimateRequest):
async def post_search_estimates(request: Request, body: schema.SearchEstimateRequest):
"""Get an estimated count of FileGroups/Zims which may or may not have been tagged."""
if not body.search_str and not body.tag_names:
return response.empty(HTTPStatus.BAD_REQUEST)
session = request.ctx.session
if body.tag_names:
# Get actual count of entries tagged with the tag names.
zims_estimates = list()
for zim, count in Zims.entries_with_tags(body.tag_names).items():
for zim, count in Zims.entries_with_tags(session, body.tag_names).items():
d = dict(
estimate=count,
**zim.__json__(),
@ -193,7 +206,7 @@ async def post_search_estimates(_: Request, body: schema.SearchEstimateRequest):
else:
# Get estimates using libzim.
zims_estimates = list()
for zim, estimate in Zims.estimate(body.search_str).items():
for zim, estimate in Zims.estimate(session, body.search_str).items():
d = dict(
estimate=estimate,
**zim.__json__(),

View file

@ -18,7 +18,7 @@ from wrolpi import flags
from wrolpi.cmd import run_command
from wrolpi.common import register_modeler, logger, extract_html_text, extract_headlines, get_media_directory, walk, \
register_refresh_cleanup, background_task, get_wrolpi_config, unique_by_predicate
from wrolpi.db import get_db_session, optional_session, get_db_curs
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.downloader import DownloadFrequency
from wrolpi.files.lib import refresh_files, split_file_name_words
from wrolpi.files.models import FileGroup
@ -148,15 +148,14 @@ def get_unique_paths(*paths: str) -> List[str]:
return list(unique_paths)
@optional_session
def headline_zim(search_str: str, zim_id: int, tag_names: List[str] = None, offset: int = 0, limit: int = 10,
session: Session = None) -> Dict:
def headline_zim(session: Session, search_str: str, zim_id: int, tag_names: List[str] = None, offset: int = 0,
limit: int = 10) -> Dict:
zim_id = int(zim_id)
zim = get_zim(zim_id, session=session)
zim = get_zim(session, zim_id)
if tag_names:
# TODO what is the count goes over the limit?
entries = zim.entries_with_tags(tag_names, offset=offset, limit=1_000, session=session)
entries = zim.entries_with_tags(session, tag_names, offset=offset, limit=1_000)
estimate = 0
elif search_str:
# Get suggested results (this searches titles).
@ -232,8 +231,7 @@ def get_estimates(search_str: str) -> List[int]:
return estimates
@optional_session
def get_zim(zim_id: int, session: Session = None) -> Zim:
def get_zim(session: Session, zim_id: int) -> Zim:
"""Return the Zim record of the provided path.
@raise UnknownZim: When no record exists with the id.
@ -251,40 +249,36 @@ def get_zim(zim_id: int, session: Session = None) -> Zim:
@functools.lru_cache(maxsize=1_000)
def get_entry(path: str, zim_id: int) -> Entry:
with get_db_session() as session:
zim = get_zim(zim_id, session=session)
zim = get_zim(session, zim_id)
entry = zim.find_entry(path)
return entry
@optional_session
def get_zims(ids: List[int] = None, session: Session = None) -> List[Zim]:
def get_zims(session: Session, ids: List[int] = None) -> List[Zim]:
if ids:
zims = session.query(Zim).filter(Zim.id.in_(ids)).all()
else:
zims = Zims.get_all(session=session)
zims = Zims.get_all(session)
return zims
@optional_session(commit=True)
def delete_zims(ids: List[int], session: Session = None):
zims = get_zims(ids, session=session)
def delete_zims(session: Session, ids: List[int]):
zims = get_zims(session, ids)
for zim in zims:
zim.delete()
@optional_session
async def add_tag(tag_name: str, zim_id: int, zim_entry: str, session: Session = None) -> TagZimEntry:
async def add_tag(session: Session, tag_name: str, zim_id: int, zim_entry: str) -> TagZimEntry:
zim = session.query(Zim).filter_by(id=zim_id).one()
tag_zim_entry = zim.tag_entry(tag_name, zim_entry)
tag_zim_entry = zim.tag_entry(session, tag_name, zim_entry)
session.commit()
return tag_zim_entry
@optional_session
async def untag(tag_name: str, zim_id: int, zim_entry: str, session: Session = None):
async def untag(session: Session, tag_name: str, zim_id: int, zim_entry: str):
zim: Zim = session.query(Zim).filter_by(id=zim_id).one()
zim.untag_entry(tag_name, zim_entry)
zim.untag_entry(session, tag_name, zim_entry)
session.commit()
@ -292,17 +286,15 @@ def get_kiwix_catalog():
return KIWIX_CATALOG.copy()
@optional_session
def get_kiwix_subscriptions(session: Session = None) -> Dict[str, ZimSubscription]:
def get_kiwix_subscriptions(session: Session) -> Dict[str, ZimSubscription]:
subscriptions = session.query(ZimSubscription)
subscriptions_by_name = {i.name: i for i in subscriptions}
return subscriptions_by_name
@optional_session(commit=True)
async def subscribe(name: str, language: str, session: Session = None,
async def subscribe(session: Session, name: str, language: str,
frequency: int = DownloadFrequency.days180) -> ZimSubscription:
subscription = ZimSubscription.get_or_create(name, session=session)
subscription = ZimSubscription.get_or_create(session, name)
subscription.language = language
if name == 'Wikipedia (with images)':
@ -378,15 +370,14 @@ async def subscribe(name: str, language: str, session: Session = None,
if language not in kiwix.KIWIX_CATALOG_BY_NAME[name]['languages']:
raise ValueError(f'Language {repr(str(language))} is invalid for {name}')
subscription.change_download(url, frequency, session=session)
subscription.change_download(session, url, frequency)
session.add(subscription)
session.flush([subscription])
session.commit()
return subscription
@optional_session
async def unsubscribe(subscription_id: int, session: Session = None):
async def unsubscribe(session: Session, subscription_id: int):
subscription: ZimSubscription = session.query(ZimSubscription).filter_by(id=subscription_id).one_or_none()
if subscription:
session.delete(subscription)
@ -596,8 +587,7 @@ async def restart_kiwix():
return result.return_code
@optional_session
def set_zim_auto_search(zim_id: int, auto_search: bool, session: Session = None):
zim = Zim.find_by_id(zim_id, session)
def set_zim_auto_search(session: Session, zim_id: int, auto_search: bool):
zim = Zim.find_by_id(session, zim_id)
zim.auto_search = auto_search
session.commit()

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 optional_session, get_db_curs
from wrolpi.db import get_db_curs
from wrolpi.downloader import Download, download_manager
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
@ -100,31 +100,27 @@ class Zim(Base, ModelHelper):
return zim
@staticmethod
@optional_session
def get_by_path(path: pathlib.Path, session: Session = None) -> Optional['Zim']:
def get_by_path(session: Session, path: pathlib.Path) -> Optional['Zim']:
zim = session.query(Zim).filter_by(path=path).one_or_none()
return zim
@staticmethod
@optional_session
def find_by_path(path: pathlib.Path, session: Session = None) -> 'Zim':
zim = Zim.get_by_path(path, session=session)
def find_by_path(session: Session, path: pathlib.Path) -> 'Zim':
zim = Zim.get_by_path(session, path)
if not zim:
raise UnknownZim(f'Cannot find zim at path')
return zim
@staticmethod
@optional_session
def get_by_id(zim_id: int, session: Session = None) -> Optional['Zim']:
zim = session.query(Zim).filter_by(id=zim_id).one_or_none()
def get_by_id(session: Session, id_: int) -> Optional['Zim']:
zim = session.query(Zim).filter_by(id=id_).one_or_none()
return zim
@staticmethod
@optional_session
def find_by_id(zim_id: int, session: Session = None) -> 'Zim':
zim = Zim.get_by_id(zim_id, session=session)
def find_by_id(session: Session, id_: int) -> 'Zim':
zim = Zim.get_by_id(session, id_)
if not zim:
raise UnknownZim(f'Cannot find zim with ID {zim_id}')
raise UnknownZim(f'Cannot find zim with ID {id_}')
return zim
def get_zim(self) -> Archive:
@ -149,7 +145,7 @@ class Zim(Base, ModelHelper):
return False
@staticmethod
def do_model(file_group: FileGroup, session: Session) -> 'Zim':
def do_model(session: Session, file_group: FileGroup) -> 'Zim':
from modules.zim.lib import model_zim
zim = model_zim(file_group, session)
return zim
@ -226,26 +222,23 @@ class Zim(Base, ModelHelper):
raise UnknownZimEntry(f'Cannot find entry at {path=}')
def tag_entry(self, tag_id_or_name: int | str, zim_entry: str) -> 'TagZimEntry':
def tag_entry(self, session: Session, tag_id_or_name: int | str, zim_entry: str) -> 'TagZimEntry':
"""Create a TagZimEntry for this Zim at the provided entry (path) for the provided Tag."""
session = Session.object_session(self)
# Ensure the entry exists.
self.find_entry(zim_entry)
tag = Tag.get_by_name(tag_id_or_name, session) if isinstance(tag_id_or_name, str) \
tag = Tag.get_by_name(session, tag_id_or_name) if isinstance(tag_id_or_name, str) \
else Tag.get_by_id(tag_id_or_name, session)
tag_zim_entry = TagZimEntry(tag=tag, zim=self, zim_entry=zim_entry)
session.add(tag_zim_entry)
tags.save_tags_config.activate_switch()
return tag_zim_entry
def untag_entry(self, tag_id_or_name: int | str, zim_entry: str):
def untag_entry(self, session: Session, tag_id_or_name: int | str, zim_entry: str):
"""Removes any TagZimEntry of the Zim entry at the provided path for the provided Tag.
@raise UnknownZimTagEntry: No entry exists to remove."""
session = Session.object_session(self)
tag = Tag.get_by_name(tag_id_or_name, session) if isinstance(tag_id_or_name, str) \
tag = Tag.get_by_name(session, tag_id_or_name) if isinstance(tag_id_or_name, str) \
else Tag.get_by_id(tag_id_or_name, session)
tag_zim_entry = TagZimEntry.get_by_primary_keys(tag.id, self.id, zim_entry, session)
if tag_zim_entry:
@ -274,23 +267,23 @@ class Zim(Base, ModelHelper):
return entries
@optional_session
def entries_with_tags(*args, session: Session = None, **kwargs) -> List[Entry]:
def entries_with_tags(self, session: Session, tag_names: List[str], limit: int = 10, offset: int = 0) -> List[
Entry]:
"""Return Zim Entries tagged with the provided names."""
limit = int(kwargs.pop('limit', 10))
offset = int(kwargs.pop('offset', 0))
args = list(args)
zim: Zim | None = args.pop(0) if isinstance(args[0], Zim) else None
zim_id = zim.id if zim else None
tag_names: List[str] = args.pop(0)
if limit < 1:
raise RuntimeError('Limit must be greater than zero')
if args:
raise RuntimeError('Extra unknown arguments')
tags_sub_select, params = tag_names_to_zim_sub_select(tag_names, zim_id=zim_id)
tags_sub_select, params = tag_names_to_zim_sub_select(tag_names, zim_id=self.id)
entries = Zim._entries_with_tags_process(limit, offset, params, session, tags_sub_select)
return entries
@staticmethod
def all_entries_with_tags(session: Session, tag_names: List[str], limit: int = 10, offset: int = 0) -> List[Entry]:
"""Return Zim Entries tagged with the provided names from ALL Zims."""
if limit < 1:
raise RuntimeError('Limit must be greater than zero')
tags_sub_select, params = tag_names_to_zim_sub_select(tag_names, zim_id=None)
entries = Zim._entries_with_tags_process(limit, offset, params, session, tags_sub_select)
return entries
@ -321,8 +314,7 @@ class Zims:
"""Convenience class which searches all known Zim files."""
@staticmethod
@optional_session
def get_all(session: Session = None) -> List[Zim]:
def get_all(session: Session) -> List[Zim]:
"""Returns all Zim records."""
zims = list()
for zim in session.query(Zim).order_by(Zim.path):
@ -335,9 +327,8 @@ class Zims:
return zims
@classmethod
@optional_session
def estimate(cls, search_str: str, session: Session = None) -> OrderedDictType[Zim, int]:
zims = cls.get_all(session=session)
def estimate(cls, session: Session, search_str: str) -> OrderedDictType[Zim, int]:
zims = cls.get_all(session)
results = OrderedDict()
for zim in zims:
if zim.auto_search:
@ -345,12 +336,11 @@ class Zims:
return results
@classmethod
@optional_session
def entries_with_tags(cls, tag_names: List[str], session: Session = None) -> OrderedDictType[Zim, int]:
zims = cls.get_all(session=session)
def entries_with_tags(cls, session: Session, tag_names: List[str]) -> OrderedDictType[Zim, int]:
zims = cls.get_all(session)
results = OrderedDict()
for zim in zims:
results[zim] = len(zim.entries_with_tags(tag_names, session=session))
results[zim] = len(zim.entries_with_tags(session, tag_names))
return results
@ -408,10 +398,10 @@ class ZimSubscription(Base):
)
return d
def change_download(self, url: str, frequency: int, session: Session):
def change_download(self, session: Session, url: str, frequency: int):
# A Zim file is found using the KiwixCatalogDownloader, then handled by the KiwixZimDownloader.
old_url = self.download.url if self.download else url
download = download_manager.get_or_create_download(old_url, session=session, reset_attempts=True)
download = download_manager.get_or_create_download(session, old_url, reset_attempts=True)
download.url = url
download.frequency = frequency
download.downloader = 'kiwix_catalog'
@ -423,8 +413,7 @@ class ZimSubscription(Base):
return download
@staticmethod
@optional_session
def get_or_create(name: str, session: Session = None) -> 'ZimSubscription':
def get_or_create(session: Session, name: str) -> 'ZimSubscription':
subscription = session.query(ZimSubscription).filter_by(name=name).one_or_none()
if subscription:
return subscription

View file

@ -12,9 +12,9 @@ from wrolpi.downloader import Download
async def test_zim_search(async_client, test_session, test_zim, tag_factory, assert_zim_search):
"""Entries can be tagged and retrieved using their containing Zim."""
tag1, tag2 = await tag_factory(), await tag_factory()
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
test_zim.tag_entry(test_session, tag1.name, 'one')
test_zim.tag_entry(test_session, tag2.name, 'one')
test_zim.tag_entry(test_session, tag1.name, 'two')
test_session.commit()
# Test searching with only `search_str`.
@ -83,18 +83,18 @@ async def test_zim_search(async_client, test_session, test_zim, tag_factory, ass
async def test_entries_by_tag(async_client, test_session, test_zim, tag_factory):
"""Entries can be tagged and retrieved using their containing Zim."""
tag1, tag2 = await tag_factory(), await tag_factory()
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
test_zim.tag_entry(test_session, tag1.name, 'one')
test_zim.tag_entry(test_session, tag2.name, 'one')
test_zim.tag_entry(test_session, tag1.name, 'two')
test_session.commit()
result = test_zim.entries_with_tags([tag1.name, tag2.name])
result = test_zim.entries_with_tags(test_session, [tag1.name, tag2.name])
assert [(i.path, i.title) for i in result] == [('one', 'One'), ]
result = test_zim.entries_with_tags([tag1.name, ])
result = test_zim.entries_with_tags(test_session, [tag1.name, ])
assert [(i.path, i.title) for i in result] == [('one', 'One'), ('two', 'Two')]
result = test_zim.entries_with_tags([tag2.name, ])
result = test_zim.entries_with_tags(test_session, [tag2.name, ])
assert [(i.path, i.title) for i in result] == [('one', 'One'), ]

View file

@ -20,10 +20,10 @@ async def test_get_zim(async_client, test_session, zim_path_factory):
zim_path_factory()
await files_lib.refresh_files()
assert lib.get_zim(1)
assert lib.get_zim(test_session, 1)
with pytest.raises(UnknownZim):
assert lib.get_zim(2)
assert lib.get_zim(test_session, 2)
@pytest.mark.asyncio
@ -54,15 +54,15 @@ async def test_zim_get_entry(async_client, test_session, zim_path_factory):
async def test_zim_bad_entry(async_client, test_session, test_zim, tag_factory):
tag1 = await tag_factory()
with pytest.raises(UnknownZimEntry):
test_zim.tag_entry(tag1.name, 'path does not exist')
test_zim.tag_entry(test_session, tag1.name, 'path does not exist')
@pytest.mark.asyncio
async def test_zim_get_entries_tags(async_client, test_session, test_zim, tag_factory):
tag1, tag2 = await tag_factory('tag1'), await tag_factory('tag2')
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
test_zim.tag_entry(test_session, tag1.name, 'one')
test_zim.tag_entry(test_session, tag2.name, 'one')
test_zim.tag_entry(test_session, tag1.name, 'two')
test_session.commit()
assert lib.get_entries_tags(['one', 'two', 'home'], 1) \
@ -72,7 +72,7 @@ async def test_zim_get_entries_tags(async_client, test_session, test_zim, tag_fa
@pytest.mark.asyncio
async def test_tag_zim_entry_model(async_client, test_session, zim_factory, tag_factory):
tag = await tag_factory()
tze = zim_factory('zim1').tag_entry(tag.name, 'one')
tze = zim_factory('zim1').tag_entry(test_session, tag.name, 'one')
# Test TagZimEntry.__repr__
assert repr(tze) == "<TagZimEntry tag='one' zim=zim1 zim_entry=one>"
@ -83,21 +83,21 @@ async def test_zim_entries_with_tags(async_client, test_session, zim_factory, ta
tag1, tag2 = await tag_factory(), await tag_factory()
zim1, zim2 = zim_factory('zim1'), zim_factory('zim2')
# Tag Zim1 with both tags, but Zim2 shares one of the tags and is returned when no Zim is passed.
zim1.tag_entry(tag1.name, 'one')
zim1.tag_entry(tag2.name, 'two')
zim2.tag_entry(tag2.name, 'home')
zim1.tag_entry(test_session, tag1.name, 'one')
zim1.tag_entry(test_session, tag2.name, 'two')
zim2.tag_entry(test_session, tag2.name, 'home')
test_session.commit()
# Get entries from zim1 only.
entries = zim1.entries_with_tags([tag1.name, ])
entries = zim1.entries_with_tags(test_session, [tag1.name, ])
assert len(entries) == 1
assert entries[0].path == 'one'
entries = zim1.entries_with_tags([tag2.name, ])
entries = zim1.entries_with_tags(test_session, [tag2.name, ])
assert len(entries) == 1
assert entries[0].path == 'two'
# Get entries from any Zim.
entries = lib.Zim.entries_with_tags([tag2.name, ])
entries = lib.Zim.all_entries_with_tags(test_session, [tag2.name, ])
assert {i.path for i in entries} == {'two', 'home'}, 'Tag2 was applied to `two` and `home`'
@ -135,9 +135,9 @@ async def test_zim_tags_config(async_client, test_session, test_directory, test_
# Tag three Zim entries.
tag1, tag2 = await tag_factory('Tag1'), await tag_factory('Tag2')
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
test_zim.tag_entry(test_session, tag1.name, 'one')
test_zim.tag_entry(test_session, tag2.name, 'one')
test_zim.tag_entry(test_session, tag1.name, 'two')
test_session.commit()
await await_switches()
# Tags are created in empty database.
@ -151,7 +151,7 @@ async def test_zim_tags_config(async_client, test_session, test_directory, test_
]
# Remove a tag, the config should change.
test_zim.untag_entry(tag1.name, 'one')
test_zim.untag_entry(test_session, tag1.name, 'one')
test_session.commit()
await await_switches()
@ -186,7 +186,7 @@ def test_zim_all_entries(test_session, test_zim):
@pytest.mark.asyncio
async def test_zim_download(test_session, kiwix_download_zim, test_directory, test_zim_bytes, flags_lock,
await_switches):
await lib.subscribe('Wikipedia (with images)', 'es')
await lib.subscribe(test_session, 'Wikipedia (with images)', 'es')
# Downloading the catalog should lead to a new Zim file being downloaded.
await kiwix_download_zim(expected_url='https://download.kiwix.org/zim/wikipedia/wikipedia_es_all_maxi_2023-06.zim')
@ -264,12 +264,12 @@ async def test_zim_tag_migration(await_switches, test_session, test_directory, z
zim3 = zim_factory('wikipedia_en_all_maxi_2020-03.zim') # The latest Zim.
tag1, tag2 = await tag_factory('tag1'), await tag_factory('tag2')
# Tag outdated Zim entries.
zim1.tag_entry(tag1.name, 'home')
zim1.tag_entry(tag2.name, 'one')
zim1.tag_entry(test_session, tag1.name, 'home')
zim1.tag_entry(test_session, tag2.name, 'one')
# This should not be migrated.
zim2.tag_entry(tag2.name, 'two')
zim2.tag_entry(test_session, tag2.name, 'two')
# Tag the latest Zim as well.
zim3.tag_entry(tag2.name, 'one')
zim3.tag_entry(test_session, tag2.name, 'one')
test_session.commit()
assert test_session.query(TagZimEntry).count() == 4
await await_switches()
@ -358,7 +358,7 @@ def test_zim_download_url_to_name(url, expected):
@pytest.mark.asyncio
async def test_zim_subscription_download_import(async_client, test_session):
# Subscription creates a ZimSubscription and Download
await lib.subscribe('Wikisource', 'en', session=test_session)
await lib.subscribe(test_session, 'Wikisource', 'en')
# Add a once-download. This should not be associated with a ZimSubscription.
test_session.add(
Download(url='https://download.kiwix.org/zim/wikibooks/wikibooks_en_all_maxi_2021-03.zim', status='complete'))
@ -376,7 +376,7 @@ async def test_zim_subscription_download_import(async_client, test_session):
for _ in range(1): # Import twice.
# Importing the config restores the Download and ZimSubscription.
await import_downloads_config(session=test_session)
await import_downloads_config(test_session)
recurring, once = test_session.query(Download).order_by(Download.frequency)
assert once.url == 'https://download.kiwix.org/zim/wikibooks/wikibooks_en_all_maxi_2021-03.zim'
assert test_session.query(Download).count() == 2
@ -404,7 +404,7 @@ async def test_zim_modeler(async_client, test_session, zim_factory):
assert fg.model == 'zim'
def test_get_custom_zims_directory(test_directory, test_wrolpi_config):
def test_get_custom_zims_directory(async_client, test_directory, test_wrolpi_config):
"""Custom directory can be used for zims directory."""
assert lib.get_zim_directory() == (test_directory / 'zims')