Compare commits

..

5 Commits

Author SHA1 Message Date
Ventilaar
38f6f04260 Fix None iterable and add new background task
All checks were successful
Update worker server / build-and-publish (release) Successful in 22s
Generate docker image / build-and-publish (release) Successful in 57s
2025-01-23 14:21:01 +01:00
Ventilaar
43e6c00787 idk
All checks were successful
Update worker server / build-and-publish (release) Successful in 18s
Generate docker image / build-and-publish (release) Successful in 20s
2025-01-21 20:49:40 +01:00
Ventilaar
d42030dcbc Small concurrency and logging fix
All checks were successful
Update worker server / build-and-publish (release) Successful in 10s
Generate docker image / build-and-publish (release) Successful in 19s
2025-01-19 13:27:09 +01:00
Ventilaar
5530179558 Small fixup
All checks were successful
Update worker server / build-and-publish (release) Successful in 11s
Generate docker image / build-and-publish (release) Successful in 20s
2025-01-18 23:39:32 +01:00
Ventilaar
1186d236f2 Rework video queue download
All checks were successful
Update worker server / build-and-publish (release) Successful in 11s
Generate docker image / build-and-publish (release) Successful in 14s
2025-01-18 23:29:12 +01:00
9 changed files with 204 additions and 111 deletions

View File

@@ -26,6 +26,7 @@ def create_app(test_config=None):
config['CELERY']['beat_schedule'] = {} config['CELERY']['beat_schedule'] = {}
config['CELERY']['beat_schedule']['Renew WebSub endpoints'] = {'task': 'ayta.tasks.websub_renew_expiring', 'schedule': 4000} config['CELERY']['beat_schedule']['Renew WebSub endpoints'] = {'task': 'ayta.tasks.websub_renew_expiring', 'schedule': 4000}
config['CELERY']['beat_schedule']['Process WebSub data'] = {'task': 'ayta.tasks.websub_process_data', 'schedule': 100} config['CELERY']['beat_schedule']['Process WebSub data'] = {'task': 'ayta.tasks.websub_process_data', 'schedule': 100}
config['CELERY']['beat_schedule']['Queue up new videos in static channel playlists'] = {'task': 'ayta.tasks.playlist_to_queue', 'schedule': 5000}
app = Flask(__name__) app = Flask(__name__)
app.config.from_mapping(config) app.config.from_mapping(config)

View File

@@ -2,7 +2,7 @@ from flask import Blueprint, render_template, request, redirect, url_for, flash,
from ..nosql import get_nosql from ..nosql import get_nosql
from ..dlp import checkChannelId, getChannelInfo from ..dlp import checkChannelId, getChannelInfo
from ..decorators import login_required from ..decorators import login_required
from ..tasks import test_sleep, websub_subscribe_callback, websub_unsubscribe_callback, video_download, video_queue from ..tasks import test_sleep, websub_subscribe_callback, websub_unsubscribe_callback, video_download, video_queue, playlist_to_queue
from datetime import datetime from datetime import datetime
from secrets import token_urlsafe from secrets import token_urlsafe
@@ -30,22 +30,29 @@ def channels():
generic = {} generic = {}
if request.method == 'POST': if request.method == 'POST':
channelId = request.form.get('channel_id', None) task = request.form.get('task', None)
originalName = request.form.get('original_name', None)
addedDate = request.form.get('added_date', None) if task == 'subscribe-websub':
channelId = request.form.get('channel_id', None)
originalName = request.form.get('original_name', None)
addedDate = request.form.get('added_date', None)
### add some validation ### add some validation
addedDate = datetime.strptime(addedDate, '%Y-%m-%d') addedDate = datetime.strptime(addedDate, '%Y-%m-%d')
if checkChannelId(channelId) is False: if checkChannelId(channelId) is False:
channelId, originalName = getChannelInfo(channelId, ('channel_id', 'uploader')) channelId, originalName = getChannelInfo(channelId, ('channel_id', 'uploader'))
if not get_nosql().insert_new_channel(channelId, originalName, addedDate): if not get_nosql().insert_new_channel(channelId, originalName, addedDate):
flash('Error inserting new channel, you probably made a mistake somewhere') flash('Error inserting new channel, you probably made a mistake somewhere')
return redirect(url_for('admin.channels')) return redirect(url_for('admin.channels'))
return redirect(url_for('admin.channel', channelId=channelId)) return redirect(url_for('admin.channel', channelId=channelId))
elif task == 'playlist-queue':
task = playlist_to_queue.delay()
flash(f'Task playlist-queue has been queued: {task.id}')
generic['currentDate'] = datetime.utcnow() generic['currentDate'] = datetime.utcnow()
channelIds = get_nosql().list_all_channels() channelIds = get_nosql().list_all_channels()
@@ -208,6 +215,12 @@ def queue():
elif task == 'empty-queue': elif task == 'empty-queue':
get_nosql().queue_emptyQueue() get_nosql().queue_emptyQueue()
flash(f'Queue has been emptied') flash(f'Queue has been emptied')
elif task == 'queue-run-once':
value = int(value) if value.isdigit() else 1
for x in range(value):
task = video_queue.delay()
flash(f'Task has been started on the oldest queued item: {task.id}')
return redirect(url_for('admin.queue')) return redirect(url_for('admin.queue'))
@@ -245,16 +258,15 @@ def users():
return render_template('admin/users.html', users=users) return render_template('admin/users.html', users=users)
@bp.route('/workers', methods=['GET', 'POST']) @bp.route('/workers', methods=['GET', 'POST'])
#@login_required @login_required
def workers(): def workers():
if request.method == 'POST': if request.method == 'POST':
task = request.form.get('task', None) task = request.form.get('task', None)
if task == 'test-sleep': if task == 'test-sleep':
test_sleep.delay() test_sleep.delay()
elif task == 'queue-single':
video_queue.delay()
celery = current_app.extensions.get('celery') celery = current_app.extensions.get('celery')
tasks = celery.control.inspect().active() tasks = celery.control.inspect().active()
return render_template('admin/workers.html', tasks=tasks) reserved = celery.control.inspect().reserved()
return render_template('admin/workers.html', tasks=tasks, reserved=reserved)

