Stopping renderd when reseting map db.

Skipping channel import during test unless explicitly requested.

Deleting gis database during upgrade, if user agrees.  Increasing API verbosity.

Using status context to prevent fetching status in useHotspot.

Disabling wifi toggle button when pending.

Toggling hotspot when clicking nav hotspot icon.

Displaying Hotspot status icon in nav menu.

Importing channels/favorites after refreshing.

Refresh tasks cancel when server shuts down.

Bumping version for release speed.

Refreshing files is 3x faster.

Creating useRecurringTimeout hook which repeatedly calls a callback after a timeout.

Changing intervals to timeout so fetches don't stack up while server is loaded.

Checking that video file exists before fetching.

Creating release candidate branch.  Not indexing model associated files.
This commit is contained in:
Roland 2022-10-19 09:18:53 -06:00
parent dbdcc7a57c
commit 6fa6be50fe
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
32 changed files with 878 additions and 358 deletions

View file

@ -1,4 +1,3 @@
import itertools
import json
import pathlib
from abc import ABC
@ -63,10 +62,10 @@ def archive_modeler(groups: Dict[str, List[File]], session: Session):
if any(lib.is_singlefile_file(i.path) for i in group):
archive_groups[stem] = group
count = itertools.cycle(range(101))
for stem, group in archive_groups.items():
readability_file, singlefile_file, readability_json_file, readability_txt_file, screenshot_file = \
match_archive_files(group)
archive: Archive = Archive.find_by_path(singlefile_file.path, session)
if not archive:
archive = Archive(singlefile_file=singlefile_file)
@ -78,16 +77,16 @@ def archive_modeler(groups: Dict[str, List[File]], session: Session):
if archive.readability_file:
archive.readability_file.associated = True
archive.readability_file.do_index()
archive.readability_file.do_stats()
if archive.readability_json_file:
archive.readability_json_file.associated = True
archive.readability_json_file.do_index()
archive.readability_json_file.do_stats()
if archive.readability_txt_file:
archive.readability_txt_file.associated = True
archive.readability_txt_file.do_index()
archive.readability_txt_file.do_stats()
if archive.screenshot_file:
archive.screenshot_file.associated = True
archive.screenshot_file.do_index()
archive.screenshot_file.do_stats()
archive.singlefile_file.model = Archive.__tablename__
@ -97,10 +96,6 @@ def archive_modeler(groups: Dict[str, List[File]], session: Session):
# Remove this group, it will not be processed by other modelers.
del groups[stem]
if next(count) == 100:
# Commit occasionally.
session.commit()
@register_after_refresh
@limit_concurrent(1)
@ -130,15 +125,14 @@ def archive_cleanup():
with get_db_session(commit=True) as session:
# Remove any Domains without any Archives.
domain_ids = [i[0] for i in session.execute('SELECT DISTINCT domain_id FROM archive') if i[0]]
deleted = 0
for domain in session.query(Domain):
if domain.id not in domain_ids:
deleted += 1
session.delete(domain)
@register_indexer('text/html')
class ArchiveIndexer(Indexer, ABC):
"""Gathers index data from the files associated with an Archive."""
@staticmethod
def get_title(file: File):

View file

