mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-10-26 19:01:39 -04:00
Handling all combinations of toggle in light and dark. Changing CPUUsageProgress colors to be more readable in dark mode. Moving theme handling into Theme.js. Importing element wrappers from Theme.js to handle element theming. Changing video menu to dark mode. Creating ThemeContext to share Dark Mode setting. Removing duplicate code for search functions. Displaying X when downloads are disabled. Using react context to share settings across components. Refusing to start workers when WROL Mode is enabled. Changing warning to debug. Queuing recurring downloads first. Adding Video.url index. Adding special handling for youtube shorts to videos. Reworking Downloads to have one worker per process. Testing creating downloads and getting downloaders. Testing video validation and poster generation. Testing video statistics. Increasing inventory test coverage. Adding pytest.ini to automatically detect async test. Adding more archive test coverage. Testing Archive CRUD. Catching and logging when encountering error during indexing. Using FileIcon when Archive has no screenshot. A Video will be assigned to a Channel by its info json first, then to its directory. Including suffix in File json. Adding index for File.suffix. Gathering suffix during indexing. Passing entire file down to FileIcon. Moving logging up. Returning File.associated in file json. Associated files are last in file search. Removing duplicate refreshing code by creating new _refresh_directory function. Changing File.idempotency to a datetime to avoid having to clear idempotency. Truncating indexes to avoid error with large files. Don't overwrite video data when info json is empty. Using already_downloaded for channel videos. Awaiting refresh in Channel.refresh. Testing that videos already downloaded aren't downloaded again. Adding indexes for video/archive referenced paths. Changing grid width for mobile or computer. Adding button to refresh specific directories. Restoring Channel edit link. Fixing caption path in video_modeler. Adding ZIP files to mimetype colors. Using model instead of first file's model. Fetching File models in batches to avoid issuing a SELECT for every File with a model. Flushing generated poster file. Getting Channel in VideoPage, relying on Video.channl_id, falling back to URL's channel_id. Attaching Video to it's Channel during download. Using ExternalCardLink for ArchivePage singlefile link. Validating and indexing videos after download. Handling glob when file name contains matching characters. Reworking and testing split_path_stem_and_suffix and glob_shared_stem. Adding associated video files to DB during upsert. Adding pending downloads to dashboard. Hiding status when download is open. Handling when load is empty. Adding load statistics to Dashboard. Limiting concurrent after_refresh functions. Handling when no onSelect is declared. Adding ImageRow for FileTable. Moving image date into Card.Meta. Using ExternalLink for FileCard. Using ExternalLink for ImageCard. Handling when error occurs during refresh of a directory. Committing during refresh to avoid losing all files if an error occurs. Removing api health check to avoid spamming logs. Creating ImageCard to display image posters when they aren't too large. Removing archive.domain_id not null. Reworking file refresh to process all files in a single directory. Bumping version for major file rework. No longer checking for video corruption. Adding duration by default to speed up tests. Using register_indexer for all indexers. Adding CPU usage progress bar in Welcome. Modifying TextIndexer to ignore large text files. Counting all files during refresh. Adding refresh_logger to clarify logging. Checking for wrol_mode before refresh functions. Removing unused idempotency from video/channel tables. Using magic module to speed up mimetype identification. All tests pass. Archive tests pass. Changing video get endpoint to return 'file' to avoid ambiguity. Video tests pass. Simplifying regex filtering. Using regex to ignore case when filtering. Converting all channel classes to functions. Restoring channel refresh and download buttons. Matching format of Archive and Video pages. Adding sorting to Archives search. Reworking video orders for file search. Using SearchInput for videos search. Archives can be searched on the Archives page. Domains can be filtered. Reworking Archive search to use Files. Videos, Archives and Global search use the FilesView. Videos are claimed by their Channel based on the Channel's directory. Prev and Next video cards are displayed on the VideoPage. Creating useVideo for reworked VideoWrapper and VideoPage. Adding Paginator to FilesView. Moving file refresh button out of manage tab. Removing Files page tabs. Limiting refresh to one at a time. Adding class for card icon to match poster height. Video and Archives always re-claim their files on refresh. Archive files are indexed and claimed. FileView table is compact and striped. Videos page uses FileView. Updated navlinks to router v6. Removing ! character from file names. Disabling select button when cards are visible. Adding show/hide button for FileTable selection. The Archive Page is displayed. Adding mimetype dropdown. Upgrading to React Router v6 for useSearchParams. Validating video during modeling. Removing screenshot during corruption check because it was very slow. Updating app to use video files as search results. Updating video search to return Files. Video and WROLPi tests pass. Creating function to refresh files within a channel's directory. Removing troubleshooting print. Updating result order in test. Reworking video_factory to handle a specific video file location. Returning video model on file search. Getting session using video_file. Screenshotting when checking for video corruption. Reducing ffmpeg calls by gathering duration during poster generation. Moving video file matching into model. VideoIndexer is moved into video module. Video files are validated. Moving files module into wrolpi in preparation to use it in modules. Title and contents are indexed for text file. Files are indexed on refresh by using their indexer. Zip files are indexed using their contents. Testing multiple zip files. Adding unique to file.path. Checking that the correct indexer is used. Adding index to file.modification_datetime and file.size. Handling file info gathering in File.do_index. Only reading contents of file if file.indexed is False. Video model is found during file refresh. A Video record is created that has the associated files. Videos without associated files are found. Videos are found using registered video_modeler() rather than in refresh code. Removing old video columns. Handling video info json files. Trying to import each module individually. Will continue to import modules even if one fails. Reworking refresh so it performs less DB calls. Converting file.path to primary key. file.path is always a pathlib.Path. Updating video_factory to use new file system, testing it. Bump sanic from 21.9.1 to 21.12.2 in /docker/archive Bumps [sanic](https://github.com/sanic-org/sanic) from 21.9.1 to 21.12.2. - [Release notes](https://github.com/sanic-org/sanic/releases) - [Changelog](https://github.com/sanic-org/sanic/blob/main/CHANGELOG.rst) - [Commits](https://github.com/sanic-org/sanic/compare/v21.9.1...v21.12.2) --- updated-dependencies: - dependency-name: sanic dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com>
237 lines
9.1 KiB
Python
237 lines
9.1 KiB
Python
import datetime
|
|
import json
|
|
import pathlib
|
|
import re
|
|
from typing import Generator
|
|
|
|
import pytz
|
|
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean
|
|
from sqlalchemy.orm import relationship, Session, validates
|
|
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.models import File
|
|
from wrolpi.media_path import MediaPathType
|
|
|
|
logger = logger.getChild(__name__)
|
|
|
|
|
|
class Archive(Base, ModelHelper):
|
|
__tablename__ = 'archive'
|
|
id = Column(Integer, primary_key=True)
|
|
|
|
domain_id = Column(Integer, ForeignKey('domains.id'))
|
|
domain = relationship('Domain', primaryjoin='Archive.domain_id==Domain.id')
|
|
|
|
url = Column(String)
|
|
title = Column(String)
|
|
archive_datetime = Column(TZDateTime)
|
|
validated = Column(Boolean)
|
|
|
|
# Associated Files.
|
|
singlefile_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
|
singlefile_file: File = relationship('File', primaryjoin='Archive.singlefile_path==File.path')
|
|
readability_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
|
readability_file: File = relationship('File', primaryjoin='Archive.readability_path==File.path')
|
|
readability_json_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
|
readability_json_file: File = relationship('File', primaryjoin='Archive.readability_json_path==File.path')
|
|
readability_txt_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
|
readability_txt_file: File = relationship('File', primaryjoin='Archive.readability_txt_path==File.path')
|
|
screenshot_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
|
screenshot_file: File = relationship('File', primaryjoin='Archive.screenshot_path==File.path')
|
|
|
|
def __repr__(self):
|
|
if self.domain:
|
|
return f'<Archive id={self.id} url={self.url} singlefile={repr(str(self.singlefile_path))} ' \
|
|
f'domain={self.domain.domain}>'
|
|
return f'<Archive id={self.id} url={self.url} singlefile={repr(str(self.singlefile_path))}>'
|
|
|
|
def my_paths(self) -> Generator:
|
|
if self.singlefile_path:
|
|
yield self.singlefile_path
|
|
if self.readability_path:
|
|
yield self.readability_path
|
|
if self.readability_json_path:
|
|
yield self.readability_json_path
|
|
if self.readability_txt_path:
|
|
yield self.readability_txt_path
|
|
if self.screenshot_path:
|
|
yield self.screenshot_path
|
|
|
|
def unlink(self):
|
|
"""
|
|
Remove any files in this archive.
|
|
"""
|
|
# Don't fail if a file is missing, it could have been deleted manually.
|
|
for path in self.my_paths():
|
|
path.unlink(missing_ok=True)
|
|
|
|
def __gt__(self, other) -> bool:
|
|
"""
|
|
Compare Archives according to their archive datetime.
|
|
"""
|
|
if not isinstance(other, Archive):
|
|
raise ValueError(f'Cannot compare {type(other)} to Archive!')
|
|
|
|
return self.archive_datetime > other.archive_datetime
|
|
|
|
def __json__(self):
|
|
d = dict(
|
|
archive_datetime=self.archive_datetime,
|
|
domain=self.domain.dict() if self.domain else None,
|
|
domain_id=self.domain_id,
|
|
id=self.id,
|
|
readability_json_path=self.readability_json_path,
|
|
readability_path=self.readability_path,
|
|
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,
|
|
title=self.title,
|
|
url=self.url,
|
|
)
|
|
return d
|
|
|
|
def delete(self):
|
|
self.unlink()
|
|
|
|
session = Session.object_session(self)
|
|
|
|
session.query(Archive).filter_by(id=self.id).delete()
|
|
|
|
if self.domain:
|
|
domain_archives = [i.id for i in self.domain.archives]
|
|
if not domain_archives:
|
|
self.domain.delete()
|
|
|
|
@property
|
|
def alternatives(self):
|
|
"""
|
|
Get a list of Archives that share my URL.
|
|
"""
|
|
session = Session.object_session(self)
|
|
alternatives = list(session.query(Archive).filter(
|
|
Archive.id != self.id,
|
|
Archive.url == self.url,
|
|
).order_by(Archive.archive_datetime))
|
|
return alternatives
|
|
|
|
def my_files(self) -> Generator[pathlib.Path, None, None]:
|
|
"""Return all paths of this Archive. Returns nothing if all paths are None.""" # noqa
|
|
if self.singlefile_path:
|
|
yield self.singlefile_path
|
|
if self.readability_path:
|
|
yield self.readability_path
|
|
if self.readability_txt_path:
|
|
yield self.readability_txt_path
|
|
if self.readability_json_path:
|
|
yield self.readability_json_path
|
|
if self.screenshot_path:
|
|
yield self.screenshot_path
|
|
|
|
@staticmethod
|
|
def find_by_path(path, session: Session) -> Base:
|
|
archive = session.query(Archive).filter_by(singlefile_path=path).one_or_none()
|
|
return archive
|
|
|
|
def read_singlefile_data(self):
|
|
"""
|
|
Read the start of the singlefile (if any) and decode the Archive information.
|
|
"""
|
|
match_url = re.compile(r'^\s+?url:\s+?(http.*)', re.MULTILINE)
|
|
match_date = re.compile(r'^\s+?saved date:\s+?(.*)', re.MULTILINE)
|
|
|
|
if self.singlefile_path:
|
|
with self.singlefile_path.open('rt') as fh:
|
|
head = fh.read(500)
|
|
if 'Page saved with SingleFile' not in head:
|
|
return
|
|
try:
|
|
if match := match_url.findall(head):
|
|
self.url = match[0].strip()
|
|
except Exception as e:
|
|
logger.error(f'Could not get URL from singlefile {self.singlefile_path}', exc_info=e)
|
|
try:
|
|
if match := match_date.findall(head):
|
|
dt = match[0].strip()
|
|
dt = ' '.join(dt.split(' ')[:5])
|
|
# SingleFile uses GMT.
|
|
dt = datetime.datetime.strptime(
|
|
dt,
|
|
'%a %b %d %Y %H:%M:%S' # Fri Jun 17 2022 19:24:52
|
|
).replace(tzinfo=pytz.timezone('GMT'))
|
|
self.archive_datetime = dt
|
|
except Exception as e:
|
|
logger.error(f'Could not get archive date from singlefile {self.singlefile_path}', exc_info=e)
|
|
|
|
def read_readability_data(self):
|
|
"""Read the Readability JSON file, apply its contents to this record."""
|
|
from modules.archive.lib import get_or_create_domain, get_title_from_html
|
|
|
|
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}')
|
|
|
|
try:
|
|
with readability_json_file.path.open() as fh:
|
|
json_contents = json.load(fh)
|
|
url = json_contents.get('url')
|
|
title = json_contents.get('title')
|
|
except Exception as e:
|
|
raise InvalidArchive() from e
|
|
|
|
domain = None
|
|
if url:
|
|
domain = get_or_create_domain(Session.object_session(self), url)
|
|
|
|
if not title:
|
|
title = get_title_from_html(self.singlefile_path.read_text())
|
|
|
|
self.url = url
|
|
self.title = title
|
|
self.domain_id = domain.id if domain else None
|
|
|
|
def validate(self):
|
|
try:
|
|
self.read_readability_data()
|
|
self.read_singlefile_data()
|
|
self.validated = True
|
|
except Exception as e:
|
|
logger.warning(f'Unable to validate {self}', exc_info=e)
|
|
|
|
@staticmethod
|
|
def find_by_paths(paths, session):
|
|
archives = list(session.query(Archive).filter(Archive.singlefile_path.in_(paths)))
|
|
return archives
|
|
|
|
@property
|
|
def primary_path(self):
|
|
return self.singlefile_path
|
|
|
|
|
|
class Domain(Base, ModelHelper):
|
|
__tablename__ = 'domains' # plural to avoid conflict
|
|
id = Column(Integer, primary_key=True)
|
|
|
|
domain = Column(String)
|
|
directory = Column(MediaPathType)
|
|
|
|
archives: InstrumentedList = relationship('Archive', primaryjoin='Archive.domain_id==Domain.id')
|
|
|
|
def __repr__(self):
|
|
return f'<Domain id={self.id} domain={self.domain} directory={self.directory}>'
|
|
|
|
def delete(self):
|
|
session = Session.object_session(self)
|
|
session.execute('DELETE FROM archive WHERE domain_id=:id', dict(id=self.id))
|
|
session.query(Domain).filter_by(id=self.id).delete()
|
|
|
|
@validates('domain')
|
|
def validate_domain(self, key, value: str):
|
|
if not isinstance(value, str):
|
|
raise ValueError('Domain must be a string')
|
|
if len(value.split('.')) < 2:
|
|
raise ValueError(f'Domain must contain at least one "." domain={repr(value)}')
|
|
return value
|