View File

@@ -411,13 +411,17 @@ class Mango:
########################################## ##########################################
def queue_insertQueue(self, videoId, endpointId=None): def queue_insertQueue(self, videoId, endpointId=None):
# if no document exists # if already queued
if not self.download_queue.count_documents({'id': videoId}) >= 1: if self.download_queue.count_documents({'id': videoId}) >= 1:
self.download_queue.insert_one({'id': videoId, 'endpoint': endpointId, 'created_time': current_time(object=True), 'status': 'queued'}).inserted_id return False
return True
# if already in archive
# key already in queue if self.check_exists(videoId):
return False return False
# add to queue
self.download_queue.insert_one({'id': videoId, 'endpoint': endpointId, 'created_time': current_time(object=True), 'status': 'queued'}).inserted_id
return True
def queue_deleteQueue(self, videoId): def queue_deleteQueue(self, videoId):
if self.download_queue.delete_one({'id': videoId}): if self.download_queue.delete_one({'id': videoId}):
@@ -430,13 +434,19 @@ class Mango:
def queue_emptyQueue(self): def queue_emptyQueue(self):
return self.download_queue.delete_many({}) return self.download_queue.delete_many({})
def queue_getNext(self, newest=False): def queue_setFailed(self, videoId):
sort = [] return self.download_queue.update_one({'id': videoId}, {'$set': {'status': 'failed'}})
if newest: def queue_getNext(self):
sort = [( 'created_time', pymongo.DESCENDING )] """ Returns a LIST of queue parameters. Function first checks if ID exists, if so deletes and then checks the next queued until queue is empty (None) or queued id does not exist yet."""
while True:
return self.download_queue.find_one({}, sort=sort) queueItem = self.download_queue.find_one({'status': 'queued'})
if not queueItem:
return None
elif self.check_exists(queueItem['id']):
self.queue_deleteQueue(queueItem['id'])
self.download_queue.update_one({'id': queueItem['id']}, {'$set': {'status': 'working'}})
return queueItem
########################################## ##########################################
# HELPER FUNCTIONS # # HELPER FUNCTIONS #

View File

@@ -4,6 +4,7 @@ class OIDC():
Additionally this class provides the function to generate redirect url's and check bearer tokens on their validity as well as caching jwt signing keys. Additionally this class provides the function to generate redirect url's and check bearer tokens on their validity as well as caching jwt signing keys.
Fairly barebones and should be 100% secure. (famous last words) Fairly barebones and should be 100% secure. (famous last words)
This is made for form posted JWT's. While not the most secure it is the most easy way to implement. Moving on to a code based solution might be preferred in the future. This is made for form posted JWT's. While not the most secure it is the most easy way to implement. Moving on to a code based solution might be preferred in the future.
The nonce and state store is in memory, so only one instance can be used at a time until central key caching is implemented.
""" """
def __init__(self, app=None): def __init__(self, app=None):
self.states = {} self.states = {}
@@ -151,7 +152,6 @@ class OIDC():
# Any exception (invalid JWT, invalid formatting etc...) must return False # Any exception (invalid JWT, invalid formatting etc...) must return False
except Exception as e: except Exception as e:
print(e, flush=True)
return False return False
# Double check if given token is really requested by us by matching the nonce in the signed key # Double check if given token is really requested by us by matching the nonce in the signed key

