From ab94c3b76473e669feecfd807eeacad4ca728c12 Mon Sep 17 00:00:00 2001 From: Mikan <72257910+Mikan-DS@users.noreply.github.com> Date: Mon, 23 Sep 2024 17:06:30 +0300 Subject: [PATCH] initial --- .idea/.gitignore | 8 + .idea/EpisodesMultifanBot.iml | 10 + .idea/dataSources.xml | 17 ++ .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 7 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + database/__init__.py | 13 ++ database/models.py | 37 ++++ loader/__init__.py | 56 +++++ main.py | 202 ++++++++++++++++++ requirements.txt | 2 + telegram_wrapper.py | 9 + 13 files changed, 381 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/EpisodesMultifanBot.iml create mode 100644 .idea/dataSources.xml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 database/__init__.py create mode 100644 database/models.py create mode 100644 loader/__init__.py create mode 100644 main.py create mode 100644 requirements.txt create mode 100644 telegram_wrapper.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/EpisodesMultifanBot.iml b/.idea/EpisodesMultifanBot.iml new file mode 100644 index 0000000..2c80e12 --- /dev/null +++ b/.idea/EpisodesMultifanBot.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..9495ce3 --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,17 @@ + + + + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:C:\Users\Mikan\PycharmProjects\EpisodesMultifanBot\cartoons.db + $ProjectFileDir$ + + + file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.43.0/org/xerial/sqlite-jdbc/3.43.0.0/sqlite-jdbc-3.43.0.0.jar + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..744f287 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..2221f40 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/database/__init__.py b/database/__init__.py new file mode 100644 index 0000000..e87fa28 --- /dev/null +++ b/database/__init__.py @@ -0,0 +1,13 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from .models import Base, Cartoon, Season, Episode + +__all__ = ['session', 'Cartoon', 'Season', 'Episode'] + +engine = create_engine('sqlite:///cartoons.db') +Base.metadata.create_all(engine) + +Session = sessionmaker(bind=engine) +session = Session() + diff --git a/database/models.py b/database/models.py new file mode 100644 index 0000000..dd9cc80 --- /dev/null +++ b/database/models.py @@ -0,0 +1,37 @@ +from sqlalchemy import Column, Integer, String, ForeignKey +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship + +Base = declarative_base() + + +class Cartoon(Base): + __tablename__ = 'cartoons' + + id = Column(Integer, primary_key=True) + name = Column(String, nullable=False) + + seasons = relationship("Season", backref="cartoon", order_by="Season.season_number") + + +class Season(Base): + __tablename__ = 'seasons' + + id = Column(Integer, primary_key=True) + season_number = Column(Integer, nullable=False) + cartoon_id = Column(Integer, ForeignKey('cartoons.id'), nullable=False) + + episodes = relationship("Episode", backref="season", order_by="Episode.episode_number") + + +class Episode(Base): + __tablename__ = 'episodes' + + id = Column(Integer, primary_key=True) + episode_number = Column(Integer, nullable=False) + season_id = Column(Integer, ForeignKey('seasons.id'), nullable=False) + file = Column(String, nullable=False) + + + + diff --git a/loader/__init__.py b/loader/__init__.py new file mode 100644 index 0000000..13f4f2d --- /dev/null +++ b/loader/__init__.py @@ -0,0 +1,56 @@ +import requests + + +def get_futurama(season, episode): + return f'https://s6.streamani.top/video1/IQCFO7Lyp1vm45ai6wpJCQ/1727007181/futurama/{season}/LostFilm/{season}%02d.mp4'%episode + +def get_amerika(season, episode): + return f'https://s6.streamani.top/video1/o_oY4tK-92WR9vZiaeuKGw/1727014428/americandad/{season}/TVShows/{season}%02d.mp4'%episode + +cartoons = { + 1: get_futurama, + 2: get_amerika +} + + + + +def load_episode(cartoon_id, season, episode): + response = requests.get(cartoons[cartoon_id](season, episode), stream=True) + + assert response.status_code == 200 + + print(f"Идет загрузка {episode} серии...") + + filename = "C%02dS%02dE%02d.mp4"%(cartoon_id, season, episode) + with open(f"episodes/{filename}", "wb") as f: + for i, chunk in enumerate(response.iter_content(1024*16)): + if not i % 50: + print("|", end="") + f.write(chunk) + print(f"\nВидео сохранено как {filename}") + +def load_season(cartoon_id, season_id, episodes=None): + print(f"Идет загрузка {season_id} сезона") + if episodes: + for episode in episodes: + try: + load_episode(cartoon_id, season_id, episode) + except AssertionError: + break + else: + episode = 0 + while True: + episode += 1 + try: + load_episode(cartoon_id, season_id, episode) + except AssertionError: + break + print("Сезон загружен") + + +load_season(2, 19, range(6, 26)) +# for season in range(16, 20): +# print("Сезон %d"%season) +# load_season(2, season) + diff --git a/main.py b/main.py new file mode 100644 index 0000000..1ca106a --- /dev/null +++ b/main.py @@ -0,0 +1,202 @@ +import re + +from telebot.types import CallbackQuery + +import database as db +from telegram_wrapper import Bot +from telebot import types + +bot = Bot(token='8038407249:AAF_sLlOFZVrV_ps85rpYvvLKtla40IzEQw') + + +def build_button_handler(name, **kwargs): + params = [] + for k, v in kwargs.items(): + params.append(f"{k}={v}") + return f"{name}:{';'.join(params)}" + + +def get_params(callback_data): + name, params_data = callback_data.split(":", maxsplit=1) + params_data = params_data.split(";") + params = {} + for param in params_data: + if not param: + continue + key, value = param.split("=", maxsplit=1) + params[key] = value + return name, params + + +@bot.bot.message_handler(commands=['start']) +@bot.bot.message_handler(content_types=['text']) +def list_cartons(message): + markup = types.InlineKeyboardMarkup() + for cartoon in db.session.query(db.Cartoon): + button = types.InlineKeyboardButton(cartoon.name, + callback_data=build_button_handler("get_cartoon", cartoon_id=cartoon.id)) + markup.add(button) + + bot.bot.send_message(message.chat.id, 'Список загруженных сериалов:', reply_markup=markup) + +@bot.bot.message_handler(content_types=['video']) +def load_episode(message): + video = message.video + + cartoon_id, season_number, episode_number = re.match(r'C(\d+)S(\d+)E(\d+)', video.file_name).groups() + + cartoon = db.session.query(db.Cartoon).filter_by(id=int(cartoon_id)).first() + season = db.session.query(db.Season).filter_by(cartoon=cartoon, season_number=int(season_number)).first() + if not season: + season = db.Season(cartoon=cartoon, season_number=int(season_number)) + db.session.add(season) + db.session.commit() + episode = db.session.query(db.Episode).filter_by(season=season, episode_number=int(episode_number)).first() + if not episode: + episode = db.Episode(season=season, episode_number=int(episode_number), file=video.file_id) + db.session.add(episode) + db.session.commit() + + bot.bot.send_message( + message.chat.id, + f'Добавлена серия в "{cartoon.name}" S%02dE%02d' % (season.season_number, episode.episode_number)) + + +@bot.bot.callback_query_handler(func=lambda call: True) +def button_handler(call: CallbackQuery): + # bot.bot.send_message(call.message.chat.id, str(call.data)) + + name, params = get_params(call.data) + + if name == "list_cartoon": + markup = types.InlineKeyboardMarkup() + for cartoon in db.session.query(db.Cartoon): + button = types.InlineKeyboardButton(cartoon.name, callback_data=build_button_handler("get_cartoon", + cartoon_id=cartoon.id)) + markup.add(button) + + bot.bot.send_message(call.message.chat.id, 'Список загруженных сериалов:', reply_markup=markup) + + elif name == "get_cartoon": + + cartoon = db.session.query(db.Cartoon).filter_by(id=params["cartoon_id"]).first() + + markup = types.InlineKeyboardMarkup() + + if cartoon.seasons: + for season in cartoon.seasons: + button = types.InlineKeyboardButton(str(season.season_number), callback_data=build_button_handler( + "get_season", + cartoon_id=params["cartoon_id"], + season_id=season.season_number + )) + markup.add(button) + + button = types.InlineKeyboardButton("Назад", callback_data=build_button_handler( + "list_cartoon" + )) + markup.add(button) + + bot.bot.send_message(call.message.chat.id, f'Список загруженных сезонов "{cartoon.name}":', + reply_markup=markup) + else: + button = types.InlineKeyboardButton("Назад", callback_data=build_button_handler( + "list_cartoon" + )) + markup.add(button) + bot.bot.send_message(call.message.chat.id, f'Для сериала "{cartoon.name}" нет доступных сезонов', + reply_markup=markup) + + elif name == "get_season": + cartoon = db.session.query(db.Cartoon).filter_by(id=params["cartoon_id"]).first() + + season = db.session.query(db.Season).filter_by( + cartoon=cartoon, + season_number=params["season_id"] + ).first() + + markup = types.InlineKeyboardMarkup() + + if season.episodes: + for episode in season.episodes: + button = types.InlineKeyboardButton(str(episode.episode_number), callback_data=build_button_handler( + "watch", + cartoon_id=params["cartoon_id"], + season_id=season.season_number, + episode_id=episode.episode_number + )) + markup.add(button) + + button = types.InlineKeyboardButton("Назад", callback_data=build_button_handler( + "get_cartoon", + cartoon_id=params["cartoon_id"] + )) + markup.add(button) + + bot.bot.send_message(call.message.chat.id, + f'Список загруженных серий {season.season_number} сезона сериала "{cartoon.name}":', + reply_markup=markup) + else: + + button = types.InlineKeyboardButton("Назад", callback_data=build_button_handler( + "get_cartoon", + cartoon_id=params["cartoon_id"] + )) + markup.add(button) + bot.bot.send_message(call.message.chat.id, + f'Для {season.season_number} сезона сериала "{cartoon.name}" нет доступных серий', + reply_markup=markup) + + elif name == "watch": + cartoon = db.session.query(db.Cartoon).filter_by(id=params["cartoon_id"]).first() + + season = db.session.query(db.Season).filter_by( + cartoon=cartoon, + season_number=params["season_id"] + ).first() + + episode = db.session.query(db.Episode).filter_by(season=season, episode_number=params["episode_id"]).first() + + markup = types.InlineKeyboardMarkup() + + next_episode = db.session.query(db.Episode).filter_by(season=season, episode_number=int(params["episode_id"])+1).first() + if next_episode: + button = types.InlineKeyboardButton("Следующая серия", callback_data=build_button_handler( + "watch", + cartoon_id=params["cartoon_id"], + season_id=params["season_id"], + episode_id=next_episode.episode_number + )) + markup.add(button) + + + before_episode = db.session.query(db.Episode).filter_by(season=season, episode_number=int(params["episode_id"])-1).first() + if before_episode: + button = types.InlineKeyboardButton("Прошлая серия", callback_data=build_button_handler( + "watch", + cartoon_id=params["cartoon_id"], + season_id=params["season_id"], + episode_id=before_episode.episode_number + )) + markup.add(button) + + button = types.InlineKeyboardButton("К списку серий", callback_data=build_button_handler( + "get_season", + cartoon_id=params["cartoon_id"], + season_id=params["season_id"] + )) + markup.add(button) + + bot.bot.send_video(call.message.chat.id, + video=episode.file, + caption=f'{cartoon.name}\nСезон {season.season_number}\nСерия {episode.episode_number}', + reply_markup=markup) + + try: + bot.bot.delete_message(call.message.chat.id, call.message.message_id) + except Exception as e: + print(repr(e)) + return True + + +bot.polling() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..af178a0 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +pyTelegramBotAPI +sqlalchemy \ No newline at end of file diff --git a/telegram_wrapper.py b/telegram_wrapper.py new file mode 100644 index 0000000..ef35221 --- /dev/null +++ b/telegram_wrapper.py @@ -0,0 +1,9 @@ +import telebot + + +class Bot: + def __init__(self, token, *args, **kwargs): + self.bot = telebot.TeleBot(token, *args, **kwargs) + + def polling(self): + self.bot.infinity_polling(interval=0, timeout=20)