diff options
-rw-r--r-- | youtube/subscriptions.py | 82 |
1 files changed, 70 insertions, 12 deletions
diff --git a/youtube/subscriptions.py b/youtube/subscriptions.py index 47f1ea3..39957bf 100644 --- a/youtube/subscriptions.py +++ b/youtube/subscriptions.py @@ -1,18 +1,76 @@ -import urllib +from youtube import common, settings +import sqlite3 +import os -with open("subscriptions.txt", 'r', encoding='utf-8') as file: - subscriptions = file.read() - -# Line format: "channel_id channel_name" -# Example: -# UCYO_jab_esuFRV4b17AJtAw 3Blue1Brown +# https://stackabuse.com/a-sqlite-tutorial-with-python/ -subscriptions = ((line[0:24], line[25: ]) for line in subscriptions.splitlines()) +database_path = os.path.join(settings.data_dir, "subscriptions.sqlite") -def get_new_videos(): - for channel_id, channel_name in subscriptions: - +def open_database(): + if not os.path.exists(settings.data_dir): + os.makedirs(settings.data_dir) + connection = sqlite3.connect(database_path) + # Create tables if they don't exist + try: + cursor = connection.cursor() + cursor.execute('''CREATE TABLE IF NOT EXISTS subscribed_channels ( + id integer PRIMARY KEY, + channel_id text NOT NULL, + channel_name text NOT NULL, + time_last_checked integer + )''') + cursor.execute('''CREATE TABLE IF NOT EXISTS videos ( + id integer PRIMARY KEY, + uploader_id integer NOT NULL REFERENCES subscribed_channels(id) ON UPDATE CASCADE ON DELETE CASCADE, + video_id text NOT NULL, + title text NOT NULL, + time_published integer NOT NULL, + description text, + )''') + connection.commit() + except: + connection.rollback() + connection.close() + raise + return connection -def get_subscriptions_page(): +def _subscribe(channel_id, channel_name): + connection = open_database() + try: + cursor = connection.cursor() + cursor.execute("INSERT INTO subscribed_channels (channel_id, name) VALUES (?, ?)", (channel_id, channel_name)) + connection.commit() + except: + connection.rollback() + raise + finally: + connection.close() + +def _unsubscribe(channel_id): + connection = open_database() + try: + cursor = connection.cursor() + cursor.execute("DELETE FROM subscribed_channels WHERE channel_id=?", (channel_id, )) + connection.commit() + except: + connection.rollback() + raise + finally: + connection.close() + +def _get_videos(number, offset): + connection = open_database() + try: + cursor = connection.cursor() + cursor.execute('''SELECT video_id, title, time_published, description, channel_id, channel_name + FROM videos + INNER JOIN subscribed_channels on videos.uploader_id = subscribed_channels.id + ORDER BY time_published DESC + LIMIT ? OFFSET ?''', number, offset) + except: + connection.rollback() + raise + finally: + connection.close() |