View File

@@ -42,6 +42,7 @@ def video_queue():
get_nosql().queue_deleteQueue(videoId) get_nosql().queue_deleteQueue(videoId)
return True return True
else: else:
get_nosql().queue_setFailed(videoId)
return False return False
@shared_task() @shared_task()
@@ -163,6 +164,19 @@ def websub_renew_expiring(hours=6):
if count >= 256: if count >= 256:
break break
@shared_task()
def playlist_to_queue(hours=6):
from .nosql import get_nosql
channels = get_nosql().list_all_channels(active=True)
for channel in channels:
info = get_nosql().get_channel_info()
for item in info['playlist']['entries']:
videoId = item['id']
get_nosql().queue_insertQueue(videoId, 'Playlist mirroring')
########################################## ##########################################
# TASK MODULES # # TASK MODULES #
########################################## ##########################################

View File

@@ -15,6 +15,18 @@
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col s12 l4 m-4">
<div class="card">
<div class="card-content">
<span class="card-title">Direct actions</span>
<form class="mt-4" method="post">
<button class="btn mb-2 green" type="submit" name="task" value="playlist-queue">Playlist to Queue</button>
<br>
<span class="supporting-text">Forcerun playlist to queue task</span>
</form>
</div>
</div>
</div>
<div class="col s12 l4 m-4"> <div class="col s12 l4 m-4">
<div class="card"> <div class="card">
<div class="card-content"> <div class="card-content">
@@ -38,7 +50,7 @@
}); });
</script> </script>
</div> </div>
<button class="btn mt-4" type="submit" name="action" value="add_channel">Add</button> <button class="btn mt-4" type="submit" name="task" value="add_channel">Add</button>
</form> </form>
</div> </div>
</div> </div>

View File

