Creating Event and Flag systems. Events are used to send and display a toast to the App. Flags are used to signal if some action has been performed, or if a package is installed.

This commit is contained in:
Roland 2022-12-23 16:04:09 -07:00
parent 5cbea1ba15
commit 93f0e7494f
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
45 changed files with 923 additions and 355 deletions

View file

@ -0,0 +1,39 @@
"""WROLPi flags
Revision ID: 930b9b7adb79
Revises: 90ac16f9140a
Create Date: 2022-12-20 21:02:28.975897
"""
import os
from alembic import op
from sqlalchemy.orm import Session
# revision identifiers, used by Alembic.
revision = '930b9b7adb79'
down_revision = '90ac16f9140a'
branch_labels = None
depends_on = None
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
def upgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('''CREATE TABLE wrolpi_flag(
id SERIAL PRIMARY KEY,
refresh_complete BOOLEAN DEFAULT FALSE
)''')
if not DOCKERIZED:
session.execute('ALTER TABLE public.wrolpi_flag OWNER TO wrolpi')
def downgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('DROP TABLE IF EXISTS wrolpi_flag')

View file

@ -18,6 +18,7 @@ import {StatusContext, ThemeContext} from "./contexts/contexts";
import {ThemeWrapper} from "./components/Theme";
import {Dashboard} from "./Dashboard";
import {Donate} from "./components/Donate";
import {useEventsInterval} from "./Events";
function PageNotFound() {
return <Container fluid>
@ -47,6 +48,7 @@ function Footer() {
export default function App() {
const status = useStatusInterval();
useEventsInterval();
return (<ThemeWrapper>
<StatusContext.Provider value={status}>

View file

@ -8,8 +8,44 @@ import {Header, Segment, Statistic, StatisticGroup} from "./components/Theme";
import {Link} from "react-router-dom";
import {BandwidthProgressCombined, CPUUsageProgress} from "./components/admin/Status";
import {ProgressPlaceholder} from "./components/Placeholder";
import {Divider} from "semantic-ui-react";
import {Divider, Icon, Message} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {refreshFiles} from "./api";
function FlagsMessages({flags}) {
if (!flags) {
return <></>
}
let refreshing;
let refreshComplete;
// Do not tell the maintainer to refresh the files if they are already refreshing.
if (flags.indexOf('refreshing') >= 0) {
// Actively refreshing.
refreshing = <Message icon>
<Icon name='circle notched' loading/>
<Message.Content>
<Message.Header>Refreshing</Message.Header>
Your files are being refreshed.
</Message.Content>
</Message>;
} else if (flags.indexOf('refresh_complete') === -1) {
// `refresh_complete` flag is not set. Tell the maintainer to refresh the files.
refreshComplete = <Message icon warning onClick={refreshFiles}>
<Icon name='hand point right'/>
<Message.Content>
<Message.Header>Refresh required</Message.Header>
Click here to refresh all your files.
</Message.Content>
</Message>;
}
return <>
{refreshing}
{refreshComplete}
</>
}
export function Dashboard() {
useTitle('Dashboard');
@ -21,7 +57,8 @@ export function Dashboard() {
const [downloadOpen, setDownloadOpen] = useState(false);
const onDownloadOpen = (name) => setDownloadOpen(!!name);
const downloads = <Segment><DownloadMenu onOpen={onDownloadOpen}/></Segment>;
const downloadsDisabled = status?.flags?.indexOf('refresh_complete') === -1;
const downloads = <Segment><DownloadMenu onOpen={onDownloadOpen} disabled={downloadsDisabled}/></Segment>;
// Only show dashboard parts if not searching.
let body;
@ -35,7 +72,7 @@ export function Dashboard() {
</>;
}
return (<PageContainer>
return <PageContainer>
<Grid>
<Grid.Row>
<Grid.Column mobile={16} computer={8}>
@ -50,8 +87,9 @@ export function Dashboard() {
</Grid.Column>
</Grid.Row>
</Grid>
{!searchStr && <FlagsMessages flags={status['flags']}/>}
{body}
</PageContainer>)
</PageContainer>
}
function DashboardStatus() {

67
app/src/Events.js Normal file
View file

@ -0,0 +1,67 @@
import React, {useEffect} from 'react';
import {toast} from "react-semantic-toasts";
import {useRecurringTimeout} from "./hooks/customHooks";
import {getEvents} from "./api";
function eventToast(title, description, type = 'success', time = 5000) {
toast({type: type, title: title, description: description, time: time});
}
function handleEvents(events) {
let processedSubjects = [];
events.forEach(e => {
const {event, message, subject} = e;
console.debug('event', e);
if (subject && processedSubjects.indexOf(subject) >= 0) {
console.debug(`Already handled subject "${subject}" this batch.`);
return;
} else if (event === 'global_refresh_completed') {
eventToast('Refresh completed', 'All files have been refreshed.');
} else if (event === 'global_directory_refresh_started') {
const description = message || 'Refresh of directory has started.';
eventToast('Refresh started', description);
} else if (event === 'global_directory_refresh_completed') {
const description = message || 'Refresh of directory has completed.';
eventToast('Refresh completed', description);
}
if (subject) {
processedSubjects = [...processedSubjects, subject];
}
})
}
export function useEventsInterval() {
const [events, setEvents] = React.useState(null);
// `now` is the last time we successfully fetched events.
const now = React.useRef(localStorage.getItem('events_now'));
const setNow = (newNow) => {
now.current = newNow;
localStorage.setItem('events_now', now.current);
}
const fetchEvents = async () => {
try {
const response = await getEvents(now.current);
setNow(response['now']);
setEvents(response['events']);
} catch (e) {
setEvents(null);
console.error(e);
}
}
useRecurringTimeout(fetchEvents, 1000 * 5);
useEffect(() => {
if (events && events.length > 1) {
handleEvents(events);
}
}, [JSON.stringify(events)]);
return {events, fetchEvents}
}

View file

@ -676,3 +676,14 @@ export async function getStatistics() {
})
}
}
export async function getEvents(after) {
let uri = `${API_URI}/events/feed`;
if (after) {
uri = `${uri}?after=${after}`
}
let response = await apiGet(uri);
if (response.status === 200) {
return await response.json();
}
}

View file

@ -20,7 +20,7 @@ import {
BackButton,
CardLink, cardTitleWrapper,
defaultSearchOrder,
epochToDateString,
isoDatetimeToString,
ExternalCardLink,
FileIcon,
HelpHeader,
@ -151,7 +151,7 @@ function ArchivePage() {
<ExternalCardLink to={singlefileUrl}>
<Header as='h2'>{textEllipsis(archive.title || archive.url)}</Header>
</ExternalCardLink>
<Header as='h3'>{epochToDateString(archive.archive_datetime)}</Header>
<Header as='h3'>{isoDatetimeToString(archive.archive_datetime)}</Header>
{domainHeader}
{urlHeader}
@ -208,7 +208,7 @@ export function ArchiveCard({file}) {
</CardLink>}
<CardMeta {...s}>
<p>
{epochToDateString(archive.archive_datetime)}
{isoDatetimeToString(archive.archive_datetime)}
</p>
</CardMeta>
<CardDescription>

View file

@ -80,6 +80,11 @@ export function secondsToElapsedPopup(seconds) {
/>
}
export function isoDatetimeToElapsedPopup(dt) {
const d = new Date(`${dt}+00:00`);
return secondsToElapsedPopup(d.getTime() / 1000);
}
export function secondsToDuration(video) {
let duration = video.duration;
let hours = Math.floor(duration / 3600);
@ -106,11 +111,11 @@ export function Duration({video}) {
}
}
export function epochToDateString(date) {
// Convert a date integer to a human-readable date format.
export function isoDatetimeToString(dt) {
// Convert a datetime to a human-readable date format.
let d = <></>;
if (date) {
d = new Date(date * 1000);
if (dt) {
d = new Date(`${dt}+00:00`);
d = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
}
return d;

View file

@ -13,7 +13,13 @@ class Downloader extends React.Component {
constructor(props) {
super(props);
this.state = {
advancedOpen: false, destination: '', downloader: props.downloader, pending: false, urls: '', valid: true,
advancedOpen: false,
destination: '',
disabled: this.props.disabled,
downloader: props.downloader,
pending: false,
urls: '',
valid: true,
};
}
@ -336,7 +342,7 @@ class RSSDownload extends ChannelDownload {
}
}
export function DownloadMenu({onOpen}) {
export function DownloadMenu({onOpen, disabled}) {
const [downloader, setDownloader] = useState();
const localOnOpen = (name) => {
@ -345,11 +351,33 @@ export function DownloadMenu({onOpen}) {
}
let body = (<>
<Button color='blue' content='Videos' onClick={() => localOnOpen('video')} style={{marginBottom: '1em'}}/>
<Button color='green' content='Archive' onClick={() => localOnOpen('archive')} style={{marginBottom: '1em'}}/>
<Button color='blue' content='Channel/Playlist' onClick={() => localOnOpen('video_channel')}
style={{marginBottom: '1em'}}/>
<Button content='RSS Feed' onClick={() => localOnOpen('rss')} style={{marginBottom: '1em'}}/>
<Button
color='blue'
content='Videos'
disabled={disabled}
onClick={() => localOnOpen('video')}
style={{marginBottom: '1em'}}
/>
<Button
color='green'
content='Archive'
disabled={disabled}
onClick={() => localOnOpen('archive')}
style={{marginBottom: '1em'}}
/>
<Button
color='blue'
content='Channel/Playlist'
disabled={disabled}
onClick={() => localOnOpen('video_channel')}
style={{marginBottom: '1em'}}
/>
<Button
content='RSS Feed'
disabled={disabled}
onClick={() => localOnOpen('rss')}
style={{marginBottom: '1em'}}
/>
</>);
function clearSelected() {
@ -358,12 +386,19 @@ export function DownloadMenu({onOpen}) {
}
const downloaders = {
'archive': <Downloader clearSelected={clearSelected} header={<><Icon name='file alternate'/> Archive</>}
downloader='archive'/>,
'video': <Downloader clearSelected={clearSelected} header={<><Icon name='video'/> Videos</>}
downloader='video' withDestination={true}/>,
'video_channel': <ChannelDownload clearSelected={clearSelected}/>,
'rss': <RSSDownload clearSelected={clearSelected} header={<><Icon name='rss square'/> RSS</>}/>,
archive: <Downloader
clearSelected={clearSelected}
header={<><Icon name='file alternate'/> Archive</>}
downloader='archive'/>,
video: <Downloader
clearSelected={clearSelected}
header={<><Icon name='video'/> Videos</>}
downloader='video'
withDestination={true}/>,
video_channel: <ChannelDownload clearSelected={clearSelected}/>,
rss: <RSSDownload
clearSelected={clearSelected}
header={<><Icon name='rss square'/> RSS</>}/>,
};
body = downloader in downloaders ? downloaders[downloader] : body;

View file

@ -22,7 +22,7 @@ import {deleteFile, refreshDirectoryFiles, refreshFiles} from "../api";
import {
CardGroupCentered,
CardPosterLink, cardTitleWrapper,
epochToDateString,
isoDatetimeToString,
ExternalCardLink,
FileIcon,
humanFileSize,
@ -242,7 +242,7 @@ function ImageCard({file}) {
</ExternalCardLink>
</CardHeader>
<CardMeta {...s}>
<p>{epochToDateString(file.modified / 1000)}</p>
<p>{isoDatetimeToString(file.modified / 1000)}</p>
</CardMeta>
<CardDescription {...s}>
<p>{humanFileSize(file.size)}</p>
@ -284,7 +284,7 @@ function FileCard({file}) {
{cardTitleWrapper(file.title || file.stem || file.path)}
</ExternalCardLink>
</CardHeader>
<p>{epochToDateString(file.modified / 1000)}</p>
<p>{isoDatetimeToString(file.modified / 1000)}</p>
<p>{size}</p>
</CardContent>
</Card>

View file

@ -2,7 +2,7 @@ import React, {useContext, useState} from 'react';
import {deleteVideos} from "../api";
import {Link, useNavigate, useParams} from "react-router-dom";
import _ from "lodash";
import {BackButton, epochToDateString, humanFileSize, humanNumber, PageContainer, useTitle} from "./Common";
import {BackButton, isoDatetimeToString, humanFileSize, humanNumber, PageContainer, useTitle} from "./Common";
import {Confirm} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
@ -175,7 +175,7 @@ function VideoPage({videoFile, prevFile, nextFile, setFavorite, ...props}) {
<Segment>
<Header as='h2'>{video.title || video.video_path}</Header>
{video.upload_date && <h3>{epochToDateString(video.upload_date)}</h3>}
{video.upload_date && <h3>{isoDatetimeToString(video.upload_date)}</h3>}
<h3>
{channel && <Link to={`/videos/channel/${channel.id}/video`}>
{channel.name}

View file

@ -6,7 +6,7 @@ import {
defaultSearchOrder,
defaultVideoOrder,
Duration,
epochToDateString,
isoDatetimeToString,
FileIcon,
isEmpty,
mimetypeColor,
@ -310,7 +310,7 @@ export function VideoCard({file}) {
const {s} = useContext(ThemeContext);
let video_url = `/videos/video/${video.id}`;
const upload_date = epochToDateString(video.upload_date);
const upload_date = isoDatetimeToString(video.upload_date);
// A video may not have a channel.
const channel = video.channel ? video.channel : null;
let channel_url = null;

View file

@ -4,7 +4,7 @@ import {Link} from "react-router-dom";
import {
DisableDownloadsToggle,
isEmpty,
secondsToElapsedPopup,
isoDatetimeToElapsedPopup,
secondsToFrequency,
textEllipsis,
useTitle,
@ -162,10 +162,10 @@ class DownloadRow extends React.Component {
</TableCell>
<TableCell>{secondsToFrequency(frequency)}</TableCell>
<TableCell>
{last_successful_download ? secondsToElapsedPopup(last_successful_download) : null}
{last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null}
{status === 'pending' ? <Loader active inline size='tiny'/> : null}
</TableCell>
<TableCell>{secondsToElapsedPopup(next_download)}</TableCell>
<TableCell>{next_download ? isoDatetimeToElapsedPopup(next_download) : null}</TableCell>
<TableCell>
{error && errorModal}
{deleteButton}
@ -223,7 +223,7 @@ class StoppableRow extends React.Component {
(text) => <Link to={location}>{text}</Link> :
(text) => <a href={url} target='_blank' rel='noopener noreferrer'>{text}</a>;
let completedAtCell = last_successful_download ? secondsToElapsedPopup(last_successful_download) : null;
let completedAtCell = last_successful_download ? isoDatetimeToElapsedPopup(last_successful_download) : null;
let buttonCell = <TableCell/>;
if (status === 'pending' || status === 'new') {
buttonCell = (

View file

@ -28,7 +28,6 @@ export class Settings extends React.Component {
hotspot_status: null,
throttle_on_startup: null,
throttle_status: null,
timezone: {timezone: null},
}
this.handleSubmit = this.handleSubmit.bind(this);
@ -50,7 +49,6 @@ export class Settings extends React.Component {
hotspot_status: settings.hotspot_status,
throttle_on_startup: settings.throttle_on_startup,
throttle_status: settings.throttle_status,
timezone: {value: settings.timezone, label: settings.timezone},
}, this.handleHotspotChange);
} catch (e) {
console.error(e);
@ -68,7 +66,6 @@ export class Settings extends React.Component {
hotspot_password: this.state.hotspot_password,
hotspot_ssid: this.state.hotspot_ssid,
throttle_on_startup: this.state.throttle_on_startup,
timezone: this.state.timezone.value,
}
await saveSettings(settings);
this.setState({disabled: false, pending: false});

View file

@ -10,13 +10,13 @@ import {
getDownloaders,
getDownloads,
getFiles,
getStatistics,
getInventory,
getSettings,
getVideosStatistics,
getStatistics,
getStatus,
getThrottleStatus,
getVideo,
getVideosStatistics,
killDownloads,
searchArchives,
searchVideos,
@ -670,6 +670,7 @@ export const useStatusInterval = () => {
return {status, fetchStatus};
}
export const useVideoStatistics = () => {
const [statistics, setStatistics] = useState({});

25
main.py
View file

@ -3,15 +3,16 @@ import argparse
import logging
import sys
import pytz
from sanic import Sanic
from sanic.signals import Event
from wrolpi import flags
from wrolpi import root_api, BEFORE_STARTUP_FUNCTIONS, admin
from wrolpi.common import logger, get_config, import_modules, check_media_directory, limit_concurrent, wrol_mode_enabled
from wrolpi.dates import set_timezone
from wrolpi.common import logger, get_config, import_modules, check_media_directory, limit_concurrent, \
wrol_mode_enabled, cancel_refresh_tasks
from wrolpi.downloader import download_manager, import_downloads_config
from wrolpi.files.lib import cancel_refresh_tasks
from wrolpi.events import Events
from wrolpi import flags
from wrolpi.root_api import api_app
from wrolpi.vars import PROJECT_DIR, DOCKERIZED, PYTEST
from wrolpi.version import get_version_string
@ -121,11 +122,7 @@ def main():
if args.sub_commands == 'db':
return db_main(args)
# Set the Timezone
config = get_config()
if config.timezone:
tz = pytz.timezone(config.timezone)
set_timezone(tz)
# Hotspot/throttle are not supported in Docker containers.
if not DOCKERIZED and config.hotspot_on_startup:
@ -171,10 +168,16 @@ def set_log_level(args):
@api_app.before_server_start
async def download_startup(app: Sanic):
async def startup(app: Sanic):
flags.init_flags()
await import_downloads_config()
@api_app.after_server_start
async def ready(app: Sanic):
Events.send_ready()
@api_app.after_server_start
async def periodic_downloads(app: Sanic):
"""
@ -182,6 +185,10 @@ async def periodic_downloads(app: Sanic):
Limited to only one process.
"""
if not flags.refresh_complete:
logger.warning('Refusing to download without refresh')
return
# Set all downloads to new.
download_manager.reset_downloads()

View file

@ -5,10 +5,10 @@ import pathlib
from uuid import uuid4
import pytest
import pytz
from modules.archive.lib import archive_strftime
from modules.archive.models import Archive, Domain
from wrolpi.dates import local_timezone
from wrolpi.files.models import File
@ -22,7 +22,7 @@ def archive_directory(test_directory) -> pathlib.Path:
@pytest.fixture
def archive_factory(test_session, archive_directory, make_files_structure):
def time_generator():
timestamp = datetime.datetime(2000, 1, 1, 0, 0, 0)
timestamp = datetime.datetime(2000, 1, 1, 0, 0, 0).astimezone(pytz.UTC)
while True:
timestamp += datetime.timedelta(seconds=1)
yield timestamp
@ -39,7 +39,7 @@ def archive_factory(test_session, archive_directory, make_files_structure):
domain_dir = archive_directory / domain_dir
domain_dir.mkdir(exist_ok=True)
archive_datetime = local_timezone(next(now))
archive_datetime = next(now)
timestamp = archive_strftime(archive_datetime)
json_contents = {}

View file

@ -15,10 +15,10 @@ from bs4 import BeautifulSoup
from selenium import webdriver
from modules.archive.models import Domain, Archive
from wrolpi.cmd import which
from wrolpi.cmd import READABILITY_BIN, SINGLE_FILE_BIN, CHROMIUM
from wrolpi.common import get_media_directory, logger, extract_domain, chdir, escape_file_name, walk, \
aiohttp_post, match_paths_to_suffixes, iterify
from wrolpi.dates import now, Seconds, local_timezone
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs, optional_session
from wrolpi.errors import UnknownArchive, InvalidOrderBy
from wrolpi.files.lib import handle_search_results
@ -146,21 +146,10 @@ async def request_archive(url: str) -> Tuple[str, Optional[str], Optional[str]]:
return singlefile, readability, screenshot
SINGLE_FILE_BIN = which('single-file',
'/usr/bin/single-file', # rpi ubuntu
'/usr/local/bin/single-file', # debian
warn=True)
CHROMIUM = which('chromium-browser', 'chromium',
'/usr/bin/chromium-browser', # rpi ubuntu
'/usr/bin/chromium', # debian
warn=True
)
def local_singlefile(url: str):
"""Run the single-file executable to create an HTML file archive."""
if not SINGLE_FILE_BIN.is_file():
raise FileNotFoundError(f'single-file not found')
if not SINGLE_FILE_BIN or not SINGLE_FILE_BIN.is_file():
raise FileNotFoundError(f'single-file not found. Is it installed?')
cmd = (str(SINGLE_FILE_BIN),
url,
@ -193,12 +182,6 @@ def local_screenshot(url: str) -> bytes:
return png
READABILITY_BIN = which('readability-extractor',
'/usr/bin/readability-extractor', # rpi ubuntu
'/usr/local/bin/readability-extractor', # debian
warn=True)
def local_extract_readability(path: str, url: str) -> dict:
"""Extract the readability from an HTML file, typically from single-file."""
logger.info(f'readability for {url}')
@ -364,9 +347,9 @@ def delete_archives(*archive_ids: List[int]):
def archive_strptime(dt: str) -> datetime:
try:
return local_timezone(datetime.strptime(dt, '%Y-%m-%d-%H-%M-%S'))
return datetime.strptime(dt, '%Y-%m-%d-%H-%M-%S')
except ValueError:
return local_timezone(datetime.strptime(dt, '%Y-%m-%d %H:%M:%S'))
return datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
def archive_strftime(dt: datetime) -> str:

View file

@ -10,7 +10,6 @@ from modules.archive import lib
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archives, do_archive, get_domains, \
group_archive_files, ArchiveFiles
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
@ -533,8 +532,8 @@ def test_group_archive_files(test_directory):
readability_json=pathlib.Path('2021-10-05 16:20:10.346823.readability.json'),
)
assert list(group_archive_files(files)) == [
(local_timezone(datetime(2000, 1, 1, 0, 0, 0)), group1),
(local_timezone(datetime(2021, 10, 5, 16, 20, 10)), group2),
(datetime(2000, 1, 1, 0, 0, 0), group1),
(datetime(2021, 10, 5, 16, 20, 10), group2),
]

View file

@ -1,4 +1,5 @@
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Union, Optional
@ -19,7 +20,7 @@ class ItemPostRequest:
def __post_init__(self):
self.item_size = Decimal(self.item_size) if self.item_size else None
self.count = Decimal(self.count) if self.count else None
self.expiration_date = from_timestamp(float(self.expiration_date)) if self.expiration_date else None
self.expiration_date = datetime.fromisoformat(self.expiration_date) if self.expiration_date else None
@dataclass
@ -33,19 +34,19 @@ class ItemPutRequest:
serving: Union[str, Decimal, None]
category: Optional[str]
subcategory: Optional[str]
expiration_date: Optional[float]
expiration_date: Optional[str]
purchase_date: Optional[float]
inventory_id: int
created_at: Optional[float]
deleted_at: Optional[float]
created_at: Optional[str]
deleted_at: Optional[str]
def __post_init__(self):
self.item_size = Decimal(self.item_size) if self.item_size else None
self.count = Decimal(self.count) if self.count else None
self.serving = Decimal(self.serving) if self.serving else None
self.expiration_date = from_timestamp(self.expiration_date) if self.expiration_date else None
self.created_at = from_timestamp(self.created_at) if self.created_at else None
self.deleted_at = from_timestamp(self.deleted_at) if self.deleted_at else None
self.expiration_date = datetime.fromisoformat(self.expiration_date) if self.expiration_date else None
self.created_at = datetime.fromisoformat(self.created_at) if self.created_at else None
self.deleted_at = datetime.fromisoformat(self.deleted_at) if self.deleted_at else None
@dataclass

View file

@ -66,7 +66,7 @@ def test_item_api(test_session, init_test_inventory, test_client):
# assert item == response.json['items'][0]
item = response.json['items'][0]
expiration_dates = (12345.12345, None)
expiration_dates = ('1969-12-31T20:25:45.123450', None)
for expiration_date in expiration_dates:
item['expiration_date'] = expiration_date
request, response = test_client.put(f'/api/inventory/item/{item["id"]}', content=json.dumps(item))

View file

@ -7,7 +7,7 @@ from typing import List
from sqlalchemy.orm import Session
from modules.map.models import MapFile
from wrolpi.cmd import which
from wrolpi.cmd import BASH_BIN
from wrolpi.common import get_media_directory, walk, logger, wrol_mode_check
from wrolpi.dates import now, timedelta_to_timestamp
from wrolpi.db import optional_session, get_db_session
@ -158,9 +158,6 @@ async def import_files(paths: List[str]):
IMPORT_EVENT.clear()
BASH_BIN = which('bash', '/bin/bash', warn=True)
async def run_import_command(*paths: Path):
"""Run the map import script on the provided paths.

View file

@ -14,7 +14,8 @@ import PIL
from PIL import Image
from sqlalchemy.orm import Session
from wrolpi.cmd import which
from wrolpi.captions import FFMPEG_BIN
from wrolpi.cmd import FFPROBE_BIN
from wrolpi.common import logger, iterify, get_media_directory, \
minimize_dict, match_paths_to_suffixes
from wrolpi.db import get_db_session, get_db_curs
@ -35,8 +36,6 @@ MINIMUM_VIDEO_KEYS = {'id', 'title', 'upload_date', 'duration', 'channel', 'chan
# These are the supported video formats. These are in order of their preference.
VIDEO_EXTENSIONS = ('mp4', 'ogg', 'webm', 'flv')
FFMPEG_BIN = which('ffmpeg', '/usr/bin/ffmpeg', warn=True)
class ConfigError(Exception):
pass
@ -170,9 +169,6 @@ def is_valid_poster(poster_path: Path) -> bool:
return False
FFPROBE_BIN = which('ffprobe', '/usr/bin/ffprobe', warn=True)
def get_video_duration(video_path: Path) -> int:
"""Get the duration of a video in seconds. Do this using ffprobe."""
if not isinstance(video_path, Path):

View file

@ -12,7 +12,7 @@ from yt_dlp import YoutubeDL
from yt_dlp.extractor import YoutubeTabIE # noqa
from yt_dlp.utils import UnsupportedError, DownloadError
from wrolpi.cmd import which
from wrolpi.cmd import YT_DLP_BIN
from wrolpi.common import logger, get_media_directory, escape_file_name
from wrolpi.dates import now
from wrolpi.db import get_db_session, get_db_curs
@ -163,14 +163,6 @@ class ChannelDownloader(Downloader, ABC):
return downloads
YT_DLP_BIN = which(
'yt-dlp',
'/usr/local/bin/yt-dlp', # Location in docker container
'/opt/wrolpi/venv/bin/yt-dlp', # Use virtual environment location
warn=True,
)
class VideoDownloader(Downloader, ABC):
"""Downloads a single video.

View file

@ -6,11 +6,12 @@ from typing import List
from unittest import mock
import pytest
import pytz
from PIL import Image
from modules.videos.models import Channel, Video
from wrolpi.common import get_absolute_media_path, sanitize_link
from wrolpi.dates import local_timezone, now
from wrolpi.dates import now
from wrolpi.downloader import Download, DownloadFrequency
from wrolpi.vars import PROJECT_DIR
from .. import common
@ -203,7 +204,7 @@ def test_import_favorites(test_session, test_directory, simple_channel, video_fa
video_factory(channel_id=simple_channel.id) # never favorited
vid2 = video_factory(channel_id=None) # has no channel
vid3 = video_factory(channel_id=simple_channel.id)
favorite = vid3.favorite = vid2.favorite = local_timezone(datetime(2000, 1, 1, 0, 0, 0))
favorite = vid3.favorite = vid2.favorite = datetime(2000, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
test_session.commit()
vid2_video_path = vid2.video_path

View file

@ -3,7 +3,7 @@ Pint==0.18
PyPDF2[crypto]==2.11.2
PyYAML==5.3.1 # this is the only version available on RPi
SQLAlchemy==1.3.22
aiohttp==3.8.1
aiohttp==3.8.3
alembic==1.7.5
beautifulsoup4==4.10.0
cachetools==5.0.0

View file

@ -1,17 +1,12 @@
import enum
import subprocess
from wrolpi.cmd import which
from wrolpi.cmd import NMCLI_BIN, CPUFREQ_INFO_BIN, SUDO_BIN, CPUFREQ_SET_BIN
from wrolpi.common import logger, WROLPI_CONFIG, get_warn_once
from wrolpi.vars import DEFAULT_CPU_FREQUENCY, DOCKERIZED
logger = logger.getChild(__name__)
SUDO_BIN = which('sudo', '/usr/bin/sudo')
NMCLI_BIN = which('nmcli', '/usr/bin/nmcli')
CPUFREQ_INFO_BIN = which('cpufreq-info', '/usr/bin/cpufreq-info')
CPUFREQ_SET_BIN = which('cpufreq-set', '/usr/bin/cpufreq-set')
POWER_SAVE_FREQ = 'powersave' # noqa
warn_once = get_warn_once('Unable to use nmcli', logger)

View file

@ -8,7 +8,7 @@ from typing import Generator, Union, Optional
import srt
import webvtt
from wrolpi.cmd import which
from wrolpi.cmd import FFMPEG_BIN
from wrolpi.common import logger
__all__ = ['read_captions', 'extract_captions']
@ -60,9 +60,6 @@ def read_captions(caption_path: Path):
logger.debug(f'Failed to parse caption file {caption_path}')
FFMPEG_BIN = which('ffmpeg', '/usr/bin/ffmpeg')
def extract_captions(path: pathlib.Path) -> Optional[str]:
"""Extract captions that are embedded in a video file."""
with tempfile.TemporaryDirectory() as directory:

View file

@ -1,7 +1,10 @@
"""Paths for third-party commands that WROLPi may require."""
import os
import shutil
from pathlib import Path
from typing import Optional
from wrolpi import flags
from wrolpi.common import logger
from wrolpi.vars import PYTEST, DOCKERIZED
@ -13,22 +16,75 @@ def is_executable(path: Path) -> bool:
return path.is_file() and os.access(path, os.X_OK)
def which(*possible_paths: str, warn: bool = False) -> Path:
def which(*possible_paths: str, warn: bool = False, flag: str = None) -> Optional[Path]:
"""
Find an executable in the system $PATH. If the executable cannot be found in $PATH, then return the first
executable found in possible_paths.
Returns None if no executable can be found.
"""
found = None
possible_paths = list(map(Path, possible_paths))
for path in possible_paths:
if is_executable(path):
# `path` was an absolute file which is executable.
return path.absolute()
found = path
break
path = shutil.which(path)
if path and (path := Path(path).absolute()) and is_executable(path):
# `path` was a name or relative path.
return path
found = path
if warn and not PYTEST and not DOCKERIZED:
if not found and warn and not PYTEST and not DOCKERIZED:
logger.warning(f'Cannot find executable {possible_paths[0]}')
return
elif found:
if flag:
# Mark the command as installed.
try:
getattr(flags, flag).set()
except AttributeError as e:
logger.error(f'Unable to set flag {flag}', exc_info=e)
return found.absolute()
# Admin
SUDO_BIN = which('sudo', '/usr/bin/sudo')
NMCLI_BIN = which('nmcli', '/usr/bin/nmcli', flag='nmcli_installed')
CPUFREQ_INFO_BIN = which('cpufreq-info', '/usr/bin/cpufreq-info')
CPUFREQ_SET_BIN = which('cpufreq-set', '/usr/bin/cpufreq-set')
# Map
BASH_BIN = which('bash', '/bin/bash', warn=True)
# Archive
SINGLE_FILE_BIN = which('single-file',
'/usr/bin/single-file', # rpi ubuntu
'/usr/local/bin/single-file', # debian
warn=True,
flag='singlefile_installed',
)
CHROMIUM = which('chromium-browser', 'chromium',
'/usr/bin/chromium-browser', # rpi ubuntu
'/usr/bin/chromium', # debian
warn=True,
flag='chromium_installed',
)
READABILITY_BIN = which('readability-extractor',
'/usr/bin/readability-extractor', # rpi ubuntu
'/usr/local/bin/readability-extractor', # debian
warn=True,
flag='readability_installed',
)
# Videos
YT_DLP_BIN = which(
'yt-dlp',
'/usr/local/bin/yt-dlp', # Location in docker container
'/opt/wrolpi/venv/bin/yt-dlp', # Use virtual environment location
warn=True,
flag='yt_dlp_installed',
)
FFPROBE_BIN = which('ffprobe', '/usr/bin/ffprobe', warn=True, flag='ffprobe_installed')
FFMPEG_BIN = which('ffmpeg', '/usr/bin/ffmpeg', flag='ffmpeg_installed')

View file

@ -28,7 +28,7 @@ from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from wrolpi.dates import DEFAULT_TIMEZONE, now
from wrolpi.dates import now, from_timestamp
from wrolpi.errors import WROLModeEnabled, NativeOnly
from wrolpi.vars import PYTEST, MODULES_DIR, \
DOCKERIZED, CONFIG_DIR, MEDIA_DIRECTORY
@ -96,6 +96,8 @@ __all__ = [
'get_warn_once',
'ordered_unique_list',
'truncate_generator_bytes',
'cancel_refresh_tasks',
'cancelable_wrapper',
]
# Base is used for all SQLAlchemy models.
@ -246,7 +248,6 @@ class WROLPiConfig(ConfigFile):
hotspot_password='wrolpi hotspot',
hotspot_ssid='WROLPi',
throttle_on_startup=False,
timezone=str(DEFAULT_TIMEZONE),
wrol_mode=False,
)
@ -306,14 +307,6 @@ class WROLPiConfig(ConfigFile):
def throttle_on_startup(self, value: bool):
self.update({'throttle_on_startup': value})
@property
def timezone(self) -> str:
return self._config['timezone']
@timezone.setter
def timezone(self, value: str):
self.update({'timezone': value})
@property
def wrol_mode(self) -> bool:
return self._config['wrol_mode']
@ -710,7 +703,7 @@ def zig_zag(low: ZIG_TYPE, high: ZIG_TYPE) -> Generator[ZIG_TYPE, None, None]:
raise ValueError(f'high and low must be same type')
if isinstance(low, datetime) and isinstance(high, datetime):
low, high = low.timestamp(), high.timestamp()
output_type = datetime.fromtimestamp
output_type = from_timestamp
# Special thanks to my wife for helping me solve this! :*
results = set()
@ -1021,7 +1014,14 @@ def background_task(coro) -> Task:
The task is stored in a global set of background tasks so the task will not be discarded by the garbage collector.
"""
task = asyncio.create_task(coro)
async def error_logger():
try:
await coro
except Exception as e:
logger.error('Background task had error', exc_info=e)
task = asyncio.create_task(error_logger())
BACKGROUND_TASKS.add(task)
task.add_done_callback(BACKGROUND_TASKS.discard)
return task
@ -1055,3 +1055,30 @@ def get_global_statistics():
return dict(
db_size=db_size,
)
REFRESH_TASKS: List[Task] = []
async def cancel_refresh_tasks():
"""Cancel all refresh tasks, if any."""
if REFRESH_TASKS:
logger.warning(f'Canceling {len(REFRESH_TASKS)} refreshes')
for task in REFRESH_TASKS:
task.cancel()
await asyncio.gather(*REFRESH_TASKS)
def cancelable_wrapper(func: callable):
"""Wraps an async function so that it will be canceled by `cancel_refresh_tasks`."""
@wraps(func)
async def wrapped(*args, **kwargs):
if PYTEST:
return await func(*args, **kwargs)
task = background_task(func(*args, **kwargs))
REFRESH_TASKS.append(task)
return wrapped

View file

@ -2,6 +2,7 @@
Fixtures for Pytest tests.
"""
import asyncio
import multiprocessing
import pathlib
import shutil
import tempfile
@ -17,6 +18,7 @@ from sanic_testing.testing import SanicTestClient
from sqlalchemy.engine import Engine, create_engine
from sqlalchemy.orm import Session, sessionmaker
from wrolpi import flags
from wrolpi.common import iterify
from wrolpi.common import set_test_media_directory, Base, set_test_config
from wrolpi.dates import set_test_now
@ -116,7 +118,7 @@ def test_client() -> SanicTestClient:
api_app.blueprint(bp)
ROUTES_ATTACHED = True
return api_app.test_client
yield api_app.test_client
@pytest.fixture
@ -313,3 +315,25 @@ def mock_create_subprocess_shell():
return create_subprocess_shell
return mocker
@pytest.fixture(autouse=True)
def events_history():
"""Give each test it's own Events history."""
with mock.patch('wrolpi.events.EVENTS_HISTORY', list()):
yield
FLAGS_LOCK = multiprocessing.Lock()
@pytest.fixture()
def flags_lock():
"""Wait for exclusive access to flags before testing."""
try:
FLAGS_LOCK.acquire(timeout=60)
flags.TESTING_LOCK.set()
yield
finally:
flags.TESTING_LOCK.clear()
FLAGS_LOCK.release()

View file

@ -1,17 +1,15 @@
import logging
from datetime import datetime, date, timezone, timedelta
from datetime import datetime, timezone, timedelta
from enum import Enum
from typing import Union
import pytz
from sqlalchemy import types
from wrolpi.errors import InvalidTimezone
from wrolpi.vars import DATETIME_FORMAT, DATETIME_FORMAT_MS, DEFAULT_TIMEZONE_STR
from wrolpi.vars import DATETIME_FORMAT_MS
logger = logging.getLogger(__name__)
DEFAULT_TIMEZONE = pytz.timezone(DEFAULT_TIMEZONE_STR)
TEST_DATETIME: datetime = None
@ -23,55 +21,28 @@ class Seconds(int, Enum):
def set_test_now(dt: datetime):
if dt and not dt.tzinfo:
dt = local_timezone(dt)
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 set_timezone(tz: pytz.timezone):
"""Change the global timezone for WROLPi. This does NOT save the config."""
global DEFAULT_TIMEZONE
if not tz:
raise InvalidTimezone('Timezone cannot be blank!')
if isinstance(tz, str):
tz = pytz.timezone(tz)
logger.info(f'Setting timezone: {tz}')
DEFAULT_TIMEZONE = tz
def utc_now() -> datetime:
"""Get the current DateTime in UTC. Timezone aware."""
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 now(tz: pytz.timezone = None) -> datetime:
"""Get the current DateTime in the provided timezone. Timezone aware."""
if TEST_DATETIME:
return TEST_DATETIME
return datetime.now(tz=tz or DEFAULT_TIMEZONE)
def local_timezone(dt: datetime) -> datetime:
"""Convert the DateTime provided to the local Timezone. Timezone aware."""
return dt.astimezone(DEFAULT_TIMEZONE)
def today() -> date:
"""Return today's date."""
return now().date()
def strftime(dt: datetime) -> str:
return dt.strftime(DATETIME_FORMAT)
return dt.isoformat()
def strptime(dt: str) -> datetime:
return local_timezone(datetime.strptime(dt, DATETIME_FORMAT))
return datetime.fromisoformat(dt).astimezone(pytz.UTC)
def strftime_ms(dt: datetime) -> str:
@ -79,11 +50,11 @@ def strftime_ms(dt: datetime) -> str:
def strptime_ms(dt: str) -> datetime:
return local_timezone(datetime.strptime(dt, DATETIME_FORMAT_MS))
return datetime.fromisoformat(dt).astimezone(pytz.UTC)
def from_timestamp(timestamp: float) -> datetime:
return local_timezone(datetime.fromtimestamp(timestamp))
return datetime.fromtimestamp(timestamp).astimezone(pytz.UTC)
def seconds_to_timestamp(seconds: Union[int, float]) -> str:
@ -114,13 +85,8 @@ def timedelta_to_timestamp(delta: timedelta) -> str:
return seconds_to_timestamp(delta.total_seconds())
def recursive_replace_tz(obj, tz=pytz.utc):
"""Recursively replace the timezone of any datetimes."""
from wrolpi.common import recursive_map
return recursive_map(obj, lambda i: i.replace(tzinfo=tz) if isinstance(i, datetime) else i)
class TZDateTime(types.TypeDecorator):
"""Forces all datetime to have a timezone. Stores all datetime in DB as UTC."""
impl = types.DateTime
cache_ok = True
@ -132,12 +98,10 @@ class TZDateTime(types.TypeDecorator):
value = value.astimezone(timezone.utc)
elif isinstance(value, str) and '-' in value:
value = datetime.fromisoformat(value)
value = value.astimezone(timezone.utc)
return value
def process_result_value(self, value: datetime, dialect):
if value is not None:
# Assume the DB timestamp is UTC if not specified.
# Assume the DB timestamp is UTC.
value = value.replace(tzinfo=pytz.utc) if not value.tzinfo else value
value = local_timezone(value)
return value

View file

@ -17,6 +17,7 @@ from typing import Tuple, Optional
from urllib.parse import urlparse
import feedparser
import pytz
from feedparser import FeedParserDict
from sqlalchemy import Column, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB
@ -24,7 +25,7 @@ from sqlalchemy.orm import Session
from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, ConfigFile, WROLPI_CONFIG, \
background_task, limit_concurrent
from wrolpi.dates import TZDateTime, now, Seconds, local_timezone, recursive_replace_tz
from wrolpi.dates import TZDateTime, now, Seconds
from wrolpi.db import get_db_session, get_db_curs, optional_session
from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError
from wrolpi.vars import PYTEST
@ -884,7 +885,6 @@ class DownloadManager:
'''
curs.execute(stmt)
recurring_downloads = list(map(dict, curs.fetchall()))
recurring_downloads = recursive_replace_tz(recurring_downloads)
stmt = f'''
SELECT
@ -907,7 +907,6 @@ class DownloadManager:
'''
curs.execute(stmt)
once_downloads = list(map(dict, curs.fetchall()))
once_downloads = recursive_replace_tz(once_downloads)
data = dict(
recurring_downloads=recurring_downloads,
@ -974,7 +973,7 @@ class DownloadManager:
index = downloads.index(download.id)
# Download was successful. Spread the same-frequency downloads out over their iteration.
start_date = local_timezone(datetime(2000, 1, 1))
start_date = datetime(2000, 1, 1).replace(tzinfo=pytz.UTC)
# Weeks/months/etc. since start_date.
iterations = ((now() - start_date) // freq).total_seconds()
# Download slots start the next nearest iteration since 2000-01-01.
@ -986,7 +985,7 @@ class DownloadManager:
# it will be downloaded the 3rd slot of next week.
zagger = zig_zag(start_date, end_date)
next_download = [i for i, j in zip(zagger, range(len(downloads)))][index]
next_download = local_timezone(next_download)
next_download = next_download
return next_download
@optional_session

93
wrolpi/events.py Normal file
View file

@ -0,0 +1,93 @@
import multiprocessing
__all__ = ['Events', 'get_events', 'send_event']
from datetime import datetime
from wrolpi.common import logger, iterify
from wrolpi.dates import now
logger = logger.getChild(__name__)
HISTORY_SIZE = 100
EVENTS_LOCK = multiprocessing.Lock()
EVENTS_HISTORY = multiprocessing.Manager().list()
class Events:
@staticmethod
def send_global_refresh_started(message: str = None):
send_event('global_refresh_started', message, subject='refresh')
@staticmethod
def send_global_refresh_completed(message: str = None):
send_event('global_refresh_completed', message, subject='refresh')
@staticmethod
def send_global_refresh_modeling_completed(message: str = None):
send_event('global_refresh_modeling_completed', message, subject='refresh')
@staticmethod
def send_global_refresh_indexing_completed(message: str = None):
send_event('global_refresh_indexing_completed', message, subject='refresh')
@staticmethod
def send_global_refresh_delete_completed(message: str = None):
send_event('global_refresh_delete_completed', message, subject='refresh')
@staticmethod
def send_ready(message: str = None):
send_event('ready', message)
@staticmethod
def send_directory_refresh_started(message: str):
send_event('global_directory_refresh_started', message, subject='refresh_directory')
@staticmethod
def send_directory_refresh_completed(message: str):
send_event('global_directory_refresh_completed', message, subject='refresh_directory')
@staticmethod
def send_refresh_required(message: str = None):
send_event('refresh_required', message, subject='refresh_required')
@staticmethod
def send_singlefile_missing():
send_event('singlefile_missing', subject='install')
def send_event(event: str, message: str = None, action: str = None, subject: str = None):
EVENTS_LOCK.acquire()
try:
# All events will be in time order, they should never be at the exact same time.
dt = now()
e = dict(
action=action,
dt=dt,
event=event,
message=message,
subject=subject,
)
EVENTS_HISTORY.append(e)
# Keep events below limit.
while len(EVENTS_HISTORY) > HISTORY_SIZE:
EVENTS_HISTORY.pop(0)
finally:
EVENTS_LOCK.release()
logger.debug(f'Sent event {event}')
@iterify(list)
def get_events(after: datetime = None):
if not after:
events = [i for i in EVENTS_HISTORY]
else:
events = [i for i in EVENTS_HISTORY if i['dt'] > after]
# Most recent first.
return events[::-1]

View file

@ -6,22 +6,23 @@ import os
import pathlib
import re
import subprocess
from asyncio import Task
from functools import wraps
from pathlib import Path
from typing import List, Tuple, Union
import psycopg2
from sqlalchemy.orm import Session
from wrolpi import flags
from wrolpi.cmd import which
from wrolpi.common import get_media_directory, wrol_mode_check, logger, limit_concurrent, \
get_files_and_directories, apply_modelers, apply_after_refresh, get_model_by_table_name, chunks_by_stem, \
background_task, partition, ordered_unique_list, chunks
partition, ordered_unique_list, chunks, cancelable_wrapper
from wrolpi.dates import now
from wrolpi.db import get_db_session, get_db_curs, get_ranked_models
from wrolpi.errors import InvalidFile
from wrolpi.events import Events
from wrolpi.files.models import File
from wrolpi import flags
from wrolpi.vars import PYTEST, FILE_REFRESH_CHUNK_SIZE
try:
@ -220,32 +221,6 @@ async def _refresh_directory_files_recursively(directory: pathlib.Path, idempote
raise
REFRESH_TASKS: List[Task] = []
async def cancel_refresh_tasks():
"""Cancel all refresh tasks, if any."""
if REFRESH_TASKS:
refresh_logger.warning(f'Canceling {len(REFRESH_TASKS)} refreshes')
for task in REFRESH_TASKS:
task.cancel()
await asyncio.gather(*REFRESH_TASKS)
def cancelable_wrapper(func: callable):
"""Wraps an async function so that it will be canceled by `cancel_refresh_tasks`."""
@wraps(func)
async def wrapped(*args, **kwargs):
if PYTEST:
return await func(*args, **kwargs)
task = background_task(func(*args, **kwargs))
REFRESH_TASKS.append(task)
return wrapped
@cancelable_wrapper
async def apply_indexers():
"""Finds all Files that have not been indexed and indexes them."""
@ -344,28 +319,39 @@ async def refresh_files_list(paths: List[str], include_files_near: bool = True):
@cancelable_wrapper
async def refresh_files():
"""Find, model, and index all files in the media directory."""
refresh_logger.warning('Refreshing all files')
with flags.refreshing:
refresh_logger.warning('Refreshing all files')
Events.send_global_refresh_started()
# TODO remove this later when everyone has migrated their files.
from modules.archive.lib import migrate_archive_files
migrate_archive_files()
# TODO remove this later when everyone has migrated their files.
from modules.archive.lib import migrate_archive_files
migrate_archive_files()
idempotency = now()
idempotency = now()
# Add all files in the media directory to the DB.
await _refresh_directory_files_recursively(get_media_directory(), idempotency)
# Add all files in the media directory to the DB.
await _refresh_directory_files_recursively(get_media_directory(), idempotency)
# Remove any records where the file no longer exists.
with get_db_curs(commit=True) as curs:
curs.execute('DELETE FROM file WHERE idempotency < %s OR idempotency is null RETURNING path', (idempotency,))
deleted = list(curs.fetchall())
logger.debug(f'{deleted=}')
logger.warning(f'Removed {len(deleted)} missing files')
Events.send_global_refresh_modeling_completed()
apply_after_refresh()
await apply_indexers()
# Remove any records where the file no longer exists.
with get_db_curs(commit=True) as curs:
curs.execute('DELETE FROM file WHERE idempotency < %s OR idempotency is null RETURNING path',
(idempotency,))
deleted = list(curs.fetchall())
logger.debug(f'{deleted=}')
logger.warning(f'Removed {len(deleted)} missing files')
refresh_logger.warning('Done refreshing Files')
Events.send_global_refresh_delete_completed()
apply_after_refresh()
await apply_indexers()
Events.send_global_refresh_indexing_completed()
Events.send_global_refresh_completed()
refresh_logger.warning('Done refreshing Files')
flags.refresh_complete.set()
@limit_concurrent(1)
@ -380,6 +366,8 @@ async def refresh_directory_files_recursively(directory: Union[pathlib.Path, str
if directory.is_file():
raise ValueError(f'Cannot refresh files of a file: {directory=}')
Events.send_directory_refresh_started(f'Refresh of {repr(directory.name)} has started.')
# All Files older than this will be removed.
idempotency = now()
@ -404,6 +392,7 @@ async def refresh_directory_files_recursively(directory: Union[pathlib.Path, str
apply_after_refresh()
await apply_indexers()
Events.send_directory_refresh_completed(f'Refresh of {repr(directory.name)} has completed.')
refresh_logger.info(f'Done refreshing files in {directory}')

View file

@ -210,6 +210,11 @@ async def test_refresh_many_files(test_session, make_files_structure):
assert test_session.query(File).count() == count
@pytest.mark.asyncio
async def test_refresh_files_flags(test_session):
pass
@pytest.mark.asyncio
async def test_refresh_files_list(test_session, make_files_structure, test_directory):
make_files_structure(['foo.txt', 'bar.txt'])

151
wrolpi/flags.py Normal file
View file

@ -0,0 +1,151 @@
import multiprocessing
import threading
from typing import List
from sqlalchemy import Column, Boolean, Integer
from wrolpi.common import logger, Base
__all__ = [
'get_flags',
'refreshing',
'refresh_complete',
]
from wrolpi.vars import PYTEST
logger = logger.getChild(__name__)
TESTING_LOCK = multiprocessing.Event()
class Flag:
"""A simple wrapper around multiprocessing.Event.
This allows synchronization between the App and this API.
This may store it's value in the DB table wrolpi_flag."""
def __init__(self, name: str, store_db: bool = False):
if PYTEST:
# Use threading Event during testing to avoid tests clobbering each other.
self._flag = threading.Event()
else:
self._flag = multiprocessing.Event()
self.name = name
self.store_db = store_db
def __repr__(self):
return f'<Flag {repr(self.name)}>'
def set(self):
"""Set the multiprocessing.Event for this Flag."""
if PYTEST and not TESTING_LOCK.is_set():
# Testing, but the test does not need flags.
return
self._flag.set()
self._save(True)
def clear(self):
"""Clear the multiprocessing.Event for this Flag."""
if PYTEST and not TESTING_LOCK.is_set():
# Testing, but the test does not need flags.
return
self._flag.clear()
self._save(False)
def is_set(self):
"""Return True if this multiprocessing.Event is set."""
if PYTEST and not TESTING_LOCK.is_set():
# Testing, but the test does not need flags.
return
return self._flag.is_set()
def __enter__(self):
if PYTEST and not TESTING_LOCK.is_set():
# Testing, but the test does not need flags.
return
if self._flag.is_set():
raise ValueError(f'{self} flag is already set!')
self.set()
def __exit__(self, exc_type, exc_val, exc_tb):
if PYTEST and not TESTING_LOCK.is_set():
# Testing, but the test does not need flags.
return
self.clear()
def _save(self, value):
if self.store_db:
from wrolpi.db import get_db_curs
# Store the value of this Flag in it's matching column in the DB. Not all flags will do this.
try:
with get_db_curs(commit=True) as curs:
# Upsert the only row in the table.
curs.execute(f'''
INSERT INTO wrolpi_flag (id, {self.name}) VALUES (1, %(value)s)
ON CONFLICT (id) DO UPDATE SET {self.name} = %(value)s
''', dict(value=value))
except Exception as e:
logger.critical(f'Unable to save flag! {repr(self)}', exc_info=e)
# The global refresh is running.
refreshing = Flag('refreshing')
# The global refresh has been performed. This is False on a fresh instance of WROLPi.
refresh_complete = Flag('refresh_complete', store_db=True)
# Third party packages that may be required. See `cmd.py`
chromium_installed = Flag('chromium_installed')
ffmpeg_installed = Flag('ffmpeg_installed')
ffprobe_installed = Flag('ffprobe_installed')
nmcli_installed = Flag('nmcli_installed')
readability_installed = Flag('readability_installed')
yt_dlp_installed = Flag('yt_dlp_installed')
def get_flags() -> List[str]:
"""Return a list of all Flags which are set."""
flags = []
if refreshing.is_set():
flags.append('refreshing')
if refresh_complete.is_set():
flags.append('refresh_complete')
if chromium_installed.is_set():
flags.append('chromium_installed')
if ffmpeg_installed.is_set():
flags.append('ffmpeg_installed')
if ffprobe_installed.is_set():
flags.append('ffprobe_installed')
if nmcli_installed.is_set():
flags.append('nmcli_installed')
if readability_installed.is_set():
flags.append('readability_installed')
if yt_dlp_installed.is_set():
flags.append('yt_dlp_installed')
return flags
class WROLPiFlag(Base):
__tablename__ = 'wrolpi_flag'
id = Column(Integer, primary_key=True)
refresh_complete = Column(Boolean, default=False)
def __repr__(self):
return f'<WROLPiFlag refresh_complete={self.refresh_complete}>'
def init_flags():
"""Set flags to match their DB values."""
from wrolpi.db import get_db_session
with get_db_session() as session:
flags: WROLPiFlag = session.query(WROLPiFlag).one_or_none()
if flags:
if flags.refresh_complete is True:
refresh_complete.set()
else:
refresh_complete.clear()

View file

@ -1,14 +1,12 @@
import json
import json
import re
from datetime import datetime, date
from datetime import datetime, date, timezone
from decimal import Decimal
from functools import wraps
from http import HTTPStatus
from pathlib import Path
from typing import Union
from pytz import UnknownTimeZoneError
from sanic import Sanic, response, Blueprint, __version__ as sanic_version
from sanic.blueprint_group import BlueprintGroup
from sanic.request import Request
@ -20,11 +18,14 @@ from wrolpi import admin, status
from wrolpi.admin import HotspotStatus
from wrolpi.common import logger, get_config, wrol_mode_enabled, Base, get_media_directory, \
wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode, get_global_statistics
from wrolpi.dates import set_timezone
from wrolpi.dates import now, strptime
from wrolpi.downloader import download_manager
from wrolpi.errors import WROLModeEnabled, InvalidTimezone, API_ERRORS, APIError, ValidationError, HotspotError
from wrolpi.errors import WROLModeEnabled, API_ERRORS, APIError, ValidationError, HotspotError
from wrolpi.events import get_events
from wrolpi.files.lib import get_file_statistics
from wrolpi.schema import RegexRequest, RegexResponse, SettingsRequest, SettingsResponse, DownloadRequest, EchoResponse
from wrolpi.flags import get_flags
from wrolpi.schema import RegexRequest, RegexResponse, SettingsRequest, SettingsResponse, DownloadRequest, EchoResponse, \
EventsRequest
from wrolpi.vars import API_HOST, API_PORT, DOCKERIZED, API_DEBUG, API_ACCESS_LOG, API_WORKERS, API_AUTO_RELOAD, \
truthy_arg
from wrolpi.version import __version__
@ -147,7 +148,6 @@ def get_settings(_: Request):
'media_directory': str(get_media_directory()), # Convert to string to avoid conversion to relative.
'throttle_on_startup': config.throttle_on_startup,
'throttle_status': admin.throttle_status().name,
'timezone': config.timezone,
'version': __version__,
'wrol_mode': config.wrol_mode,
}
@ -171,12 +171,6 @@ def update_settings(_: Request, body: SettingsRequest):
enable_wrol_mode()
return response.empty()
try:
if body.timezone:
set_timezone(body.timezone)
except UnknownTimeZoneError:
raise InvalidTimezone(f'Invalid timezone: {body.timezone}')
# Remove any keys with None values, then save the config.
config = {k: v for k, v in body.__dict__.items() if v is not None}
wrolpi_config = get_config()
@ -343,6 +337,8 @@ async def get_status(_: Request):
logger.error('Unable to get download status', exc_info=e)
downloads = dict()
flags = get_flags()
ret = dict(
bandwidth=s.bandwidth,
cpu_info=s.cpu_info,
@ -350,6 +346,7 @@ async def get_status(_: Request):
dockerized=DOCKERIZED,
downloads=downloads,
drives=s.drives,
flags=flags,
hotspot_status=admin.hotspot_status().name,
load=s.load,
memory_stats=s.memory_stats,
@ -373,6 +370,15 @@ async def get_statistics(_):
})
@api_bp.get('/events/feed')
@validate(query=EventsRequest)
async def feed(_: Request, query: EventsRequest):
start = now()
after = None if query.after == 'None' else strptime(query.after)
events = get_events(after)
return json_response(dict(events=events, now=start))
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
@ -381,9 +387,11 @@ class CustomJSONEncoder(json.JSONEncoder):
# Get __json__ before others.
return obj.__json__()
elif isinstance(obj, datetime):
return obj.timestamp()
if obj.tzinfo == timezone.utc:
obj = obj.replace(tzinfo=None)
return obj.isoformat()
elif isinstance(obj, date):
return datetime(obj.year, obj.month, obj.day).timestamp()
return datetime(obj.year, obj.month, obj.day).isoformat()
elif isinstance(obj, Decimal):
return str(obj)
elif isinstance(obj, Base):

View file

@ -24,7 +24,6 @@ class SettingsRequest:
media_directory: Optional[str] = None
throttle_on: Optional[bool] = None
throttle_on_startup: Optional[bool] = None
timezone: Optional[str] = None
wrol_mode: Optional[bool] = None
@ -60,3 +59,8 @@ class DownloadRequest:
@dataclass
class JSONErrorResponse:
error: str
@dataclass
class EventsRequest:
after: Optional[str] = None

View file

@ -12,11 +12,12 @@ from time import sleep
from unittest import mock
import pytest
import pytz
import wrolpi.vars
from wrolpi import common
from wrolpi.common import cum_timer, TIMERS, print_timer, limit_concurrent, run_after
from wrolpi.dates import set_timezone, now
from wrolpi.dates import now
from wrolpi.errors import InvalidTimezone
from wrolpi.test.common import build_test_directories
@ -186,22 +187,6 @@ class TestCommon(unittest.TestCase):
date(1970, 1, 6),
]
def test_set_timezone(self):
"""
The global timezone can be changed. Invalid timezones are rejected.
"""
original_timezone = now().tzinfo
try:
self.assertRaises(InvalidTimezone, set_timezone, '')
self.assertEqual(now().tzinfo, original_timezone)
set_timezone('US/Pacific')
self.assertNotEqual(now().tzinfo, original_timezone)
finally:
# Restore the timezone before the test.
set_timezone(original_timezone)
@pytest.mark.parametrize(
'i,expected', [
@ -271,9 +256,10 @@ def test_chdir():
Decimal('81.25'), Decimal('93.75'), Decimal('53.125'), Decimal('59.375'), Decimal('65.625')
]),
# Datetimes are supported.
(datetime(2000, 1, 1), datetime(2000, 1, 8), [
datetime(2000, 1, 1), datetime(2000, 1, 4, 12), datetime(2000, 1, 2, 18), datetime(2000, 1, 6, 6),
datetime(2000, 1, 1, 21), datetime(2000, 1, 3, 15),
(datetime(2000, 1, 1, tzinfo=pytz.UTC), datetime(2000, 1, 8, tzinfo=pytz.UTC), [
datetime(2000, 1, 1, tzinfo=pytz.UTC), datetime(2000, 1, 4, 12, tzinfo=pytz.UTC),
datetime(2000, 1, 2, 18, tzinfo=pytz.UTC), datetime(2000, 1, 6, 6, tzinfo=pytz.UTC),
datetime(2000, 1, 1, 21, tzinfo=pytz.UTC), datetime(2000, 1, 3, 15, tzinfo=pytz.UTC),
])
])
def test_zig_zag(low, high, expected):

View file

@ -1,12 +1,12 @@
from datetime import datetime, timedelta
import pytest
import pytz
from sqlalchemy import Column, Integer
from wrolpi.common import Base
from wrolpi.dates import TZDateTime, local_timezone, strftime_ms, timedelta_to_timestamp
from wrolpi.dates import TZDateTime, timedelta_to_timestamp
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.test.common import TestAPI, wrap_test_db, skip_circleci
class TestTable(Base):
@ -18,49 +18,41 @@ class TestTable(Base):
dt = Column(TZDateTime)
@skip_circleci
class TestDates(TestAPI):
def assert_raw_datetime(expected_datetime: str):
with get_db_curs() as curs:
curs.execute('SELECT * FROM test_table')
dt_ = curs.fetchone()['dt']
assert dt_.isoformat() == expected_datetime
def assert_raw_datetime(self, expected_datetime: str):
with get_db_curs() as curs:
curs.execute('SELECT * FROM test_table')
dt_ = curs.fetchone()['dt']
self.assertEqual(strftime_ms(dt_), expected_datetime)
@wrap_test_db
def test_TZDateTime(self):
with get_db_session(commit=True) as session:
# TZDateTime can be None
tt = TestTable()
session.add(tt)
self.assertIsNone(tt.dt)
def test_TZDateTime(test_session):
with get_db_session(commit=True) as session:
# TZDateTime can be None
tt = TestTable()
session.add(tt)
assert tt.dt is None
with get_db_session(commit=True) as session:
tt = session.query(TestTable).one()
self.assertIsNone(tt.dt)
with get_db_session(commit=True) as session:
tt = session.query(TestTable).one()
assert tt.dt is None
# Store a timezone naive string, it should be assumed this is a local time.
tt.dt = '2021-10-05 16:20:10.346823'
# ISO string will be converted.
tt.dt = '2021-10-05T22:20:10.346823'
# DB actually contains a UTC timestamp.
self.assert_raw_datetime('2021-10-05 22:20:10.346823')
# DB actually contains a UTC timestamp.
assert_raw_datetime('2021-10-05T22:20:10.346823')
with get_db_session(commit=True) as session:
tt = session.query(TestTable).one()
# Datetime is unchanged and localized.
self.assertEqual(tt.dt, local_timezone(datetime(2021, 10, 5, 16, 20, 10, 346823)))
with get_db_session(commit=True) as session:
tt = session.query(TestTable).one()
# Datetime is unchanged.
assert tt.dt == datetime(2021, 10, 5, 22, 20, 10, 346823, tzinfo=pytz.UTC)
# Increment by one hour.
tt.dt += timedelta(seconds=60 * 60)
self.assertEqual(tt.dt, local_timezone(datetime(2021, 10, 5, 17, 20, 10, 346823)))
# Increment by one hour.
tt.dt += timedelta(seconds=60 * 60)
assert tt.dt == datetime(2021, 10, 5, 23, 20, 10, 346823, tzinfo=pytz.UTC)
# DB is incremented by one hour.
self.assert_raw_datetime('2021-10-05 23:20:10.346823')
with get_db_session(commit=True) as session:
tt = session.query(TestTable).one()
# Datetime is incremented by an hour.
self.assertEqual(tt.dt, local_timezone(datetime(2021, 10, 5, 17, 20, 10, 346823)))
# DB is incremented by one hour.
assert_raw_datetime('2021-10-05T23:20:10.346823')
@pytest.mark.parametrize('td,expected', [

View file

@ -8,8 +8,9 @@ from unittest import mock
from unittest.mock import MagicMock
import pytest
import pytz
from wrolpi.dates import local_timezone, Seconds
from wrolpi.dates import Seconds
from wrolpi.db import get_db_context
from wrolpi.downloader import Downloader, Download, DownloadFrequency, DownloadResult, import_downloads_config, \
RSSDownloader
@ -63,7 +64,7 @@ def test_register_downloader(test_session, test_download_manager):
async def test_delete_old_once_downloads(test_session, test_download_manager):
"""Once-downloads over a month old should be deleted."""
with mock.patch('wrolpi.downloader.now') as mock_now:
mock_now.return_value = local_timezone(datetime(2020, 6, 5, 0, 0))
mock_now.return_value = datetime(2020, 6, 5, 0, 0, tzinfo=pytz.UTC)
permissive_downloader = PermissiveDownloader(priority=0)
test_download_manager.register_downloader(permissive_downloader)
@ -78,14 +79,14 @@ async def test_delete_old_once_downloads(test_session, test_download_manager):
d4 = test_download_manager.create_download('https://example.com/4')
d3.complete()
d4.complete()
d3.last_successful_download = local_timezone(datetime(2020, 1, 1, 0, 0, 0))
d4.last_successful_download = local_timezone(datetime(2020, 5, 1, 0, 0, 0))
d3.last_successful_download = datetime(2020, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
d4.last_successful_download = datetime(2020, 5, 1, 0, 0, 0, tzinfo=pytz.UTC)
# Not a month old.
d5 = test_download_manager.create_download('https://example.com/5')
d5.last_successful_download = local_timezone(datetime(2020, 6, 1, 0, 0, 0))
d5.last_successful_download = datetime(2020, 6, 1, 0, 0, 0, tzinfo=pytz.UTC)
# An old, but pending download should not be deleted.
d6 = test_download_manager.create_download('https://example.com/6')
d6.last_successful_download = local_timezone(datetime(2020, 4, 1, 0, 0, 0))
d6.last_successful_download = datetime(2020, 4, 1, 0, 0, 0, tzinfo=pytz.UTC)
d6.started()
test_download_manager.delete_old_once_downloads()
@ -189,13 +190,13 @@ def test_calculate_next_download(test_session, test_download_manager, fake_now):
# next_download slowly increases as we accumulate attempts. Largest gap is the download frequency.
attempts_expected = [
(0, local_timezone(datetime(2000, 1, 1, 3))),
(1, local_timezone(datetime(2000, 1, 1, 3))),
(2, local_timezone(datetime(2000, 1, 1, 9))),
(3, local_timezone(datetime(2000, 1, 2, 3))),
(4, local_timezone(datetime(2000, 1, 4, 9))),
(5, local_timezone(datetime(2000, 1, 8))),
(6, local_timezone(datetime(2000, 1, 8))),
(0, datetime(2000, 1, 1, 3, tzinfo=pytz.UTC)),
(1, datetime(2000, 1, 1, 3, tzinfo=pytz.UTC)),
(2, datetime(2000, 1, 1, 9, tzinfo=pytz.UTC)),
(3, datetime(2000, 1, 2, 3, tzinfo=pytz.UTC)),
(4, datetime(2000, 1, 4, 9, tzinfo=pytz.UTC)),
(5, datetime(2000, 1, 8, tzinfo=pytz.UTC)),
(6, datetime(2000, 1, 8, tzinfo=pytz.UTC)),
]
for attempts, expected in attempts_expected:
download.attempts = attempts
@ -208,9 +209,9 @@ def test_calculate_next_download(test_session, test_download_manager, fake_now):
test_session.add_all([d1, d2, d3])
test_session.commit()
# Downloads are spread out over the next week.
assert test_download_manager.calculate_next_download(d1) == local_timezone(datetime(2000, 1, 8))
assert test_download_manager.calculate_next_download(d2) == local_timezone(datetime(2000, 1, 11, 12))
assert test_download_manager.calculate_next_download(d3) == local_timezone(datetime(2000, 1, 9, 18))
assert test_download_manager.calculate_next_download(d1) == datetime(2000, 1, 8, tzinfo=pytz.UTC)
assert test_download_manager.calculate_next_download(d2) == datetime(2000, 1, 11, 12, tzinfo=pytz.UTC)
assert test_download_manager.calculate_next_download(d3) == datetime(2000, 1, 9, 18, tzinfo=pytz.UTC)
@pytest.mark.asyncio
@ -228,7 +229,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
downloads = test_download_manager.get_new_downloads(test_session)
assert [(i.url, i.frequency) for i in downloads] == [('https://example.com', Seconds.hour)]
now_ = fake_now(datetime(2020, 1, 1, 0, 0, 0))
now_ = fake_now(datetime(2020, 1, 1, 0, 0, 0, tzinfo=pytz.UTC))
# Download is processed and successful, no longer "new".
await test_download_manager.wait_for_all_downloads()
@ -237,7 +238,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
downloads = list(test_download_manager.get_recurring_downloads(test_session))
assert len(downloads) == 1
download = downloads[0]
expected = local_timezone(datetime(2020, 1, 1, 1, 0, 0))
expected = datetime(2020, 1, 1, 1, 0, 0, tzinfo=pytz.UTC)
assert download.next_download == expected
assert download.last_successful_download == now_
@ -248,7 +249,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
assert download.last_successful_download == now_
# Download is due an hour later.
fake_now(datetime(2020, 1, 1, 2, 0, 1))
fake_now(datetime(2020, 1, 1, 2, 0, 1, tzinfo=pytz.UTC))
test_download_manager.renew_recurring_downloads(test_session)
(download,) = list(test_download_manager.get_new_downloads(test_session))
# Download is "new" but has not been downloaded a second time.
@ -266,12 +267,12 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
assert download.status == 'deferred'
assert download.last_successful_download == now_
# Download should be retried after the DEFAULT_RETRY_FREQUENCY.
expected = local_timezone(datetime(2020, 1, 1, 3, 0, 0, 997200))
expected = datetime(2020, 1, 1, 3, 0, 0, 997200, tzinfo=pytz.UTC)
assert download.next_download == expected
# Try the download again, it finally succeeds.
http_downloader.do_download.reset_mock()
now_ = fake_now(datetime(2020, 1, 1, 4, 0, 1))
now_ = fake_now(datetime(2020, 1, 1, 4, 0, 1, tzinfo=pytz.UTC))
http_downloader.do_download.return_value = DownloadResult(success=True)
test_download_manager.renew_recurring_downloads(test_session)
await test_download_manager.wait_for_all_downloads()
@ -280,7 +281,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
assert download.status == 'complete'
assert download.last_successful_download == now_
# Floats cause slightly wrong date.
assert download.next_download == local_timezone(datetime(2020, 1, 1, 5, 0, 0, 997200))
assert download.next_download == datetime(2020, 1, 1, 5, 0, 0, 997200, tzinfo=pytz.UTC)
@pytest.mark.asyncio
@ -435,9 +436,9 @@ async def test_downloads_config(test_client, test_session, test_download_manager
frequency=DownloadFrequency.weekly,
downloader=HTTPDownloader.name,
)
download2.next_download = local_timezone(datetime(2000, 1, 2, 0, 0, 0))
download2.next_download = datetime(2000, 1, 2, 0, 0, 0, tzinfo=pytz.UTC)
# Completed once-downloads should be ignored.
download1.last_successful_download = local_timezone(datetime(2000, 1, 1, 0, 0, 0))
download1.last_successful_download = datetime(2000, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
test_session.commit()
# Allow background tasks to run.
@ -450,7 +451,7 @@ async def test_downloads_config(test_client, test_session, test_download_manager
dict(
url='https://example.com/2',
frequency=None,
next_download=local_timezone(datetime(2000, 1, 2, 0, 0, 0)),
next_download=datetime(2000, 1, 2, 0, 0, 0, tzinfo=pytz.UTC),
downloader='http',
sub_downloader=None,
),
@ -474,7 +475,7 @@ async def test_downloads_config(test_client, test_session, test_download_manager
dict(
url='https://example.com/2',
frequency=None,
next_download=local_timezone(datetime(2000, 1, 2, 0, 0, 0)),
next_download=datetime(2000, 1, 2, 0, 0, 0, tzinfo=pytz.UTC),
downloader='http',
sub_downloader=None,
),

View file

@ -0,0 +1,60 @@
import asyncio
from datetime import timedelta
from http import HTTPStatus
from itertools import zip_longest
from typing import List, Dict
import pytest
from wrolpi.dates import now
from wrolpi.events import Events, get_events, HISTORY_SIZE
from wrolpi.test.common import assert_dict_contains
def assert_events(expected: List[Dict], after=None):
events = get_events(after)
for expected, event in zip_longest(expected, events):
assert_dict_contains(event, expected)
def test_events_api_feed(test_session, test_client):
"""Events can be gotten from the API."""
# refresh_files() creates a few events.
request, response = test_client.post('/api/files/refresh')
assert response.status_code == HTTPStatus.NO_CONTENT
request, response = test_client.get('/api/events/feed')
assert response.status_code == HTTPStatus.OK
assert (result := response.json.get('events'))
expected = [
dict(event='global_refresh_completed', subject='refresh'),
dict(event='global_refresh_indexing_completed', subject='refresh'),
dict(event='global_refresh_delete_completed', subject='refresh'),
dict(event='global_refresh_modeling_completed', subject='refresh'),
dict(event='global_refresh_started', subject='refresh'),
]
for expected, event in zip_longest(expected, result):
assert_dict_contains(event, expected)
def test_events_history_limit():
"""EVENTS_HISTORY has a limited size."""
for i in range(HISTORY_SIZE + 5):
Events.send_ready()
assert len(get_events()) == HISTORY_SIZE
@pytest.mark.asyncio
async def test_get_events(test_client):
after = now()
Events.send_global_refresh_started()
await asyncio.sleep(1)
Events.send_ready()
assert_events([dict(event='ready'), dict(event='global_refresh_started')], after=after)
after = after + timedelta(seconds=0.1)
assert_events([dict(event='ready')], after=after)

45
wrolpi/test/test_flags.py Normal file
View file

@ -0,0 +1,45 @@
import pytest
from sqlalchemy.orm import Session
from wrolpi import flags
def assert_db(session: Session, name: str, expected: bool):
f = session.query(flags.WROLPiFlag).one_or_none()
if not f:
raise AssertionError('No flags row in DB!')
assert getattr(f, name) is expected
def test_flags(test_session, flags_lock):
"""DB flags can be saved."""
assert flags.refresh_complete.is_set() is False
assert flags.get_flags() == []
flags.refresh_complete.set()
assert_db(test_session, 'refresh_complete', True)
assert flags.get_flags() == ['refresh_complete']
flags.refresh_complete.clear()
assert_db(test_session, 'refresh_complete', False)
assert flags.get_flags() == []
def test_flags_with(flags_lock):
"""A Flag can be used with `with` context."""
assert flags.refreshing.is_set() is False, 'Flag should not be set by default'
assert flags.get_flags() == []
with flags.refreshing:
assert flags.refreshing.is_set() is True, 'Flag should be set within context.'
assert flags.get_flags() == ['refreshing']
assert flags.refreshing.is_set() is False, 'Flag should not be restored after context.'
assert flags.get_flags() == []
with pytest.raises(ValueError):
# Can't do two `refreshing` as once.
with flags.refreshing:
with flags.refreshing:
raise Exception('We should not get here!')

View file

@ -105,29 +105,29 @@ class TestRootAPI(TestAPI):
def test_downloads_sorter(self):
with get_db_session(commit=True) as session:
downloads = [
dict(status='complete', last_successful_download=strptime('2020-01-01 00:00:01')),
dict(status='complete', last_successful_download=strptime('2020-01-01 00:00:03')),
dict(status='complete', last_successful_download=strptime('2020-01-01 00:00:02')),
dict(status='complete', last_successful_download='2020-01-01T00:00:01'),
dict(status='complete', last_successful_download='2020-01-01T00:00:03'),
dict(status='complete', last_successful_download='2020-01-01T00:00:02'),
# last_successful_download are equal, so id is used next.
dict(status='pending', last_successful_download=strptime('2020-01-01 00:00:01'), url='1'),
dict(status='pending', last_successful_download=strptime('2020-01-01 00:00:01'), url='2'),
dict(status='pending', last_successful_download='2020-01-01T00:00:01', url='1'),
dict(status='pending', last_successful_download='2020-01-01T00:00:01', url='2'),
dict(status='pending', last_successful_download=strptime('2020-01-01 00:00:04')),
dict(status='pending', last_successful_download='2020-01-01T00:00:04'),
dict(status='failed'),
dict(status='failed', last_successful_download=strptime('2020-01-01 00:00:01')),
dict(status='failed', last_successful_download='2020-01-01T00:00:01'),
]
for download in downloads:
session.add(Download(url=download.pop('url', 'https://example.com'), **download))
expected = [
dict(status='pending', last_successful_download=strptime('2020-01-01 00:00:04').timestamp()),
dict(status='pending', last_successful_download=strptime('2020-01-01 00:00:01').timestamp(), url='1'),
dict(status='pending', last_successful_download=strptime('2020-01-01 00:00:01').timestamp(), url='2'),
dict(status='pending', last_successful_download='2020-01-01T00:00:04'),
dict(status='pending', last_successful_download='2020-01-01T00:00:01', url='1'),
dict(status='pending', last_successful_download='2020-01-01T00:00:01', url='2'),
dict(status='failed'),
dict(status='failed', last_successful_download=strptime('2020-01-01 00:00:01').timestamp()),
dict(status='complete', last_successful_download=strptime('2020-01-01 00:00:03').timestamp()),
dict(status='complete', last_successful_download=strptime('2020-01-01 00:00:02').timestamp()),
dict(status='complete', last_successful_download=strptime('2020-01-01 00:00:01').timestamp()),
dict(status='failed', last_successful_download='2020-01-01T00:00:01'),
dict(status='complete', last_successful_download='2020-01-01T00:00:03'),
dict(status='complete', last_successful_download='2020-01-01T00:00:02'),
dict(status='complete', last_successful_download='2020-01-01T00:00:01'),
]
request, response = api_app.test_client.get('/api/download')
once_downloads = response.json['once_downloads']
@ -139,8 +139,8 @@ class TestRootAPI(TestAPI):
with get_db_session(commit=True) as session:
downloads = [
dict(status='complete', frequency=1),
dict(status='complete', frequency=2, next_download=strptime('2020-01-01 00:00:01')),
dict(status='complete', frequency=2, next_download=strptime('2020-01-01 00:00:02')),
dict(status='complete', frequency=2, next_download='2020-01-01T00:00:01'),
dict(status='complete', frequency=2, next_download='2020-01-01T00:00:02'),
dict(status='pending', frequency=1),
dict(status='pending', frequency=4),
dict(status='failed', frequency=1),
@ -154,8 +154,8 @@ class TestRootAPI(TestAPI):
dict(status='pending', frequency=4),
dict(status='failed', frequency=1),
dict(status='failed'),
dict(status='complete', frequency=2, next_download=strptime('2020-01-01 00:00:01').timestamp()),
dict(status='complete', frequency=2, next_download=strptime('2020-01-01 00:00:02').timestamp()),
dict(status='complete', frequency=2, next_download='2020-01-01T00:00:01'),
dict(status='complete', frequency=2, next_download='2020-01-01T00:00:02'),
dict(status='complete', frequency=1),
]
request, response = api_app.test_client.get('/api/download')
@ -313,6 +313,7 @@ def test_get_status(test_client, test_session):
assert 'throttle_status' in response.json and isinstance(response.json['throttle_status'], str)
assert 'version' in response.json and isinstance(response.json['version'], str)
assert 'memory_stats' in response.json and isinstance(response.json['memory_stats'], dict)
assert 'flags' in response.json and isinstance(response.json['flags'], list)
def test_post_download(test_session, test_client, test_download_manager_config):

View file

@ -1,4 +1,4 @@
__version__ = '0.7.8-beta'
__version__ = '0.8.0-beta'
import subprocess