Removing unused /videos/tag. Sending events when Channels are created or deleted.

This commit is contained in:
Roland 2023-07-17 17:32:29 -06:00
parent fdaaa510c4
commit 6458316d1a
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
14 changed files with 90 additions and 35 deletions

View file

@ -16,6 +16,13 @@ function handleEvents(events) {
const {event, message, subject, dt, url} = e;
document.dispatchEvent(new CustomEvent(apiEventName, {detail: e}));
if (event === 'directory_refresh') {
eventToast(
'Refresh started',
message,
);
}
if (subject && newestEvents[subject] && newestEvents[subject] > dt) {
console.debug(`Already handled newer event of "${subject}".`);
return;
@ -37,6 +44,18 @@ function handleEvents(events) {
() => window.open(url, '_self'));
}
if (event === 'deleted') {
eventToast('Successful Delete', message, 'warning');
}
if (event === 'created') {
eventToast('Successful Creation', message, 'success');
}
if (event === 'tagged') {
eventToast('Successful tag', message, 'success');
}
if (subject) {
newestEvents[subject] = dt;
}

View file

@ -244,6 +244,7 @@ export async function downloadChannel(channelId) {
});
}
}
return response;
}
export async function refreshChannel(channelId) {

View file

@ -219,7 +219,19 @@ function ChannelPage({create, header}) {
const handleDownloadChannel = async (e) => {
e.preventDefault();
return await downloadChannel(channelId);
try {
const response = await downloadChannel(channelId);
if (response.status === 204) {
toast({
type: 'success',
title: 'Download Created',
description: 'Channel download has been started.',
time: 5000,
});
}
} catch (e) {
console.error(e);
}
}
const handleRefreshChannel = async (e) => {

View file

@ -17,8 +17,8 @@ const links = [
links: [
{text: 'Inventory', to: '/inventory', key: 'inventory'},
{to: '/more/otp', text: 'One Time Pad', end: true},
{to: '/more/statistics', text: 'Statistics', end: true},
{to: '/more/vin', text: 'VIN Decoder', end: true},
{to: '/more/statistics', text: 'Statistics', end: true},
]
},
];

View file

@ -1,16 +1,13 @@
from http import HTTPStatus
from sanic import Blueprint, response
from sanic import Blueprint
from sanic.request import Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.common import logger
from wrolpi.root_api import add_blueprint, json_response
from wrolpi.schema import JSONErrorResponse
from . import lib, schema
from .channel.api import channel_bp
from .video import lib as video_lib
from .video.api import video_bp
content_bp = Blueprint('VideoContent', '/api/videos')
@ -24,18 +21,6 @@ add_blueprint(bp)
logger = logger.getChild(__name__)
@content_bp.post('/tag')
@openapi.definition(
description='Associate a Video with a Tag',
body=schema.TagRequest,
)
@validate(schema.TagRequest)
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
async def tag(_: Request, body: schema.TagRequest):
video_lib.tag_video(body.video_id, body.tag_name)
return response.empty()
@content_bp.get('/statistics')
@openapi.response(HTTPStatus.OK, schema.VideosStatisticsResponse)
async def statistics(_: Request):

View file

@ -8,13 +8,15 @@ from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.common import logger, wrol_mode_check, make_media_directory, \
get_media_directory, run_after
from ..errors import UnknownChannel
get_media_directory, run_after, get_relative_to_media_directory
from wrolpi.downloader import download_manager
from wrolpi.events import Events
from wrolpi.root_api import json_response
from wrolpi.schema import JSONErrorResponse
from wrolpi.vars import PYTEST
from . import lib
from .. import schema, Channel
from ..errors import UnknownChannel
from ..lib import save_channels_config
channel_bp = Blueprint('Channel', url_prefix='/api/videos/channels')
@ -59,6 +61,8 @@ def channel_post(_: Request, body: schema.ChannelPostRequest):
if not PYTEST:
asyncio.ensure_future(channel.refresh_files())
Events.send_created(f'Created Channel: {channel.name}')
return response.json({'success': 'Channel created successfully'}, HTTPStatus.CREATED,
{'Location': f'/api/videos/channels/{channel.id}'})
@ -85,7 +89,8 @@ def channel_update(_: Request, channel_id: int, body: schema.ChannelPutRequest):
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
@wrol_mode_check
def channel_delete(_: Request, channel_id: int):
lib.delete_channel(channel_id=channel_id)
channel = lib.delete_channel(channel_id=channel_id)
Events.send_deleted(f'Deleted Channel: {channel["name"]}')
return response.raw('', HTTPStatus.NO_CONTENT)
@ -99,6 +104,8 @@ def channel_refresh(_: Request, channel_id: int):
raise UnknownChannel()
asyncio.ensure_future(channel.refresh_files())
directory = get_relative_to_media_directory(channel.directory)
Events.send_directory_refresh(f'Refreshing: {directory}')
return response.empty()
@ -108,4 +115,7 @@ def channel_refresh(_: Request, channel_id: int):
@wrol_mode_check
def channel_download(_: Request, channel_id: int):
lib.download_channel(channel_id)
if download_manager.disabled.is_set():
# Warn the user that downloads are disabled.
Events.send_downloads_disabled('Channel download created. But downloads are disabled.')
return response.empty()

View file

@ -176,22 +176,25 @@ def create_channel(session: Session, data: schema.ChannelPostRequest, return_dic
def delete_channel(session: Session, *, channel_id: int):
try:
channel = session.query(Channel).filter_by(id=channel_id).one()
channel_dict = channel.dict()
except NoResultFound:
raise UnknownChannel()
channel.delete_with_videos()
session.commit()
return channel_dict
def download_channel(id_: int):
"""Create a Download record for a Channel's entire catalog. Start downloading."""
channel = get_channel(channel_id=id_, return_dict=False)
channel: Channel = get_channel(channel_id=id_, return_dict=False)
session = Session.object_session(channel)
download = channel.get_download()
if not download:
raise InvalidDownload(f'Channel {channel.name} does not have a download!')
download.renew(reset_attempts=True)
logger.info(f'Created download for {channel} with {download}')
session.commit()

View file

@ -7,6 +7,7 @@ from sanic_ext.extensions.openapi import openapi
from wrolpi.common import logger, wrol_mode_check, run_after
from wrolpi.errors import InvalidOrderBy, ValidationError
from wrolpi.events import Events
from wrolpi.root_api import json_response
from wrolpi.schema import JSONErrorResponse
from . import lib
@ -66,4 +67,6 @@ def video_delete(_: Request, video_ids: str):
raise ValidationError('Unable to parse video ids')
lib.delete_videos(*video_ids)
Events.send_deleted(f'Deleted {len(video_ids)} videos')
return response.raw('', HTTPStatus.NO_CONTENT)

View file

@ -1,4 +1,4 @@
from typing import Tuple, Optional, List
from typing import Tuple, Optional, List, Dict
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import NoResultFound
@ -152,11 +152,13 @@ def search_videos(
@run_after(save_channels_config)
def tag_video(video_id: int, tag_name: str):
def tag_video(video_id: int, tag_name: str) -> Dict:
"""Tag a video"""
with get_db_session(commit=True):
video = Video.find_by_id(video_id)
video.add_tag(tag_name)
video_dict = video.dict()
return video_dict
@optional_session

View file

@ -155,9 +155,9 @@ async def test_wrol_mode(test_async_client, test_directory, simple_channel, simp
assert resp.json['code'] == 'WROL_MODE_ENABLED'
# THE REST OF THESE METHODS ARE ALLOWED
content = dict(video_id=simple_video.id, tag_name=tag.name)
_, resp = await test_async_client.post('/api/videos/tag', content=json.dumps(content))
assert resp.status_code == HTTPStatus.NO_CONTENT
content = dict(file_group_id=simple_video.file_group_id, tag_name=tag.name)
_, resp = await test_async_client.post('/api/files/tag', content=json.dumps(content))
assert resp.status_code == HTTPStatus.CREATED
assert test_download_manager.stopped.is_set()

View file

@ -115,14 +115,15 @@ async def get_zim_subscriptions(_: Request):
@bp.post('/subscribe')
@openapi.definition(
summary='Subscribe to a particular Kiwix Zim',
body=schema.TagZimSubscribe,
body=schema.ZimSubscribeRequest,
)
@validate(schema.TagZimSubscribe)
async def post_zim_subscribe(_: Request, body: schema.TagZimSubscribe):
@validate(schema.ZimSubscribeRequest)
async def post_zim_subscribe(_: Request, body: schema.ZimSubscribeRequest):
await lib.subscribe(body.name, body.language)
if download_manager.disabled.is_set() or download_manager.stopped.is_set():
# Downloads are disabled, warn the user.
Events.send_downloads_disabled('Download created. But, downloads are disabled.')
Events.send_created(f'Zim subscription created')
return response.empty(HTTPStatus.CREATED)
@ -132,6 +133,7 @@ async def post_zim_subscribe(_: Request, body: schema.TagZimSubscribe):
)
async def delete_zim_subscription(_: Request, subscription_id: int):
await lib.unsubscribe(subscription_id)
Events.send_deleted(f'Zim subscription deleted')
return response.empty(HTTPStatus.NO_CONTENT)
@ -151,6 +153,8 @@ async def get_outdated_zims(_: Request):
summary='Remove all outdated Zims, if any.'
)
async def delete_outdated_zims(_: Request):
await lib.remove_outdated_zim_files()
lib.flag_outdated_zim_files()
deleted_count = await lib.remove_outdated_zim_files()
if deleted_count:
lib.flag_outdated_zim_files()
Events.send_deleted(f'Deleted {deleted_count} outdated Zims')
return response.empty(HTTPStatus.NO_CONTENT)

View file

@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import NoResultFound # noqa
from modules.zim import kiwix
from modules.zim.errors import UnknownZim, UnknownZimSubscription
from modules.zim.kiwix import KIWIX_CATALOG
from modules.zim.models import Zim, Zims, TagZimEntry, ZimSubscription
from wrolpi import flags
@ -17,7 +18,6 @@ from wrolpi.common import register_modeler, logger, extract_html_text, extract_h
register_refresh_cleanup, background_task
from wrolpi.db import get_db_session, optional_session, get_db_curs
from wrolpi.downloader import DownloadFrequency
from modules.zim.errors import UnknownZim, UnknownZimSubscription
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, DOCKERIZED
@ -449,12 +449,14 @@ def find_outdated_zim_files(path: pathlib.Path = None) -> Tuple[List[pathlib.Pat
return sorted(outdated_files), sorted(current_files)
async def remove_outdated_zim_files(path: pathlib.Path = None):
async def remove_outdated_zim_files(path: pathlib.Path = None) -> int:
"""Deletes all old Zim files."""
outdated, _ = find_outdated_zim_files(path)
logger.info(f'Deleting {len(outdated)} outdated Zim files: {outdated}')
deleted_count = 0
for file in outdated:
file.unlink()
deleted_count += 1
if PYTEST:
await refresh_files(outdated)
@ -463,6 +465,8 @@ async def remove_outdated_zim_files(path: pathlib.Path = None):
await restart_kiwix()
return deleted_count
@register_refresh_cleanup
def flag_outdated_zim_files():

View file

@ -84,7 +84,7 @@ class ZimSubscriptions:
@dataclass
class TagZimSubscribe:
class ZimSubscribeRequest:
name: str
language: str

View file

@ -53,6 +53,18 @@ class Events:
def send_user_notify(message: str, url: str = None):
send_event('user_notify_message', message, subject='user_notify', url=url)
@staticmethod
def send_directory_refresh(message: str = None):
send_event('directory_refresh', message, subject='refresh')
@staticmethod
def send_deleted(message: str = None):
send_event('deleted', message, subject='deleted')
@staticmethod
def send_created(message: str = None):
send_event('created', message, subject='created')
def log_event(event: str, message: str = None, action: str = None, subject: str = None):
log = f'{event=}'