Merge pull request #201 from EstrellaXD/2.6.0-dev

2.6.0
This commit is contained in:
Estrella Pan
2023-04-26 22:45:42 +08:00
committed by GitHub
47 changed files with 1028 additions and 485 deletions

View File

@@ -30,4 +30,10 @@ config/bangumi.json/config/bangumi.json
/LICENSE
/README.md
/setup.py
dist.zip
dist.zip
data
config
.pytest_cache
test
.env
test.py

44
.github/release-drafter.yml vendored Normal file
View File

@@ -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

View File

@@ -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
@@ -35,6 +35,5 @@ jobs:
push: true
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

View File

@@ -2,6 +2,8 @@ name: Build(Docker)
on:
push:
branches:
- main
tags:
- '\d+\.\d+\.\d+'
pull_request:
@@ -41,6 +43,5 @@ jobs:
push: true
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 }}

21
.github/workflows/release-drafter.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: Release Drafter
on:
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 }}

View File

@@ -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

View File

@@ -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 src/requirements.txt .
RUN python3 -m pip install --upgrade pip \
&& pip install -r requirements.txt --no-cache-dir
COPY --chmod=755 src/. /app/.
RUN apk add --no-cache \
curl \
shadow \
su-exec \
bash
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/*
# 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
COPY --chmod=755 src/. .
COPY --chmod=755 ./docker /
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" ]

View File

@@ -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"

View File

@@ -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"

View File

@@ -0,0 +1,4 @@
#!/usr/bin/with-contenv bash
# shellcheck shell=bash
pkill -f 'python3 main.py'

View File

@@ -0,0 +1 @@
3

View File

@@ -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

View File

@@ -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:

View File

@@ -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
@@ -27,23 +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
- '7892:7892'
dns:
- 8.8.8.8
- 223.5.5.5
@@ -57,5 +50,3 @@ networks:
volumes:
qb_config:
external: false
auto_bangumi:
external: false

View File

@@ -19,3 +19,4 @@ urllib3
uvicorn
attrdict
jinja2
python-dotenv

8
src/icon Normal file
View File

@@ -0,0 +1,8 @@
_ ____ _
/\ | | | _ \ (_)
/ \ _ _| |_ ___ | |_) | __ _ _ __ __ _ _ _ _ __ ___ _
/ /\ \| | | | __/ _ \| _ < / _` | '_ \ / _` | | | | '_ ` _ \| |
/ ____ \ |_| | || (_) | |_) | (_| | | | | (_| | |_| | | | | | | |
/_/ \_\__,_|\__\___/|____/ \__,_|_| |_|\__, |\__,_|_| |_| |_|_|
__/ |
|___/

View File

@@ -1,17 +1,88 @@
from module import app
from module import api
import os
import signal
import logging
import uvicorn
import multiprocessing
if __name__ == "__main__":
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()
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, settings
logger = logging.getLogger(__name__)
main_process = multiprocessing.Process(target=app.run)
@router.get("/api/v1/restart", tags=["program"])
async def restart():
global main_process
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")
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 = multiprocessing.Process(target=app.run)
main_process.start()
logger.info("Started")
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")
# 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__":
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, log_config=log_config)

View File

@@ -0,0 +1 @@

View File

@@ -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

View File

@@ -1,70 +1,115 @@
import uvicorn
from uvicorn.config import LOGGING_CONFIG
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
import logging
import os
from .core import APIProcess
from .conf import settings, DATA_PATH, LOG_PATH
from .utils import json_config
from .models.api import *
from fastapi import FastAPI
from fastapi.responses import FileResponse, Response
logger = logging.getLogger(__name__)
from module.core import APIProcess
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
app = FastAPI()
router = FastAPI()
api_func = APIProcess()
app.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)
@app.get("/", response_class=HTMLResponse)
def index(request: Request):
context = {"request": request}
return templates.TemplateResponse("index.html", context)
@router.get("/api/v1/data", tags=["info"])
async def get_data():
try:
data = json_config.load(DATA_PATH)
return data
except FileNotFoundError:
return {
"rss_link": "",
"data_version": settings.data_version,
"bangumi_info": [],
}
@app.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", tags=["info"])
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)
@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}")
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)
@app.post("/api/v1/collection")
@router.post("/api/v1/collection", tags=["download"])
async def collection(link: RssLink):
return api_func.download_collection(link.rss_link)
@app.post("/api/v1/subscribe")
@router.post("/api/v1/subscribe", tags=["download"])
async def subscribe(link: RssLink):
return api_func.add_subscribe(link.rss_link)
@app.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)
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)
@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)
@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)
return Response(content, media_type="application/xml")
@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")

View File

@@ -2,12 +2,14 @@ import os
import time
import logging
from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, VERSION
from module.utils import json_config
from module.conf import settings, setup_logger, LOG_PATH, DATA_PATH, RSSLink, VERSION
from module.utils import load_program_data, save_program_data
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__)
@@ -17,74 +19,64 @@ def reset_log():
os.remove(LOG_PATH)
def load_data_file():
def load_data_file(rss_link: str) -> ProgramData:
empty_data = ProgramData(
rss_link=rss_link,
data_version=settings.data_version,
)
if not os.path.exists(DATA_PATH):
bangumi_data = {
"rss_link": settings.rss_parser.link,
"data_version": settings.program.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.program.data_version or bangumi_data["rss_link"] != settings.rss_parser.link:
bangumi_data = {
"rss_link": settings.rss_parser.link,
"data_version": settings.program.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 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):
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, 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....")
save_data_file(bangumi_data)
while times < settings.program.times:
save_program_data(DATA_PATH, program_data)
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 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():
# 初始化
settings.reload()
rss_link = RSSLink()
reset_log()
setup_logger()
show_info()
if settings.rss_parser.token in ["", "token", None]:
logger.error("Please set your RSS token in config file.")
exit(1)
download_client = DownloadClient()
download_client.auth()
download_client.init_downloader()
if settings.rss_parser.link is None:
logger.error("Please add RIGHT RSS url.")
quit()
download_client.rss_feed()
bangumi_data = load_data_file()
download_client.rss_feed(rss_link)
bangumi_data = load_data_file(rss_link)
# 主程序循环
main_process(bangumi_data, download_client)

View File

@@ -4,3 +4,10 @@ from .config import settings, VERSION
TMDB_API = "32b19d6a05b512190a056fa4e747cbbc"
DATA_PATH = "data/data.json"
class RSSLink(str):
def __new__(cls):
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}"

View File

@@ -1,75 +1,80 @@
import json
import os
import logging
from dotenv import load_dotenv
from dataclasses import dataclass
from module.conf.const import ENV_TO_ATTR
from module.models.config import Config
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"
class ConfLoad(dict):
def __getattr__(self, item):
return self.get(item)
def __setattr__(self, key, value):
self[key] = value
@dataclass
class Settings:
program: ConfLoad
downloader: ConfLoad
rss_parser: ConfLoad
bangumi_manage: ConfLoad
debug: ConfLoad
proxy: ConfLoad
notification: ConfLoad
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:
conf = json.load(f)
else:
conf = self._create_config()
for key, section in conf.items():
setattr(self, key, ConfLoad(section))
class Setting(Config):
@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 reload():
load_config_from_file(CONFIG_PATH)
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:
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_dict, f, indent=4)
logger.info(f"Config saved")
def load_config_from_file(path: str) -> Config:
with open(path, "r", encoding="utf-8") as f:
config = json.load(f)
return Setting(**config)
def _val_from_env(env: str, attr: tuple):
if isinstance(attr, tuple):
conv_func = attr[1]
return conv_func(os.environ[env])
else:
return os.environ[env]
def env_to_config() -> Setting:
_settings = Setting().dict()
for key, section in ENV_TO_ATTR.items():
for env, attr in section.items():
if env in os.environ:
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] = self._val_from_env(env, attr)
with open(CONFIG_PATH, "w") as f:
json.dump(settings, f, indent=4)
return settings
_settings[key][attr_name] = _val_from_env(env, attr)
return Setting(**_settings)
if os.path.isdir("config") and VERSION == "DEV_VERSION":
CONFIG_PATH = "config/config_dev.json"
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":
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:
CONFIG_PATH = None
settings = Settings(CONFIG_PATH)
settings = Setting()

View File

@@ -1,4 +1,6 @@
# -*- encoding: utf-8 -*-
from urllib.parse import urlparse, parse_qs
DEFAULT_SETTINGS = {
"program": {
@@ -18,7 +20,8 @@ DEFAULT_SETTINGS = {
"rss_parser": {
"enable": True,
"type": "mikan",
"link": "",
"custom_url": "mikanani.me",
"token": "",
"enable_tmdb": False,
"filter": ["720", "\\d+-\\d+"],
"language": "zh"
@@ -30,11 +33,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,
@@ -55,9 +55,9 @@ DEFAULT_SETTINGS = {
ENV_TO_ATTR = {
"program": {
"AB_INTERVAL_TIME": ("sleep_time", float),
"AB_RENAME_FREQ": ("times", float),
"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",
@@ -67,7 +67,10 @@ 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: 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")),
@@ -79,12 +82,24 @@ 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")),
},
"proxy": {
"AB_HTTP_PROXY": "http",
"AB_SOCKS": "socks",
"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]),
],
},
}

View File

@@ -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:')

View File

@@ -1,34 +1,44 @@
import re
import logging
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
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):
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):
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.official_title)
self._client.set_rule(data, link)
return data
@staticmethod
@@ -39,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):
@@ -63,4 +74,29 @@ class APIProcess:
}
data["bangumi_info"].append(extra_data)
json_config.save(DATA_PATH, data)
return "Success"
return "Success"
@staticmethod
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)
@staticmethod
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"https://mikanani.me", custom_url, content)
@staticmethod
def get_torrent(full_path):
url = f"https://mikanani.me/Download/{full_path}"
with RequestContent() as request:
return request.get_content(url)

View File

@@ -3,8 +3,9 @@ import logging
import os
from module.downloader import getClient
from module.conf import settings
from module.models import BangumiData
logger = logging.getLogger(__name__)
@@ -12,6 +13,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
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 = {
@@ -21,12 +31,17 @@ class DownloadClient:
"rss_refresh_interval": 30,
}
self.client.prefs_init(prefs=prefs)
if settings.downloader.download_path == "":
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")
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,
@@ -38,7 +53,7 @@ class DownloadClient:
"affectedFeeds": [rss_link],
"ignoreDays": 0,
"lastMatch": "",
"addPaused": settings.debug.dev_debug,
"addPaused": False,
"assignedCategory": "Bangumi",
"savePath": str(
os.path.join(
@@ -52,38 +67,37 @@ 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() == 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: list[BangumiData], rss_link: str):
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):
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 +128,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)

View File

@@ -2,10 +2,10 @@ 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)
if settings.downloader.type == "qbittorrent":
from .qb_downloader import QbDownloader
return QbDownloader()
else:
raise Exception(f"Unsupported downloader type: {settings.downloader.type}")

View File

@@ -7,25 +7,29 @@ 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:
def __init__(self):
self._client: Client | None = None
@qb_connect_failed_wait
def __init__(self, host, username, password):
def auth(self, host, username, password):
self._client = Client(
host=host,
username=username,
password=password,
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)
@@ -38,13 +42,16 @@ 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)
def torrents_add(self, urls, save_path, category):
return self._client.torrents_add(
is_paused=settings.DEBUG["enable"],
is_paused=False,
urls=urls,
save_path=save_path,
category=category,
@@ -56,9 +63,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 +98,11 @@ 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)
def check_connection(self):
return self._client.app_version()

View File

@@ -6,9 +6,15 @@ 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"]
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:
@@ -16,51 +22,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"https://mikanani.me/RSS/Search?searchstr={keyword}")
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!")

View File

@@ -7,7 +7,7 @@ from module.core.download_client import DownloadClient
from module.conf import settings
from module.parser import TitleParser
from module.network import PostNotification, ServerChanNotification
from module.network import PostNotification
logger = logging.getLogger(__name__)
@@ -16,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):
@@ -23,68 +24,117 @@ 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
@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]
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)
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}")
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)
_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)
# 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):
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}")
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):
# 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[-2]) is not None:
season = int(re.search(r"\d{1,2}", path_parts[-2]).group())
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
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
return folder_name, season
def run(self):
def rename(self):
# Get torrent info
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.")
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:
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)
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)
logger.warning(f"{info.name} has no media file")
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}")
# print(new_path)
self.client.move_torrent(torrent_hash, new_path)
if __name__ == '__main__':
client = DownloadClient()
rn = Renamer(client)
rn.rename()

View File

@@ -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):

View File

@@ -1 +1,2 @@
from .bangumi import *
from .config import Config

View File

@@ -1,6 +1,30 @@
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 | 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="番剧季度原名")
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="番剧过滤器")
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:
keyword: str
@@ -26,3 +50,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

View File

@@ -0,0 +1,67 @@
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 Log(BaseModel):
debug_enable: bool = Field(False, description="Enable 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(5.0, description="Data version")
program: Program = Program()
downloader: Downloader = Downloader()
rss_parser: RSSParser = RSSParser()
bangumi_manage: BangumiManage = BangumiManage()
log: Log = Log()
proxy: Proxy = Proxy()
notification: Notification = Notification()

View File

@@ -1,7 +1,6 @@
import logging
import requests
from .request_contents import RequestContent
from module.conf import settings
@@ -10,53 +9,53 @@ 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()
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() == "server-chan":
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:
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:
"""Server酱推送"""
def __init__(self):
self.token = settings.notification.token
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,
}
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

View File

@@ -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)
@@ -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
@@ -35,9 +38,21 @@ 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:
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)
def get_html(self, _url):
return self.get_url(_url).text
def get_content(self, _url):
return self.get_url(_url).content

View File

@@ -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(e)
logger.warning(f"Cannot connect to {url}.")
logger.warning("Please check DNS/Connection settings")
time.sleep(5)
try_time += 1
except Exception as e:
logger.debug(f"URL: {url}")
logger.debug(e)

View File

@@ -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__":

View File

@@ -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))

View File

@@ -0,0 +1,2 @@

View File

@@ -3,6 +3,7 @@ import logging
from .analyser import RawParser, DownloadParser, TMDBMatcher
from module.conf import settings
from module.models import BangumiData
logger = logging.getLogger(__name__)
LANGUAGE = settings.rss_parser.language
@@ -17,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):
@@ -38,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):
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
@@ -48,19 +56,22 @@ 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,
}
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:
logger.debug(e)
logger.debug(e)

View File

@@ -1,11 +1,10 @@
import re
import logging
from module.network import RequestContent
from module.parser import TitleParser
from module.conf import settings
from module.core import DownloadClient
from module.models import BangumiData
logger = logging.getLogger(__name__)
@@ -14,39 +13,50 @@ class RSSAnalyser:
def __init__(self):
self._title_analyser = TitleParser()
def rss_to_datas(self, bangumi_info: list) -> list:
@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], rss_link: str) -> list[BangumiData]:
with RequestContent() as req:
rss_torrents = req.get_torrents(settings.rss_parser.link)
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) -> dict:
def rss_to_data(self, url, filter: bool = True) -> BangumiData:
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)
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, rss_link: str):
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)
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")

View File

@@ -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

View File

@@ -0,0 +1 @@
from .bangumi_data import load_program_data, save_program_data

View File

@@ -0,0 +1,27 @@
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 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"],
bangumi_info=[]
)
return data
def save_program_data(path: str, data: ProgramData):
save(path, data.dict())
logger.debug("Data file saved")

View File

@@ -1,10 +0,0 @@
#!/bin/bash
# Check old version
if [ -f /config/bangumi.json ]; then
mv /config/bangumi.json /data/bangumi.json
fi
umask ${UMASK}
python3 main.py