FEAT: Added Celery Beat

FEAT: Added preferences Celery task to automatically record what categories users watched
This commit is contained in:
JustIceO7
2025-02-18 02:02:34 +00:00
parent 62d83aa4eb
commit 76de1b7d9d
9 changed files with 135 additions and 12 deletions

View File

@@ -3,6 +3,7 @@ from utils.stream_utils import generate_thumbnail, get_streamer_live_status
from time import sleep
from os import listdir, remove
from datetime import datetime
from celery_tasks.preferences import user_preferences
import subprocess
def celery_init_app(app) -> Celery:
@@ -13,10 +14,17 @@ def celery_init_app(app) -> Celery:
celery_app = Celery(app.name, task_cls=FlaskTask)
celery_app.config_from_object(app.config["CELERY"])
celery_app.conf.beat_schedule = {
'user-favourability-task': {
'task': 'celery_tasks.preferences.user_preferences',
'schedule': 30.0,
},
}
celery_app.set_default()
app.extensions["celery"] = celery_app
return celery_app
@shared_task
def update_thumbnail(user_id, stream_file, thumbnail_file, sleep_time) -> None:
"""

View File

@@ -0,0 +1,36 @@
from celery import shared_task
from database.database import Database
import redis
import json
redis_url = "redis://redis:6379/1"
r = redis.from_url(redis_url, decode_responses=True)
@shared_task
def user_preferences():
"""
Updates users preferences on different stream categories based on the streams they are currently watching
"""
stats = r.hget("current_viewers", "viewers")
# If there are any current viewers
if stats:
stats = json.loads(stats)
print(stats, flush=True)
with Database() as db:
# Loop over all users and their currently watching streams
for user_id, stream_ids in stats.items():
# For each user and stream combination
for stream_id in stream_ids:
# Retrieves category associated with stream
current_category = db.fetchone("""SELECT category_id FROM streams
WHERE user_id = ?
""", (stream_id))
# If stream is still live then update the user_preferences table to reflect their preferences
if current_category:
db.execute("""INSERT INTO user_preferences (user_id,category_id,favourability)
VALUES (?,?,?)
ON CONFLICT(user_id, category_id)
DO UPDATE SET favourability = favourability + 1
""", (user_id, current_category["category_id"], 1))
data = db.fetchall("SELECT * FROM user_preferences")
print(data,flush=True)