@@ -11,67 +11,72 @@
<div class="divider"></div> <div class="divider"></div>
<div class="row"> <div class="row">
<div class="col s12"> <div class="col s12">
<h5>Options</h5> <h5>Options</h5>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col s12 l4 m-4"> <div class="col s12 l4 m-4">
<div class="card"> <div class="card">
<div class="card-content"> <div class="card-content">
<span class="card-title">Direct actions</span> <span class="card-title">Direct actions</span>
<form class="mt-4" method="post" onsubmit="return confirm('Are you sure?');"> <form class="mt-4" method="post" onsubmit="return confirm('Are you sure?');">
<button class="btn mb-2 red" type="submit" name="task" value="empty-queue">Empty Queue</button> <button class="btn mb-2 red" type="submit" name="task" value="empty-queue">Empty Queue</button>
<br> <br>
<span class="supporting-text">Removes all queued ids</span> <span class="supporting-text">Removes all queued ids</span>
</form> </form>
<form class="mt-4" method="post" onsubmit="return confirm('Are you sure?');"> <form class="mt-4" method="post" onsubmit="return confirm('Are you sure?');">
<button class="btn mb-2" type="submit" name="task" value="clean-retired">Clean retired</button> <button class="btn mb-2" type="submit" name="task" value="clean-retired">Clean retired</button>
<br> <br>
<span class="supporting-text">Prunes all deactivated endpoints, but keeps last 3 days</span> <span class="supporting-text">Prunes all deactivated endpoints, but keeps last 3 days</span>
</form> </form>
<form class="mt-4 input-field" method="post" onsubmit="return confirm('Are you sure?');">
<input type="number" style="width: 80px" value="1" name="value" min="1" max="99">
<button class="btn mb-2 green" type="submit" name="task" value="queue-run-once">Download oldest queued</button>
<br>
<span class="supporting-text">Will download the oldest queued video ID</span>
</form>
</div> </div>
</div> </div>
</div> </div>
<div class="col s12 l4 m-4"> <div class="col s12 l4 m-4">
<div class="card"> <div class="card">
<div class="card-content"> <div class="card-content">
<span class="card-title">Create new endpoint</span> <span class="card-title">Create new endpoint</span>
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col s12 input-field"> <div class="col s12 input-field">
<input placeholder="Custom endpoint" name="value" type="text" class="validate" minlength="12"> <input placeholder="Custom endpoint" name="value" type="text" class="validate" minlength="12">
<span class="supporting-text">Leaving this empty will create a random secure string</span> <span class="supporting-text">Leaving this empty will create a random secure string</span>
</div> </div>
<div class="col s12 input-field"> <div class="col s12 input-field">
<input placeholder="Description" name="description" type="text" class="validate" minlength="8" maxlength="64" required> <input placeholder="Description" name="description" type="text" class="validate" minlength="8" maxlength="64" required>
<span class="supporting-text">Description for the endpoint for better administration</span> <span class="supporting-text">Description for the endpoint for better administration</span>
</div> </div>
<button class="btn mt-4" type="submit" name="task" value="add-endpoint">Create</button> <button class="btn mt-4" type="submit" name="task" value="add-endpoint">Create</button>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div> </div>
<div class="col s12 l4 m-4"> <div class="col s12 l4 m-4">
<div class="card"> <div class="card">
<div class="card-content"> <div class="card-content">
<span class="card-title">Queue manually</span> <span class="card-title">Queue manually</span>
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col s12 input-field"> <div class="col s12 input-field">
<input placeholder="Youtube video ID" name="value" type="text" class="validate" minlength="11" maxlength="11" required> <input placeholder="Youtube video ID" name="value" type="text" class="validate" minlength="11" maxlength="11" required>
<span class="supporting-text">Must be a valid Youtube video ID</span> <span class="supporting-text">Must be a valid Youtube video ID</span>
</div> </div>
<div class="col s12 mt-5 input-field"> <div class="col s12 mt-5 input-field">
<div class="switch"> <div class="switch">
<label>Queue<input type="checkbox" value="direct" name="direct"><span class="lever"></span>Direct</label> <label>Queue<input type="checkbox" value="direct" name="direct"><span class="lever"></span>Direct</label>
<span class="supporting-text">Queue up or start directly</span> <span class="supporting-text">Queue up or start directly</span>
</div> </div>
</div> </div>
<button class="btn mt-4" type="submit" name="task" value="manual-queue">Queue</button> <button class="btn mt-4" type="submit" name="task" value="manual-queue">Queue</button>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div> </div>
@@ -79,10 +84,10 @@
<div class="divider"></div> <div class="divider"></div>
<div class="row"> <div class="row">
<div class="col s6 l9"> <div class="col s6 l9">
<h5>Registered endpoints</h5> <h5>Registered endpoints</h5>
</div> </div>
<div class="col s6 l3 m-4 input-field"> <div class="col s6 l3 m-4 input-field">
<input id="filter_query" type="text"> <input id="filter_query" type="text">
<label for="filter_query">Filter results</label> <label for="filter_query">Filter results</label>
</div> </div>
</div> </div>
@@ -91,30 +96,30 @@
<table class="striped highlight responsive-table"> <table class="striped highlight responsive-table">
<thead> <thead>
<tr> <tr>
<th>Actions</th> <th>Actions</th>
<th>id</th> <th>id</th>
<th>description</th> <th>description</th>
<th>status</th> <th>status</th>
<th>created_time</th> <th>created_time</th>
<th>retired_time</th> <th>retired_time</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for endpoint in endpoints %} {% for endpoint in endpoints %}
<tr class="filterable"> <tr class="filterable">
<td> <td>
<form method="post"> <form method="post">
<input type="text" value="{{ endpoint.get('id') }}" name="value" hidden> <input type="text" value="{{ endpoint.get('id') }}" name="value" hidden>
<button class="btn-small waves-effect waves-light" type="submit" name="task" value="retire" title="Retire endpoint" {% if endpoint.get('status') != 'active' %}disabled{% endif %}>🗑️</button> <button class="btn-small waves-effect waves-light" type="submit" name="task" value="retire" title="Retire endpoint" {% if endpoint.get('status') != 'active' %}disabled{% endif %}>🗑️</button>
</form> </form>
</td> </td>
<td>{{ endpoint.get('id') }}</td> <td>{{ endpoint.get('id') }}</td>
<td>{{ endpoint.get('description') }}</td> <td>{{ endpoint.get('description') }}</td>
<td>{{ endpoint.get('status') }}</td> <td>{{ endpoint.get('status') }}</td>
<td>{{ endpoint.get('created_time') }}</td> <td>{{ endpoint.get('created_time') }}</td>
<td>{{ endpoint.get('retired_time') }}</td> <td>{{ endpoint.get('retired_time') }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
</div> </div>
@@ -122,10 +127,10 @@
<div class="divider"></div> <div class="divider"></div>
<div class="row"> <div class="row">
<div class="col s6 l9"> <div class="col s6 l9">
<h5>Queued ID's</h5> <h5>Queued ID's</h5>
</div> </div>
<div class="col s6 l3 m-4 input-field"> <div class="col s6 l3 m-4 input-field">
<input id="filter_query" type="text"> <input id="filter_query" type="text">
<label for="filter_query">Filter results</label> <label for="filter_query">Filter results</label>
</div> </div>
</div> </div>
@@ -134,28 +139,33 @@
<table class="striped highlight responsive-table"> <table class="striped highlight responsive-table">
<thead> <thead>
<tr> <tr>
<th>Actions</th> <th>Actions</th>
<th>id</th> <th>id</th>
<th>endpoint</th> <th>endpoint</th>
<th>status</th> <th>status</th>
<th>created_time</th> <th>created_time</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for id in queue %} {% for id in queue %}
<tr class="filterable"> <tr class="filterable">
<td> <td>
<form method="post"> <form method="post">
<input type="text" value="{{ id.get('id') }}" name="value" hidden> <input type="text" value="{{ id.get('id') }}" name="value" hidden>
<button class="btn-small waves-effect waves-light" type="submit" name="task" value="delete-queue" title="Delete from queue" {% if id.get('status') != 'queued' %}disabled{% endif %}>🗑️</button> <button class="btn-small waves-effect waves-light" type="submit" name="task" value="delete-queue" title="Delete from queue" {% if id.get('status') == 'working' %}disabled{% endif %}>🗑️</button>
</form> </form>
</td> <form method="post">
<td>{{ id.get('id') }}</td> <input type="text" value="{{ id.get('id') }}" name="value" hidden>
<td>{{ id.get('endpoint') }}</td> <button class="btn-small waves-effect waves-light" type="submit" name="task" value="run-download" title="Run download task" disabled>⏩</button>
<td>{{ id.get('status') }}</td> <!-- This function fill not work until the download queue and video download process is rewritten -->
<td>{{ id.get('created_time') }}</td> </form>
</td>
<td>{{ id.get('id') }}</td>
<td>{{ id.get('endpoint') }}</td>
<td>{{ id.get('status') }}</td>
<td>{{ id.get('created_time') }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@@ -16,12 +16,43 @@
</div> </div>
<form method="POST"> <form method="POST">
<input title="test-sleep" type="submit" value="test-sleep" name="task"> <input title="test-sleep" type="submit" value="test-sleep" name="task">
<input title="test-sleep" type="submit" value="queue-single" name="task">
</form> </form>
<div class="divider"></div> <div class="divider"></div>
<div class="row"> <div class="row">
<div class="col s12"> <div class="col s12 m-4">
<h6>Current workers</h6> <h5>Reserved tasks per worker</h5>
<p>Usually 4 tasks per worker</p>
{% if reserved is none %}
<h6>No workers with reserved tasks, are there any workers with stuck tasks or are they even online?</h6>
{% else %}
{% for worker in reserved %}
<span>{{ worker }}</span>
<table class="striped highlight responsive-table" style=" border: 1px solid black;">
<thead>
<tr>
<th>ID</th>
<th>Task</th>
<th>Arguments</th>
</tr>
</thead>
<tbody>
{% for task in reserved[worker] %}
<tr>
<td>{{ task.get('id') }}</td>
<td>{{ task.get('name') }}</td>
<td>{{ task.get('args') }} {{ task.get('kwargs') }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
{% endif %}
</div>
<div class="col s12 m-4">
<h5>Current workers and processing tasks</h5>
{% if tasks is none %}
<h6>No workers with running tasks, are there any workers with stuck tasks or are they even online?</h6>
{% else %}
{% for worker in tasks %} {% for worker in tasks %}
<span>{{ worker }}</span> <span>{{ worker }}</span>
<table class="striped highlight responsive-table" style=" border: 1px solid black;"> <table class="striped highlight responsive-table" style=" border: 1px solid black;">
@@ -36,13 +67,14 @@
{% for task in tasks[worker] %} {% for task in tasks[worker] %}
<tr> <tr>
<td>{{ task.get('id') }}</td> <td>{{ task.get('id') }}</td>
<td>{{ task.get('type') }}</td> <td>{{ task.get('name') }}</td>
<td>{{ task.get('time_start')|epoch_time }}</td> <td>{{ task.get('time_start')|epoch_time }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
{% endfor %} {% endfor %}
{% endif %}
</div> </div>
</div> </div>
{% endblock %} {% endblock %}

View File

@@ -3,6 +3,8 @@
flask flask
flask-caching flask-caching
flask-limiter flask-limiter
flask-sqlalchemy
flask-migrate
pymongo pymongo
yt-dlp yt-dlp
gunicorn gunicorn