mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 20:06:22 -05:00
* A secondary WROLPi copies its primary's library over HTTP A WROLPi with role "secondary" pulls from its primary: a manifest of every FileGroup's files (/api/sync/manifest), then each missing or changed file from the primary's Caddy /media/ (resumable, written to a hidden partial and renamed with the primary's mtime), a refresh, then the library configs, imported as the primary wrote them. wrolpi.yaml contributes only its library settings. Files deleted on the primary are kept. A secondary never saves the synced configs and never downloads. Its API answers 503 SYNCING while a sync runs, and every page warns that it is a copy. It syncs in a daily window or on "Sync now"; WROL Mode stops it. On a Pi 4 (no AES instructions) the client uses TLS 1.2 ChaCha20, which pulls ~110 MB/s from Caddy versus ~41 MB/s for rsync over ssh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Sync has its own /admin tab; a sync's reads from the primary are bounded The sync settings and progress move from Settings (and the component gallery, which is for library components) to /admin/sync. A download never writes past the size in the primary's manifest, and configs, listings, and manifest pages are capped. A primary address may not carry a user name or password (it is logged and shown). While a sync runs, the API answers only the exact requests that show its progress or stop it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A sync keeps the secondary's replaced configs in today's config backup The first copy of the day is kept, like a save, so a config backup import undoes a sync's config changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Docker's Caddy logs every request `docker compose logs -f web` shows each request with its status, size and duration, e.g. a secondary's /media/ downloads during a sync. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A sync reports its progress as it downloads, and refuses quietly The status updated only when a page of 500 FileGroups finished, so a page of large files looked stuck; it now updates every 2 seconds. Requests refused while syncing are answered by the middleware instead of raised, so the UI's polling no longer logs an error each time. The primary's version is stored without its trailing newline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A WROLPi can back up to a second drive; sync settings live in sync.yaml The Sync tab's Backup Drive copies the media directory to a second mounted drive with rsync during the sync window (hourly), or on "Back Up Now". Nothing on the backup drive is deleted. The Tags and playlists directories are left out (WROLPi rebuilds them from the configs), and the database is written as an SQLite snapshot rather than copied as files, so the drive can be mounted as the media directory and start. A backup is written only while the chosen drive (by UUID) is mounted where it was chosen, and is not the media or system drive; rsync is stopped if the drive disappears. Not in Docker, which cannot reach other drives. Role, primary, window and backup drive move from wrolpi.yaml to sync.yaml: they belong to this machine, and are never copied from a primary. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * The Sync tab shows the configured backup drive getSettings copies each setting by name and did not list the backup drive, so the Sync tab showed "None" while one was configured. It also dropped `version`. A test now fails for any setting the API sends that getSettings drops. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A backup can go to a folder on its drive, and remembers its last success The Backup Drive panel takes a folder on the chosen drive. The drive is checked through the folder's mount point: the folder is written only when the drive with the saved UUID is mounted there, so a folder left on the system drive by an unplugged drive, or on another drive mounted inside the chosen one, is refused. A missing folder is created once the drive is checked. When the last backup succeeded is saved in sync.yaml, so it is known after a restart. "Stop Backup" is disabled while the database snapshot is written (it runs to the end), and a finished backup clears the request to stop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * The backup drive has its own window The sync window was shown in the Sync panel but also scheduled the backup drive. The Backup Drive panel now has its own window (sync.yaml backup_window_start/end), saved with the drive; the sync window is shown, and used, only for a secondary's sync. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Sync and the backup drive can each exclude folders A secondary or a backup drive may be smaller than the primary's library. Each Sync tab panel has its own excluded folders in sync.yaml, chosen in a folder browser: a secondary browses its primary's folders (through Caddy), the backup drive browses this WROLPi's media directory. Excluded folders are never copied; what was copied before is kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * The folder browser does not offer lost+found Every ext4 drive has a root-only lost+found folder; a sync and a backup never copy it, so it is not offered for exclusion. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A sync never writes into config or tags, whatever their case On a media drive that ignores case (exFAT, NTFS, macOS), a manifest path like Config/wrolpi.db is the real config folder. The protected and unlisted top-level folders are now compared case-insensitively in the manifest, in resolve_destination, in excluded-folder validation, and in both folder listings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A backup writes the database snapshot only when the database changed Every backup rewrote the whole database snapshot (2.5 GB on a busy WROLPi), even on the window's idle hourly runs. The snapshot is now skipped when the live database (its size and mtime, and those of a non-empty WAL) and the drive's copy are both unchanged since the last snapshot. The record is in memory, so the first backup after a restart writes it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Remove the unused save_sync_config switch Nothing activated it; SyncConfig saves directly. The test server's log_message override is called by http.server, so it goes in the vulture baseline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
228 lines
7.8 KiB
Python
228 lines
7.8 KiB
Python
import logging
|
|
from datetime import datetime, timezone, time
|
|
from enum import Enum
|
|
from typing import Union, List
|
|
|
|
import pytz
|
|
from sqlalchemy import types
|
|
|
|
from wrolpi.errors import InvalidDatetime
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
TEST_DATETIME: datetime = None
|
|
|
|
|
|
class Seconds(int, Enum):
|
|
minute = 60
|
|
hour = minute * 60
|
|
day = hour * 24
|
|
week = day * 7
|
|
|
|
|
|
def set_test_now(dt: datetime):
|
|
global TEST_DATETIME
|
|
if dt and not dt.tzinfo:
|
|
# Assume any datetime is UTC during testing.
|
|
dt = dt.replace(tzinfo=pytz.UTC)
|
|
TEST_DATETIME = dt
|
|
return dt
|
|
|
|
|
|
def now() -> datetime:
|
|
"""Get the current DateTime in the provided timezone. Timezone aware."""
|
|
global TEST_DATETIME
|
|
if TEST_DATETIME:
|
|
return TEST_DATETIME
|
|
return datetime.now(tz=timezone.utc)
|
|
|
|
|
|
def strftime(dt: datetime) -> str:
|
|
return dt.isoformat()
|
|
|
|
|
|
def strpdate(dt: str) -> datetime:
|
|
"""
|
|
Attempt to parse a datetime string. Tries to find a Timezone, if possible. DB requires timezone.
|
|
"""
|
|
if not dt or dt in ('undefined', 'null'):
|
|
InvalidDatetime(f'Unable to parse empty datetime string: {dt}')
|
|
|
|
try:
|
|
if dt.count('/') == 2:
|
|
# No timezone info.
|
|
a, b, c = dt.split('/')
|
|
if len(c) == 4:
|
|
# Assume m/d/Y
|
|
return datetime.strptime(dt, '%m/%d/%Y')
|
|
if len(a) == 4:
|
|
# Y/m/d
|
|
return datetime.strptime(dt, '%Y/%m/%d')
|
|
if len(a) in (1, 2) and len(b) in (1, 2):
|
|
# Day/Month may or may not have 0 prefix.
|
|
if len(c) == 13:
|
|
# d/m/Y HH:MM:SS
|
|
return datetime.strptime(dt, '%m/%d/%Y %H:%M:%S')
|
|
elif len(c) in (15, 16):
|
|
# d/m/Y HH:MM:SS PM
|
|
return datetime.strptime(dt, '%m/%d/%Y %H:%M:%S %p')
|
|
elif dt.count('-') == 2 and len(dt) <= 10:
|
|
# No timezone info.
|
|
a, b, c = dt.split('-')
|
|
if len(a) == 4:
|
|
# Y-m-d
|
|
return datetime.strptime(dt, '%Y-%m-%d')
|
|
|
|
if dt.startswith('D:'):
|
|
# D:20221226113758-07'00, D:20200205184724, etc.
|
|
dt2 = dt.replace("'", '').rstrip('+')
|
|
try:
|
|
return datetime.strptime(dt2, "D:%Y%m%d%H%M%S%z")
|
|
except ValueError:
|
|
pass
|
|
|
|
return datetime.strptime(dt2, "D:%Y%m%d%H%M%S")
|
|
|
|
if dt.count('.') == 2 and len(dt) <= 9:
|
|
# yyyy.mm.dd or dd.mm.yyyy
|
|
a, b, c = dt.split('.')
|
|
if len(a) == 4:
|
|
return datetime.strptime(dt, '%Y.%m.%d')
|
|
if len(c) == 4:
|
|
return datetime.strptime(dt, '%d.%m.%Y')
|
|
|
|
try:
|
|
# Fri Jun 17 2022 19:24:52 (from Singlefile)
|
|
return datetime.strptime(dt, '%a %b %d %Y %H:%M:%S')
|
|
except ValueError:
|
|
pass
|
|
|
|
if len(dt) == 4 and dt.isdigit():
|
|
# Assume this is a year
|
|
return datetime.strptime(dt, '%Y').replace(tzinfo=pytz.UTC)
|
|
|
|
if ',' in dt and (dt.endswith('AM') or dt.endswith('PM')):
|
|
try:
|
|
# Tuesday, October 19, 1999 3:41:01 PM
|
|
return datetime.strptime(dt, '%A, %B %d, %Y %I:%M:%S %p')
|
|
except ValueError:
|
|
pass
|
|
|
|
try:
|
|
# Tue, October 19, 1999 3:41:01 PM
|
|
return datetime.strptime(dt, '%a, %B %d, %Y %I:%M:%S %p')
|
|
except ValueError:
|
|
pass
|
|
|
|
# Last, try third-party module to parse ISO 8601 datetime.
|
|
return datetime.fromisoformat(dt)
|
|
except Exception as e:
|
|
raise InvalidDatetime(f'Unable to parse datetime string: {dt}') from e
|
|
|
|
|
|
def strptime_ms(dt: str) -> datetime:
|
|
return datetime.fromisoformat(dt).astimezone(pytz.UTC)
|
|
|
|
|
|
def from_timestamp(timestamp: float) -> datetime:
|
|
return datetime.fromtimestamp(timestamp).astimezone(pytz.UTC)
|
|
|
|
|
|
def seconds_to_timestamp(seconds: Union[int, float]) -> str:
|
|
"""Convert an integer into a timestamp string.
|
|
|
|
>>> seconds_to_timestamp(5)
|
|
# '00:00:05'
|
|
>>> seconds_to_timestamp(60)
|
|
|
|
# '00:01:00'
|
|
>>> seconds_to_timestamp(86400)
|
|
# '1d 00:00:00'
|
|
"""
|
|
seconds = int(seconds)
|
|
weeks, seconds = divmod(seconds, Seconds.week)
|
|
days, seconds = divmod(seconds, Seconds.day)
|
|
hours, seconds = divmod(seconds, Seconds.hour)
|
|
minutes, seconds = divmod(seconds, Seconds.minute)
|
|
timestamp = f'{hours:02}:{minutes:02}:{seconds:02}'
|
|
if weeks:
|
|
timestamp = f'{weeks}w {days}d {timestamp}'
|
|
elif days:
|
|
timestamp = f'{days}d {timestamp}'
|
|
return timestamp
|
|
|
|
|
|
class TZDateTime(types.TypeDecorator):
|
|
"""Forces all datetime to have a timezone. Stores all datetime in DB as UTC."""
|
|
impl = types.DateTime
|
|
cache_ok = True
|
|
|
|
def process_bind_param(self, value, dialect):
|
|
if isinstance(value, datetime):
|
|
if not value.tzinfo:
|
|
raise TypeError(f"tzinfo is required: {value}")
|
|
# Store all timestamps as UTC timezone.
|
|
value = value.astimezone(timezone.utc)
|
|
elif isinstance(value, str) and '-' in value:
|
|
value = datetime.fromisoformat(value)
|
|
return value
|
|
|
|
def process_result_value(self, value: datetime, dialect):
|
|
if value is not None:
|
|
# Assume the DB timestamp is UTC.
|
|
value = value.replace(tzinfo=pytz.utc) if not value.tzinfo else value
|
|
return value
|
|
|
|
|
|
def months_selector_to_where(wheres: list, params: dict, months: List[int]):
|
|
"""Filter FileGroup results by the month that the file was published. Returns wheres/params unchanged if months
|
|
is empty.
|
|
|
|
@param months: List of integers representing the index of the month of the year (January is 1).
|
|
@param wheres: A list of strings which are SQL where filters.
|
|
@param params: Dict which contains the parameters passed to SQLAlchemy query.
|
|
"""
|
|
if not months:
|
|
return wheres, params
|
|
|
|
if not set(months).issubset(set(range(1, 13))):
|
|
raise ValueError('Months must be between 1 and 12')
|
|
|
|
# sqlite3 cannot bind a tuple; use a named placeholder for each month.
|
|
placeholders = ', '.join(f':month_{idx}' for idx in range(len(months)))
|
|
for idx, month in enumerate(months):
|
|
params[f'month_{idx}'] = month
|
|
wheres.append(f"CAST(strftime('%m', published_datetime) AS INTEGER) IN ({placeholders})")
|
|
return wheres, params
|
|
|
|
|
|
def date_range_to_where(wheres: list, params: dict, from_year: int, to_year: int):
|
|
"""Filter FileGroup results by the year that the file was published.
|
|
|
|
@param from_year: The earliest year the file was published
|
|
@param to_year: The latest year the file was published
|
|
@param wheres: A list of strings which are SQL where filters.
|
|
@param params: Dict which contains the parameters passed to SQLAlchemy query.
|
|
"""
|
|
if from_year and to_year:
|
|
wheres.append("CAST(strftime('%Y', published_datetime) AS INTEGER) BETWEEN :from_year AND :to_year")
|
|
params['from_year'] = from_year
|
|
params['to_year'] = to_year
|
|
elif from_year:
|
|
wheres.append("CAST(strftime('%Y', published_datetime) AS INTEGER) >= :from_year")
|
|
params['from_year'] = from_year
|
|
elif to_year:
|
|
wheres.append("CAST(strftime('%Y', published_datetime) AS INTEGER) <= :to_year")
|
|
params['to_year'] = to_year
|
|
|
|
return wheres, params
|
|
|
|
|
|
def is_within_daily_window(start: str | None, end: str | None, current: time) -> bool:
|
|
"""True if `current` is within the daily window from `start` to `end` ('HH:MM'). A window whose end is before
|
|
its start crosses midnight (e.g. 22:00-06:00). Callers decide what a missing window means."""
|
|
start_time = datetime.strptime(start, '%H:%M').time()
|
|
end_time = datetime.strptime(end, '%H:%M').time()
|
|
if start_time <= end_time:
|
|
return start_time <= current < end_time
|
|
return current >= start_time or current < end_time
|