@ -12,6 +12,7 @@ from sqlalchemy.orm.collections import InstrumentedList
from wrolpi.common import ModelHelper, Base, logger
from wrolpi.dates import TZDateTime
from wrolpi.errors import InvalidArchive
from wrolpi.files.lib import split_path_stem_and_suffix
from wrolpi.files.models import File
from wrolpi.media_path import MediaPathType
@ -78,6 +79,7 @@ class Archive(Base, ModelHelper):
return self.archive_datetime > other.archive_datetime
def __json__(self):
stem, _ = split_path_stem_and_suffix(self.singlefile_path) if self.singlefile_path else (None, None)
d = dict(
archive_datetime=self.archive_datetime,
domain=self.domain.dict() if self.domain else None,
@ -88,7 +90,7 @@ class Archive(Base, ModelHelper):
readability_txt_path=self.readability_txt_path,
screenshot_path=self.screenshot_path,
singlefile_path=self.singlefile_path,
stem=self.singlefile_path.stem if self.singlefile_path else None,
stem=stem,
title=self.title,
url=self.url,
)
@ -172,7 +174,8 @@ class Archive(Base, ModelHelper):
readability_json_file = self.readability_json_file
if not readability_json_file or not readability_json_file.path.is_file():
raise InvalidArchive(f'Archive must have a readability json file: {self.singlefile_file.path}')
logger.warning(f'Archive must have a readability json file: {self.singlefile_file.path}')
return
try:
with readability_json_file.path.open() as fh:

View file

