Merge branch '3.1-dev-up' into pwa

This commit is contained in:
Rewrite0
2023-08-12 23:22:25 +08:00
19 changed files with 79 additions and 54 deletions

View File

@@ -14,7 +14,8 @@
- 增加手动刷新 API,可以手动刷新 RSS 订阅。
- 新增 RSS 订阅管理 API。
- 新增 `Search Engine`模块,可以通过关键词搜索种子并解析成收集或者订阅任务。
- 插件化的搜索引擎,可以通过插件的方式添加新的搜索目标,目前支持 `mikan` 和 `dmhy`。
- 插件化的搜索引擎,可以通过插件的方式添加新的搜索目标,目前支持 `mikan`、`dmhy` 和 `nyaa`
- 新增对字幕组的特异性规则,可以针对不同的字幕组进行单独设置。
- 新增 IPv6 监听支持,需要在环境变量中设置 `IPV6=1`。
- API 新增批量操作,可以批量管理规则和 RSS 订阅。

View File

@@ -1,7 +1,7 @@
from fastapi import APIRouter, Depends
from module.manager import SeasonCollector
from module.models import Bangumi
from module.models import Bangumi, RSSItem
from module.models.api import RssLink
from module.rss import RSSAnalyser
from module.security.api import get_current_user, UNAUTHORIZED
@@ -11,10 +11,10 @@ analyser = RSSAnalyser()
@router.post("/analysis")
async def analysis(link: RssLink, current_user=Depends(get_current_user)):
async def analysis(rss: RSSItem, current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
data = analyser.link_to_data(link.rss_link)
data = analyser.link_to_data(rss)
if data:
return data
else:

View File

@@ -2,9 +2,10 @@ import logging
import os
import signal
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException
from module.core import Program
from module.conf import VERSION
from module.security.api import get_current_user, UNAUTHORIZED
logger = logging.getLogger(__name__)
@@ -82,8 +83,8 @@ async def check_downloader_status(current_user=Depends(get_current_user)):
return program.check_downloader()
@router.get("/check/rss", tags=["check"])
async def check_rss_status(current_user=Depends(get_current_user)):
@router.get("/check/version", tags=["check"])
async def check_version(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
return program.check_analyser()
return VERSION

View File

@@ -1,7 +1,6 @@
from typing import Optional
from fastapi import APIRouter, Depends, status
from fastapi.responses import JSONResponse
from fastapi import APIRouter, Depends
from .response import u_response
@@ -23,13 +22,11 @@ async def get_rss(current_user=Depends(get_current_user)):
@router.post("/add")
async def add_rss(
url: str, name: Optional[str], combine: bool, current_user=Depends(get_current_user)
):
async def add_rss(rss: RSSItem, current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
with RSSEngine() as engine:
result = engine.add_rss(url, name, combine)
result = engine.add_rss(rss.url, rss.item_path, rss.combine)
return u_response(result)
@@ -65,3 +62,11 @@ async def refresh_rss(rss_id: int, current_user=Depends(get_current_user)):
raise UNAUTHORIZED
with RSSEngine() as engine, DownloadClient() as client:
response = engine.refresh_rss(client, rss_id)
@router.get("/torrent/{rss_id}")
async def get_torrent(rss_id: int, current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
with RSSEngine() as engine:
return engine.get_rss_torrents(rss_id)

View File

@@ -32,19 +32,6 @@ class Checker:
else:
return False
@staticmethod
def check_torrents() -> bool:
with RequestContent() as req:
try:
torrents = req.get_torrents(settings.rss_link, retry=2)
if torrents:
return True
except AttributeError:
link = f"https://mikanani.me/RSS/MyBangumi?token={settings.rss_parser.token}"
if req.get_torrents(link):
return True
return False
@staticmethod
def check_first_run() -> bool:
if settings.dict() == Config().dict():

View File

@@ -79,5 +79,9 @@ class Settings(Config):
else:
return os.environ[env]
@property
def group_rules(self):
return self.__dict__["group_rules"]
settings = Settings()

View File

@@ -31,12 +31,6 @@ class ProgramStatus(Checker):
self._downloader_status = self.check_downloader()
return self._downloader_status
@property
def torrents_status(self):
if not self._torrents_status:
self._torrents_status = self.check_torrents()
return self._torrents_status
@property
def enable_rss(self):
return self.check_analyser()

View File

@@ -19,8 +19,6 @@ class RSSThread(ProgramStatus):
self.analyser = RSSAnalyser()
def rss_loop(self):
with DownloadClient() as client:
client.init_downloader()
while not self.stop_event.is_set():
with DownloadClient() as client, RSSEngine() as engine:
# Analyse RSS

View File

@@ -44,6 +44,9 @@ class TorrentDatabase:
def search_all(self) -> list[Torrent]:
return self.session.exec(select(Torrent)).all()
def search_rss(self, rss_id: int) -> list[Torrent]:
return self.session.exec(select(Torrent).where(Torrent.rss_id == rss_id)).all()
def check_new(self, torrents_list: list[Torrent]) -> list[Torrent]:
new_torrents = []
old_torrents = self.search_all()

View File

@@ -82,9 +82,10 @@ class QbDownloader:
status_filter=status_filter, category=category, tag=tag
)
def torrents_add(self, torrent_files, save_path, category):
def add_torrents(self, torrent_urls, torrent_files, save_path, category):
resp = self._client.torrents_add(
is_paused=False,
urls=torrent_urls,
torrent_files=torrent_files,
save_path=save_path,
category=category,

View File

@@ -119,10 +119,21 @@ class DownloadClient(TorrentPath):
bangumi.save_path = self._gen_save_path(bangumi)
with RequestContent() as req:
if isinstance(torrent, list):
torrent_file = [req.get_content(t.url) for t in torrent]
if "magnet" in torrent[0].url:
torrent_url = [t.url for t in torrent]
torrent_file = None
else:
torrent_file = [req.get_content(t.url) for t in torrent]
torrent_url = None
else:
torrent_file = req.get_content(torrent.url)
if self.client.torrents_add(
if "magnet" in torrent.url:
torrent_url = torrent.url
torrent_file = None
else:
torrent_file = req.get_content(torrent.url)
torrent_url = None
if self.client.add_torrents(
torrent_urls=torrent_url,
torrent_files=torrent_file,
save_path=bangumi.save_path,
category="Bangumi",
@@ -130,7 +141,7 @@ class DownloadClient(TorrentPath):
logger.debug(f"[Downloader] Add torrent: {bangumi.official_title}")
return True
else:
logger.error(f"[Downloader] Add torrent failed: {bangumi.official_title}")
logger.debug(f"[Downloader] Torrent added before: {bangumi.official_title}")
return False
def move_torrent(self, hashes, location):

View File

@@ -4,7 +4,7 @@ from typing import Optional
class RSSItem(SQLModel, table=True):
id: int = Field(default=None, primary_key=True, alias="id")
item_path: str = Field("example path", alias="item_path")
item_path: Optional[str] = Field(None, alias="item_path")
url: str = Field("https://mikanani.me", alias="url")
combine: bool = Field(True, alias="combine")
parser: str = Field("mikan", alias="parser")

View File

@@ -14,7 +14,7 @@ logger = logging.getLogger(__name__)
class RSSAnalyser(TitleParser):
def official_title_parser(self, bangumi: Bangumi, rss: RSSItem, torrent: Torrent):
if rss.parser == "mikan":
bangumi.official_title, bangumi.poster_link = self.mikan_parser(
bangumi.poster_link, bangumi.official_title = self.mikan_parser(
torrent.homepage
)
elif rss.parser == "tmdb":
@@ -55,6 +55,7 @@ class RSSAnalyser(TitleParser):
bangumi = self.raw_parser(raw=torrent.name)
if bangumi:
self.official_title_parser(bangumi=bangumi, rss=rss, torrent=torrent)
bangumi.rss_link = rss.url
return bangumi
def rss_to_data(

View File

@@ -28,6 +28,13 @@ class RSSEngine(Database):
def get_combine_rss(self) -> list[RSSItem]:
return self.rss.get_combine()
def get_rss_torrents(self, rss_id: int) -> list[Torrent]:
rss = self.rss.search_id(rss_id)
if rss:
return self.torrent.search_rss(rss_id)
else:
return []
def add_rss(self, rss_link: str, name: str | None = None, combine: bool = True):
if not name:
with RequestContent() as req:
@@ -79,6 +86,6 @@ class RSSEngine(Database):
if matched_data:
if client.add_torrent(torrent, matched_data):
logger.debug(f"[Engine] Add torrent {torrent.name} to client")
torrent.downloaded = True
torrent.downloaded = True
# Add all torrents to database
self.torrent.add_all(new_torrents)

View File

@@ -1,8 +1,14 @@
from .mikan import mikan_url
from .nyaa import nyaa_url
from .dmhy import dmhy_url
def search_url(site: str, keywords: list[str]):
if site == "mikan":
return mikan_url(keywords)
elif site == "nyaa":
return nyaa_url(keywords)
elif site == "dmhy":
return dmhy_url(keywords)
else:
raise NotImplementedError(f"site {site} is not supported")

View File

@@ -0,0 +1,8 @@
import re
def dmhy_url(keywords: list[str]):
keyword = "+".join(keywords)
search_str = re.sub(r"[\W_ ]", "+", keyword)
url = f"http://dmhy.org/topics/rss/rss.xml?keyword={search_str}"
return url

View File

@@ -1,12 +1,8 @@
import re
from module.conf import settings
def mikan_url(keywords: list[str]):
keyword = "+".join(keywords)
search_str = re.sub(r"[\W_ ]", "+", keyword)
url = f"{settings.rss_parser.custom_url}/RSS/Search?searchstr={search_str}"
if "://" not in url:
url = f"https://{url}"
url = f"https://mikanani.me/RSS/Search?searchstr={search_str}"
return url

View File

@@ -0,0 +1,8 @@
import re
def nyaa_url(keywords: list[str]):
keyword = "+".join(keywords)
search_str = re.sub(r"[\W_ ]", "+", keyword)
url = f"https://nyaa.si/?page=rss&q={search_str}&c=0_0&f=0"
return url

View File

@@ -10,12 +10,6 @@ def start_up():
with RSSEngine() as engine:
engine.create_table()
engine.user.add_default_user()
main_rss = engine.rss.search_id(1)
if not main_rss:
engine.add_rss(settings.rss_link, name="Mikan RSS", combine=True)
elif main_rss.url != settings.rss_link:
main_rss.url = settings.rss_link
engine.rss.update(1, main_rss)
def first_run():