Files
web-framework-resources/plugins/watchlist/plugin.py
T

222 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""General watchlists and their scheduler, with replaceable capability integrations."""
import json
import secrets
import time
from pathlib import Path
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify, g
from web_framework.auth import require_permission
from web_framework.plugins import Plugin, Setting, get_plugins
from web_framework.plugin_runtime import Service, QUEUE_SETTING, text, integer, run_one
CATEGORIES = ('plan-to-watch', 'watching', 'on-hold', 'finished', 'dropped')
bp = Blueprint('plugin_watchlist', __name__, template_folder='templates')
class Watchlist(Service):
plugin_id = 'watchlist'
def __init__(self, app=None):
super().__init__(app)
with self.state.db() as db:
db.execute('CREATE TABLE IF NOT EXISTS watchlist_entries (id TEXT PRIMARY KEY, data TEXT NOT NULL, due REAL NOT NULL DEFAULT 0)')
def items(self):
self.check()
with self.state.db() as db:
return [{'id': row['id'], **json.loads(row['data']), 'due': row['due']} for row in db.execute('SELECT * FROM watchlist_entries ORDER BY rowid DESC')]
def get(self, item_id):
return next((item for item in self.items() if item['id'] == item_id), None)
def add(self, title, *, external_id='', category='plan-to-watch', media_path='', expected=0, season=1, media_type='tv'):
self.check()
if category not in CATEGORIES or media_type not in ('tv', 'movie', 'generic'):
raise ValueError('Choose a valid category and media type.')
media_path = str(media_path or '').strip()
if media_path and (Path(media_path).is_absolute() or '..' in Path(media_path).parts):
raise ValueError('Media folder must be relative to the handoff source root.')
item = {'title': text(title, 'Title', 200), 'external_id': str(external_id or '')[:2000], 'category': category,
'media_path': media_path, 'expected': integer(expected, 'Expected episodes', 0, 10000),
'season': integer(season, 'Season', 1, 999), 'media_type': media_type, 'available': 0,
'checked': None, 'last_error': '', 'thumbnail': '', 'handoff': '', 'updated': time.time()}
item_id = secrets.token_hex(12)
with self.state.db() as db:
db.execute('INSERT INTO watchlist_entries(id,data) VALUES(?,?)', (item_id, json.dumps(item)))
return item_id
def edit(self, item_id, *, title, external_id='', category='plan-to-watch', media_path='', expected=0, season=1, media_type='tv'):
if category not in CATEGORIES or media_type not in ('tv', 'movie', 'generic'):
raise ValueError('Choose a valid category and media type.')
media_path = str(media_path or '').strip()
if media_path and (Path(media_path).is_absolute() or '..' in Path(media_path).parts):
raise ValueError('Media folder must be relative to the handoff source root.')
return self.update(item_id, title=text(title, 'Title', 200), external_id=str(external_id or '')[:2000],
category=category, media_path=media_path, expected=integer(expected, 'Expected episodes', 0, 10000),
season=integer(season, 'Season', 1, 999), media_type=media_type)
def update(self, item_id, **changes):
self.check()
with self.state.db() as db:
row = db.execute('SELECT data FROM watchlist_entries WHERE id=?', (item_id,)).fetchone()
if not row:
raise ValueError('Watchlist item not found.')
value = json.loads(row['data'])
if 'category' in changes and changes['category'] not in CATEGORIES:
raise ValueError('Choose a valid category.')
value.update(changes)
value['updated'] = time.time()
db.execute('UPDATE watchlist_entries SET data=? WHERE id=?', (json.dumps(value), item_id))
return value
def delete(self, item_id):
self.check()
with self.state.db() as db:
db.execute('DELETE FROM watchlist_entries WHERE id=?', (item_id,))
def refresh(self, item_id, progress):
item = self.get(item_id)
if not item:
raise ValueError('Watchlist item not found.')
search = self.resolve('search')
if not search or not item['external_id']:
raise ValueError('Select a search plugin and set an external show ID to refresh this item.')
progress(0, 3, 'Refreshing show metadata.')
info = search.info(item['external_id'])
progress(1, 3, 'Checking available episodes.')
episodes = search.episodes(item['external_id'])
if not isinstance(info, dict) or not isinstance(episodes, list):
raise ValueError('Search plugin returned invalid metadata.')
available = len({str(episode.get('id', index)) for index, episode in enumerate(episodes) if isinstance(episode, dict)})
expected = item['expected']
if not expected and isinstance(info.get('episodes'), int):
expected = integer(info['episodes'], 'Expected episodes', 0, 10000)
thumbnail = self.resolve('thumbnails')
if thumbnail:
thumbnail.request(item['title'], image_url=info.get('image') or '')
self.update(item_id, available=available, expected=expected, checked=time.time(), last_error='')
if available > item['available']:
self.notify('watchlist.episodes', f"{item['title']}: {available} episode(s) available.")
progress(3, 3, 'Watchlist refreshed.')
def handoff(self, item_id):
item = self.get(item_id)
if not item:
raise ValueError('Watchlist item not found.')
target = self.resolve('handoff')
if not target:
raise ValueError('Select a Media Handoff plugin in Watchlist settings.')
job = target.submit(item)
self.update(item_id, handoff=job)
return job
def process(self, payload, progress):
item_id = payload.get('item_id')
try:
self.refresh(item_id, progress)
except ValueError as exc:
if self.get(item_id):
self.update(item_id, last_error=str(exc)[:500])
raise
def run_due(self):
settings = self.settings()
if not settings['scheduler']:
return 15
interval = integer(settings['interval'], 'Refresh interval', 60, 604800)
now = time.time()
selected = None
with self.state.db() as db:
for row in db.execute('SELECT * FROM watchlist_entries WHERE due<=? ORDER BY due', (now,)):
item = json.loads(row['data'])
if settings['search'] and item['category'] == 'watching' and item.get('external_id'):
selected = row['id']
db.execute('UPDATE watchlist_entries SET due=? WHERE id=?', (now + interval, selected))
break
if selected:
try:
self.enqueue('Scheduled watchlist refresh', {'item_id': selected})
except ValueError:
with self.state.db() as db:
db.execute('UPDATE watchlist_entries SET due=? WHERE id=?', (now + 60, selected))
if settings['auto-handoff']:
for item in self.items():
if item['category'] == 'finished' and item['media_path'] and not item['handoff']:
try:
self.handoff(item['id'])
except ValueError as exc:
self.update(item['id'], last_error=str(exc)[:500])
return 10
def validate_settings(values):
integer(values['interval'], 'Refresh interval', 60, 604800)
def service():
return get_plugins().service('watchlist', 'watchlist')
@bp.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
return mutate()
manager = service()
selected = request.args.get('category', '')
items = [item for item in manager.items() if not selected or item['category'] == selected]
thumbnail = manager.resolve('thumbnails')
images = {item['id']: thumbnail.get(item['title']) for item in items} if thumbnail else {}
return render_template('watchlist/index.html', title='Watchlist', items=items, categories=CATEGORIES, selected=selected, images=images)
@bp.get('/api/items')
def api_items():
return jsonify(items=service().items())
@require_permission('content.write')
def mutate():
manager = service()
action, item_id = request.form.get('action', 'add'), request.form.get('item_id', '')
try:
if action == 'add':
manager.add(request.form.get('title'), external_id=request.form.get('external_id'), category=request.form.get('category', 'plan-to-watch'),
media_path=request.form.get('media_path', ''), expected=request.form.get('expected', '0'), season=request.form.get('season', '1'), media_type=request.form.get('media_type', 'tv'))
elif action == 'edit':
manager.edit(item_id, title=request.form.get('title'), external_id=request.form.get('external_id'),
category=request.form.get('category'), media_path=request.form.get('media_path'), expected=request.form.get('expected', '0'),
season=request.form.get('season', '1'), media_type=request.form.get('media_type', 'tv'))
elif action == 'category':
manager.update(item_id, category=request.form.get('category'))
elif action == 'delete':
manager.delete(item_id)
elif action == 'refresh':
manager.enqueue('Refresh watchlist item', {'item_id': item_id})
elif action == 'handoff':
manager.handoff(item_id)
elif action == 'thumbnail':
item = manager.get(item_id)
target = manager.resolve('thumbnails')
if not target or not item:
raise ValueError('Choose a thumbnail plugin and an existing item.')
target.request(item['title'])
else:
raise ValueError('Unknown watchlist action.')
manager.state.audit(g.user['username'], 'watchlist.' + action, item_id)
flash('Watchlist updated. Queued work appears in Queue.', 'success')
except ValueError as exc:
flash(str(exc), 'error')
return redirect(url_for('plugin_watchlist.index'))
plugin = Plugin('watchlist', 'Watchlist', version='0.1.1', description='Watchlists and scheduled refreshes with selectable integrations.', blueprint=bp,
endpoint='plugin_watchlist.index', hooks={'validate_settings': validate_settings}, services={'watchlist': Watchlist}, workers={'jobs': lambda: run_one(service()), 'scheduler': lambda: service().run_due()}, settings_schema={
'queue': QUEUE_SETTING,
'search': Setting('Search plugin', kind='service', service='anime-search'),
'thumbnails': Setting('Thumbnail plugin', kind='service', service='thumbnails'),
'handoff': Setting('Media handoff plugin', kind='service', service='media-handoff'),
'notifications': Setting('Notification plugin', kind='service', service='notify'),
'scheduler': Setting('Enable watchlist scheduler', kind='boolean', default=False),
'interval': Setting('Refresh interval (seconds, 60–604800)', kind='integer', default=3600),
'auto-handoff': Setting('Automatically hand off finished items', kind='boolean', default=False),
})