@ -12,6 +12,7 @@ from modules.archive.lib import get_or_create_domain, get_new_archive_files, del
from modules.archive.models import Archive, Domain
from wrolpi.dates import local_timezone
from wrolpi.db import get_db_session
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import File
from wrolpi.root_api import CustomJSONEncoder
from wrolpi.test.common import skip_circleci
@ -430,6 +431,43 @@ def test_refresh_archives(test_session, test_directory, test_client, make_files_
assert response.json['files'][0]['archive']['archive_datetime'], 'Archive has no datetime'
@pytest.mark.asyncio
async def test_refresh_archives_index(test_session, test_directory, test_client, make_files_structure):
"""Archives are indexed using ArchiveIndexer and archive_modeler."""
# The start of a typical singlefile html file.
singlefile_contents = '''<!DOCTYPE html> <html lang="en"><!--
Page saved with SingleFile
url: https://example.com
saved date: Mon May 16 2022 23:51:35 GMT+0000 (Coordinated Universal Time)
--><head><meta charset="utf-8">'''
singlefile, *_ = make_files_structure({
'archive/example.com/2021-10-05-16-20-10_NA.html': singlefile_contents,
'archive/example.com/2021-10-05-16-20-10_NA.png': None,
'archive/example.com/2021-10-05-16-20-10_NA.readability.txt': 'article text contents',
'archive/example.com/2021-10-05-16-20-10_NA.readability.json':
'{"url": "https://example.com", "title": "the title"}',
'archive/example.com/2021-10-05-16-20-10_NA.readability.html': '<html></html>',
})
await refresh_files()
archive: Archive = test_session.query(Archive).one()
assert archive.singlefile_path == singlefile
assert archive.singlefile_file.a_text == 'the title'
assert archive.singlefile_file.d_text == 'article text contents'
# The associated files are not indexed.
for name in ('screenshot_file', 'readability_file', 'readability_json_file', 'readability_txt_file'):
file = getattr(archive, name)
assert file.associated is True, 'The associated file is not marked'
assert file.indexed is False
# file.a_text is the file name.
assert not file.b_text
assert not file.c_text
assert not file.d_text
def test_refresh_archives_invalid_file(test_session, test_directory, test_client, make_files_structure):
"""
Invalid Archives should be removed during refresh.

View file

@ -1,4 +1,3 @@
import itertools
import json
import pathlib
from abc import ABC
@ -22,12 +21,10 @@ __all__ = ['video_modeler', 'VideoIndexer']
@register_modeler
def video_modeler(groups: Dict[str, List[File]], session: Session):
count = itertools.cycle(range(101))
# Only process groups that contain a video file.
local_groups = groups.copy()
videos = []
for stem, group in local_groups.items():
video_file = next((i for i in group if i.mimetype.split('/')[0] == 'video' and i.path.suffix != '.part'), None)
video_file = next((i for i in group if i.mimetype.startswith('video/') and i.path.suffix != '.part'), None)
if not video_file:
# Not a video group.
continue
@ -40,28 +37,34 @@ def video_modeler(groups: Dict[str, List[File]], session: Session):
if poster_file:
poster_file.associated = True
poster_file.do_index()
poster_file.do_stats()
if caption_file:
caption_file.associated = True
caption_file.do_index()
caption_file.do_stats()
if info_json_file:
info_json_file.associated = True
info_json_file.do_index()
info_json_file.do_stats()
video: Video = Video.upsert(video_file, session)
video = session.query(Video).filter_by(video_file=video_file).one_or_none()
if not video:
video = Video(video_file=video_file)
session.add(video)
video.poster_file = poster_file
video.caption_file = caption_file
video.info_json_file = info_json_file
video.size = video_file.path.stat().st_size
video_file.model = Video.__tablename__
video.video_file.do_index()
video.validate(session)
videos.append(video)
# Remove this group, it will not be processed by other modelers.
del groups[stem]
if videos:
session.flush(videos)
for video in videos:
video.video_file.do_index()
video.validate(session)
if next(count) == 100:
# Commit occasionally.
session.commit()
# Remove this group, it will not be processed by other modelers.
del groups[video.video_path.stem]
@register_after_refresh

View file

@ -7,6 +7,7 @@ from modules.videos.channel import lib
from modules.videos.lib import save_channels_config, import_channels_config
from modules.videos.models import Channel, Video
from wrolpi.errors import UnknownChannel
from wrolpi.files.lib import refresh_files
@pytest.mark.parametrize('params', [
@ -93,7 +94,8 @@ def test_channels_no_url(test_session, test_directory):
import_channels_config()
def test_refresh_videos_finds_channel(test_session, test_client, channel_factory, video_factory):
@pytest.mark.asyncio
async def test_refresh_videos_finds_channel(test_session, test_client, channel_factory, video_factory):
"""A Video will be assigned to a Channel by its info json first, then to its directory."""
channel1 = channel_factory(source_id='channel1')
channel2 = channel_factory(source_id='channel2')
@ -110,20 +112,20 @@ def test_refresh_videos_finds_channel(test_session, test_client, channel_factory
with mock.patch('wrolpi.common.after_refresh') as mock_after_refresh:
# Channel can be found in `video_cleanup`, prevent that with mock.
mock_after_refresh.side_effect = []
test_client.post('/api/files/refresh')
await refresh_files()
# Channel in info_json was found during validation.
assert vid1.channel_id == channel1.id
# Refresh using cleanup, info json should be trusted.
test_client.post('/api/files/refresh')
await refresh_files()
assert vid1.channel_id == channel1.id
# Remove the info json, the Video's Channel will be its directory.
vid1.channel_id = None
vid1.info_json_path.unlink()
test_session.commit()
test_client.post('/api/files/refresh')
await refresh_files()
test_session.refresh(vid1)
vid1 = test_session.query(Video).one()
assert vid1.channel_id == channel2.id

View file

@ -10,7 +10,7 @@ from sqlalchemy.orm import Session
from yt_dlp import YoutubeDL
from wrolpi import before_startup
from wrolpi.common import ConfigFile, get_media_directory, sanitize_link
from wrolpi.common import ConfigFile, get_media_directory, sanitize_link, after_refresh, register_after_refresh
from wrolpi.dates import from_timestamp, Seconds
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.files.models import File
@ -375,8 +375,14 @@ def save_channels_config(session=None, preserve_favorites: bool = True):
@before_startup
@register_after_refresh
def import_channels_config():
"""Import channel settings to the DB. Existing channels will be updated."""
if PYTEST and not TEST_CHANNELS_CONFIG:
logger.warning(f'Not importing channels during this test. Use `test_channels_config` fixture if you would'
f'like to call this.')
return
logger.info('Importing videos config')
try:
config = get_channels_config()

View file

@ -13,7 +13,7 @@ from wrolpi.dates import now, TZDateTime
from wrolpi.db import get_db_curs
from wrolpi.downloader import Download, download_manager
from wrolpi.errors import UnknownVideo
from wrolpi.files.lib import refresh_directory_files_recursively, glob_shared_stem
from wrolpi.files.lib import refresh_directory_files_recursively, glob_shared_stem, split_path_stem_and_suffix
from wrolpi.files.models import File
from wrolpi.media_path import MediaPathType
@ -240,7 +240,7 @@ class Video(ModelHelper, Base):
def __json__(self):
from modules.videos.common import minimize_video_info_json
info_json = minimize_video_info_json(self.get_info_json()) if self.info_json_path else None
stem = self.video_path.stem if self.video_path else None
stem, _ = split_path_stem_and_suffix(self.video_path) if self.video_file else (None, None)
d = dict(
caption_path=self.caption_path,

View file

@ -3,13 +3,41 @@ import shutil
from http import HTTPStatus
from pathlib import Path
import pytest
from modules.videos.models import Video, Channel
from modules.videos.video import lib as video_lib
from wrolpi.downloader import DownloadFrequency
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import File
from wrolpi.vars import PROJECT_DIR
@pytest.mark.asyncio
async def test_refresh_videos_index(test_session, test_directory, video_factory):
"""A video discovered during refresh has files associated with it. Only the video file is indexed."""
video_factory(with_video_file=True, with_caption_file=True, with_poster_ext='jpg', with_info_json=True)
test_session.commit()
test_session.query(Video).delete()
test_session.query(File).delete()
test_session.commit()
for _ in range(1):
# Refreshing twice does not change the results.
await refresh_files()
assert test_session.query(File).count() == 4
video: Video = test_session.query(Video).one()
assert video.video_file.indexed is True, 'Video was not indexed'
assert video.video_file.a_text, 'Video title was not indexed'
assert video.video_file.d_text, 'Video captions were not indexed'
assert not video.poster_file.indexed
assert not video.caption_file.indexed
assert not video.info_json_file.indexed
def test_refresh_videos(test_client, test_session, test_directory, simple_channel, video_factory):
subdir = test_directory / 'subdir'
subdir.mkdir()

View file

@ -70,14 +70,14 @@ def test_parse_video_file_name(file_name, expected):
@pytest.mark.asyncio
async def test_associated_files(test_session, test_directory, video_file, image_file, vtt_file1):
async def test_associated_video_files(test_session, test_directory, video_file, image_file, vtt_file1):
"""A Video file has files related to it. They should be attached to the Video record."""
caption_file = video_file.with_suffix('.en.vtt')
vtt_file1.rename(caption_file)
poster_file = video_file.with_suffix('.jpeg')
image_file.rename(poster_file)
await files_lib._refresh_all_files()
await files_lib.refresh_files()
test_session.commit()
# All files were found.
@ -93,7 +93,7 @@ async def test_associated_files(test_session, test_directory, video_file, image_
assert video.video_file.size
assert video.video_file.indexed
await files_lib._refresh_all_files()
await files_lib.refresh_files()
test_session.commit()
# No new files were added.
@ -113,7 +113,7 @@ async def test_unassociated_video(test_session, test_directory, video_file):
video_file.rename(new_video_file_path)
video_file = new_video_file_path
await files_lib._refresh_all_files()
await files_lib.refresh_files()
test_session.commit()
video: Video = test_session.query(Video).one()

View file

@ -34,8 +34,8 @@ def get_video_for_app(video_id: int) -> Tuple[dict, Optional[dict], Optional[dic
caption = video.video_file.d_text
video = video.video_file.__json__()
video['video']['caption'] = caption
previous_video = previous_video.video_file.__json__() if previous_video else None
next_video = next_video.video_file.__json__() if next_video else None
previous_video = previous_video.video_file.__json__() if previous_video and previous_video.video_file else None
next_video = next_video.video_file.__json__() if next_video and next_video.video_file else None
return video, previous_video, next_video