qBitorrent 导出所有种子脚本

2 篇文章 0 订阅
1 篇文章 0 订阅

qBitorrent 本身不支持将加入的种子导出,因此创建此脚本导出其所有种子
注意:使用脚本必须开启 WebUI。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import getopt
import json
import os
import sys

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"
}

config = {
    "address": "http://127.0.0.1:10100",
    "username": "admin",
    "password": None,
    "dir": None
}

BASE_PATH = os.path.dirname(os.path.abspath(__file__))


class Export(object):

    def __init__(self, base_url: str):
        self.base_url = base_url
        self.login_url = self.base_url + "/api/v2/auth/login"
        self.info_url = self.base_url + "/api/v2/sync/maindata?rid=0&l8pkqe0z"
        self.session = requests.session()

    def login(self, username, password):
        response = self.session.post(self.login_url, data={"username": username, "password": password}, headers=headers)
        if response.content == b'Fails.':
            return False
        else:
            return True

    def _info(self):
        response = self.session.get(self.info_url, headers=headers)
        if response.status_code == 403:
            return None
        else:
            return response.json()

    def export(self, bt_dir: str = None):
        if bt_dir is None:
            if "linux" in sys.platform:
                bt_dir = os.path.join(os.getenv("HOME"), ".local", "share", "data", "qBittorrent", "BT_backup")
            elif "win" in sys.platform:
                bt_dir = os.path.join(os.getenv("LOCALAPPDATA"), "qBittorrent", "BT_backup")
            else:
                print("操作系统不支持")
                return

        if not os.path.exists(bt_dir) or len(os.listdir(bt_dir)) <= 0:
            print("BT_backup目录不存在或为空")
            return

        info = self._info()
        if info is None:
            print("登录失败")
            return

        torrents = info["torrents"]
        target_dir = os.path.join(BASE_PATH, "BT_export")
        if not os.path.exists(target_dir):
            os.mkdir(target_dir)

        d = 0
        size = len(torrents)
        while size > 0:
            d += 1
            size //= 10
        ft = "%0{}d.%s%s.torrent".format(d)

        i = 0
        for key, val in sorted(torrents.items(), key=lambda x: (x[1]['category'], x[1]['name'])):
            source_file = os.path.join(bt_dir, key + ".torrent")
            if len(val['category']) > 0:
                target_file = os.path.join(target_dir, ft % (i, "[%s]." % val['category'], val["name"]))
            else:
                target_file = os.path.join(target_dir, ft % (i, "", val["name"]))
            with open(source_file, 'rb') as fr:
                with open(target_file, 'wb') as fw:
                    fw.write(fr.read())
            i += 1

        with open(os.path.join(BASE_PATH, "qbitorrent.json"), "w", encoding="utf-8") as f:
            json.dump(info, f, ensure_ascii=False)


def menu():
    print()
    print("用法: ping [-a address] [-u username] [-p password] [-h]")
    print()
    print("选项:")
    print("    -a address     WebUI运行的地址(default: http://127.0.0.1:10100)")
    print("    -u username    WebUI登录用户名(default: admin)")
    print("    -p password    WebUI登录密码")
    print("    -d dir         BT_backup文件夹路径(不指定会自行查找)")
    print("    -h             显示帮助信息")


if __name__ == '__main__':
    try:
        opts, _ = getopt.getopt(sys.argv[1:], "a:u:p:d:h:", ["address=", "username=", "password=", "dir=", "help"])
        for opt, val in opts:
            if opt in ("-a", "--address"):
                config["address"] = val
            elif opt in ("-u", "--username"):
                config["username"] = val
            elif opt in ("-p", "--password"):
                config["password"] = val
            elif opt in ("-d", "--dir"):
                config["password"] = val
            elif opt in ("-h", "--help"):
                menu()
    except getopt.GetoptError as err:
        print(str(err))
        menu()
        sys.exit(2)

    if config["password"].strip() is None or not config["address"].startswith("http"):
        if config["password"].strip() is None:
            print("必须输入登录密码")
        if not config["address"].startswith("http"):
            print("URL地址格式错误")
        menu()
        sys.exit(2)

    export = Export(base_url=config["address"])
    export.login(username=config["username"], password=config["password"])
    export.export(bt_dir=config["dir"])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

憶夣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值