From 99bc017a4d6b3d6dd351e59395962fbdf456d719 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 15 Mar 2023 11:01:59 +0800 Subject: [PATCH 01/40] Fix GitHub action --- .github/workflows/dev-latest.yml | 4 ++-- .github/workflows/docker.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-latest.yml b/.github/workflows/dev-latest.yml index db6ce2e1..de98e0d0 100644 --- a/.github/workflows/dev-latest.yml +++ b/.github/workflows/dev-latest.yml @@ -14,7 +14,7 @@ jobs: - name: Create Version info working-directory: ./src run: | - echo "VERSION = '2.6.0-beta'" > module/__version__.py + echo "VERSION = '$GITHUB_REF_NAME'" > module/__version__.py - name: Set up QEMU uses: docker/setup-qemu-action@v2 @@ -36,5 +36,5 @@ jobs: tags: | estrellaxd/auto_bangumi:dev-latest estrellaxd/auto_bangumi:dev-${{ github.sha }} - estrellaxd/auto_bangumi:${{ github.ref }} + estrellaxd/auto_bangumi:${{ github.ref_name }} file: Dockerfile diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 3c13a29e..81ed6af1 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -42,5 +42,5 @@ jobs: tags: | estrellaxd/auto_bangumi:latest estrellaxd/auto_bangumi:${{ github.sha }} - estrellaxd/auto_bangumi:${{ github.ref }} + estrellaxd/auto_bangumi:${{ github.ref_name }} labels: ${{ steps.meta.outputs.labels }} From ad1d431549ab6b107e629f118d0c1259bab36a4e Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 15 Mar 2023 12:48:01 +0800 Subject: [PATCH 02/40] Fix eps collect bugs. --- src/module/downloader/qb_downloader.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/module/downloader/qb_downloader.py b/src/module/downloader/qb_downloader.py index d0f65121..c9fe9dbe 100644 --- a/src/module/downloader/qb_downloader.py +++ b/src/module/downloader/qb_downloader.py @@ -44,7 +44,7 @@ class QbDownloader: def torrents_add(self, urls, save_path, category): return self._client.torrents_add( - is_paused=settings.DEBUG["enable"], + is_paused=settings.debug.dev_debug, urls=urls, save_path=save_path, category=category, From 0a819d32bd2a9ce54a68af533f85b2c9cb884209 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 15 Mar 2023 20:39:14 +0800 Subject: [PATCH 03/40] Complete notification.py --- src/module/api.py | 1 + src/module/app.py | 2 +- src/module/models/bangumi.py | 19 ++++++++++++ src/module/network/notification.py | 40 ++++++++++++------------ src/module/network/request_contents.py | 10 ++++-- src/module/network/request_url.py | 24 +++++++++++++-- src/module/parser/fuzz_match.py | 42 -------------------------- src/module/parser/openai.py | 17 +++++++++++ src/module/parser/title_parser.py | 7 +++-- src/run.sh | 2 +- 10 files changed, 93 insertions(+), 71 deletions(-) delete mode 100644 src/module/parser/fuzz_match.py create mode 100644 src/module/parser/openai.py diff --git a/src/module/api.py b/src/module/api.py index 1d6fdb83..00cccbde 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -20,6 +20,7 @@ app.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") templates = Jinja2Templates(directory="templates") +# HTML Response @app.get("/", response_class=HTMLResponse) def index(request: Request): context = {"request": request} diff --git a/src/module/app.py b/src/module/app.py index 6904f384..dd720977 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -71,7 +71,7 @@ def main_process(bangumi_data, download_client: DownloadClient): if settings.bangumi_manage.enable: rename.run() times += 1 - time.sleep(settings.program.sleep_time/settings.program.times) + time.sleep(settings.program.sleep_time / settings.program.times) def run(): diff --git a/src/module/models/bangumi.py b/src/module/models/bangumi.py index cb66fc45..f8b8d6b2 100644 --- a/src/module/models/bangumi.py +++ b/src/module/models/bangumi.py @@ -26,3 +26,22 @@ class Episode: group: str resolution: str source: str + + +@dataclass +class SeasonInfo(dict): + official_title: str + title_raw: str + season: int + season_raw: str + group: str + filter: list | None + offset: int | None + dpi: str + source: str + subtitle: str + added: bool + eps_collect: bool + + + diff --git a/src/module/network/notification.py b/src/module/network/notification.py index 50860b90..c6dca0ba 100644 --- a/src/module/network/notification.py +++ b/src/module/network/notification.py @@ -1,7 +1,6 @@ import logging -import requests - +from .request_contents import RequestContent from module.conf import settings @@ -12,11 +11,23 @@ class PostNotification: def __init__(self): self.token = settings.notification_token self.notification_url = lambda message: f"https://api.pushbullet.com/v2/{self.token}/{message}" + self.client = self.getClient() - def ifttt_post(self, message): - url = self.notification_url(message) - response = requests.get(url) - return response.status_code == 200 + @staticmethod + def getClient(): + if settings.notification.type.lower() == "telegram": + return TelegramNotification() + elif settings.notification.type.lower() == "serverchan": + return ServerChanNotification() + else: + return None + + def send_msg(self, title: str, desp: str) -> bool: + if not settings.notification.enable: + return False + if self.client is None: + return False + return self.client.send_msg(title, desp) class TelegramNotification: @@ -35,7 +46,6 @@ class TelegramNotification: class ServerChanNotification: """Server酱推送""" - def __init__(self): self.token = settings.notification.token self.notification_url = f"https://sctapi.ftqq.com/{self.token}.send" @@ -47,16 +57,6 @@ class ServerChanNotification: "title": title, "desp": desp, } - try: - resp = requests.post(self.notification_url, json=data, timeout=3) - resp.raise_for_status() - except requests.RequestException as e: - logging.error("[ServerChanNotification] send fail, error: %s" % e) - return False - return True - - -if __name__ == '__main__': - name = "勇者、辞职不干了" - notification = ServerChanNotification() - notification.send_msg(f"《{name[:10]}》缓存成功", f"[Auto Bangumi]《{name}》缓存成功") + with RequestContent() as req: + resp = req.post_data(self.notification_url, data) + return resp.status_code == 200 diff --git a/src/module/network/request_contents.py b/src/module/network/request_contents.py index 497c89c1..078d8dca 100644 --- a/src/module/network/request_contents.py +++ b/src/module/network/request_contents.py @@ -1,12 +1,12 @@ -from dataclasses import dataclass +import re +from dataclasses import dataclass from bs4 import BeautifulSoup from .request_url import RequestURL from module.conf import settings -import re FILTER = "|".join(settings.rss_parser.filter) @@ -41,3 +41,9 @@ class RequestContent(RequestURL): # API JSON def get_json(self, _url) -> dict: return self.get_url(_url).json() + + def post_json(self, _url, data: dict) -> dict: + return self.post_url(_url, data).json() + + def post_data(self, _url, data: dict) -> dict: + return self.post_url(_url, data) diff --git a/src/module/network/request_url.py b/src/module/network/request_url.py index 90be4c1a..44b53b64 100644 --- a/src/module/network/request_url.py +++ b/src/module/network/request_url.py @@ -18,8 +18,8 @@ class RequestURL: } def get_url(self, url): - times = 0 - while times < 5: + try_time = 0 + while try_time < 5: try: req = self.session.get(url=url, headers=self.header) req.raise_for_status() @@ -29,7 +29,25 @@ class RequestURL: logger.debug(e) logger.warning("ERROR with Connection.Please check DNS/Connection settings") time.sleep(5) - times += 1 + try_time += 1 + except Exception as e: + logger.debug(f"URL: {url}") + logger.debug(e) + break + + def post_url(self, url: str, data: dict): + try_time = 0 + while try_time < 5: + try: + req = self.session.post(url=url, headers=self.header, data=data) + req.raise_for_status() + return req + except requests.RequestException as e: + logger.debug(f"URL: {url}") + logger.debug(e) + logger.warning("ERROR with Connection.Please check DNS/Connection settings") + time.sleep(5) + try_time += 1 except Exception as e: logger.debug(f"URL: {url}") logger.debug(e) diff --git a/src/module/parser/fuzz_match.py b/src/module/parser/fuzz_match.py deleted file mode 100644 index 15b761d6..00000000 --- a/src/module/parser/fuzz_match.py +++ /dev/null @@ -1,42 +0,0 @@ -from thefuzz import fuzz -import logging -from module.utils import json_config -from module.conf import settings - -logger = logging.getLogger(__name__) - - -class FuzzMatch: - def __init__(self): - try: - anidb_data = json_config.get(settings.anidb_url) - json_config.save(settings.anidb_path, anidb_data) - except Exception as e: - logger.debug(e) - logger.info(f"Fail to get anidb data, reading local data") - anidb_data = json_config.load(settings.anidb_path) - self.match_data = anidb_data - - @staticmethod - def match(title_raw, info: dict): - compare_value = [] - for tag in ["main", "en", "ja", "zh-Hans", "zh-Hant"]: - if info[tag] is not None: - a = fuzz.token_sort_ratio(title_raw.lower(), info[tag].lower()) - compare_value.append(a) - for compare in info["other"]: - a = fuzz.token_sort_ratio(title_raw.lower(), compare.lower()) - compare_value.append(a) - return max(compare_value) - - def find_max_name(self, title_raw): - max_value = 0 - max_info = None - for info in self.match_data: - a = self.match(title_raw, info) - if a > max_value: - max_value = a - max_info = info - return max_value, max_info["main"] - # logger.debug(max(value)) - diff --git a/src/module/parser/openai.py b/src/module/parser/openai.py new file mode 100644 index 00000000..cd34c8b2 --- /dev/null +++ b/src/module/parser/openai.py @@ -0,0 +1,17 @@ +from module.network import RequestContent +from module.conf import settings + + +API_URL = "https://openai.estrella.cloud" + + +class OpenAIParser: + def __init__(self): + pass + + def parse(self, title: str) -> dict: + prompt = { + "prompt": "This is a test prompt", + } + with RequestContent() as req: + req.get_json(API_URL, params=prompt) diff --git a/src/module/parser/title_parser.py b/src/module/parser/title_parser.py index 0cfdaad3..72404619 100644 --- a/src/module/parser/title_parser.py +++ b/src/module/parser/title_parser.py @@ -3,6 +3,7 @@ import logging from .analyser import RawParser, DownloadParser, TMDBMatcher from module.conf import settings +from module.models import SeasonInfo logger = logging.getLogger(__name__) LANGUAGE = settings.rss_parser.language @@ -38,7 +39,7 @@ class TitleParser: official_title = official_title if official_title else title return official_title, tmdb_season - def return_dict(self, _raw: str): + def return_dict(self, _raw: str) -> dict: try: episode = self.raw_parser(_raw) title_search = episode.title_zh if episode.title_zh else episode.title_en @@ -59,8 +60,10 @@ class TitleParser: "subtitle": episode.sub, "added": False, "eps_collect": True if episode.episode > 1 else False, + "offset": 0, + "filter": settings.rss_parser.filter } logger.debug(f"RAW:{_raw} >> {episode.title_en}") return data except Exception as e: - logger.debug(e) \ No newline at end of file + logger.debug(e) diff --git a/src/run.sh b/src/run.sh index 39000cb9..bf18b90f 100755 --- a/src/run.sh +++ b/src/run.sh @@ -2,7 +2,7 @@ # Check old version if [ -f /config/bangumi.json ]; then - mv /config/bangumi.json /data/bangumi.json + mv /config/bangumi.json /app/data/bangumi.json fi From 247178b183ed1a9e88de27ecb5306afe32ac425f Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Thu, 16 Mar 2023 09:53:43 +0800 Subject: [PATCH 04/40] Optimize starting log --- .github/workflows/dev-latest.yml | 1 - .github/workflows/docker.yml | 1 - src/icon | 8 ++++++++ src/main.py | 19 ++++++++++++++++++- src/module/app.py | 19 ++----------------- 5 files changed, 28 insertions(+), 20 deletions(-) create mode 100644 src/icon diff --git a/.github/workflows/dev-latest.yml b/.github/workflows/dev-latest.yml index de98e0d0..2e1eeaae 100644 --- a/.github/workflows/dev-latest.yml +++ b/.github/workflows/dev-latest.yml @@ -35,6 +35,5 @@ jobs: push: true tags: | estrellaxd/auto_bangumi:dev-latest - estrellaxd/auto_bangumi:dev-${{ github.sha }} estrellaxd/auto_bangumi:${{ github.ref_name }} file: Dockerfile diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 81ed6af1..7befefc9 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -41,6 +41,5 @@ jobs: push: true tags: | estrellaxd/auto_bangumi:latest - estrellaxd/auto_bangumi:${{ github.sha }} estrellaxd/auto_bangumi:${{ github.ref_name }} labels: ${{ steps.meta.outputs.labels }} diff --git a/src/icon b/src/icon new file mode 100644 index 00000000..b5ddfb0a --- /dev/null +++ b/src/icon @@ -0,0 +1,8 @@ + _ ____ _ + /\ | | | _ \ (_) + / \ _ _| |_ ___ | |_) | __ _ _ __ __ _ _ _ _ __ ___ _ + / /\ \| | | | __/ _ \| _ < / _` | '_ \ / _` | | | | '_ ` _ \| | + / ____ \ |_| | || (_) | |_) | (_| | | | | (_| | |_| | | | | | | | + /_/ \_\__,_|\__\___/|____/ \__,_|_| |_|\__, |\__,_|_| |_| |_|_| + __/ | + |___/ \ No newline at end of file diff --git a/src/main.py b/src/main.py index 4496dec6..3763ae31 100644 --- a/src/main.py +++ b/src/main.py @@ -1,9 +1,26 @@ +import multiprocessing +import logging + from module import app from module import api +from module.conf import VERSION, setup_logger + + +logger = logging.getLogger(__name__) + + +def show_info(): + with open("icon", "r") as f: + for line in f.readlines(): + logger.info(line.strip("\n")) + logger.info(f"Version {VERSION} Author: EstrellaXD Twitter: https://twitter.com/Estrella_Pan") + logger.info("GitHub: https://github.com/EstrellaXD/Auto_Bangumi/") + logger.info("Starting AutoBangumi...") -import multiprocessing if __name__ == "__main__": + setup_logger() + show_info() num_processes = 2 processes = [] p1 = multiprocessing.Process(target=app.run) diff --git a/src/module/app.py b/src/module/app.py index dd720977..70210b5f 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -2,13 +2,14 @@ import os import time import logging -from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, VERSION +from module.conf import settings, LOG_PATH, DATA_PATH from module.utils import json_config from module.core import DownloadClient from module.manager import Renamer, FullSeasonGet from module.rss import RSSAnalyser + logger = logging.getLogger(__name__) @@ -42,20 +43,6 @@ def save_data_file(bangumi_data): logger.debug("Saved") -def show_info(): - logger.info(r" _ ____ _ ") - logger.info(r" /\ | | | _ \ (_)") - logger.info(r" / \ _ _| |_ ___ | |_) | __ _ _ __ __ _ _ _ _ __ ___ _ ") - logger.info(r" / /\ \| | | | __/ _ \| _ < / _` | '_ \ / _` | | | | '_ ` _ \| |") - logger.info(r" / ____ \ |_| | || (_) | |_) | (_| | | | | (_| | |_| | | | | | | |") - logger.info(r" /_/ \_\__,_|\__\___/|____/ \__,_|_| |_|\__, |\__,_|_| |_| |_|_|") - logger.info(" __/ | ") - logger.info(" |___/ ") - logger.info(f"Version {VERSION} Author: EstrellaXD Twitter: https://twitter.com/Estrella_Pan") - logger.info("GitHub: https://github.com/EstrellaXD/Auto_Bangumi/") - logger.info("Starting AutoBangumi...") - - def main_process(bangumi_data, download_client: DownloadClient): rename = Renamer(download_client) rss_analyser = RSSAnalyser() @@ -77,8 +64,6 @@ def main_process(bangumi_data, download_client: DownloadClient): def run(): # 初始化 reset_log() - setup_logger() - show_info() download_client = DownloadClient() download_client.init_downloader() if settings.rss_parser.link is None: From 6fb177700a09dc1f12b74ea4fbb54321d83f086b Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 22 Mar 2023 22:12:19 +0800 Subject: [PATCH 05/40] Fix uft-8 problem --- src/module/conf/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 9090f1c4..1701582f 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -36,7 +36,7 @@ class Settings: if path is None: conf = DEFAULT_SETTINGS elif os.path.isfile(path): - with open(path, "r") as f: + with open(path, "r", encoding="utf-8") as f: conf = json.load(f) else: conf = self._create_config() From 12309b43b3e231f3e11f06ae883778a8e4213a99 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Sat, 22 Apr 2023 16:29:54 +0800 Subject: [PATCH 06/40] Add custom url for mikanani. Fix eps_complete.py. --- Dockerfile | 2 +- src/requirements.txt => requirements.txt | 0 src/module/conf/config.py | 19 ++++++++++++++----- src/module/conf/const.py | 5 +++-- src/module/manager/eps_complete.py | 3 ++- src/module/parser/openai.py | 15 --------------- 6 files changed, 20 insertions(+), 24 deletions(-) rename src/requirements.txt => requirements.txt (100%) diff --git a/Dockerfile b/Dockerfile index d7b99cbe..9b0b4ba1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ ENV TZ=Asia/Shanghai \ WORKDIR /app -COPY src/requirements.txt . +COPY requirements.txt . RUN python3 -m pip install --upgrade pip \ && pip install -r requirements.txt --no-cache-dir diff --git a/src/requirements.txt b/requirements.txt similarity index 100% rename from src/requirements.txt rename to requirements.txt diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 9090f1c4..346034f5 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -1,13 +1,17 @@ import json import os +import logging from dataclasses import dataclass from .const import DEFAULT_SETTINGS, ENV_TO_ATTR +logger = logging.getLogger(__name__) + try: from ..__version__ import VERSION except ImportError: + logger.info("Can't find version info, use DEV_VERSION instead") VERSION = "DEV_VERSION" @@ -37,7 +41,8 @@ class Settings: conf = DEFAULT_SETTINGS elif os.path.isfile(path): with open(path, "r") as f: - conf = json.load(f) + # Use utf-8 to avoid encoding error + conf = json.load(f, encoding="utf-8") else: conf = self._create_config() for key, section in conf.items(): @@ -52,15 +57,19 @@ class Settings: return val def _create_config(self): - settings = DEFAULT_SETTINGS + _settings = DEFAULT_SETTINGS for key, section in ENV_TO_ATTR.items(): for env, attr in section.items(): if env in os.environ: attr_name = attr[0] if isinstance(attr, tuple) else attr - settings[key][attr_name] = self._val_from_env(env, attr) + _settings[key][attr_name] = self._val_from_env(env, attr) with open(CONFIG_PATH, "w") as f: - json.dump(settings, f, indent=4) - return settings + # Save utf-8 to avoid encoding error + json.dump(_settings, f, indent=4, ensure_ascii=False) + logger.warning(f"Config file had been transferred from environment variables to {CONFIG_PATH}, some settings may be lost.") + logger.warning("Please check the config file and restart the program.") + logger.warning("Please check github wiki (https://github.com/EstrellaXD/Auto_Bangumi/#/wiki) for more information.") + return _settings if os.path.isdir("config") and VERSION == "DEV_VERSION": diff --git a/src/module/conf/const.py b/src/module/conf/const.py index d81a6bd7..82d82c86 100644 --- a/src/module/conf/const.py +++ b/src/module/conf/const.py @@ -18,7 +18,8 @@ DEFAULT_SETTINGS = { "rss_parser": { "enable": True, "type": "mikan", - "link": "", + "custom_url": "mikanani.me", + "token": "", "enable_tmdb": False, "filter": ["720", "\\d+-\\d+"], "language": "zh" @@ -67,7 +68,7 @@ ENV_TO_ATTR = { }, "rss_parser": { "AB_RSS_COLLECTOR": ("enable", lambda e: e.lower() in ("true", "1", "t")), - "AB_RSS": "link", + "AB_RSS": ("token", lambda e: e.replace("https://mikanani.me/RSS/MyBangumi?token=", "")), "AB_NOT_CONTAIN": ("filter", lambda e: e.split("|")), "AB_LANGUAGE": "language", "AB_ENABLE_TMDB": ("enable_tmdb", lambda e: e.lower() in ("true", "1", "t")), diff --git a/src/module/manager/eps_complete.py b/src/module/manager/eps_complete.py index a12cb8b7..4ede11a1 100644 --- a/src/module/manager/eps_complete.py +++ b/src/module/manager/eps_complete.py @@ -9,6 +9,7 @@ from module.core.download_client import DownloadClient logger = logging.getLogger(__name__) SEARCH_KEY = ["group", "title_raw", "season_raw", "subtitle", "source", "dpi"] +CUSTOM_URL = "mikanani.me" if settings.rss_parser.custom_url == "" else settings.rss_parser.custom_url class FullSeasonGet: @@ -25,7 +26,7 @@ class FullSeasonGet: def get_season_torrents(self, data: dict): keyword = self.init_eps_complete_search_str(data) with RequestContent() as req: - torrents = req.get_torrents(f"https://mikanani.me/RSS/Search?searchstr={keyword}") + torrents = req.get_torrents(f"https://{CUSTOM_URL}/RSS/Search?searchstr={keyword}") return torrents @staticmethod diff --git a/src/module/parser/openai.py b/src/module/parser/openai.py index cd34c8b2..139597f9 100644 --- a/src/module/parser/openai.py +++ b/src/module/parser/openai.py @@ -1,17 +1,2 @@ -from module.network import RequestContent -from module.conf import settings -API_URL = "https://openai.estrella.cloud" - - -class OpenAIParser: - def __init__(self): - pass - - def parse(self, title: str) -> dict: - prompt = { - "prompt": "This is a test prompt", - } - with RequestContent() as req: - req.get_json(API_URL, params=prompt) From ee8f7dd1a259e66ab54cdb103894c2d16ee794cd Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Sun, 23 Apr 2023 21:35:57 +0800 Subject: [PATCH 07/40] =?UTF-8?q?-=20=E6=96=B0=E5=A2=9E=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=9F=9F=E5=90=8D=20-=20=E5=A2=9E=E5=8A=A0=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=8A=A5=E9=94=99=E5=9F=9F=E5=90=8D=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=20#195=20-=20=E4=BF=AE=E5=A4=8D=20Dev-debug=20=E5=BC=80?= =?UTF-8?q?=E5=90=AF=E7=9A=84=E9=94=99=E8=AF=AF=20#192=20-=20=E9=87=8D?= =?UTF-8?q?=E5=81=9A=E9=87=8D=E5=91=BD=E5=90=8D=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=90=88=E9=9B=86=E9=87=8D=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BB=A5=E5=8F=8A=E6=96=87=E4=BB=B6=E5=A4=B9=E5=86=85=E9=87=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D=EF=BC=8C=E6=94=AF=E6=8C=81=E5=AD=97=E5=B9=95?= =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/module/conf/config.py | 87 ++++++--------- src/module/core/download_client.py | 13 ++- src/module/downloader/qb_downloader.py | 14 ++- src/module/manager/renamer.py | 117 ++++++++++++++++++-- src/module/models/__init__.py | 1 + src/module/models/config.py | 69 ++++++++++++ src/module/network/request_url.py | 4 +- src/module/parser/analyser/rename_parser.py | 60 ++++++---- src/module/parser/title_parser.py | 9 +- 9 files changed, 276 insertions(+), 98 deletions(-) create mode 100644 src/module/models/config.py diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 346034f5..9570512b 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -2,9 +2,8 @@ import json import os import logging -from dataclasses import dataclass - -from .const import DEFAULT_SETTINGS, ENV_TO_ATTR +from module.conf.const import ENV_TO_ATTR +from module.models import Config logger = logging.getLogger(__name__) @@ -15,70 +14,48 @@ except ImportError: VERSION = "DEV_VERSION" -class ConfLoad(dict): - def __getattr__(self, item): - return self.get(item) - - def __setattr__(self, key, value): - self[key] = value +def save_config_to_file(config: Config, path: str): + with open(path, "w", encoding="utf-8") as f: + json.dump(config, f, indent=4) + logger.info(f"Config saved") -@dataclass -class Settings: - program: ConfLoad - downloader: ConfLoad - rss_parser: ConfLoad - bangumi_manage: ConfLoad - debug: ConfLoad - proxy: ConfLoad - notification: ConfLoad +def load_config_from_file(path: str) -> Config: + with open(path, "r", encoding="utf-8") as f: + config = json.load(f) + return config - def __init__(self, path: str | None): - self.load(path) - def load(self, path: str | None): - if path is None: - conf = DEFAULT_SETTINGS - elif os.path.isfile(path): - with open(path, "r") as f: - # Use utf-8 to avoid encoding error - conf = json.load(f, encoding="utf-8") +def _val_from_env(env: str, attr: tuple): + if isinstance(attr, tuple): + if attr[1] == "bool": + return os.environ[env].lower() == "true" + elif attr[1] == "int": + return int(os.environ[env]) + elif attr[1] == "float": + return float(os.environ[env]) else: - conf = self._create_config() - for key, section in conf.items(): - setattr(self, key, ConfLoad(section)) + return os.environ[env] + else: + return os.environ[env] - @staticmethod - def _val_from_env(env, attr): - val = os.environ[env] - if isinstance(attr, tuple): - conv_func = attr[1] - val = conv_func(val) - return val - def _create_config(self): - _settings = DEFAULT_SETTINGS - for key, section in ENV_TO_ATTR.items(): - for env, attr in section.items(): - if env in os.environ: - attr_name = attr[0] if isinstance(attr, tuple) else attr - _settings[key][attr_name] = self._val_from_env(env, attr) - with open(CONFIG_PATH, "w") as f: - # Save utf-8 to avoid encoding error - json.dump(_settings, f, indent=4, ensure_ascii=False) - logger.warning(f"Config file had been transferred from environment variables to {CONFIG_PATH}, some settings may be lost.") - logger.warning("Please check the config file and restart the program.") - logger.warning("Please check github wiki (https://github.com/EstrellaXD/Auto_Bangumi/#/wiki) for more information.") - return _settings +def env_to_config() -> Config: + _settings = Config() + for key, section in ENV_TO_ATTR.items(): + for env, attr in section.items(): + if env in os.environ: + attr_name = attr[0] if isinstance(attr, tuple) else attr + setattr(_settings, attr_name, _val_from_env(env, attr)) + return _settings if os.path.isdir("config") and VERSION == "DEV_VERSION": CONFIG_PATH = "config/config_dev.json" + settings = load_config_from_file(CONFIG_PATH) + print(dict(settings)) elif os.path.isdir("config") and VERSION != "DEV_VERSION": CONFIG_PATH = "config/config.json" -else: - CONFIG_PATH = None - -settings = Settings(CONFIG_PATH) + diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index 6d92b47d..2800d028 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -74,16 +74,16 @@ class DownloadClient: # logger.info("to rule.") logger.debug("Finished.") - def get_torrent_info(self): + def get_torrent_info(self, category="Bangumi"): return self.client.torrents_info( - status_filter="completed", category="Bangumi" + status_filter="completed", category=category ) - def rename_torrent_file(self, hash, new_file_name, old_path, new_path): + def rename_torrent_file(self, _hash, old_path, new_path): self.client.torrents_rename_file( - torrent_hash=hash, new_file_name=new_file_name, old_path=old_path, new_path=new_path + torrent_hash=_hash, old_path=old_path, new_path=new_path ) - logger.info(f"{old_path} >> {new_path}, new name {new_file_name}") + logger.info(f"{old_path} >> {new_path}") def delete_torrent(self, hashes): self.client.torrents_delete( @@ -114,3 +114,6 @@ class DownloadClient: def get_torrent_path(self, hashes): return self.client.get_torrent_path(hashes) + def set_category(self, hashes, category): + self.client.set_category(hashes, category) + diff --git a/src/module/downloader/qb_downloader.py b/src/module/downloader/qb_downloader.py index c9fe9dbe..4170dfb5 100644 --- a/src/module/downloader/qb_downloader.py +++ b/src/module/downloader/qb_downloader.py @@ -19,6 +19,8 @@ class QbDownloader: host=host, username=username, password=password, + VERIFY_WEBUI_CERTIFICATE=settings.downloader.ssl, + RAISE_ERROR_FOR_UNSUPPORTED_QBITTORRENT_VERSIONS=True, ) while True: try: @@ -56,9 +58,8 @@ class QbDownloader: torrent_hashes=hash ) - def torrents_rename_file(self, torrent_hash, new_file_name, old_path, new_path): - self._client.torrents_rename_file(torrent_hash=torrent_hash, new_file_name=new_file_name, - old_path=old_path, new_path=new_path) + def torrents_rename_file(self, torrent_hash, old_path, new_path): + self._client.torrents_rename_file(torrent_hash=torrent_hash, old_path=old_path, new_path=new_path) def get_rss_info(self): item = self._client.rss_items().get("Mikan_RSS") @@ -92,5 +93,8 @@ class QbDownloader: def get_download_rule(self): return self._client.rss_rules() - def get_torrent_path(self, hash): - return self._client.torrents_info(hashes=hash)[0].save_path + def get_torrent_path(self, _hash): + return self._client.torrents_info(hashes=_hash)[0].save_path + + def set_category(self, _hash, category): + self._client.torrents_set_category(category, hashes=_hash) diff --git a/src/module/manager/renamer.py b/src/module/manager/renamer.py index 0782377c..e02e3ecb 100644 --- a/src/module/manager/renamer.py +++ b/src/module/manager/renamer.py @@ -7,7 +7,6 @@ from module.core.download_client import DownloadClient from module.conf import settings from module.parser import TitleParser -from module.network import PostNotification, ServerChanNotification logger = logging.getLogger(__name__) @@ -23,8 +22,8 @@ class Renamer: logger.info(f"Finished checking {torrent_count} files' name, renamed {rename_count} files.") logger.debug(f"Checked {torrent_count} files") - def get_torrent_info(self): - recent_info = self.client.get_torrent_info() + def get_torrent_info(self, category="Bangumi"): + recent_info = self.client.get_torrent_info(category=category) torrent_count = len(recent_info) return recent_info, torrent_count @@ -65,9 +64,8 @@ class Renamer: try: new_name = self._renamer.download_parser(name, folder_name, season, suffix, settings.bangumi_manage.rename_method) if path_name != new_name: - old_path = info.content_path.replace(info.save_path, "") - old_path = old_path[len(os.path.sep):] - self.client.rename_torrent_file(torrent_hash, new_name, old_path, new_name) + old_path = info.content_path.replace(info.save_path, "")[len(os.path.sep):] + self.client.rename_torrent_file(torrent_hash, old_path, new_name) rename_count += 1 else: continue @@ -85,6 +83,111 @@ class Renamer: torrent_hash = info.hash _, season, folder_name, _, download_path = self.split_path(info.content_path) new_path = os.path.join(settings.downloader.path, folder_name, f"Season {season}") - # print(new_path) self.client.move_torrent(torrent_hash, new_path) + @staticmethod + def check_files(info, suffix_type: str = "media"): + if suffix_type == "subtitle": + suffix_list = [".ass", ".srt"] + else: + suffix_list = [".mp4", ".mkv"] + file_list = [] + for f in info.files: + file_name = f.name + suffix = os.path.splitext(file_name)[-1] + if suffix in suffix_list: + file_list.append(file_name) + return file_list + + def rename_file(self, info, media_path): + old_name = info.name + suffix = os.path.splitext(media_path)[-1] + compare_name = media_path.split(os.path.sep)[-1] + folder_name, season = self.get_folder_and_season(info.save_path) + new_path = self._renamer.download_parser(old_name, folder_name, season, suffix) + if compare_name != new_path: + try: + self.client.rename_torrent_file(_hash=info.hash, old_path=media_path, new_path=new_path) + except Exception as e: + logger.warning(f"{old_name} rename failed") + logger.warning(f"Folder name: {folder_name}, Season: {season}, Suffix: {suffix}") + logger.debug(e) + + def rename_collection(self, info, media_list: list[str]): + folder_name, season = self.get_folder_and_season(info.save_path) + _hash = info.hash + for media_path in media_list: + path_len = len(media_path.split(os.path.sep)) + if path_len <= 2: + suffix = os.path.splitext(media_path)[-1] + old_name = media_path.split(os.path.sep)[-1] + new_name = self._renamer.download_parser(old_name, folder_name, season, suffix) + if old_name != new_name: + try: + self.client.rename_torrent_file(_hash=_hash, old_path=media_path, new_path=new_name) + except Exception as e: + logger.warning(f"{old_name} rename failed") + logger.warning(f"Folder name: {folder_name}, Season: {season}, Suffix: {suffix}") + logger.debug(e) + self.client.set_category(category="BangumiCollection", hashes=_hash) + + def rename_subtitles(self, subtitle_list: list[str], media_old_name, media_new_name, _hash): + for subtitle_file in subtitle_list: + if re.search(media_old_name, subtitle_file) is not None: + subtitle_lang = subtitle_file.split(".")[-2] + new_subtitle_name = f"{media_new_name}.{subtitle_lang}.ass" + self.client.rename_torrent_file(_hash, subtitle_file, new_subtitle_name) + logger.info(f"Rename subtitles for {media_old_name} to {media_new_name}") + + + @staticmethod + def get_folder_and_season(save_path: str): + # Remove default save path + save_path = save_path.replace(settings.downloader.path, "") + # Check windows or linux path + path_parts = PurePath(save_path).parts \ + if PurePath(save_path).name != save_path \ + else PureWindowsPath(save_path).parts + # Get folder name + folder_name = path_parts[1] if path_parts[0] == "/" else path_parts[0] + # Get season + try: + if re.search(r"S\d{1,2}|[Ss]eason", path_parts[-1]) is not None: + season = int(re.search(r"\d{1,2}", path_parts[-1]).group()) + else: + season = 1 + except Exception as e: + logger.debug(e) + logger.debug("No Season info") + season = 1 + return folder_name, season + + def rename(self): + # Get torrent info + recent_info, torrent_count = self.get_torrent_info() + rename_count = 0 + for info in recent_info: + try: + media_list = self.check_files(info) + if len(media_list) == 1: + self.rename_file(info, media_list[0]) + rename_count += 1 + # TODO: Rename subtitles + elif len(media_list) > 1: + logger.info("Start rename collection") + self.rename_collection(info, media_list) + rename_count += len(media_list) + else: + logger.warning(f"{info.name} has no media file") + except Exception as e: + logger.warning(f"{info.name} rename failed") + logger.debug(e) + if settings.bangumi_manage.remove_bad_torrent: + self.client.delete_torrent(info.hash) + + +if __name__ == '__main__': + client = DownloadClient() + rn = Renamer(client) + rn.rename() + diff --git a/src/module/models/__init__.py b/src/module/models/__init__.py index 1cf896d6..0e595e71 100644 --- a/src/module/models/__init__.py +++ b/src/module/models/__init__.py @@ -1 +1,2 @@ from .bangumi import * +from .config import Config diff --git a/src/module/models/config.py b/src/module/models/config.py new file mode 100644 index 00000000..a4d5a6b7 --- /dev/null +++ b/src/module/models/config.py @@ -0,0 +1,69 @@ +from pydantic import BaseModel, Field + +# Sub config + + +class Program(BaseModel): + sleep_time: int = Field(7200, description="Sleep time") + rename_times: int = Field(20, description="Rename times in one loop") + webui_port: int = Field(7892, description="WebUI port") + + +class Downloader(BaseModel): + type: str = Field("qbittorrent", description="Downloader type") + host: str = Field("172.17.0.1:8080", description="Downloader host") + username: str = Field("admin", description="Downloader username") + password: str = Field("adminadmin", description="Downloader password") + path: str = Field("/downloads/Bangumi", description="Downloader path") + ssl: bool = Field(False, description="Downloader ssl") + +class RSSParser(BaseModel): + enable: bool = Field(True, description="Enable RSS parser") + type: str = Field("mikan", description="RSS parser type") + token: str = Field("token", description="RSS parser token") + custom_url: str = Field("mikanani.me", description="Custom RSS host url") + enable_tmdb: bool = Field(False, description="Enable TMDB") + filter: list[str] = Field(["720", r"\d+-\d"], description="Filter") + language: str = "zh" + + +class BangumiManage(BaseModel): + enable: bool = Field(True, description="Enable bangumi manage") + eps_complete: bool = Field(False, description="Enable eps complete") + rename_method: str = Field("pn", description="Rename method") + group_tag: bool = Field(False, description="Enable group tag") + remove_bad_torrent: bool = Field(False, description="Remove bad torrent") + + +class Debug(BaseModel): + enable: bool = Field(False, description="Enable debug") + level: str = Field("debug", description="Debug level") + file: str = Field("debug.log", description="Debug file") + dev_debug: bool = Field(False, description="Enable dev debug") + + +class Proxy(BaseModel): + enable: bool = Field(False, description="Enable proxy") + type: str = Field("http", description="Proxy type") + host: str = Field("", description="Proxy host") + port: int = Field(0, description="Proxy port") + username: str = Field("", description="Proxy username") + password: str = Field("", description="Proxy password") + + +class Notification(BaseModel): + enable: bool = Field(False, description="Enable notification") + type: str = Field("telegram", description="Notification type") + token: str = Field("", description="Notification token") + chat_id: str = Field("", description="Notification chat id") + + +class Config(BaseModel): + data_version: float = Field(4.0, description="Data version") + program: Program + downloader: Downloader + rss_parser: RSSParser + bangumi_manage: BangumiManage + debug: Debug + proxy: Proxy + notification: Notification diff --git a/src/module/network/request_url.py b/src/module/network/request_url.py index 44b53b64..1b98d905 100644 --- a/src/module/network/request_url.py +++ b/src/module/network/request_url.py @@ -43,9 +43,9 @@ class RequestURL: req.raise_for_status() return req except requests.RequestException as e: - logger.debug(f"URL: {url}") logger.debug(e) - logger.warning("ERROR with Connection.Please check DNS/Connection settings") + logger.warning(f"Cannot connect to {url}.") + logger.warning("Please check DNS/Connection settings") time.sleep(5) try_time += 1 except Exception as e: diff --git a/src/module/parser/analyser/rename_parser.py b/src/module/parser/analyser/rename_parser.py index b511f031..aa169c36 100644 --- a/src/module/parser/analyser/rename_parser.py +++ b/src/module/parser/analyser/rename_parser.py @@ -15,28 +15,42 @@ class DownloadInfo: folder_name: str +RULES = [ + r"(.*) - (\d{1,4}|\d{1,4}\.\d{1,2})(?:v\d{1,2})?(?: )?(?:END)?(.*)", + r"(.*)[\[ E](\d{1,3}|\d{1,3}\.\d{1,2})(?:v\d{1,2})?(?: )?(?:END)?[\] ](.*)", + r"(.*)\[第(\d*\.*\d*)话(?:END)?\](.*)", + r"(.*)\[第(\d*\.*\d*)話(?:END)?\](.*)", + r"(.*)第(\d*\.*\d*)话(?:END)?(.*)", + r"(.*)第(\d*\.*\d*)話(?:END)?(.*)", + r"(.*)E(\d{1,3})(.*)", +] + + class DownloadParser: def __init__(self): - self.rules = [ - r"(.*) - (\d{1,4}|\d{1,4}\.\d{1,2})(?:v\d{1,2})?(?: )?(?:END)?(.*)", - r"(.*)[\[ E](\d{1,3}|\d{1,3}\.\d{1,2})(?:v\d{1,2})?(?: )?(?:END)?[\] ](.*)", - r"(.*)\[第(\d*\.*\d*)话(?:END)?\](.*)", - r"(.*)\[第(\d*\.*\d*)話(?:END)?\](.*)", - r"(.*)第(\d*\.*\d*)话(?:END)?(.*)", - r"(.*)第(\d*\.*\d*)話(?:END)?(.*)", - ] + self.method_dict = { + "normal": self.rename_normal, + "pn": self.rename_pn, + "advance": self.rename_advance, + "no_season_pn": self.rename_no_season_pn, + "none": self.rename_none + } + @staticmethod def rename_init(name, folder_name, season, suffix) -> DownloadInfo: n = re.split(r"[\[\]()【】()]", name) - suffix = suffix if suffix is not None else n[-1] - file_name = name.replace(f"[{n[1]}]", "") + suffix = suffix if suffix else n[-1] + if len(n) > 1: + file_name = name.replace(f"[{n[1]}]", "") + else: + file_name = name if season < 10: season = f"0{season}" return DownloadInfo(name, season, suffix, file_name, folder_name) def rename_normal(self, info: DownloadInfo): - for rule in self.rules: + for rule in RULES: match_obj = re.match(rule, info.name, re.I) if match_obj is not None: title = re.sub(r"([Ss]|Season )\d{1,3}", "", match_obj.group(1)).strip() @@ -44,7 +58,7 @@ class DownloadParser: return new_name def rename_pn(self, info: DownloadInfo): - for rule in self.rules: + for rule in RULES: match_obj = re.match(rule, info.file_name, re.I) if match_obj is not None: title = re.sub(r"([Ss]|Season )\d{1,3}", "", match_obj.group(1)).strip() @@ -57,7 +71,7 @@ class DownloadParser: return new_name def rename_advance(self, info: DownloadInfo): - for rule in self.rules: + for rule in RULES: match_obj = re.match(rule, info.file_name, re.I) if match_obj is not None: new_name = re.sub( @@ -68,7 +82,7 @@ class DownloadParser: return new_name def rename_no_season_pn(self, info: DownloadInfo): - for rule in self.rules: + for rule in RULES: match_obj = re.match(rule, info.file_name, re.I) if match_obj is not None: title = match_obj.group(1).strip() @@ -83,16 +97,16 @@ class DownloadParser: def rename_none(info: DownloadInfo): return info.name - def download_rename(self, name, folder_name, season, suffix, method): + def download_rename( + self, + name: str, + folder_name, + season, + suffix, + method + ): rename_info = self.rename_init(name, folder_name, season, suffix) - method_dict = { - "normal": self.rename_normal, - "pn": self.rename_pn, - "advance": self.rename_advance, - "no_season_pn": self.rename_no_season_pn, - "none": self.rename_none - } - return method_dict[method.lower()](rename_info) + return self.method_dict[method.lower()](rename_info) if __name__ == "__main__": diff --git a/src/module/parser/title_parser.py b/src/module/parser/title_parser.py index 72404619..ffd6f724 100644 --- a/src/module/parser/title_parser.py +++ b/src/module/parser/title_parser.py @@ -18,7 +18,14 @@ class TitleParser: def raw_parser(self, raw: str): return self._raw_parser.analyse(raw) - def download_parser(self, download_raw, folder_name, season, suffix, method=settings.bangumi_manage.method): + def download_parser( + self, + download_raw: str, + folder_name: str | None = None, + season: int | None = None, + suffix: str | None = None, + method: str = settings.bangumi_manage.rename_method + ): return self._download_parser.download_rename(download_raw, folder_name, season, suffix, method) def tmdb_parser(self, title: str, season: int): From 9fd9dadbc137c024bb9102b251f278d9285b5e35 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Sun, 23 Apr 2023 21:47:08 +0800 Subject: [PATCH 08/40] =?UTF-8?q?-=20=E6=96=B0=E5=A2=9E=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=9F=9F=E5=90=8D=20-=20=E5=A2=9E=E5=8A=A0=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=8A=A5=E9=94=99=E5=9F=9F=E5=90=8D=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=20#195=20-=20=E4=BF=AE=E5=A4=8D=20Dev-debug=20=E5=BC=80?= =?UTF-8?q?=E5=90=AF=E7=9A=84=E9=94=99=E8=AF=AF=20#192=20-=20=E9=87=8D?= =?UTF-8?q?=E5=81=9A=E9=87=8D=E5=91=BD=E5=90=8D=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=90=88=E9=9B=86=E9=87=8D=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BB=A5=E5=8F=8A=E6=96=87=E4=BB=B6=E5=A4=B9=E5=86=85=E9=87=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D=EF=BC=8C=E6=94=AF=E6=8C=81=E5=AD=97=E5=B9=95?= =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D=E3=80=82=20-=20Fix=20pytest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/module/conf/config.py | 15 +++++++++++++-- src/module/models/config.py | 14 +++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 9570512b..1e5826f4 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -52,10 +52,21 @@ def env_to_config() -> Config: if os.path.isdir("config") and VERSION == "DEV_VERSION": CONFIG_PATH = "config/config_dev.json" - settings = load_config_from_file(CONFIG_PATH) - print(dict(settings)) + if os.path.isfile(CONFIG_PATH): + settings = load_config_from_file(CONFIG_PATH) + else: + settings = env_to_config() + save_config_to_file(settings, CONFIG_PATH) elif os.path.isdir("config") and VERSION != "DEV_VERSION": CONFIG_PATH = "config/config.json" + if os.path.isfile(CONFIG_PATH): + settings = load_config_from_file(CONFIG_PATH) + else: + settings = env_to_config() + save_config_to_file(settings, CONFIG_PATH) +else: + settings = Config() + diff --git a/src/module/models/config.py b/src/module/models/config.py index a4d5a6b7..b2d0a62b 100644 --- a/src/module/models/config.py +++ b/src/module/models/config.py @@ -60,10 +60,10 @@ class Notification(BaseModel): class Config(BaseModel): data_version: float = Field(4.0, description="Data version") - program: Program - downloader: Downloader - rss_parser: RSSParser - bangumi_manage: BangumiManage - debug: Debug - proxy: Proxy - notification: Notification + program: Program = Program() + downloader: Downloader = Downloader() + rss_parser: RSSParser = RSSParser() + bangumi_manage: BangumiManage = BangumiManage() + debug: Debug = Debug() + proxy: Proxy = Proxy() + notification: Notification = Notification() From 6bc7a2dd6283c03791ee111a7d76376f005212a7 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Sun, 23 Apr 2023 21:49:14 +0800 Subject: [PATCH 09/40] =?UTF-8?q?-=20=E6=96=B0=E5=A2=9E=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=9F=9F=E5=90=8D=20-=20=E5=A2=9E=E5=8A=A0=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=8A=A5=E9=94=99=E5=9F=9F=E5=90=8D=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=20#195=20-=20=E4=BF=AE=E5=A4=8D=20Dev-debug=20=E5=BC=80?= =?UTF-8?q?=E5=90=AF=E7=9A=84=E9=94=99=E8=AF=AF=20#192=20-=20=E9=87=8D?= =?UTF-8?q?=E5=81=9A=E9=87=8D=E5=91=BD=E5=90=8D=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=90=88=E9=9B=86=E9=87=8D=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BB=A5=E5=8F=8A=E6=96=87=E4=BB=B6=E5=A4=B9=E5=86=85=E9=87=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D=EF=BC=8C=E6=94=AF=E6=8C=81=E5=AD=97=E5=B9=95?= =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D=E3=80=82=20-=20Fix=20pytest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 2 +- requirements.txt => src/requirements.txt | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename requirements.txt => src/requirements.txt (100%) diff --git a/Dockerfile b/Dockerfile index 9b0b4ba1..d7b99cbe 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ ENV TZ=Asia/Shanghai \ WORKDIR /app -COPY requirements.txt . +COPY src/requirements.txt . RUN python3 -m pip install --upgrade pip \ && pip install -r requirements.txt --no-cache-dir diff --git a/requirements.txt b/src/requirements.txt similarity index 100% rename from requirements.txt rename to src/requirements.txt From 664eadb3fd16b7d16f81fea1b7768d84dc780b2f Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Sun, 23 Apr 2023 23:14:03 +0800 Subject: [PATCH 10/40] =?UTF-8?q?-=20=E6=96=B0=E5=A2=9E=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E5=9F=9F=E5=90=8D=20-=20=E5=A2=9E=E5=8A=A0=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=8A=A5=E9=94=99=E5=9F=9F=E5=90=8D=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=20#195=20-=20=E4=BF=AE=E5=A4=8D=20Dev-debug=20=E5=BC=80?= =?UTF-8?q?=E5=90=AF=E7=9A=84=E9=94=99=E8=AF=AF=20#192=20-=20=E9=87=8D?= =?UTF-8?q?=E5=81=9A=E9=87=8D=E5=91=BD=E5=90=8D=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=90=88=E9=9B=86=E9=87=8D=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BB=A5=E5=8F=8A=E6=96=87=E4=BB=B6=E5=A4=B9=E5=86=85=E9=87=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D=EF=BC=8C=E6=94=AF=E6=8C=81=E5=AD=97=E5=B9=95?= =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D=E3=80=82=20-=20Fix=20pytest=20-=20F?= =?UTF-8?q?ix=20Bugs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/module/app.py | 20 ++++++++++---------- src/module/conf/__init__.py | 1 + src/module/conf/config.py | 4 ++-- src/module/core/download_client.py | 10 +++++----- src/module/rss/rss_analyser.py | 6 +++--- 5 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/module/app.py b/src/module/app.py index 70210b5f..362325fa 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -2,7 +2,7 @@ import os import time import logging -from module.conf import settings, LOG_PATH, DATA_PATH +from module.conf import settings, LOG_PATH, DATA_PATH, RSS_LINK from module.utils import json_config from module.core import DownloadClient @@ -21,17 +21,17 @@ def reset_log(): def load_data_file(): if not os.path.exists(DATA_PATH): bangumi_data = { - "rss_link": settings.rss_parser.link, + "rss_link": RSS_LINK, "data_version": settings.program.data_version, "bangumi_info": [] } logger.info("Building data information...") else: bangumi_data = json_config.load(DATA_PATH) - if bangumi_data["data_version"] != settings.program.data_version or bangumi_data["rss_link"] != settings.rss_parser.link: + if bangumi_data["data_version"] != settings.data_version or bangumi_data["rss_link"] != RSS_LINK: bangumi_data = { - "rss_link": settings.rss_parser.link, - "data_version": settings.program.data_version, + "rss_link": RSS_LINK, + "data_version": settings.data_version, "bangumi_info": [] } logger.info("Rebuilding data information...") @@ -54,11 +54,11 @@ def main_process(bangumi_data, download_client: DownloadClient): FullSeasonGet().eps_complete(bangumi_data["bangumi_info"], download_client) logger.info("Running....") save_data_file(bangumi_data) - while times < settings.program.times: + while times < settings.program.rename_times: if settings.bangumi_manage.enable: - rename.run() + rename.rename() times += 1 - time.sleep(settings.program.sleep_time / settings.program.times) + time.sleep(settings.program.sleep_time / settings.program.rename_times) def run(): @@ -66,8 +66,8 @@ def run(): reset_log() download_client = DownloadClient() download_client.init_downloader() - if settings.rss_parser.link is None: - logger.error("Please add RIGHT RSS url.") + if settings.rss_parser.token is None: + logger.error("Please set your RSS token in config file.") quit() download_client.rss_feed() bangumi_data = load_data_file() diff --git a/src/module/conf/__init__.py b/src/module/conf/__init__.py index a3b86de5..1bec68d2 100644 --- a/src/module/conf/__init__.py +++ b/src/module/conf/__init__.py @@ -4,3 +4,4 @@ from .config import settings, VERSION TMDB_API = "32b19d6a05b512190a056fa4e747cbbc" DATA_PATH = "data/data.json" +RSS_LINK = f"https://{settings.rss_parser.custom_url}/RSS/MyBangumi?token={settings.rss_parser.token}" diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 1e5826f4..69c06975 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -2,7 +2,7 @@ import json import os import logging -from module.conf.const import ENV_TO_ATTR +from .const import ENV_TO_ATTR from module.models import Config logger = logging.getLogger(__name__) @@ -23,7 +23,7 @@ def save_config_to_file(config: Config, path: str): def load_config_from_file(path: str) -> Config: with open(path, "r", encoding="utf-8") as f: config = json.load(f) - return config + return Config(**config) def _val_from_env(env: str, attr: tuple): diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index 2800d028..94297bfd 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -4,7 +4,7 @@ import os from module.downloader import getClient -from module.conf import settings +from module.conf import settings, RSS_LINK logger = logging.getLogger(__name__) @@ -21,7 +21,7 @@ class DownloadClient: "rss_refresh_interval": 30, } self.client.prefs_init(prefs=prefs) - if settings.downloader.download_path == "": + if settings.downloader.path == "": prefs = self.client.get_app_prefs() settings.downloader.path = os.path.join(prefs["save_path"], "Bangumi") @@ -54,18 +54,18 @@ class DownloadClient: def rss_feed(self): # TODO: 定时刷新 RSS - if self.client.get_rss_info() == settings.rss_parser.link: + if self.client.get_rss_info() == RSS_LINK: logger.info("RSS Already exists.") else: logger.info("No feed exists, start adding feed.") - self.client.rss_add_feed(url=settings.rss_parser.link, item_path="Mikan_RSS") + self.client.rss_add_feed(url=RSS_LINK, item_path="Mikan_RSS") logger.info("Add RSS Feed successfully.") def add_collection_feed(self, rss_link, item_path): self.client.rss_add_feed(url=rss_link, item_path=item_path) logger.info("Add RSS Feed successfully.") - def add_rules(self, bangumi_info, rss_link=settings.rss_parser.link): + def add_rules(self, bangumi_info, rss_link=RSS_LINK): logger.debug("Start adding rules.") for info in bangumi_info: if not info["added"]: diff --git a/src/module/rss/rss_analyser.py b/src/module/rss/rss_analyser.py index 9060e27b..57704a95 100644 --- a/src/module/rss/rss_analyser.py +++ b/src/module/rss/rss_analyser.py @@ -3,7 +3,7 @@ import logging from module.network import RequestContent from module.parser import TitleParser -from module.conf import settings +from module.conf import settings, RSS_LINK from module.core import DownloadClient @@ -16,7 +16,7 @@ class RSSAnalyser: def rss_to_datas(self, bangumi_info: list) -> list: with RequestContent() as req: - rss_torrents = req.get_torrents(settings.rss_parser.link) + rss_torrents = req.get_torrents(RSS_LINK) for torrent in rss_torrents: raw_title = torrent.name extra_add = True @@ -46,7 +46,7 @@ class RSSAnalyser: logger.info("Start collecting RSS info.") try: self.rss_to_datas(bangumi_info) - download_client.add_rules(bangumi_info, rss_link=settings.rss_parser.link) + download_client.add_rules(bangumi_info, rss_link=RSS_LINK) except Exception as e: logger.debug(e) logger.info("Finished") From 792643b8e9f9cbf835a3515df0913c1e7f70d90e Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 09:54:58 +0800 Subject: [PATCH 11/40] - Add set config api --- src/module/api.py | 28 +++++++++++++++++----------- src/module/core/api_func.py | 20 +++++++++++++++++++- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/module/api.py b/src/module/api.py index 00cccbde..9368c47c 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -6,10 +6,11 @@ from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles import logging -from .core import APIProcess -from .conf import settings, DATA_PATH, LOG_PATH -from .utils import json_config -from .models.api import * +from module.core import APIProcess +from module.conf import settings, DATA_PATH, LOG_PATH +from module.utils import json_config +from module.models.api import * +from module.models import Config logger = logging.getLogger(__name__) @@ -20,13 +21,6 @@ app.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") templates = Jinja2Templates(directory="templates") -# HTML Response -@app.get("/", response_class=HTMLResponse) -def index(request: Request): - context = {"request": request} - return templates.TemplateResponse("index.html", context) - - @app.get("/api/v1/data") def get_data(): data = json_config.load(DATA_PATH) @@ -63,6 +57,18 @@ async def add_rule(info: AddRule): return api_func.add_rule(info.title, info.season) +@app.post("/api/v1/updateConfig", tags=["config"]) +async def update_config(config: Config): + return api_func.update_config(config) + + +# HTML Response +@app.get("/{full_path:path}", response_class=HTMLResponse) +def index(request: Request): + context = {"request": request} + return templates.TemplateResponse("index.html", context) + + def run(): LOGGING_CONFIG["formatters"]["default"]["fmt"] = "[%(asctime)s] %(levelprefix)s %(message)s" uvicorn.run(app, host="0.0.0.0", port=settings.program.webui_port) diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 9c48d242..1a64315f 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -1,13 +1,20 @@ import re +import os +import logging +import signal from module.core import DownloadClient from module.manager import FullSeasonGet from module.rss import RSSAnalyser from module.utils import json_config from module.conf import DATA_PATH +from module.conf.config import save_config_to_file, CONFIG_PATH +from module.models import Config from module.ab_decorator import api_failed +logger = logging.getLogger(__name__) + class APIProcess: def __init__(self): @@ -63,4 +70,15 @@ class APIProcess: } data["bangumi_info"].append(extra_data) json_config.save(DATA_PATH, data) - return "Success" \ No newline at end of file + return "Success" + + @staticmethod + def update_config(config: Config): + save_config_to_file(config, CONFIG_PATH) + return {"message": "Success"} + + def restart_main_process(self, mp): + os.kill(mp.pid, signal.SIGTERM) + global main_process + main_process = multiprocessing.Process(target=main_program) + main_process.start() From c47d81e8016152d4bae773542d376474dcc4b503 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 11:28:44 +0800 Subject: [PATCH 12/40] Fix log bug --- src/main.py | 2 +- src/module/__init__.py | 1 + src/module/api.py | 44 +++++++++++++++++++++---------------- src/module/app.py | 5 +++-- src/module/core/api_func.py | 6 ----- 5 files changed, 30 insertions(+), 28 deletions(-) diff --git a/src/main.py b/src/main.py index 3763ae31..dd1b9d16 100644 --- a/src/main.py +++ b/src/main.py @@ -1,5 +1,5 @@ -import multiprocessing import logging +import multiprocessing from module import app from module import api diff --git a/src/module/__init__.py b/src/module/__init__.py index e69de29b..8b137891 100644 --- a/src/module/__init__.py +++ b/src/module/__init__.py @@ -0,0 +1 @@ + diff --git a/src/module/api.py b/src/module/api.py index 9368c47c..6556c339 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -1,77 +1,83 @@ import uvicorn from uvicorn.config import LOGGING_CONFIG from fastapi import FastAPI, Request -from fastapi.responses import HTMLResponse, FileResponse +from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles import logging from module.core import APIProcess -from module.conf import settings, DATA_PATH, LOG_PATH +from module.conf import settings, DATA_PATH, LOG_PATH, VERSION from module.utils import json_config from module.models.api import * from module.models import Config logger = logging.getLogger(__name__) -app = FastAPI() +router = FastAPI() api_func = APIProcess() -app.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") -templates = Jinja2Templates(directory="templates") +if VERSION != "DEV_VERSION": + router.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") + templates = Jinja2Templates(directory="templates") -@app.get("/api/v1/data") + +@router.get("/api/v1/data") def get_data(): data = json_config.load(DATA_PATH) return data -@app.get("/api/v1/log") +@router.get("/api/v1/log") async def get_log(): return FileResponse(LOG_PATH) -@app.get("/api/v1/resetRule") +@router.get("/api/v1/resetRule") def reset_rule(): return api_func.reset_rule() -@app.get("api/v1/removeRule/{bangumi_title}") +@router.get("api/v1/removeRule/{bangumi_title}") def remove_rule(bangumi_title: str): return api_func.remove_rule(bangumi_title) -@app.post("/api/v1/collection") +@router.post("/api/v1/collection") async def collection(link: RssLink): return api_func.download_collection(link.rss_link) -@app.post("/api/v1/subscribe") +@router.post("/api/v1/subscribe") async def subscribe(link: RssLink): return api_func.add_subscribe(link.rss_link) -@app.post("/api/v1/addRule") +@router.post("/api/v1/addRule") async def add_rule(info: AddRule): return api_func.add_rule(info.title, info.season) -@app.post("/api/v1/updateConfig", tags=["config"]) +@router.post("/api/v1/updateConfig", tags=["config"]) async def update_config(config: Config): return api_func.update_config(config) - +if VERSION != "DEV_VERSION": # HTML Response -@app.get("/{full_path:path}", response_class=HTMLResponse) -def index(request: Request): - context = {"request": request} - return templates.TemplateResponse("index.html", context) + @router.get("/{full_path:path}", response_class=HTMLResponse) + def index(request: Request): + context = {"request": request} + return templates.TemplateResponse("index.html", context) +else: + @router.get("/", status_code=302) + def index(): + return RedirectResponse("/docs") def run(): LOGGING_CONFIG["formatters"]["default"]["fmt"] = "[%(asctime)s] %(levelprefix)s %(message)s" - uvicorn.run(app, host="0.0.0.0", port=settings.program.webui_port) + uvicorn.run(router, host="0.0.0.0", port=settings.program.webui_port) diff --git a/src/module/app.py b/src/module/app.py index 362325fa..248ac32b 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -2,7 +2,7 @@ import os import time import logging -from module.conf import settings, LOG_PATH, DATA_PATH, RSS_LINK +from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSS_LINK from module.utils import json_config from module.core import DownloadClient @@ -22,7 +22,7 @@ def load_data_file(): if not os.path.exists(DATA_PATH): bangumi_data = { "rss_link": RSS_LINK, - "data_version": settings.program.data_version, + "data_version": settings.data_version, "bangumi_info": [] } logger.info("Building data information...") @@ -62,6 +62,7 @@ def main_process(bangumi_data, download_client: DownloadClient): def run(): + setup_logger() # 初始化 reset_log() download_client = DownloadClient() diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 1a64315f..5b94239d 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -76,9 +76,3 @@ class APIProcess: def update_config(config: Config): save_config_to_file(config, CONFIG_PATH) return {"message": "Success"} - - def restart_main_process(self, mp): - os.kill(mp.pid, signal.SIGTERM) - global main_process - main_process = multiprocessing.Process(target=main_program) - main_process.start() From ce5736c2845f389569da7050a44e33e8f2967298 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 12:22:44 +0800 Subject: [PATCH 13/40] Add restart in api --- src/main.py | 32 ++++++++++++++++++++------------ src/module/app.py | 1 + src/module/conf/config.py | 14 ++++++++++---- src/module/manager/repath.py | 8 ++++---- 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/src/main.py b/src/main.py index dd1b9d16..e2bc8cb9 100644 --- a/src/main.py +++ b/src/main.py @@ -1,13 +1,29 @@ +import os +import signal import logging import multiprocessing +import uvicorn from module import app -from module import api -from module.conf import VERSION, setup_logger +from module.api import router +from module.conf import VERSION, setup_logger, settings logger = logging.getLogger(__name__) +main_process = multiprocessing.Process(target=app.run) + + +@router.get("/api/v1/restart") +async def restart(): + global main_process + logger.info("Restarting...") + os.kill(main_process.pid, signal.SIGTERM) + main_process = multiprocessing.Process(target=app.run) + main_process.start() + logger.info("Restarted") + return {"status": "success"} + def show_info(): with open("icon", "r") as f: @@ -21,14 +37,6 @@ def show_info(): if __name__ == "__main__": setup_logger() show_info() - num_processes = 2 - processes = [] - p1 = multiprocessing.Process(target=app.run) - p2 = multiprocessing.Process(target=api.run) - process_list = [p1, p2] - for p in process_list: - p.start() - processes.append(p) - for p in processes: - p.join() + main_process.start() + uvicorn.run(router, host="0.0.0.0", port=settings.program.webui_port) diff --git a/src/module/app.py b/src/module/app.py index 248ac32b..668f2f18 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -65,6 +65,7 @@ def run(): setup_logger() # 初始化 reset_log() + settings.reload() download_client = DownloadClient() download_client.init_downloader() if settings.rss_parser.token is None: diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 69c06975..a1b6cfb7 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -14,6 +14,12 @@ except ImportError: VERSION = "DEV_VERSION" +class Setting(Config): + @staticmethod + def reload(): + load_config_from_file(CONFIG_PATH) + + def save_config_to_file(config: Config, path: str): with open(path, "w", encoding="utf-8") as f: json.dump(config, f, indent=4) @@ -23,7 +29,7 @@ def save_config_to_file(config: Config, path: str): def load_config_from_file(path: str) -> Config: with open(path, "r", encoding="utf-8") as f: config = json.load(f) - return Config(**config) + return Setting(**config) def _val_from_env(env: str, attr: tuple): @@ -40,8 +46,8 @@ def _val_from_env(env: str, attr: tuple): return os.environ[env] -def env_to_config() -> Config: - _settings = Config() +def env_to_config() -> Setting: + _settings = Setting() for key, section in ENV_TO_ATTR.items(): for env, attr in section.items(): if env in os.environ: @@ -65,7 +71,7 @@ elif os.path.isdir("config") and VERSION != "DEV_VERSION": settings = env_to_config() save_config_to_file(settings, CONFIG_PATH) else: - settings = Config() + settings = Setting() diff --git a/src/module/manager/repath.py b/src/module/manager/repath.py index 99e32cd3..b53fd4fd 100644 --- a/src/module/manager/repath.py +++ b/src/module/manager/repath.py @@ -20,12 +20,12 @@ class RuleInfo: @dataclass -class RePathInfo: +class RepathInfo: path: str hashes: list -class RePath: +class RepathTorrents: def __init__(self, download_client: DownloadClient): self._client = download_client self.re_season = re.compile(r"S\d{1,2}") @@ -73,10 +73,10 @@ class RePath: hashes.append(info.hash) infos.remove(info) if hashes: - repath_list.append(RePathInfo(rule.new_path, hashes)) + repath_list.append(RepathInfo(rule.new_path, hashes)) return repath_list - def re_path(self, repath_info: RePathInfo): + def re_path(self, repath_info: RepathInfo): self._client.move_torrent(repath_info.hashes, repath_info.path) def run(self): From 8ffa1c9d4db3a1918f7b3bedd17b061bdbee93dd Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 13:54:10 +0800 Subject: [PATCH 14/40] Fix logger --- src/main.py | 37 ++++++++++++++++++++++------------- src/module/api.py | 41 +++++++++++---------------------------- src/module/app.py | 16 ++++++++++++--- src/module/conf/config.py | 3 ++- 4 files changed, 50 insertions(+), 47 deletions(-) diff --git a/src/main.py b/src/main.py index e2bc8cb9..b5e1971f 100644 --- a/src/main.py +++ b/src/main.py @@ -1,12 +1,17 @@ import os import signal import logging -import multiprocessing import uvicorn +import multiprocessing + +from fastapi import Request +from fastapi.responses import HTMLResponse, RedirectResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates from module import app from module.api import router -from module.conf import VERSION, setup_logger, settings +from module.conf import VERSION, settings logger = logging.getLogger(__name__) @@ -14,7 +19,7 @@ logger = logging.getLogger(__name__) main_process = multiprocessing.Process(target=app.run) -@router.get("/api/v1/restart") +@router.get("/api/v1/restart", tags=["program"]) async def restart(): global main_process logger.info("Restarting...") @@ -25,18 +30,24 @@ async def restart(): return {"status": "success"} -def show_info(): - with open("icon", "r") as f: - for line in f.readlines(): - logger.info(line.strip("\n")) - logger.info(f"Version {VERSION} Author: EstrellaXD Twitter: https://twitter.com/Estrella_Pan") - logger.info("GitHub: https://github.com/EstrellaXD/Auto_Bangumi/") - logger.info("Starting AutoBangumi...") +if VERSION != "DEV_VERSION": + router.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") + templates = Jinja2Templates(directory="templates") + + # HTML Response + @router.get("/{full_path:path}", response_class=HTMLResponse, tags=["html"]) + def index(request: Request): + context = {"request": request} + return templates.TemplateResponse("index.html", context) +else: + @router.get("/", status_code=302, tags=["html"]) + def index(): + return RedirectResponse("/docs") if __name__ == "__main__": - setup_logger() - show_info() + log_config = uvicorn.config.LOGGING_CONFIG + log_config["formatters"]["default"]["fmt"] = "[%(asctime)s] %(levelname)-8s %(message)s" main_process.start() - uvicorn.run(router, host="0.0.0.0", port=settings.program.webui_port) + uvicorn.run(router, host="0.0.0.0", port=settings.program.webui_port, log_config=log_config) diff --git a/src/module/api.py b/src/module/api.py index 6556c339..8cae4b31 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -1,30 +1,29 @@ -import uvicorn -from uvicorn.config import LOGGING_CONFIG -from fastapi import FastAPI, Request -from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse -from fastapi.templating import Jinja2Templates -from fastapi.staticfiles import StaticFiles import logging +from fastapi import FastAPI +from fastapi.responses import FileResponse from module.core import APIProcess -from module.conf import settings, DATA_PATH, LOG_PATH, VERSION +from module.conf import DATA_PATH, LOG_PATH, settings from module.utils import json_config from module.models.api import * from module.models import Config -logger = logging.getLogger(__name__) router = FastAPI() api_func = APIProcess() -if VERSION != "DEV_VERSION": - router.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") - templates = Jinja2Templates(directory="templates") +@router.on_event("startup") +async def startup_event(): + logger = logging.getLogger("uvicorn.access") + handler = logging.StreamHandler() + handler.setLevel(logging.INFO) + handler.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)-8s %(message)s")) + logger.addHandler(handler) @router.get("/api/v1/data") -def get_data(): +async def get_data(): data = json_config.load(DATA_PATH) return data @@ -63,21 +62,3 @@ async def add_rule(info: AddRule): async def update_config(config: Config): return api_func.update_config(config) -if VERSION != "DEV_VERSION": -# HTML Response - @router.get("/{full_path:path}", response_class=HTMLResponse) - def index(request: Request): - context = {"request": request} - return templates.TemplateResponse("index.html", context) -else: - @router.get("/", status_code=302) - def index(): - return RedirectResponse("/docs") - - -def run(): - LOGGING_CONFIG["formatters"]["default"]["fmt"] = "[%(asctime)s] %(levelprefix)s %(message)s" - uvicorn.run(router, host="0.0.0.0", port=settings.program.webui_port) - - - diff --git a/src/module/app.py b/src/module/app.py index 668f2f18..aced1330 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -2,7 +2,7 @@ import os import time import logging -from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSS_LINK +from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSS_LINK, VERSION from module.utils import json_config from module.core import DownloadClient @@ -61,11 +61,21 @@ def main_process(bangumi_data, download_client: DownloadClient): time.sleep(settings.program.sleep_time / settings.program.rename_times) +def show_info(): + with open("icon", "r") as f: + for line in f.readlines(): + logger.info(line.strip("\n")) + logger.info(f"Version {VERSION} Author: EstrellaXD Twitter: https://twitter.com/Estrella_Pan") + logger.info("GitHub: https://github.com/EstrellaXD/Auto_Bangumi/") + logger.info("Starting AutoBangumi...") + + def run(): - setup_logger() # 初始化 - reset_log() settings.reload() + reset_log() + setup_logger() + show_info() download_client = DownloadClient() download_client.init_downloader() if settings.rss_parser.token is None: diff --git a/src/module/conf/config.py b/src/module/conf/config.py index a1b6cfb7..ec513609 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -21,8 +21,9 @@ class Setting(Config): def save_config_to_file(config: Config, path: str): + config_dict = config.dict() with open(path, "w", encoding="utf-8") as f: - json.dump(config, f, indent=4) + json.dump(config_dict, f, indent=4) logger.info(f"Config saved") From b8906f53f4af816fa42d94bda5655f542b23548b Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 14:19:53 +0800 Subject: [PATCH 15/40] 2.6.0-beta6 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index d7b99cbe..df759319 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ COPY src/requirements.txt . RUN python3 -m pip install --upgrade pip \ && pip install -r requirements.txt --no-cache-dir -COPY --chmod=755 src/. /app/. +COPY --chmod=755 src/. . RUN apk add --no-cache \ curl \ From eb9f51a755eba00cd7e14aa1c79307d934254d78 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 15:10:58 +0800 Subject: [PATCH 16/40] - Fix remove torrent bug --- src/module/manager/renamer.py | 94 +++++++---------------------------- 1 file changed, 19 insertions(+), 75 deletions(-) diff --git a/src/module/manager/renamer.py b/src/module/manager/renamer.py index e02e3ecb..2e8c8c4b 100644 --- a/src/module/manager/renamer.py +++ b/src/module/manager/renamer.py @@ -27,64 +27,6 @@ class Renamer: torrent_count = len(recent_info) return recent_info, torrent_count - @staticmethod - def split_path(path: str): - suffix = os.path.splitext(path)[-1] - path = path.replace(settings.downloader.path, "") - path_parts = PurePath(path).parts \ - if PurePath(path).name != path \ - else PureWindowsPath(path).parts - path_name = path_parts[-1] - try: - if re.search(r"S\d{1,2}|[Ss]eason", path_parts[-2]) is not None: - season = int(re.search(r"\d{1,2}", path_parts[-2]).group()) - else: - season = 1 - except Exception as e: - logger.debug(e) - logger.debug("No Season info") - season = 1 - folder_name = path_parts[1] if path_parts[0] == "/" else path_parts[0] - try: - download_path = path_parts[1] - except IndexError: - download_path = "" - return path_name, season, folder_name, suffix, download_path - - def run(self): - recent_info, torrent_count = self.get_torrent_info() - rename_count = 0 - for info in recent_info: - name = info.name - torrent_hash = info.hash - path_name, season, folder_name, suffix, _ = self.split_path(info.content_path) - if path_name is folder_name: - logger.warning("Wrong bangumi path, please check your qbittorrent settings.") - else: - try: - new_name = self._renamer.download_parser(name, folder_name, season, suffix, settings.bangumi_manage.rename_method) - if path_name != new_name: - old_path = info.content_path.replace(info.save_path, "")[len(os.path.sep):] - self.client.rename_torrent_file(torrent_hash, old_path, new_name) - rename_count += 1 - else: - continue - except Exception as e: - logger.warning(f"{path_name} rename failed") - logger.warning(f"Folder name: {folder_name}, Season: {season}, Suffix: {suffix}") - logger.debug(e) - if settings.bangumi_manage.remove_bad_torrent: - self.client.delete_torrent(torrent_hash) - self.print_result(torrent_count, rename_count) - - def set_folder(self): - recent_info, _ = self.get_torrent_info() - for info in recent_info: - torrent_hash = info.hash - _, season, folder_name, _, download_path = self.split_path(info.content_path) - new_path = os.path.join(settings.downloader.path, folder_name, f"Season {season}") - self.client.move_torrent(torrent_hash, new_path) - @staticmethod def check_files(info, suffix_type: str = "media"): if suffix_type == "subtitle": @@ -112,6 +54,8 @@ class Renamer: logger.warning(f"{old_name} rename failed") logger.warning(f"Folder name: {folder_name}, Season: {season}, Suffix: {suffix}") logger.debug(e) + # Delete bad torrent + self.delete_bad_torrent(info) def rename_collection(self, info, media_list: list[str]): folder_name, season = self.get_folder_and_season(info.save_path) @@ -129,6 +73,8 @@ class Renamer: logger.warning(f"{old_name} rename failed") logger.warning(f"Folder name: {folder_name}, Season: {season}, Suffix: {suffix}") logger.debug(e) + # Delete bad torrent. + self.delete_bad_torrent(info) self.client.set_category(category="BangumiCollection", hashes=_hash) def rename_subtitles(self, subtitle_list: list[str], media_old_name, media_new_name, _hash): @@ -139,6 +85,10 @@ class Renamer: self.client.rename_torrent_file(_hash, subtitle_file, new_subtitle_name) logger.info(f"Rename subtitles for {media_old_name} to {media_new_name}") + def delete_bad_torrent(self, info): + if settings.bangumi_manage.remove_bad_torrent: + self.client.delete_torrent(info.hash) + logger.info(f"{info.name} have been deleted.") @staticmethod def get_folder_and_season(save_path: str): @@ -167,23 +117,17 @@ class Renamer: recent_info, torrent_count = self.get_torrent_info() rename_count = 0 for info in recent_info: - try: - media_list = self.check_files(info) - if len(media_list) == 1: - self.rename_file(info, media_list[0]) - rename_count += 1 - # TODO: Rename subtitles - elif len(media_list) > 1: - logger.info("Start rename collection") - self.rename_collection(info, media_list) - rename_count += len(media_list) - else: - logger.warning(f"{info.name} has no media file") - except Exception as e: - logger.warning(f"{info.name} rename failed") - logger.debug(e) - if settings.bangumi_manage.remove_bad_torrent: - self.client.delete_torrent(info.hash) + media_list = self.check_files(info) + if len(media_list) == 1: + self.rename_file(info, media_list[0]) + rename_count += 1 + # TODO: Rename subtitles + elif len(media_list) > 1: + logger.info("Start rename collection") + self.rename_collection(info, media_list) + rename_count += len(media_list) + else: + logger.warning(f"{info.name} has no media file") if __name__ == '__main__': From c01703629306117e8b343b9ca1c9bcb4935d1cd7 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 21:56:58 +0800 Subject: [PATCH 17/40] - Add getConfig API - Fix env to config bug --- src/module/api.py | 5 +++++ src/module/conf/config.py | 12 +++++++----- src/module/conf/const.py | 8 ++------ src/module/core/api_func.py | 6 ++++-- src/module/models/bangumi.py | 19 +++++++++++++++++++ 5 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/module/api.py b/src/module/api.py index 8cae4b31..32a06259 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -58,6 +58,11 @@ async def add_rule(info: AddRule): return api_func.add_rule(info.title, info.season) +@router.get("/api/v1/getConfig", tags=["config"]) +async def get_config(): + return api_func.get_config() + + @router.post("/api/v1/updateConfig", tags=["config"]) async def update_config(config: Config): return api_func.update_config(config) diff --git a/src/module/conf/config.py b/src/module/conf/config.py index ec513609..38d87029 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -1,9 +1,10 @@ import json import os import logging +from dotenv import load_dotenv -from .const import ENV_TO_ATTR -from module.models import Config +from module.conf.const import ENV_TO_ATTR +from module.models.config import Config logger = logging.getLogger(__name__) @@ -48,13 +49,13 @@ def _val_from_env(env: str, attr: tuple): def env_to_config() -> Setting: - _settings = Setting() + _settings = Setting().dict() for key, section in ENV_TO_ATTR.items(): for env, attr in section.items(): if env in os.environ: attr_name = attr[0] if isinstance(attr, tuple) else attr - setattr(_settings, attr_name, _val_from_env(env, attr)) - return _settings + _settings[key][attr_name] = _val_from_env(env, attr) + return Setting(**_settings) if os.path.isdir("config") and VERSION == "DEV_VERSION": @@ -62,6 +63,7 @@ if os.path.isdir("config") and VERSION == "DEV_VERSION": if os.path.isfile(CONFIG_PATH): settings = load_config_from_file(CONFIG_PATH) else: + load_dotenv(".env") settings = env_to_config() save_config_to_file(settings, CONFIG_PATH) elif os.path.isdir("config") and VERSION != "DEV_VERSION": diff --git a/src/module/conf/const.py b/src/module/conf/const.py index 82d82c86..175a1e4b 100644 --- a/src/module/conf/const.py +++ b/src/module/conf/const.py @@ -56,8 +56,8 @@ DEFAULT_SETTINGS = { ENV_TO_ATTR = { "program": { - "AB_INTERVAL_TIME": ("sleep_time", float), - "AB_RENAME_FREQ": ("times", float), + "AB_INTERVAL_TIME": ("sleep_time", int), + "AB_RENAME_FREQ": ("times", int), "AB_WEBUI_PORT": ("webui_port", int), }, "downloader": { @@ -83,10 +83,6 @@ ENV_TO_ATTR = { "debug": { "AB_DEBUG_MODE": ("enable", lambda e: e.lower() in ("true", "1", "t")), }, - "proxy": { - "AB_HTTP_PROXY": "http", - "AB_SOCKS": "socks", - }, } diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 5b94239d..449faf4a 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -1,7 +1,5 @@ import re -import os import logging -import signal from module.core import DownloadClient from module.manager import FullSeasonGet @@ -76,3 +74,7 @@ class APIProcess: def update_config(config: Config): save_config_to_file(config, CONFIG_PATH) return {"message": "Success"} + + @staticmethod + def get_config() -> dict: + return json_config.load(CONFIG_PATH) diff --git a/src/module/models/bangumi.py b/src/module/models/bangumi.py index f8b8d6b2..c9a08fd8 100644 --- a/src/module/models/bangumi.py +++ b/src/module/models/bangumi.py @@ -1,6 +1,25 @@ +from pydantic import BaseModel, Field from dataclasses import dataclass +class BangumiData(BaseModel): + id: int = Field(..., alias="id", title="番剧ID") + official_title: str = Field(..., alias="official_title", title="番剧中文名") + year: int = Field(..., alias="year", title="番剧年份") + title_raw: str = Field(..., alias="title_raw", title="番剧原名") + season: int = Field(..., alias="season", title="番剧季度") + season_raw: str = Field(..., alias="season_raw", title="番剧季度原名") + group: str = Field(..., alias="group", title="字幕组") + dpi: str = Field(..., alias="dpi", title="分辨率") + source: str = Field(..., alias="source", title="来源") + subtitle: str = Field(..., alias="subtitle", title="字幕") + added: bool = Field(False, alias="added", title="是否已添加") + eps_collect: bool = Field(False, alias="eps_collect", title="是否已收集") + offset: int = Field(0, alias="offset", title="番剧偏移量") + filter: list[str] = Field(..., alias="filter", title="番剧过滤器") + + + @dataclass class MatchRule: keyword: str From f2693c0e80b0a84202d2f8374c70f3b34ba22243 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Mon, 24 Apr 2023 22:01:28 +0800 Subject: [PATCH 18/40] Fix pytest --- src/requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/requirements.txt b/src/requirements.txt index 374d29f4..cc092cf0 100644 --- a/src/requirements.txt +++ b/src/requirements.txt @@ -19,3 +19,4 @@ urllib3 uvicorn attrdict jinja2 +python-dotenv From 608f2c00d4271e0a332732d157dcb7e39d70d4c8 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Tue, 25 Apr 2023 00:06:12 +0800 Subject: [PATCH 19/40] Fix env to config bug --- .../qBittorrent+AutoBangumi/docker-compose.yml | 11 ++--------- src/module/conf/config.py | 10 ++-------- 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml b/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml index f25a0487..ae00cab1 100644 --- a/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml +++ b/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml @@ -27,21 +27,16 @@ services: - TZ=Asia/Shanghai - PGID=${GID} - PUID=${UID} - - AB_INTERVAL_TIME=1800 - AB_DOWNLOADER_HOST=qbittorrent:${QB_PORT} - AB_DOWNLOADER_USERNAME=admin - AB_DOWNLOADER_PASSWORD=adminadmin - - AB_METHOD=pn - - AB_GROUP_TAG=True - - AB_NOT_CONTAIN=720 - AB_DOWNLOAD_PATH=/downloads/Bangumi - AB_RSS=${RSS} - - AB_DEBUG_MODE=False - - AB_EP_COMPLETE=False volumes: - auto_bangumi:/config networks: - - auto_bangumi + - /path/to/config:/app/config + - /path/to/data:/app/data ports: - 7892:7892 dns: @@ -57,5 +52,3 @@ networks: volumes: qb_config: external: false - auto_bangumi: - external: false diff --git a/src/module/conf/config.py b/src/module/conf/config.py index 38d87029..c58e9ef5 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -36,14 +36,8 @@ def load_config_from_file(path: str) -> Config: def _val_from_env(env: str, attr: tuple): if isinstance(attr, tuple): - if attr[1] == "bool": - return os.environ[env].lower() == "true" - elif attr[1] == "int": - return int(os.environ[env]) - elif attr[1] == "float": - return float(os.environ[env]) - else: - return os.environ[env] + conv_func = attr[1] + return conv_func(os.environ[env]) else: return os.environ[env] From 43da3808ecf591e9c24f8deda451f5a35b791a6f Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Tue, 25 Apr 2023 09:56:24 +0800 Subject: [PATCH 20/40] Add extra auth func to aviod program fail to startup --- src/module/core/download_client.py | 4 ++++ src/module/downloader/__init__.py | 8 +------- src/module/downloader/qb_downloader.py | 13 ++++++++----- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index 94297bfd..236f2cc9 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -13,6 +13,10 @@ class DownloadClient: def __init__(self): self.client = getClient() + def auth(self): + host, username, password = settings.downloader.host, settings.downloader.username, settings.downloader.password + self.client.auth(host, username, password) + def init_downloader(self): prefs = { "rss_auto_downloading_enabled": True, diff --git a/src/module/downloader/__init__.py b/src/module/downloader/__init__.py index 2dd7a157..527d6a40 100644 --- a/src/module/downloader/__init__.py +++ b/src/module/downloader/__init__.py @@ -1,11 +1,5 @@ -from module.conf import settings - - def getClient(): - host = settings.downloader.host - username = settings.downloader.username - password = settings.downloader.password # TODO 多下载器支持 # 从 settings 里读取下载器名称,然后返回对应 Client from .qb_downloader import QbDownloader - return QbDownloader(host, username, password) + return QbDownloader() diff --git a/src/module/downloader/qb_downloader.py b/src/module/downloader/qb_downloader.py index 4170dfb5..64e8b643 100644 --- a/src/module/downloader/qb_downloader.py +++ b/src/module/downloader/qb_downloader.py @@ -7,27 +7,30 @@ from qbittorrentapi.exceptions import Conflict409Error from module.conf import settings from module.ab_decorator import qb_connect_failed_wait -from .exceptions import ConflictError +from module.downloader.exceptions import ConflictError logger = logging.getLogger(__name__) class QbDownloader: @qb_connect_failed_wait - def __init__(self, host, username, password): + def __init__(self): + self._client: Client | None = None + + @qb_connect_failed_wait + def auth(self, host, username, password): self._client = Client( host=host, username=username, password=password, - VERIFY_WEBUI_CERTIFICATE=settings.downloader.ssl, - RAISE_ERROR_FOR_UNSUPPORTED_QBITTORRENT_VERSIONS=True, + VERIFY_WEBUI_CERTIFICATE=settings.downloader.ssl ) while True: try: self._client.auth_log_in() break except LoginFailed: - logger.debug( + logger.warning( f"Can't login qBittorrent Server {host} by {username}, retry in {5} seconds." ) time.sleep(5) From 6f438be19ae5971eb0e8858300d118f1d9c34897 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Tue, 25 Apr 2023 14:46:45 +0800 Subject: [PATCH 21/40] Add RSS Link refresh --- src/main.py | 24 ++++++++++++++++++++++++ src/module/ab_decorator/__init__.py | 1 + src/module/app.py | 3 ++- src/module/conf/__init__.py | 6 +++++- src/module/conf/const.py | 17 +++++++---------- src/module/conf/log.py | 2 +- src/module/core/api_func.py | 12 ++++++++---- src/module/core/download_client.py | 11 +++++++++-- src/module/downloader/__init__.py | 10 ++++++++-- src/module/downloader/qb_downloader.py | 4 +++- src/module/models/config.py | 10 ++++------ src/module/rss/rss_analyser.py | 3 ++- src/module/setID.sh | 10 ---------- 13 files changed, 74 insertions(+), 39 deletions(-) delete mode 100644 src/module/setID.sh diff --git a/src/main.py b/src/main.py index b5e1971f..3caa7a1c 100644 --- a/src/main.py +++ b/src/main.py @@ -22,6 +22,8 @@ main_process = multiprocessing.Process(target=app.run) @router.get("/api/v1/restart", tags=["program"]) async def restart(): global main_process + if not main_process.is_alive(): + return {"status": "failed", "reason": "Already stopped"} logger.info("Restarting...") os.kill(main_process.pid, signal.SIGTERM) main_process = multiprocessing.Process(target=app.run) @@ -30,6 +32,28 @@ async def restart(): return {"status": "success"} +@router.get("/api/v1/stop", tags=["program"]) +async def stop(): + global main_process + if not main_process.is_alive(): + return {"status": "failed", "reason": "Already stopped"} + logger.info("Stopping...") + os.kill(main_process.pid, signal.SIGTERM) + logger.info("Stopped") + return {"status": "success"} + + +@router.get("/api/v1/start", tags=["program"]) +async def start(): + global main_process + if main_process.is_alive(): + return {"status": "failed", "reason": "Already started"} + logger.info("Starting...") + main_process.start() + logger.info("Started") + return {"status": "success"} + + if VERSION != "DEV_VERSION": router.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") templates = Jinja2Templates(directory="templates") diff --git a/src/module/ab_decorator/__init__.py b/src/module/ab_decorator/__init__.py index d504865e..78a18e93 100644 --- a/src/module/ab_decorator/__init__.py +++ b/src/module/ab_decorator/__init__.py @@ -12,6 +12,7 @@ def qb_connect_failed_wait(func): return func(*args, **kwargs) except Exception as e: logger.debug(f"URL: {args[0]}") + logger.warning(e) logger.warning("Cannot connect to qBittorrent. Wait 5 min and retry...") time.sleep(300) times += 1 diff --git a/src/module/app.py b/src/module/app.py index aced1330..9e731ac8 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -77,8 +77,9 @@ def run(): setup_logger() show_info() download_client = DownloadClient() + download_client.auth() download_client.init_downloader() - if settings.rss_parser.token is None: + if settings.rss_parser.token in ["", "token", None]: logger.error("Please set your RSS token in config file.") quit() download_client.rss_feed() diff --git a/src/module/conf/__init__.py b/src/module/conf/__init__.py index 1bec68d2..c716bbd8 100644 --- a/src/module/conf/__init__.py +++ b/src/module/conf/__init__.py @@ -4,4 +4,8 @@ from .config import settings, VERSION TMDB_API = "32b19d6a05b512190a056fa4e747cbbc" DATA_PATH = "data/data.json" -RSS_LINK = f"https://{settings.rss_parser.custom_url}/RSS/MyBangumi?token={settings.rss_parser.token}" + + +class RSSLink(str): + def __new__(cls): + return f"https://{settings.rss_parser.custom_url}/RSS/MyBangumi?token={settings.rss_parser.token}" \ No newline at end of file diff --git a/src/module/conf/const.py b/src/module/conf/const.py index 175a1e4b..bfe6c3cf 100644 --- a/src/module/conf/const.py +++ b/src/module/conf/const.py @@ -31,11 +31,8 @@ DEFAULT_SETTINGS = { "group_tag": False, "remove_bad_torrent": False }, - "debug": { - "enable": False, - "level": "info", - "file": "bangumi.log", - "dev_debug": False + "log": { + "debug_enable": False, }, "proxy": { "enable": False, @@ -56,9 +53,9 @@ DEFAULT_SETTINGS = { ENV_TO_ATTR = { "program": { - "AB_INTERVAL_TIME": ("sleep_time", int), - "AB_RENAME_FREQ": ("times", int), - "AB_WEBUI_PORT": ("webui_port", int), + "AB_INTERVAL_TIME": ("sleep_time", lambda e: int(e)), + "AB_RENAME_FREQ": ("times", lambda e: int(e)), + "AB_WEBUI_PORT": ("webui_port", lambda e: int(e)), }, "downloader": { "AB_DOWNLOADER_HOST": "host", @@ -80,8 +77,8 @@ ENV_TO_ATTR = { "AB_EP_COMPLETE": ("eps_complete", lambda e: e.lower() in ("true", "1", "t")), "AB_REMOVE_BAD_BT": ("remove_bad_torrent", lambda e: e.lower() in ("true", "1", "t")), }, - "debug": { - "AB_DEBUG_MODE": ("enable", lambda e: e.lower() in ("true", "1", "t")), + "log": { + "AB_DEBUG_MODE": ("debug_enable", lambda e: e.lower() in ("true", "1", "t")), }, } diff --git a/src/module/conf/log.py b/src/module/conf/log.py index b8516603..475b475c 100644 --- a/src/module/conf/log.py +++ b/src/module/conf/log.py @@ -6,7 +6,7 @@ LOG_PATH = "data/log.txt" def setup_logger(): - level = logging.DEBUG if settings.debug.enable else logging.INFO + level = logging.DEBUG if settings.log.debug_enable else logging.INFO logging.addLevelName(logging.DEBUG, 'DEBUG:') logging.addLevelName(logging.INFO, 'INFO:') logging.addLevelName(logging.WARNING, 'WARNING:') diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 449faf4a..fae3b2d4 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -17,7 +17,7 @@ logger = logging.getLogger(__name__) class APIProcess: def __init__(self): self._rss_analyser = RSSAnalyser() - self._download_client = DownloadClient() + self._client = DownloadClient() self._full_season_get = FullSeasonGet() def link_process(self, link): @@ -25,15 +25,19 @@ class APIProcess: @api_failed def download_collection(self, link): + if not self._client.authed: + self._client.auth() data = self.link_process(link) - self._full_season_get.download_collection(data, link, self._download_client) + self._full_season_get.download_collection(data, link, self._client) return data @api_failed def add_subscribe(self, link): + if not self._client.authed: + self._client.auth() data = self.link_process(link) - self._download_client.add_rss_feed(link, data.get("official_title")) - self._download_client.set_rule(data, link) + self._client.add_rss_feed(link, data.get("official_title")) + self._client.set_rule(data, link) return data @staticmethod diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index 236f2cc9..f103e6ef 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -4,7 +4,9 @@ import os from module.downloader import getClient -from module.conf import settings, RSS_LINK +from module.conf import settings, RSSLink + +RSS_LINK = RSSLink() logger = logging.getLogger(__name__) @@ -12,10 +14,15 @@ logger = logging.getLogger(__name__) class DownloadClient: def __init__(self): self.client = getClient() + self.authed = False def auth(self): host, username, password = settings.downloader.host, settings.downloader.username, settings.downloader.password - self.client.auth(host, username, password) + try: + self.client.auth(host, username, password) + self.authed = True + except Exception as e: + logger.error(f"Can't login {host} by {username}, {e}") def init_downloader(self): prefs = { diff --git a/src/module/downloader/__init__.py b/src/module/downloader/__init__.py index 527d6a40..a7612e6c 100644 --- a/src/module/downloader/__init__.py +++ b/src/module/downloader/__init__.py @@ -1,5 +1,11 @@ +from module.conf import settings + + def getClient(): # TODO 多下载器支持 # 从 settings 里读取下载器名称,然后返回对应 Client - from .qb_downloader import QbDownloader - return QbDownloader() + if settings.downloader.type == "qbittorrent": + from .qb_downloader import QbDownloader + return QbDownloader() + else: + raise Exception(f"Unsupported downloader type: {settings.downloader.type}") diff --git a/src/module/downloader/qb_downloader.py b/src/module/downloader/qb_downloader.py index 64e8b643..568ee107 100644 --- a/src/module/downloader/qb_downloader.py +++ b/src/module/downloader/qb_downloader.py @@ -13,7 +13,6 @@ logger = logging.getLogger(__name__) class QbDownloader: - @qb_connect_failed_wait def __init__(self): self._client: Client | None = None @@ -101,3 +100,6 @@ class QbDownloader: def set_category(self, _hash, category): self._client.torrents_set_category(category, hashes=_hash) + + def check_connection(self): + return self._client.app_version() diff --git a/src/module/models/config.py b/src/module/models/config.py index b2d0a62b..9f341df4 100644 --- a/src/module/models/config.py +++ b/src/module/models/config.py @@ -17,6 +17,7 @@ class Downloader(BaseModel): path: str = Field("/downloads/Bangumi", description="Downloader path") ssl: bool = Field(False, description="Downloader ssl") + class RSSParser(BaseModel): enable: bool = Field(True, description="Enable RSS parser") type: str = Field("mikan", description="RSS parser type") @@ -35,11 +36,8 @@ class BangumiManage(BaseModel): remove_bad_torrent: bool = Field(False, description="Remove bad torrent") -class Debug(BaseModel): - enable: bool = Field(False, description="Enable debug") - level: str = Field("debug", description="Debug level") - file: str = Field("debug.log", description="Debug file") - dev_debug: bool = Field(False, description="Enable dev debug") +class Log(BaseModel): + debug_enable: bool = Field(False, description="Enable debug") class Proxy(BaseModel): @@ -64,6 +62,6 @@ class Config(BaseModel): downloader: Downloader = Downloader() rss_parser: RSSParser = RSSParser() bangumi_manage: BangumiManage = BangumiManage() - debug: Debug = Debug() + log: Log = Log() proxy: Proxy = Proxy() notification: Notification = Notification() diff --git a/src/module/rss/rss_analyser.py b/src/module/rss/rss_analyser.py index 57704a95..b833b7b1 100644 --- a/src/module/rss/rss_analyser.py +++ b/src/module/rss/rss_analyser.py @@ -3,11 +3,12 @@ import logging from module.network import RequestContent from module.parser import TitleParser -from module.conf import settings, RSS_LINK +from module.conf import RSSLink from module.core import DownloadClient logger = logging.getLogger(__name__) +RSS_LINK = RSSLink() class RSSAnalyser: diff --git a/src/module/setID.sh b/src/module/setID.sh deleted file mode 100644 index 64b28214..00000000 --- a/src/module/setID.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -echo "设置文件夹权限" -echo "PUID=${PUID}" -echo "PGID=${PGID}" - -groupmod -o -g "$PGID" auto_bangumi -usermod -o -u "$PUID" auto_bangumi - -chown -R auto_bangumi:auto_bangumi /src /templates /config \ No newline at end of file From 99cd86a22808075d751caeaea76b5272b33dc817 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Tue, 25 Apr 2023 15:08:59 +0800 Subject: [PATCH 22/40] Fix api bug. --- src/main.py | 1 + src/module/app.py | 5 +++-- src/module/core/download_client.py | 2 +- src/module/downloader/qb_downloader.py | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main.py b/src/main.py index 3caa7a1c..c5688170 100644 --- a/src/main.py +++ b/src/main.py @@ -49,6 +49,7 @@ async def start(): if main_process.is_alive(): return {"status": "failed", "reason": "Already started"} logger.info("Starting...") + main_process = multiprocessing.Process(target=app.run) main_process.start() logger.info("Started") return {"status": "success"} diff --git a/src/module/app.py b/src/module/app.py index 9e731ac8..f6c5e9f8 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -2,7 +2,7 @@ import os import time import logging -from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSS_LINK, VERSION +from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSSLink, VERSION from module.utils import json_config from module.core import DownloadClient @@ -11,6 +11,7 @@ from module.rss import RSSAnalyser logger = logging.getLogger(__name__) +RSS_LINK = RSSLink() def reset_log(): @@ -81,7 +82,7 @@ def run(): download_client.init_downloader() if settings.rss_parser.token in ["", "token", None]: logger.error("Please set your RSS token in config file.") - quit() + exit(0) download_client.rss_feed() bangumi_data = load_data_file() # 主程序循环 diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index f103e6ef..c9e41650 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -49,7 +49,7 @@ class DownloadClient: "affectedFeeds": [rss_link], "ignoreDays": 0, "lastMatch": "", - "addPaused": settings.debug.dev_debug, + "addPaused": False, "assignedCategory": "Bangumi", "savePath": str( os.path.join( diff --git a/src/module/downloader/qb_downloader.py b/src/module/downloader/qb_downloader.py index 568ee107..b2b57c1f 100644 --- a/src/module/downloader/qb_downloader.py +++ b/src/module/downloader/qb_downloader.py @@ -48,7 +48,7 @@ class QbDownloader: def torrents_add(self, urls, save_path, category): return self._client.torrents_add( - is_paused=settings.debug.dev_debug, + is_paused=False, urls=urls, save_path=save_path, category=category, From f1204fab4746e4867319a14405e984c035f85485 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Tue, 25 Apr 2023 20:35:52 +0800 Subject: [PATCH 23/40] Add telegram and server-chan notification --- src/main.py | 1 - src/module/manager/renamer.py | 3 +++ src/module/network/notification.py | 15 ++++++++------- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/main.py b/src/main.py index c5688170..c951d767 100644 --- a/src/main.py +++ b/src/main.py @@ -31,7 +31,6 @@ async def restart(): logger.info("Restarted") return {"status": "success"} - @router.get("/api/v1/stop", tags=["program"]) async def stop(): global main_process diff --git a/src/module/manager/renamer.py b/src/module/manager/renamer.py index 2e8c8c4b..fa50c63b 100644 --- a/src/module/manager/renamer.py +++ b/src/module/manager/renamer.py @@ -7,6 +7,7 @@ from module.core.download_client import DownloadClient from module.conf import settings from module.parser import TitleParser +from module.network import PostNotification logger = logging.getLogger(__name__) @@ -15,6 +16,7 @@ class Renamer: def __init__(self, download_client: DownloadClient): self.client = download_client self._renamer = TitleParser() + self.notification = PostNotification() @staticmethod def print_result(torrent_count, rename_count): @@ -50,6 +52,7 @@ class Renamer: if compare_name != new_path: try: self.client.rename_torrent_file(_hash=info.hash, old_path=media_path, new_path=new_path) + self.notification.send_msg(folder_name, "update") except Exception as e: logger.warning(f"{old_name} rename failed") logger.warning(f"Folder name: {folder_name}, Season: {season}, Suffix: {suffix}") diff --git a/src/module/network/notification.py b/src/module/network/notification.py index c6dca0ba..edb7103a 100644 --- a/src/module/network/notification.py +++ b/src/module/network/notification.py @@ -17,7 +17,7 @@ class PostNotification: def getClient(): if settings.notification.type.lower() == "telegram": return TelegramNotification() - elif settings.notification.type.lower() == "serverchan": + elif settings.notification.type.lower() == "server-chan": return ServerChanNotification() else: return None @@ -32,16 +32,19 @@ class PostNotification: class TelegramNotification: def __init__(self): - self.token = settings.notification_token + self.token = settings.notification.token + self.chat_id = settings.notification.chat_id self.notification_url = f"https://api.telegram.org/bot{self.token}/sendMessage" - def send_msg(self, title: str, desp: str) -> bool: - if not settings.notification_enable: - return False + def send_msg(self, title: str, desp: str): data = { "chat_id": settings.notification_chat_id, "text": f"{title}\n{desp}", + "disable_notification": True, } + with RequestContent() as req: + resp = req.post_data(self.notification_url, data) + return resp.status_code == 200 class ServerChanNotification: @@ -51,8 +54,6 @@ class ServerChanNotification: self.notification_url = f"https://sctapi.ftqq.com/{self.token}.send" def send_msg(self, title: str, desp: str) -> bool: - if not settings.notification.enable: - return False data = { "title": title, "desp": desp, From bdb3126d8ebf1f5d4306684f1547374c7fd96789 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Tue, 25 Apr 2023 21:05:13 +0800 Subject: [PATCH 24/40] Add filter switch --- src/module/core/api_func.py | 2 +- src/module/network/request_contents.py | 7 +++++-- src/module/rss/rss_analyser.py | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index fae3b2d4..1baa1a28 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -21,7 +21,7 @@ class APIProcess: self._full_season_get = FullSeasonGet() def link_process(self, link): - return self._rss_analyser.rss_to_data(link) + return self._rss_analyser.rss_to_data(link, filter=False) @api_failed def download_collection(self, link): diff --git a/src/module/network/request_contents.py b/src/module/network/request_contents.py index 078d8dca..4f621d38 100644 --- a/src/module/network/request_contents.py +++ b/src/module/network/request_contents.py @@ -19,13 +19,16 @@ class TorrentInfo: class RequestContent(RequestURL): # Mikanani RSS - def get_torrents(self, _url: str) -> [TorrentInfo]: + def get_torrents(self, _url: str, filter: bool = True) -> [TorrentInfo]: soup = self.get_xml(_url) torrent_titles = [item.title.string for item in soup.find_all("item")] torrent_urls = [item.get("url") for item in soup.find_all("enclosure")] torrents = [] for _title, torrent_url in zip(torrent_titles, torrent_urls): - if re.search(FILTER, _title) is None: + if filter: + if re.search(FILTER, _title) is None: + torrents.append(TorrentInfo(_title, torrent_url)) + else: torrents.append(TorrentInfo(_title, torrent_url)) return torrents diff --git a/src/module/rss/rss_analyser.py b/src/module/rss/rss_analyser.py index b833b7b1..8acc1306 100644 --- a/src/module/rss/rss_analyser.py +++ b/src/module/rss/rss_analyser.py @@ -33,9 +33,9 @@ class RSSAnalyser: bangumi_info.append(data) return bangumi_info - def rss_to_data(self, url) -> dict: + def rss_to_data(self, url, filter: bool = True) -> dict: with RequestContent() as req: - rss_torrents = req.get_torrents(url) + rss_torrents = req.get_torrents(url, filter) for torrent in rss_torrents: try: data = self._title_analyser.return_dict(torrent.name) From 750b70cd76689b421ab633cb9e558f6faf2fc45f Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 10:31:12 +0800 Subject: [PATCH 25/40] Add release-drafter.yml --- .github/release-drafter.yml | 44 +++++++++++++++++++++++++++ .github/workflows/release-drafter.yml | 25 +++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 .github/release-drafter.yml create mode 100644 .github/workflows/release-drafter.yml diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 00000000..70dda3cc --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,44 @@ +# Configuration for Release Drafter: https://github.com/toolmantim/release-drafter +name-template: 'v$NEXT_PATCH_VERSION 🌈' +tag-template: 'v$NEXT_PATCH_VERSION' +version-template: $MAJOR.$MINOR.$PATCH +# Emoji reference: https://gitmoji.carloscuesta.me/ +categories: + - title: '🚀 Features' + labels: + - 'feature' + - 'enhancement' + - 'kind/feature' + - title: '🐛 Bug Fixes' + labels: + - 'fix' + - 'bugfix' + - 'bug' + - 'regression' + - 'kind/bug' + - title: 📝 Documentation updates + labels: + - documentation + - 'kind/doc' + - title: 👻 Maintenance + labels: + - chore + - dependencies + - 'kind/chore' + - 'kind/dep' + - title: 🚦 Tests + labels: + - test + - tests +exclude-labels: + - reverted + - no-changelog + - skip-changelog + - invalid +change-template: '* $TITLE (#$NUMBER) @$AUTHOR' +template: | + ## What’s Changed + $CHANGES +Terms +Privacy +Security \ No newline at end of file diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 00000000..c85f313c --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,25 @@ +name: Release Drafter + +on: + push: + branches: + tags: + - '\d+\.\d+\.\d+' + pull_request: + tags: + - '\d+\.\d+\.\d+' + +permissions: + contents: read + + +jobs: + update_release_draft: + permissions: + contents: write # for release-drafter/release-drafter to create a github release + pull-requests: write # for release-drafter/release-drafter to add label to PR + runs-on: ubuntu-latest + steps: + - uses: release-drafter/release-drafter@v5 + env: + GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} \ No newline at end of file From e6f1c5f292d7eb2e587accec3c1b73dcff6e24a1 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 10:32:29 +0800 Subject: [PATCH 26/40] Add release-drafter.yml --- .github/workflows/docker.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 7befefc9..378f09a2 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -2,6 +2,8 @@ name: Build(Docker) on: push: + branches: + - main tags: - '\d+\.\d+\.\d+' pull_request: From e1923d47a5baf4e41e934d44a8421c4de758d88a Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 10:48:09 +0800 Subject: [PATCH 27/40] =?UTF-8?q?Feature=20=E5=A2=9E=E5=8A=A0=E5=86=85?= =?UTF-8?q?=E7=BD=AE=E5=8F=8D=E4=BB=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AutoBangumi/docker-compose.yml | 9 +-------- .../qBittorrent+AutoBangumi/docker-compose.yml | 10 ++++------ src/module/api.py | 14 +++++++++++++- src/module/core/api_func.py | 16 +++++++++++++++- src/module/network/request_contents.py | 10 ++++++++-- 5 files changed, 41 insertions(+), 18 deletions(-) diff --git a/docs/docker-compose/AutoBangumi/docker-compose.yml b/docs/docker-compose/AutoBangumi/docker-compose.yml index 04e2663c..107cda55 100644 --- a/docs/docker-compose/AutoBangumi/docker-compose.yml +++ b/docs/docker-compose/AutoBangumi/docker-compose.yml @@ -6,22 +6,15 @@ services: - TZ=Asia/Shanghai - PGID=${GID} - PUID=${UID} - - AB_INTERVAL_TIME=1800 - AB_DOWNLOADER_HOST=localhost:${QB_PORT} - AB_DOWNLOADER_USERNAME=admin - AB_DOWNLOADER_PASSWORD=adminadmin - - AB_METHOD=pn - - AB_GROUP_TAG=True - - AB_NOT_CONTAIN=720 - AB_DOWNLOAD_PATH=${DOWNLOAD_PATH} - AB_RSS=${RSS} - - AB_DEBUG_MODE=False - - AB_EP_COMPLETE=False - - AB_SEASON_ONE=True networks: - auto_bangumi ports: - - 7892:7892 + - '7892:7892' volumes: - auto_bangumi:/config dns: diff --git a/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml b/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml index ae00cab1..61e387b6 100644 --- a/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml +++ b/docs/docker-compose/qBittorrent+AutoBangumi/docker-compose.yml @@ -14,12 +14,12 @@ services: - ${DOWNLOAD_PATH}:/downloads # 填入下载绝对路径 ports: - ${QB_PORT}:${QB_PORT} - - 6881:6881 - - 6881:6881/udp + - "6881:6881" + - "6881:6881/udp" networks: - auto_bangumi restart: unless-stopped - image: lscr.io/linuxserver/qbittorrent:4.4.3 + image: superng6/qbittorrent auto_bangumi: container_name: AutoBangumi @@ -32,13 +32,11 @@ services: - AB_DOWNLOADER_PASSWORD=adminadmin - AB_DOWNLOAD_PATH=/downloads/Bangumi - AB_RSS=${RSS} - volumes: - - auto_bangumi:/config networks: - /path/to/config:/app/config - /path/to/data:/app/data ports: - - 7892:7892 + - '7892:7892' dns: - 8.8.8.8 - 223.5.5.5 diff --git a/src/module/api.py b/src/module/api.py index 32a06259..53821975 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -1,6 +1,6 @@ import logging from fastapi import FastAPI -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, Response from module.core import APIProcess from module.conf import DATA_PATH, LOG_PATH, settings @@ -67,3 +67,15 @@ async def get_config(): async def update_config(config: Config): return api_func.update_config(config) + +@router.get("/RSS/MyBangumi") +async def get_rss(token: str): + content = api_func.get_rss(token) + return Response(content, media_type="application/xml") + + +@router.get("/Download/{full_path:path}") +async def download(full_path: str): + torrent = api_func.get_torrent(full_path) + return Response(torrent, media_type="application/x-bittorrent") + diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 1baa1a28..2a4e7589 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -5,9 +5,10 @@ from module.core import DownloadClient from module.manager import FullSeasonGet from module.rss import RSSAnalyser from module.utils import json_config -from module.conf import DATA_PATH +from module.conf import DATA_PATH, settings from module.conf.config import save_config_to_file, CONFIG_PATH from module.models import Config +from module.network import RequestContent from module.ab_decorator import api_failed @@ -82,3 +83,16 @@ class APIProcess: @staticmethod def get_config() -> dict: return json_config.load(CONFIG_PATH) + + @staticmethod + def get_rss(token: str): + url = f"https://mikanani.me/RSS/MyBangumi?token={token}" + with RequestContent() as request: + content = request.get_html(url) + return re.sub(r"mikanani.me", settings.rss_parser.custom_url, content) + + @staticmethod + def get_torrent(full_path): + url = f"https://mikanani.me/Downloads/{full_path}" + with RequestContent() as request: + return request.get_content(url) diff --git a/src/module/network/request_contents.py b/src/module/network/request_contents.py index 4f621d38..d20ec81a 100644 --- a/src/module/network/request_contents.py +++ b/src/module/network/request_contents.py @@ -38,8 +38,8 @@ class RequestContent(RequestURL): enclosure = item.find("enclosure") return TorrentInfo(item.title.string, enclosure["url"]) - def get_xml(self, url): - return BeautifulSoup(self.get_url(url).text, "xml") + def get_xml(self, _url): + return BeautifulSoup(self.get_url(_url).text, "xml") # API JSON def get_json(self, _url) -> dict: @@ -50,3 +50,9 @@ class RequestContent(RequestURL): def post_data(self, _url, data: dict) -> dict: return self.post_url(_url, data) + + def get_html(self, _url): + return self.get_url(_url).text + + def get_content(self, _url): + return self.get_url(_url).content From 85ff3acf3bbfb79c37e1fe3b31935ed979d043ed Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 11:02:26 +0800 Subject: [PATCH 28/40] Fix API bugs --- src/module/api.py | 18 +++++++++++++++--- src/module/app.py | 2 +- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/module/api.py b/src/module/api.py index 53821975..b3e73020 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -1,4 +1,6 @@ import logging +import os + from fastapi import FastAPI from fastapi.responses import FileResponse, Response @@ -24,13 +26,23 @@ async def startup_event(): @router.get("/api/v1/data") async def get_data(): - data = json_config.load(DATA_PATH) - return data + try: + data = json_config.load(DATA_PATH) + return data + except FileNotFoundError: + return { + "rss_link": "", + "data_version": settings.data_version, + "bangumi_info": [], + } @router.get("/api/v1/log") async def get_log(): - return FileResponse(LOG_PATH) + if os.path.isfile(LOG_PATH): + return FileResponse(LOG_PATH) + else: + return Response("Log file not found", status_code=404) @router.get("/api/v1/resetRule") diff --git a/src/module/app.py b/src/module/app.py index f6c5e9f8..0b4aab7a 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -82,7 +82,7 @@ def run(): download_client.init_downloader() if settings.rss_parser.token in ["", "token", None]: logger.error("Please set your RSS token in config file.") - exit(0) + exit(1) download_client.rss_feed() bangumi_data = load_data_file() # 主程序循环 From d26d31635fc401b8d3079643c9daee760e76ac0b Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 12:16:16 +0800 Subject: [PATCH 29/40] Add local proxy --- src/module/api.py | 11 ++++++++--- src/module/conf/__init__.py | 6 +++++- src/module/core/api_func.py | 11 +++++++---- src/module/manager/eps_complete.py | 4 ++-- src/module/network/notification.py | 2 -- 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/module/api.py b/src/module/api.py index b3e73020..5a1e8f2d 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -80,9 +80,14 @@ async def update_config(config: Config): return api_func.update_config(config) -@router.get("/RSS/MyBangumi") -async def get_rss(token: str): - content = api_func.get_rss(token) +@router.get("/RSS/{full_path:path}") +async def get_rss(full_path: str, token: str = None, searchstr: str = None): + if token is not None: + full_path = full_path + "?token=" + token + if searchstr is not None: + full_path = full_path + "?searchstr=" + searchstr + content = api_func.get_rss(full_path) + print(full_path) return Response(content, media_type="application/xml") diff --git a/src/module/conf/__init__.py b/src/module/conf/__init__.py index c716bbd8..1afbfad9 100644 --- a/src/module/conf/__init__.py +++ b/src/module/conf/__init__.py @@ -1,6 +1,8 @@ from .log import setup_logger, LOG_PATH from .config import settings, VERSION +import re + TMDB_API = "32b19d6a05b512190a056fa4e747cbbc" DATA_PATH = "data/data.json" @@ -8,4 +10,6 @@ DATA_PATH = "data/data.json" class RSSLink(str): def __new__(cls): - return f"https://{settings.rss_parser.custom_url}/RSS/MyBangumi?token={settings.rss_parser.token}" \ No newline at end of file + if "://" not in settings.rss_parser.custom_url: + return f"https://{settings.rss_parser.custom_url}/RSS/MyBangumi?token={settings.rss_parser.token}" + return f"{settings.rss_parser.custom_url}/RSS/MyBangumi?token={settings.rss_parser.token}" diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 2a4e7589..1ac3cc06 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -85,14 +85,17 @@ class APIProcess: return json_config.load(CONFIG_PATH) @staticmethod - def get_rss(token: str): - url = f"https://mikanani.me/RSS/MyBangumi?token={token}" + def get_rss(full_path: str): + url = f"https://mikanani.me/RSS/{full_path}" + custom_url = settings.rss_parser.custom_url + if "://" not in custom_url: + custom_url = f"https://{custom_url}" with RequestContent() as request: content = request.get_html(url) - return re.sub(r"mikanani.me", settings.rss_parser.custom_url, content) + return re.sub(r"https://mikanani.me", custom_url, content) @staticmethod def get_torrent(full_path): - url = f"https://mikanani.me/Downloads/{full_path}" + url = f"https://mikanani.me/Download/{full_path}" with RequestContent() as request: return request.get_content(url) diff --git a/src/module/manager/eps_complete.py b/src/module/manager/eps_complete.py index 4ede11a1..3e9105e4 100644 --- a/src/module/manager/eps_complete.py +++ b/src/module/manager/eps_complete.py @@ -9,7 +9,7 @@ from module.core.download_client import DownloadClient logger = logging.getLogger(__name__) SEARCH_KEY = ["group", "title_raw", "season_raw", "subtitle", "source", "dpi"] -CUSTOM_URL = "mikanani.me" if settings.rss_parser.custom_url == "" else settings.rss_parser.custom_url +CUSTOM_URL = "https://mikanani.me" if settings.rss_parser.custom_url == "" else settings.rss_parser.custom_url class FullSeasonGet: @@ -26,7 +26,7 @@ class FullSeasonGet: def get_season_torrents(self, data: dict): keyword = self.init_eps_complete_search_str(data) with RequestContent() as req: - torrents = req.get_torrents(f"https://{CUSTOM_URL}/RSS/Search?searchstr={keyword}") + torrents = req.get_torrents(f"{CUSTOM_URL}/RSS/Search?searchstr={keyword}") return torrents @staticmethod diff --git a/src/module/network/notification.py b/src/module/network/notification.py index edb7103a..10e6c5b6 100644 --- a/src/module/network/notification.py +++ b/src/module/network/notification.py @@ -9,8 +9,6 @@ logger = logging.getLogger(__name__) class PostNotification: def __init__(self): - self.token = settings.notification_token - self.notification_url = lambda message: f"https://api.pushbullet.com/v2/{self.token}/{message}" self.client = self.getClient() @staticmethod From 946cb449eb7841a5eb596742d0039c1157b41975 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 12:24:38 +0800 Subject: [PATCH 30/40] Fix collection downloads in local proxy --- src/module/api.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/module/api.py b/src/module/api.py index 5a1e8f2d..94e490a8 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -81,11 +81,19 @@ async def update_config(config: Config): @router.get("/RSS/{full_path:path}") -async def get_rss(full_path: str, token: str = None, searchstr: str = None): +async def get_rss( + full_path: str, + token: str = None, + searchstr: str = None, + bangumiId: str = None, + groupid: str = None, +): if token is not None: full_path = full_path + "?token=" + token if searchstr is not None: full_path = full_path + "?searchstr=" + searchstr + if bangumiId is not None and groupid is not None: + full_path = full_path + "?bangumiId=" + bangumiId + "&groupid=" + groupid content = api_func.get_rss(full_path) print(full_path) return Response(content, media_type="application/xml") From e193cc26427d0afb7ed924c653e56234db382913 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 13:38:27 +0800 Subject: [PATCH 31/40] Fix collection downloads in local proxy --- src/module/api.py | 50 +++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/src/module/api.py b/src/module/api.py index 94e490a8..8e617a91 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -24,7 +24,7 @@ async def startup_event(): logger.addHandler(handler) -@router.get("/api/v1/data") +@router.get("/api/v1/data", tags=["info"]) async def get_data(): try: data = json_config.load(DATA_PATH) @@ -37,7 +37,7 @@ async def get_data(): } -@router.get("/api/v1/log") +@router.get("/api/v1/log", tags=["info"]) async def get_log(): if os.path.isfile(LOG_PATH): return FileResponse(LOG_PATH) @@ -55,17 +55,17 @@ def remove_rule(bangumi_title: str): return api_func.remove_rule(bangumi_title) -@router.post("/api/v1/collection") +@router.post("/api/v1/collection", tags=["download"]) async def collection(link: RssLink): return api_func.download_collection(link.rss_link) -@router.post("/api/v1/subscribe") +@router.post("/api/v1/subscribe", tags=["download"]) async def subscribe(link: RssLink): return api_func.add_subscribe(link.rss_link) -@router.post("/api/v1/addRule") +@router.post("/api/v1/addRule", tags=["download"]) async def add_rule(info: AddRule): return api_func.add_rule(info.title, info.season) @@ -80,26 +80,34 @@ async def update_config(config: Config): return api_func.update_config(config) -@router.get("/RSS/{full_path:path}") -async def get_rss( - full_path: str, - token: str = None, - searchstr: str = None, - bangumiId: str = None, - groupid: str = None, -): - if token is not None: - full_path = full_path + "?token=" + token - if searchstr is not None: - full_path = full_path + "?searchstr=" + searchstr - if bangumiId is not None and groupid is not None: - full_path = full_path + "?bangumiId=" + bangumiId + "&groupid=" + groupid +@router.get("/RSS/MyBangumi", tags=["proxy"]) +async def get_my_bangumi(token: str): + full_path = "MyBangumi?token=" + token content = api_func.get_rss(full_path) - print(full_path) return Response(content, media_type="application/xml") -@router.get("/Download/{full_path:path}") +@router.get("/RSS/Search", tags=["proxy"]) +async def get_search_result(searchstr: str): + full_path = "Search?searchstr=" + searchstr + content = api_func.get_rss(full_path) + return Response(content, media_type="application/xml") + + +@router.get("/RSS/Bangumi", tags=["proxy"]) +async def get_bangumi(bangumiId: str, groupid: str): + full_path = "Bangumi?bangumiId=" + bangumiId + "&groupid=" + groupid + content = api_func.get_rss(full_path) + return Response(content, media_type="application/xml") + + +@router.get("/RSS/{full_path:path}", tags=["proxy"]) +async def get_rss(full_path: str): + content = api_func.get_rss(full_path) + return Response(content, media_type="application/xml") + + +@router.get("/Download/{full_path:path}", tags=["proxy"]) async def download(full_path: str): torrent = api_func.get_torrent(full_path) return Response(torrent, media_type="application/x-bittorrent") From 53c9884e94e7eea6a57ad04e8983b4763c121ad7 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 14:39:02 +0800 Subject: [PATCH 32/40] Fix from url get token --- src/module/conf/const.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/module/conf/const.py b/src/module/conf/const.py index bfe6c3cf..39516187 100644 --- a/src/module/conf/const.py +++ b/src/module/conf/const.py @@ -1,4 +1,6 @@ # -*- encoding: utf-8 -*- +from urllib.parse import urlparse, parse_qs + DEFAULT_SETTINGS = { "program": { @@ -65,7 +67,7 @@ ENV_TO_ATTR = { }, "rss_parser": { "AB_RSS_COLLECTOR": ("enable", lambda e: e.lower() in ("true", "1", "t")), - "AB_RSS": ("token", lambda e: e.replace("https://mikanani.me/RSS/MyBangumi?token=", "")), + "AB_RSS": ("token", lambda e: parse_qs(urlparse(e).query).get("token", [None])[0]), "AB_NOT_CONTAIN": ("filter", lambda e: e.split("|")), "AB_LANGUAGE": "language", "AB_ENABLE_TMDB": ("enable_tmdb", lambda e: e.lower() in ("true", "1", "t")), From b2fc5c2bba226c1a3cdc94f461ea185b8d729057 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 14:39:44 +0800 Subject: [PATCH 33/40] Fix from url get token --- .github/workflows/release-drafter.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml index c85f313c..f9b8d68f 100644 --- a/.github/workflows/release-drafter.yml +++ b/.github/workflows/release-drafter.yml @@ -1,10 +1,6 @@ name: Release Drafter on: - push: - branches: - tags: - - '\d+\.\d+\.\d+' pull_request: tags: - '\d+\.\d+\.\d+' From 7dc6d8d8a5d8f2a154de2c4e303fd283f38ae628 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 18:14:17 +0800 Subject: [PATCH 34/40] Change Data Model --- .github/workflows/unittest.yml | 1 - Dockerfile | 2 +- src/requirements.txt => requirements.txt | 0 src/module/api.py | 7 ++-- src/module/app.py | 42 ++++++++++-------------- src/module/conf/__init__.py | 3 +- src/module/core/api_func.py | 13 ++++---- src/module/core/download_client.py | 13 ++++---- src/module/manager/eps_complete.py | 31 +++++++++-------- src/module/models/bangumi.py | 7 +++- src/module/models/config.py | 2 +- src/module/parser/title_parser.py | 33 ++++++++++--------- src/module/rss/rss_analyser.py | 32 +++++++++++------- src/module/utils/__init__.py | 1 + src/module/utils/bangumi_data.py | 26 +++++++++++++++ 15 files changed, 127 insertions(+), 86 deletions(-) rename src/requirements.txt => requirements.txt (100%) create mode 100644 src/module/utils/bangumi_data.py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index d5c6dc46..564c5440 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -22,7 +22,6 @@ jobs: with: python-version: "3.11" - name: Install dependencies - working-directory: ./src run: | python -m pip install --upgrade pip if [ -f requirements.txt ]; then pip install -r requirements.txt; fi diff --git a/Dockerfile b/Dockerfile index df759319..007948ed 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ ENV TZ=Asia/Shanghai \ WORKDIR /app -COPY src/requirements.txt . +COPY requirements.txt . RUN python3 -m pip install --upgrade pip \ && pip install -r requirements.txt --no-cache-dir diff --git a/src/requirements.txt b/requirements.txt similarity index 100% rename from src/requirements.txt rename to requirements.txt diff --git a/src/module/api.py b/src/module/api.py index 8e617a91..c080d489 100644 --- a/src/module/api.py +++ b/src/module/api.py @@ -50,9 +50,10 @@ def reset_rule(): return api_func.reset_rule() -@router.get("api/v1/removeRule/{bangumi_title}") -def remove_rule(bangumi_title: str): - return api_func.remove_rule(bangumi_title) +@router.get("api/v1/removeRule/{bangumi_id}") +def remove_rule(bangumi_id: str): + bangumi_id = int(bangumi_id) + return api_func.remove_rule(bangumi_id) @router.post("/api/v1/collection", tags=["download"]) diff --git a/src/module/app.py b/src/module/app.py index 0b4aab7a..579d2708 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -3,11 +3,12 @@ import time import logging from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSSLink, VERSION -from module.utils import json_config +from module.utils import load_program_data, save_program_data, json_config from module.core import DownloadClient from module.manager import Renamer, FullSeasonGet from module.rss import RSSAnalyser +from module.models import ProgramData logger = logging.getLogger(__name__) @@ -19,42 +20,35 @@ def reset_log(): os.remove(LOG_PATH) -def load_data_file(): +def load_data_file() -> ProgramData: + empty_data = ProgramData( + rss_link=RSS_LINK, + data_version=settings.data_version, + ) if not os.path.exists(DATA_PATH): - bangumi_data = { - "rss_link": RSS_LINK, - "data_version": settings.data_version, - "bangumi_info": [] - } + program_data = empty_data + save_program_data(DATA_PATH, program_data) logger.info("Building data information...") else: - bangumi_data = json_config.load(DATA_PATH) - if bangumi_data["data_version"] != settings.data_version or bangumi_data["rss_link"] != RSS_LINK: - bangumi_data = { - "rss_link": RSS_LINK, - "data_version": settings.data_version, - "bangumi_info": [] - } + program_data = load_program_data(DATA_PATH) + if program_data.rss_link != RSS_LINK or program_data.data_version != settings.data_version: + program_data = empty_data logger.info("Rebuilding data information...") - return bangumi_data + return program_data -def save_data_file(bangumi_data): - json_config.save(DATA_PATH, bangumi_data) - logger.debug("Saved") - -def main_process(bangumi_data, download_client: DownloadClient): +def main_process(program_data: ProgramData, download_client: DownloadClient): rename = Renamer(download_client) rss_analyser = RSSAnalyser() while True: times = 0 if settings.rss_parser.enable: - rss_analyser.run(bangumi_data["bangumi_info"], download_client) - if settings.bangumi_manage.eps_complete and bangumi_data["bangumi_info"] != []: - FullSeasonGet().eps_complete(bangumi_data["bangumi_info"], download_client) + rss_analyser.run(program_data.bangumi_info, download_client) + if settings.bangumi_manage.eps_complete and program_data.bangumi_info != []: + FullSeasonGet().eps_complete(program_data.bangumi_info, download_client) logger.info("Running....") - save_data_file(bangumi_data) + save_program_data(DATA_PATH, program_data) while times < settings.program.rename_times: if settings.bangumi_manage.enable: rename.rename() diff --git a/src/module/conf/__init__.py b/src/module/conf/__init__.py index 1afbfad9..7911a72d 100644 --- a/src/module/conf/__init__.py +++ b/src/module/conf/__init__.py @@ -1,13 +1,12 @@ from .log import setup_logger, LOG_PATH from .config import settings, VERSION -import re - TMDB_API = "32b19d6a05b512190a056fa4e747cbbc" DATA_PATH = "data/data.json" + class RSSLink(str): def __new__(cls): if "://" not in settings.rss_parser.custom_url: diff --git a/src/module/core/api_func.py b/src/module/core/api_func.py index 1ac3cc06..4374cfe9 100644 --- a/src/module/core/api_func.py +++ b/src/module/core/api_func.py @@ -37,7 +37,7 @@ class APIProcess: if not self._client.authed: self._client.auth() data = self.link_process(link) - self._client.add_rss_feed(link, data.get("official_title")) + self._client.add_rss_feed(link, data.official_title) self._client.set_rule(data, link) return data @@ -49,14 +49,15 @@ class APIProcess: return "Success" @staticmethod - def remove_rule(name): + def remove_rule(_id: int): datas = json_config.load(DATA_PATH)["bangumi_info"] for data in datas: - if re.search(name.lower(), data["title_raw"].lower()): + if data["id"] == _id: datas.remove(data) - json_config.save(DATA_PATH, datas) - return "Success" - return "Not matched" + break + json_config.save(DATA_PATH, datas) + return "Success" + @staticmethod def add_rule(title, season): diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index c9e41650..a1a03e92 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -3,8 +3,8 @@ import logging import os from module.downloader import getClient - from module.conf import settings, RSSLink +from module.models import BangumiData RSS_LINK = RSSLink() @@ -36,8 +36,8 @@ class DownloadClient: prefs = self.client.get_app_prefs() settings.downloader.path = os.path.join(prefs["save_path"], "Bangumi") - def set_rule(self, info: dict, rss_link): - official_name, raw_name, season, group = info["official_title"], info["title_raw"], info["season"], info["group"] + def set_rule(self, info: BangumiData, rss_link): + official_name, raw_name, season, group = info.official_title, info.title_raw, info.season, info.group rule = { "enable": True, "mustContain": raw_name, @@ -76,13 +76,12 @@ class DownloadClient: self.client.rss_add_feed(url=rss_link, item_path=item_path) logger.info("Add RSS Feed successfully.") - def add_rules(self, bangumi_info, rss_link=RSS_LINK): + def add_rules(self, bangumi_info: list[BangumiData], rss_link=RSS_LINK): logger.debug("Start adding rules.") for info in bangumi_info: - if not info["added"]: + if not info.added: self.set_rule(info, rss_link) - info["added"] = True - # logger.info("to rule.") + info.added = True logger.debug("Finished.") def get_torrent_info(self, category="Bangumi"): diff --git a/src/module/manager/eps_complete.py b/src/module/manager/eps_complete.py index 3e9105e4..8e62d5c4 100644 --- a/src/module/manager/eps_complete.py +++ b/src/module/manager/eps_complete.py @@ -6,6 +6,7 @@ from module.conf import settings from module.network import RequestContent from module.core.download_client import DownloadClient +from module.models import BangumiData logger = logging.getLogger(__name__) SEARCH_KEY = ["group", "title_raw", "season_raw", "subtitle", "source", "dpi"] @@ -17,51 +18,55 @@ class FullSeasonGet: pass @staticmethod - def init_eps_complete_search_str(data: dict): - test = [data.get(key).strip() for key in SEARCH_KEY if data.get(key) is not None] + def init_eps_complete_search_str(data: BangumiData): + test = [] + for key in SEARCH_KEY: + data_dict = data.dict() + if data_dict[key] is not None: + test.append(data_dict[key]) search_str_pre = "+".join(test) search_str = re.sub(r"[\W_ ]", "+", search_str_pre) return search_str - def get_season_torrents(self, data: dict): + def get_season_torrents(self, data: BangumiData): keyword = self.init_eps_complete_search_str(data) with RequestContent() as req: torrents = req.get_torrents(f"{CUSTOM_URL}/RSS/Search?searchstr={keyword}") return torrents @staticmethod - def collect_season_torrents(data: dict, torrents): + def collect_season_torrents(data: BangumiData, torrents): downloads = [] for torrent in torrents: download_info = { "url": torrent.torrent_link, "save_path": os.path.join( settings.downloader.path, - data["official_title"], - f"Season {data['season']}") + data.official_title, + f"Season {data.season}") } downloads.append(download_info) return downloads - def download_eps(self, data, download_client: DownloadClient): - logger.info(f"Start collecting {data['official_title']} Season {data['season']}...") + def download_eps(self, data: BangumiData, download_client: DownloadClient): + logger.info(f"Start collecting {data.official_title} Season {data.season}...") torrents = self.get_season_torrents(data) downloads = self.collect_season_torrents(data, torrents) for download in downloads: download_client.add_torrent(download) logger.info("Completed!") - data["eps_collect"] = False + data.eps_collect = False - def eps_complete(self, bangumi_info, download_client: DownloadClient): + def eps_complete(self, bangumi_info: list[BangumiData], download_client: DownloadClient): for data in bangumi_info: - if data["eps_collect"]: + if data.eps_collect: self.download_eps(data, download_client) - def download_collection(self, data, link, download_client: DownloadClient): + def download_collection(self, data: BangumiData, link, download_client: DownloadClient): with RequestContent() as req: torrents = req.get_torrents(link) downloads = self.collect_season_torrents(data, torrents) - logger.info(f"Starting download {data.get('official_title')}") + logger.info(f"Starting download {data.official_title} Season {data.season}...") for download in downloads: download_client.add_torrent(download) logger.info("Completed!") diff --git a/src/module/models/bangumi.py b/src/module/models/bangumi.py index c9a08fd8..2e6eb466 100644 --- a/src/module/models/bangumi.py +++ b/src/module/models/bangumi.py @@ -5,7 +5,7 @@ from dataclasses import dataclass class BangumiData(BaseModel): id: int = Field(..., alias="id", title="番剧ID") official_title: str = Field(..., alias="official_title", title="番剧中文名") - year: int = Field(..., alias="year", title="番剧年份") + year: int | None = Field(None, alias="year", title="番剧年份") title_raw: str = Field(..., alias="title_raw", title="番剧原名") season: int = Field(..., alias="season", title="番剧季度") season_raw: str = Field(..., alias="season_raw", title="番剧季度原名") @@ -19,6 +19,11 @@ class BangumiData(BaseModel): filter: list[str] = Field(..., alias="filter", title="番剧过滤器") +class ProgramData(BaseModel): + rss_link: str = Field(..., alias="rss_link", title="RSS链接") + data_version: float = Field(..., alias="data_version", title="数据版本") + bangumi_info: list[BangumiData] = Field([], alias="bangumi_info", title="番剧信息") + @dataclass class MatchRule: diff --git a/src/module/models/config.py b/src/module/models/config.py index 9f341df4..1690cafe 100644 --- a/src/module/models/config.py +++ b/src/module/models/config.py @@ -57,7 +57,7 @@ class Notification(BaseModel): class Config(BaseModel): - data_version: float = Field(4.0, description="Data version") + data_version: float = Field(5.0, description="Data version") program: Program = Program() downloader: Downloader = Downloader() rss_parser: RSSParser = RSSParser() diff --git a/src/module/parser/title_parser.py b/src/module/parser/title_parser.py index ffd6f724..c79e938d 100644 --- a/src/module/parser/title_parser.py +++ b/src/module/parser/title_parser.py @@ -3,7 +3,7 @@ import logging from .analyser import RawParser, DownloadParser, TMDBMatcher from module.conf import settings -from module.models import SeasonInfo +from module.models import BangumiData logger = logging.getLogger(__name__) LANGUAGE = settings.rss_parser.language @@ -46,7 +46,7 @@ class TitleParser: official_title = official_title if official_title else title return official_title, tmdb_season - def return_dict(self, _raw: str) -> dict: + def return_data(self, _raw: str, _id: int) -> BangumiData: try: episode = self.raw_parser(_raw) title_search = episode.title_zh if episode.title_zh else episode.title_en @@ -56,20 +56,21 @@ class TitleParser: else: official_title = title_search if LANGUAGE == "zh" else title_raw _season = episode.season - data = { - "official_title": official_title, - "title_raw": title_raw, - "season": _season, - "season_raw": episode.season_raw, - "group": episode.group, - "dpi": episode.resolution, - "source": episode.source, - "subtitle": episode.sub, - "added": False, - "eps_collect": True if episode.episode > 1 else False, - "offset": 0, - "filter": settings.rss_parser.filter - } + data = BangumiData( + id=_id, + official_title=official_title, + title_raw=title_raw, + season=_season, + season_raw=episode.season_raw, + group=episode.group, + dpi=episode.resolution, + source=episode.source, + subtitle=episode.sub, + added=False, + eps_collect=True if episode.episode > 1 else False, + offset=0, + filter=settings.rss_parser.filter + ) logger.debug(f"RAW:{_raw} >> {episode.title_en}") return data except Exception as e: diff --git a/src/module/rss/rss_analyser.py b/src/module/rss/rss_analyser.py index 8acc1306..f90ad34e 100644 --- a/src/module/rss/rss_analyser.py +++ b/src/module/rss/rss_analyser.py @@ -2,10 +2,9 @@ import re import logging from module.network import RequestContent from module.parser import TitleParser - from module.conf import RSSLink - from module.core import DownloadClient +from module.models import BangumiData logger = logging.getLogger(__name__) RSS_LINK = RSSLink() @@ -15,35 +14,46 @@ class RSSAnalyser: def __init__(self): self._title_analyser = TitleParser() - def rss_to_datas(self, bangumi_info: list) -> list: + + def find_id(self, bangumi_info: list[BangumiData]) -> int: + _id = 0 + for info in bangumi_info: + if info.id > _id: + _id = info.id + return _id + + def rss_to_datas(self, bangumi_info: list[BangumiData]) -> list[BangumiData]: with RequestContent() as req: rss_torrents = req.get_torrents(RSS_LINK) + # Find largest bangumi id + _id = self.find_id(bangumi_info) for torrent in rss_torrents: raw_title = torrent.name extra_add = True if bangumi_info is not []: - for d in bangumi_info: - if re.search(d["title_raw"], raw_title) is not None: - logger.debug(f"Had added {d['title_raw']} in auto_download rule before") + for info in bangumi_info: + if re.search(info.title_raw, raw_title) is not None: + logger.debug(f"Had added {info.official_title} in auto_download rule before") extra_add = False break if extra_add: - data = self._title_analyser.return_dict(raw_title) - if data is not None and data["official_title"] not in bangumi_info: + _id += 1 + data = self._title_analyser.return_data(raw_title, _id) + if data is not None and data.official_title not in bangumi_info: bangumi_info.append(data) return bangumi_info - def rss_to_data(self, url, filter: bool = True) -> dict: + def rss_to_data(self, url, filter: bool = True) -> BangumiData: with RequestContent() as req: rss_torrents = req.get_torrents(url, filter) for torrent in rss_torrents: try: - data = self._title_analyser.return_dict(torrent.name) + data = self._title_analyser.return_data(torrent.name, 9999) return data except Exception as e: logger.debug(e) - def run(self, bangumi_info: list, download_client: DownloadClient): + def run(self, bangumi_info: list[BangumiData], download_client: DownloadClient): logger.info("Start collecting RSS info.") try: self.rss_to_datas(bangumi_info) diff --git a/src/module/utils/__init__.py b/src/module/utils/__init__.py index e69de29b..edd834d9 100644 --- a/src/module/utils/__init__.py +++ b/src/module/utils/__init__.py @@ -0,0 +1 @@ +from .bangumi_data import load_program_data, save_program_data \ No newline at end of file diff --git a/src/module/utils/bangumi_data.py b/src/module/utils/bangumi_data.py new file mode 100644 index 00000000..e01a6d14 --- /dev/null +++ b/src/module/utils/bangumi_data.py @@ -0,0 +1,26 @@ +import logging + +from .json_config import save, load +from module.models import ProgramData + +logger = logging.getLogger(__name__) + + +def load_program_data(path: str) -> ProgramData: + data = load(path) + try: + data = ProgramData(**data) + logger.info("Data file loaded") + except TypeError: + logger.warning("Data file is not compatible with the current version, rebuilding...") + data = ProgramData( + rss_link=data["rss_link"], + data_version=data["data_version"], + bangumi_info=[] + ) + return data + + +def save_program_data(path: str, data: ProgramData): + save(path, data.dict()) + logger.debug("Data file saved") From 8e69506e77b730374ae57ebb1a410e54e7ca8f80 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 18:32:42 +0800 Subject: [PATCH 35/40] Fix env to config.py --- src/module/conf/config.py | 9 +++++++-- src/module/conf/const.py | 21 ++++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/module/conf/config.py b/src/module/conf/config.py index c58e9ef5..683067e4 100644 --- a/src/module/conf/config.py +++ b/src/module/conf/config.py @@ -47,8 +47,13 @@ def env_to_config() -> Setting: for key, section in ENV_TO_ATTR.items(): for env, attr in section.items(): if env in os.environ: - attr_name = attr[0] if isinstance(attr, tuple) else attr - _settings[key][attr_name] = _val_from_env(env, attr) + if isinstance(attr, list): + for _attr in attr: + attr_name = _attr[0] if isinstance(_attr, tuple) else _attr + _settings[key][attr_name] = _val_from_env(env, _attr) + else: + attr_name = attr[0] if isinstance(attr, tuple) else attr + _settings[key][attr_name] = _val_from_env(env, attr) return Setting(**_settings) diff --git a/src/module/conf/const.py b/src/module/conf/const.py index 39516187..571db099 100644 --- a/src/module/conf/const.py +++ b/src/module/conf/const.py @@ -67,7 +67,10 @@ ENV_TO_ATTR = { }, "rss_parser": { "AB_RSS_COLLECTOR": ("enable", lambda e: e.lower() in ("true", "1", "t")), - "AB_RSS": ("token", lambda e: parse_qs(urlparse(e).query).get("token", [None])[0]), + "AB_RSS": [ + ("token", lambda e: parse_qs(urlparse(e).query).get("token", [None])[0]), + ("custom_url", lambda e: urlparse(e).netloc), + ], "AB_NOT_CONTAIN": ("filter", lambda e: e.split("|")), "AB_LANGUAGE": "language", "AB_ENABLE_TMDB": ("enable_tmdb", lambda e: e.lower() in ("true", "1", "t")), @@ -82,6 +85,22 @@ ENV_TO_ATTR = { "log": { "AB_DEBUG_MODE": ("debug_enable", lambda e: e.lower() in ("true", "1", "t")), }, + "proxy": { + "AB_HTTP_PROXY": [ + ("enable", lambda e: True), + ("type", lambda e: "http"), + ("host", lambda e: e.split(":")[0]), + ("port", lambda e: int(e.split(":")[1])), + ], + "AB_SOCKS": [ + ("enable", lambda e: True), + ("type", lambda e: "socks"), + ("host", lambda e: e.split(",")[0]), + ("port", lambda e: int(e.split(",")[1])), + ("username", lambda e: e.split(",")[2]), + ("password", lambda e: e.split(",")[3]), + ], + }, } From 99ff764cb7755be8851e128958bbdb0c179c7571 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 19:10:51 +0800 Subject: [PATCH 36/40] Fix custom_url caused bug in eps_complete.py --- src/module/manager/eps_complete.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/module/manager/eps_complete.py b/src/module/manager/eps_complete.py index 8e62d5c4..8bff2fa8 100644 --- a/src/module/manager/eps_complete.py +++ b/src/module/manager/eps_complete.py @@ -11,6 +11,10 @@ from module.models import BangumiData logger = logging.getLogger(__name__) SEARCH_KEY = ["group", "title_raw", "season_raw", "subtitle", "source", "dpi"] CUSTOM_URL = "https://mikanani.me" if settings.rss_parser.custom_url == "" else settings.rss_parser.custom_url +if "://" not in CUSTOM_URL: + if re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", CUSTOM_URL): + CUSTOM_URL = f"http://{CUSTOM_URL}" + CUSTOM_URL = f"https://{CUSTOM_URL}" class FullSeasonGet: From 00c93599ee1f7b5aaaad9804a9caea9f56aa9bab Mon Sep 17 00:00:00 2001 From: DDSRem <1448139087@qq.com> Date: Wed, 26 Apr 2023 20:12:46 +0800 Subject: [PATCH 37/40] feat: Rewrite docker --- Dockerfile | 80 ++++++++++++------- docker/etc/cont-init.d/010-old-compatible | 14 ++++ docker/etc/cont-init.d/020-fixuser | 13 +++ docker/etc/services.d/auto_bangumi/finish | 4 + .../services.d/auto_bangumi/notification-fd | 1 + docker/etc/services.d/auto_bangumi/run | 16 ++++ src/run.sh | 10 --- 7 files changed, 100 insertions(+), 38 deletions(-) create mode 100644 docker/etc/cont-init.d/010-old-compatible create mode 100644 docker/etc/cont-init.d/020-fixuser create mode 100644 docker/etc/services.d/auto_bangumi/finish create mode 100644 docker/etc/services.d/auto_bangumi/notification-fd create mode 100644 docker/etc/services.d/auto_bangumi/run delete mode 100755 src/run.sh diff --git a/Dockerfile b/Dockerfile index 007948ed..cc750ece 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,41 +1,65 @@ # syntax=docker/dockerfile:1 -FROM python:3.11-alpine -ENV TZ=Asia/Shanghai \ +FROM python:3.11-alpine AS Builder +WORKDIR /app +COPY requirements.txt . +RUN apk add --no-cache --virtual=build-dependencies \ + libxml2-dev \ + libxslt-dev \ + gcc \ + g++ \ + linux-headers \ + build-base && \ + python3 -m pip install --upgrade pip && \ + pip install cython && \ + pip install --no-cache-dir -r requirements.txt && \ + apk del --purge \ + build-dependencies && \ + rm -rf \ + /root/.cache \ + /tmp/* + +FROM scratch AS APP + +ENV S6_SERVICES_GRACETIME=30000 \ + S6_KILL_GRACETIME=60000 \ + S6_CMD_WAIT_FOR_SERVICES_MAXTIME=0 \ + S6_SYNC_DISKS=1 \ + TERM="xterm" \ + HOME="/ab" \ + LANG="C.UTF-8" \ + TZ=Asia/Shanghai \ PUID=1000 \ PGID=1000 \ UMASK=022 +COPY --from=Builder / / + WORKDIR /app -COPY requirements.txt . - -RUN python3 -m pip install --upgrade pip \ - && pip install -r requirements.txt --no-cache-dir +RUN apk add --no-cache \ + curl \ + wget \ + jq \ + shadow \ + s6-overlay \ + bash && \ + # Download WebUI + wget "https://github.com/Rewrite0/Auto_Bangumi_WebUI/releases/latest/download/dist.zip" -O /tmp/dist.zip && \ + unzip -q -d /tmp /tmp/dist.zip && \ + mv /tmp/dist /app/templates && \ + # Add user + mkdir /ab && \ + addgroup -S ab -g 911 && \ + adduser -S ab -G ab -h /ab -s /bin/bash -u 911 && \ + rm -rf \ + /root/.cache \ + /tmp/* COPY --chmod=755 src/. . +COPY --chmod=755 ./docker / -RUN apk add --no-cache \ - curl \ - shadow \ - su-exec \ - bash - -# Download WebUI -RUN wget "https://github.com/Rewrite0/Auto_Bangumi_WebUI/releases/download/$(curl 'https://api.github.com/repos/Rewrite0/Auto_Bangumi_WebUI/releases/latest' | grep "tag_name" | head -n 1 | awk -F ":" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')/dist.zip" && \ - unzip dist.zip && \ - mv dist templates - -RUN addgroup -S auto_bangumi -g 1000 && \ - adduser -S auto_bangumi -G auto_bangumi -h /home/auto_bangumi -u 1000 && \ - usermod -s /bin/bash auto_bangumi && \ - mkdir -p "config" && \ - mkdir -p "data" && \ - chmod a+x \ - run.sh +ENTRYPOINT [ "/init" ] EXPOSE 7892 - -VOLUME [ "/app/config" , "/app/data"] - -CMD ["sh", "run.sh"] +VOLUME [ "/app/config" , "/app/data" ] diff --git a/docker/etc/cont-init.d/010-old-compatible b/docker/etc/cont-init.d/010-old-compatible new file mode 100644 index 00000000..f6136488 --- /dev/null +++ b/docker/etc/cont-init.d/010-old-compatible @@ -0,0 +1,14 @@ +#!/usr/bin/with-contenv bash +# shellcheck shell=bash + +function __old_compatible { + + umask ${UMASK} + + if [ -f /config/bangumi.json ]; then + mv /config/bangumi.json /app/data/bangumi.json + fi + +} + +__old_compatible 2>&1 | sed "s#^#cont-init: info: $(realpath $0): &#g" \ No newline at end of file diff --git a/docker/etc/cont-init.d/020-fixuser b/docker/etc/cont-init.d/020-fixuser new file mode 100644 index 00000000..51856377 --- /dev/null +++ b/docker/etc/cont-init.d/020-fixuser @@ -0,0 +1,13 @@ +#!/usr/bin/with-contenv bash +# shellcheck shell=bash + +function __fixuser { + + groupmod -o -g "${PGID}" ab + usermod -o -u "${PUID}" ab + + chown ab:ab -R /app + +} + +__fixuser 2>&1 | sed "s#^#cont-init: info: $(realpath $0): &#g" \ No newline at end of file diff --git a/docker/etc/services.d/auto_bangumi/finish b/docker/etc/services.d/auto_bangumi/finish new file mode 100644 index 00000000..b1ccd97a --- /dev/null +++ b/docker/etc/services.d/auto_bangumi/finish @@ -0,0 +1,4 @@ +#!/usr/bin/with-contenv bash +# shellcheck shell=bash + +pkill -f 'python3 main.py' \ No newline at end of file diff --git a/docker/etc/services.d/auto_bangumi/notification-fd b/docker/etc/services.d/auto_bangumi/notification-fd new file mode 100644 index 00000000..e440e5c8 --- /dev/null +++ b/docker/etc/services.d/auto_bangumi/notification-fd @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/docker/etc/services.d/auto_bangumi/run b/docker/etc/services.d/auto_bangumi/run new file mode 100644 index 00000000..ea0d1347 --- /dev/null +++ b/docker/etc/services.d/auto_bangumi/run @@ -0,0 +1,16 @@ +#!/usr/bin/with-contenv bash +# shellcheck shell=bash + +umask ${UMASK} + +if [ -f /app/config/config.json ]; then + AB_PORT=$(jq '.program.webui_port' /app/config/config.json) +elif [ -f /app/config/config_dev.json ]; then + AB_PORT=$(jq '.program.webui_port' /app/config/config_dev.json) +else + AB_PORT=7892 +fi + +exec \ + s6-notifyoncheck -d -n 300 -w 1000 -c "nc -z localhost ${AB_PORT}" \ + cd /app s6-setuidgid ab python3 main.py \ No newline at end of file diff --git a/src/run.sh b/src/run.sh deleted file mode 100755 index bf18b90f..00000000 --- a/src/run.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# Check old version -if [ -f /config/bangumi.json ]; then - mv /config/bangumi.json /app/data/bangumi.json -fi - - -umask ${UMASK} -python3 main.py From 585399aa941aeef0f24dcd096124284b37438b9c Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 20:18:00 +0800 Subject: [PATCH 38/40] Fix custom_url caused bug in eps_complete.py --- src/main.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main.py b/src/main.py index c951d767..0515485a 100644 --- a/src/main.py +++ b/src/main.py @@ -31,6 +31,7 @@ async def restart(): logger.info("Restarted") return {"status": "success"} + @router.get("/api/v1/stop", tags=["program"]) async def stop(): global main_process @@ -54,6 +55,15 @@ async def start(): return {"status": "success"} +@router.get("/api/v1/status", tags=["program"]) +async def status(): + global main_process + if main_process.is_alive(): + return True + else: + return False + + if VERSION != "DEV_VERSION": router.mount("/assets", StaticFiles(directory="templates/assets"), name="assets") templates = Jinja2Templates(directory="templates") From cfe1fba9c720fc9dd450f95cf59626b742e3f7b0 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 21:36:50 +0800 Subject: [PATCH 39/40] Fix rss token can not be hot changed --- src/module/app.py | 23 +++++++++++------------ src/module/conf/__init__.py | 1 - src/module/core/download_client.py | 11 +++++------ src/module/rss/rss_analyser.py | 17 ++++++++--------- src/module/utils/bangumi_data.py | 3 ++- 5 files changed, 26 insertions(+), 29 deletions(-) diff --git a/src/module/app.py b/src/module/app.py index 579d2708..5eb02247 100644 --- a/src/module/app.py +++ b/src/module/app.py @@ -3,7 +3,7 @@ import time import logging from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSSLink, VERSION -from module.utils import load_program_data, save_program_data, json_config +from module.utils import load_program_data, save_program_data from module.core import DownloadClient from module.manager import Renamer, FullSeasonGet @@ -12,7 +12,6 @@ from module.models import ProgramData logger = logging.getLogger(__name__) -RSS_LINK = RSSLink() def reset_log(): @@ -20,9 +19,9 @@ def reset_log(): os.remove(LOG_PATH) -def load_data_file() -> ProgramData: +def load_data_file(rss_link: str) -> ProgramData: empty_data = ProgramData( - rss_link=RSS_LINK, + rss_link=rss_link, data_version=settings.data_version, ) if not os.path.exists(DATA_PATH): @@ -31,20 +30,19 @@ def load_data_file() -> ProgramData: logger.info("Building data information...") else: program_data = load_program_data(DATA_PATH) - if program_data.rss_link != RSS_LINK or program_data.data_version != settings.data_version: + if program_data.rss_link != rss_link or program_data.data_version != settings.data_version: program_data = empty_data logger.info("Rebuilding data information...") return program_data - def main_process(program_data: ProgramData, download_client: DownloadClient): rename = Renamer(download_client) rss_analyser = RSSAnalyser() while True: times = 0 if settings.rss_parser.enable: - rss_analyser.run(program_data.bangumi_info, download_client) + rss_analyser.run(program_data.bangumi_info, download_client, program_data.rss_link) if settings.bangumi_manage.eps_complete and program_data.bangumi_info != []: FullSeasonGet().eps_complete(program_data.bangumi_info, download_client) logger.info("Running....") @@ -68,16 +66,17 @@ def show_info(): def run(): # 初始化 settings.reload() + rss_link = RSSLink() reset_log() setup_logger() show_info() - download_client = DownloadClient() - download_client.auth() - download_client.init_downloader() if settings.rss_parser.token in ["", "token", None]: logger.error("Please set your RSS token in config file.") exit(1) - download_client.rss_feed() - bangumi_data = load_data_file() + download_client = DownloadClient() + download_client.auth() + download_client.init_downloader() + download_client.rss_feed(rss_link) + bangumi_data = load_data_file(rss_link) # 主程序循环 main_process(bangumi_data, download_client) diff --git a/src/module/conf/__init__.py b/src/module/conf/__init__.py index 7911a72d..ffc8702d 100644 --- a/src/module/conf/__init__.py +++ b/src/module/conf/__init__.py @@ -6,7 +6,6 @@ TMDB_API = "32b19d6a05b512190a056fa4e747cbbc" DATA_PATH = "data/data.json" - class RSSLink(str): def __new__(cls): if "://" not in settings.rss_parser.custom_url: diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index a1a03e92..ef4d3ce1 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -3,10 +3,9 @@ import logging import os from module.downloader import getClient -from module.conf import settings, RSSLink +from module.conf import settings from module.models import BangumiData -RSS_LINK = RSSLink() logger = logging.getLogger(__name__) @@ -63,20 +62,20 @@ class DownloadClient: self.client.rss_set_rule(rule_name=f"{rule_name} S{season}", rule_def=rule) logger.info(f"Add {official_name} Season {season}") - def rss_feed(self): + def rss_feed(self, rss_link): # TODO: 定时刷新 RSS - if self.client.get_rss_info() == RSS_LINK: + if self.client.get_rss_info() == rss_link: logger.info("RSS Already exists.") else: logger.info("No feed exists, start adding feed.") - self.client.rss_add_feed(url=RSS_LINK, item_path="Mikan_RSS") + self.client.rss_add_feed(url=rss_link, item_path="Mikan_RSS") logger.info("Add RSS Feed successfully.") def add_collection_feed(self, rss_link, item_path): self.client.rss_add_feed(url=rss_link, item_path=item_path) logger.info("Add RSS Feed successfully.") - def add_rules(self, bangumi_info: list[BangumiData], rss_link=RSS_LINK): + def add_rules(self, bangumi_info: list[BangumiData], rss_link: str): logger.debug("Start adding rules.") for info in bangumi_info: if not info.added: diff --git a/src/module/rss/rss_analyser.py b/src/module/rss/rss_analyser.py index f90ad34e..b2e8e7c7 100644 --- a/src/module/rss/rss_analyser.py +++ b/src/module/rss/rss_analyser.py @@ -1,30 +1,29 @@ import re import logging + from module.network import RequestContent from module.parser import TitleParser -from module.conf import RSSLink from module.core import DownloadClient from module.models import BangumiData logger = logging.getLogger(__name__) -RSS_LINK = RSSLink() class RSSAnalyser: def __init__(self): self._title_analyser = TitleParser() - - def find_id(self, bangumi_info: list[BangumiData]) -> int: + @staticmethod + def find_id(bangumi_info: list[BangumiData]) -> int: _id = 0 for info in bangumi_info: if info.id > _id: _id = info.id return _id - def rss_to_datas(self, bangumi_info: list[BangumiData]) -> list[BangumiData]: + def rss_to_datas(self, bangumi_info: list[BangumiData], rss_link: str) -> list[BangumiData]: with RequestContent() as req: - rss_torrents = req.get_torrents(RSS_LINK) + rss_torrents = req.get_torrents(rss_link) # Find largest bangumi id _id = self.find_id(bangumi_info) for torrent in rss_torrents: @@ -53,11 +52,11 @@ class RSSAnalyser: except Exception as e: logger.debug(e) - def run(self, bangumi_info: list[BangumiData], download_client: DownloadClient): + def run(self, bangumi_info: list[BangumiData], download_client: DownloadClient, rss_link: str): logger.info("Start collecting RSS info.") try: - self.rss_to_datas(bangumi_info) - download_client.add_rules(bangumi_info, rss_link=RSS_LINK) + self.rss_to_datas(bangumi_info, rss_link) + download_client.add_rules(bangumi_info, rss_link=rss_link) except Exception as e: logger.debug(e) logger.info("Finished") diff --git a/src/module/utils/bangumi_data.py b/src/module/utils/bangumi_data.py index e01a6d14..248e6d93 100644 --- a/src/module/utils/bangumi_data.py +++ b/src/module/utils/bangumi_data.py @@ -11,8 +11,9 @@ def load_program_data(path: str) -> ProgramData: try: data = ProgramData(**data) logger.info("Data file loaded") - except TypeError: + except Exception as e: logger.warning("Data file is not compatible with the current version, rebuilding...") + logger.debug(e) data = ProgramData( rss_link=data["rss_link"], data_version=data["data_version"], From 6e4be5345b3499abda4842242360bccea5655f95 Mon Sep 17 00:00:00 2001 From: EstrellaXD Date: Wed, 26 Apr 2023 22:34:09 +0800 Subject: [PATCH 40/40] Fix minor bug --- .dockerignore | 8 +++++++- src/main.py | 9 +++++---- src/module/core/download_client.py | 5 +++++ src/module/downloader/qb_downloader.py | 3 +++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/.dockerignore b/.dockerignore index 6713638d..a1784928 100644 --- a/.dockerignore +++ b/.dockerignore @@ -30,4 +30,10 @@ config/bangumi.json/config/bangumi.json /LICENSE /README.md /setup.py -dist.zip \ No newline at end of file +dist.zip +data +config +.pytest_cache +test +.env +test.py \ No newline at end of file diff --git a/src/main.py b/src/main.py index 0515485a..b5e5d620 100644 --- a/src/main.py +++ b/src/main.py @@ -22,10 +22,11 @@ main_process = multiprocessing.Process(target=app.run) @router.get("/api/v1/restart", tags=["program"]) async def restart(): global main_process - if not main_process.is_alive(): - return {"status": "failed", "reason": "Already stopped"} - logger.info("Restarting...") - os.kill(main_process.pid, signal.SIGTERM) + if main_process.is_alive(): + os.kill(main_process.pid, signal.SIGTERM) + logger.info("Restarting...") + else: + logger.info("Starting...") main_process = multiprocessing.Process(target=app.run) main_process.start() logger.info("Restarted") diff --git a/src/module/core/download_client.py b/src/module/core/download_client.py index ef4d3ce1..7f89bdf7 100644 --- a/src/module/core/download_client.py +++ b/src/module/core/download_client.py @@ -31,6 +31,11 @@ class DownloadClient: "rss_refresh_interval": 30, } self.client.prefs_init(prefs=prefs) + try: + self.client.add_category("BangumiCollection") + except Exception as e: + logger.warning("Cannot add new category, maybe already exists.") + logger.debug(e) if settings.downloader.path == "": prefs = self.client.get_app_prefs() settings.downloader.path = os.path.join(prefs["save_path"], "Bangumi") diff --git a/src/module/downloader/qb_downloader.py b/src/module/downloader/qb_downloader.py index b2b57c1f..dc52ec18 100644 --- a/src/module/downloader/qb_downloader.py +++ b/src/module/downloader/qb_downloader.py @@ -42,6 +42,9 @@ class QbDownloader: def get_app_prefs(self): return self._client.app_preferences() + def add_category(self, category): + return self._client.torrents_createCategory(name=category) + @qb_connect_failed_wait def torrents_info(self, status_filter, category): return self._client.torrents_info(status_filter, category)