ATM转载机
import re
import sys
import os
from utils.para_ctrl.para_ctrl import *
from utils.site.site import makesites
from utils.pathinfo.pathinfo import findpathinfo
from utils.seed_machine.seed_machine import start_machine
from utils.seed_machine.seedupload_machine import startupload_machine
from utils.img_upload.imgupload import img_upload
from utils.mediafile.mediafile import *
from utils.mediafile.upload_mediafile import *
import utils.getinfo.torrent_download as td
from utils.getinfo.info_transfer import *
from doubaninfo.doubaninfo import getdoubaninfo

@logger.catch
def main():
    os.system('clear')
    logger.info(f'欢迎使用大胡开发的ATM自动转种机，如果你有意和我一起开发和测试本工具，欢迎你加入ATM研发群870081858')
    yamlinfo=read_para()
    os.chdir(yamlinfo['basic']['screenshot_path'])
    if 'basic' in yamlinfo and 'log' in yamlinfo['basic'] and yamlinfo['basic']['log']!=None:
        log = yamlinfo['basic']['log']
        if os.path.exists(log):
            os.remove(log)
        logger.add(log, level="TRACE", backtrace=True, diagnose=True)

    if yamlinfo['mod']=='img_upload':
        logger.info('正在使用上传图床模式')
        res=img_upload(imgdata=yamlinfo['image hosting'],imglist=yamlinfo['imgfilelist'],host=yamlinfo['img_host'],form=yamlinfo['img_form'])
        logger.info('成功上传图床')
        print(res)

    if yamlinfo['mod'] == 'upload':
        sites = makesites(yamlinfo['site info'])
        # for item in sites:
        #    sites[item].print()

        pathlist = findpathinfo(yamlinfo, sites)
        # for item in pathlist:
        #    item.print()

        startupload_machine(pathlist, sites, yamlinfo)
        write_yaml(yamlinfo)

    if yamlinfo['mod']=='transfer':
        torrentaddress = yamlinfo['basic']['torrent_path']
        sites=makesites(yamlinfo['site info'])
        #for item in sites:
        #    sites[item].print()
        
        pathlist=findpathinfo(yamlinfo,sites)
        #for item in pathlist:
        #    item.print()

        start_machine(pathlist,sites,yamlinfo)
        write_yaml(yamlinfo)

    if yamlinfo['mod']=='douban_info':
        #doubaninfo(yamlinfo['douban_url'])
        if 'doubancookie' in yamlinfo['basic'] and yamlinfo['basic']['doubancookie']:
            getdoubaninfo(url=yamlinfo['douban_url'],cookie=yamlinfo['basic']['doubancookie'])
        else:
            getdoubaninfo(url=yamlinfo['douban_url'])

    if yamlinfo['mod']=='media_img':
        screenshotnum=int(yamlinfo['basic']['picture_num'])
        screenshotaddress=yamlinfo['basic']['screenshot_path']
        takescreenshot(yamlinfo['media_file'],screenshotaddress,screenshotnum)
        imgpaths=[]
        for i in range (screenshotnum):
            imgpaths.append(os.path.join(screenshotaddress,str(i+1)+'.jpg'))
        res=img_upload(imgdata=yamlinfo['image hosting'],imglist=imgpaths,host=yamlinfo['img_host'],form=yamlinfo['img_form'])
        if res=='':
            print(self.chinesename+'上传图床失败')
        else:
            print('成功获得图片链接：\n'+res)

    if yamlinfo['mod']=='download':
        td.get_torrent(yamlinfo)


    if yamlinfo['mod']=='transinfo':
        if yamlinfo['basic']['torrent_list']:
            if "csv" in yamlinfo['basic']['torrent_list']:
                getmediainfo(yamlinfo)
            else:
                print('torrent_list的路径不是一个正确的csv文件路径，请检查配置文件')

        else:
            print('配置文件中无torrent_list项,请检查配置文件')



if __name__ == '__main__':
    main()
main.py
Ethan930717/AutoTransferMachine
class Torrent:
    def __init__(self):
        self.data={}
    def load(self,filename):
        self.stream=Stream(filename,"rb")
        if self.stream.next()==b'd':
            self.data=build_dic(self.stream)
        else:
            raise Exception("invalid torrent file")
    def dump(self,filename):
        self.stream=Stream(filename,"wb")
        dump_dic(self.stream,self.data)
        self.stream.close()
        
def build_dic(stream):#call after symbol 'd' found
    list=[]
    proxy_build(stream,list)
    dic={}
    for i in range(0,len(list)-1,2):   #convert a list[k1,v1,k2,v2...] to a dic
        dic[list[i]]=list[i+1]
    return dic
def build_list(stream):#call after symbol 'l' found
    list=[]
    proxy_build(stream,list)
    return list
def build_str(stream,str_len):#call after num found
    values=[]
    for i in range(str_len):
        values.append(stream.next())
    return b''.join(values)
def build_num(stream):#call after symbol 'i' found
    num=0
    minus=False
    while True:
        ch=stream.next()
        if ch>=b'0' and ch<=b'9':
            num=num*10+int(ch)
        elif ch==b'-':
            minus=True
        elif ch==b'e':
            break
        else:
            raise Exception("invalid torrent file")
    num=-num if minus else num
    return num
def proxy_build(stream,list): #because build_dic and build_list is simaliar,so I def a proxy-function  
    while True:
        ch=stream.next()
        if ch>=b'0' and ch<=b'9':#I think ch==0 is not very valid,but just do this.
            str_len=int(ch)
            while True:
                ch=stream.next()
                if ch==b':':
                    break
                elif ch>=b'0' and ch<=b'9':
                    str_len=str_len*10+int(ch)
                else:
                    raise Exception("invalid torrent file")
            list.append(build_str(stream,str_len))
        elif ch==b'l':
            list.append(build_list(stream))
        elif ch==b'i':
            list.append(build_num(stream))
        elif ch==b'd':
            list.append(build_dic(stream))
        elif ch==b'e':
            break
        else:
            raise Exception("invalid torrent file")

def str2bytes(s):
    return s.encode("utf-8")

def bytes2str(s):
    return s.decode("utf-8")
"""
for dumpfile
"""
import types
def dump_dic(stream,dic):
    stream.put(str2bytes("d"))
    for k,v in dic.items():
        dump_str(stream,k)
        proxy_dump(stream,v)
    stream.put(str2bytes("e"))
def dump_list(stream,list):
    stream.put(str2bytes("l"))
    for item in list:
        proxy_dump(stream,item)
    stream.put(str2bytes("e"))
def dump_str(stream,mystr):
    stream.put(str2bytes(str(len(mystr))+":"))
    stream.put(mystr)
def dump_num(stream,num):
    stream.put(str2bytes("i"))
    stream.put(str2bytes(str(num)))
    stream.put(str2bytes("e"))

def proxy_dump_python2(stream,item):
    if isinstance(item,types.DictionaryType):
        dump_dic(stream,item)
    elif isinstance(item,types.ListType):
        dump_list(stream,item)
    elif isinstance(item,types.StringType):
        dump_str(stream,item)
    elif isinstance(item,types.IntType) or isinstance(item,types.LongType):
        dump_num(stream,item)
    else:
        raise Exception("dump info error")
def proxy_dump(stream,item):
    if isinstance(item,dict):
        dump_dic(stream,item)
    elif isinstance(item,list):
        dump_list(stream,item)
    elif isinstance(item,bytes):
        dump_str(stream,item)
    elif isinstance(item,int):
        dump_num(stream,item)
    else:
        raise Exception("dump info error")
"""
byte stream
"""
class Stream:       
    def __init__(self,filename,mode):
        self.file=open(filename,mode)
    def next(self): #for mode r
        return self.file.read(1)
    def put(self,byte): #for mode w
        self.file.write(byte)
    def close(self):
        self.file.close()
    def __del__(self):
        self.file.close()

utils/edittorrent/edittorrent.py
Ethan930717/AutoTransferMachine
import lxml
import cloudscraper
from bs4 import BeautifulSoup
from lxml import etree
import requests
from requests.cookies import cookiejar_from_dict
from utils.getinfo.makeyaml import mkyaml
import openpyxl
import urllib
from loguru import logger
import re

def cookies_raw2jar(raw_cookies): # 定义一个函数，将原始的cookie字符串转换为cookiejar对象
    cookie_dict = {}
    for cookie in raw_cookies.split(";"):
        key, value = cookie.split("=", 1)
        cookie_dict[key] = value
    return cookiejar_from_dict(cookie_dict) # 调用requests模块中的函数
scraper = cloudscraper.create_scraper()


def getmediainfo(yamlinfo):
    au = f"{yamlinfo['basic']['workpath']}au.yaml"
    wb = openpyxl.load_workbook(yamlinfo['basic']['torrent_list'])
    ws = wb.active
    data = ws.values
    url_list = [cell for row in data for cell in row if "detail" in cell]
    writemode = input(f"请选择模板转换方式\nY.在原有的pathinfo下自动续写\nN.覆盖原有的pathinfo，从path1开始生成（默认自动续写）")
    if writemode.lower() == "n":
        logger.info('当前为覆盖模式')
        with open(au, "r",encoding="utf-8") as f:
            lines = f.readlines()
        above_path_info = True
        new_lines = []
        for line in lines:
            if "path info" in line:
                above_path_info = False  # 发现 "path info" 行，将标志设为 False
            if above_path_info:
                new_lines.append(line)
        with open(au, "w", encoding="utf-8") as f:
            for new_line in new_lines:
                f.write(new_line)
    else:
        logger.info('当前为续写模式')
    print(yamlinfo['basic']['torrent_list'])
    tmdb_api = yamlinfo['basic']['tmdb_api']
    counter = 1
    for url in url_list:
        result = urllib.parse.urlparse(url)
        siteurl = urllib.parse.urlunparse((result.scheme, result.netloc, '', '', '', ''))
        sitename = ws["G" + str(counter + 1)].value
        cookie = ws["H" + str(counter + 1)].value
        print(f"当前域名 {siteurl},匹配站点{sitename}")
        r = scraper.post(url, cookies=cookies_raw2jar(cookie), timeout=30)
        soup = BeautifulSoup(r.text, "html.parser")
        tree = lxml.etree.HTML(r.text)
        print(f"当前检索链接 {url}")

    #主标题
        xpath_name = "//*[@id='top']/text()"
        try:
            name = tree.xpath(xpath_name)[0]
            name = name.rstrip()
            getteam = name.split("-")
            # 取列表的最后一个元素，即最后一个"-"后面的内容
            team = getteam[-1]
        except IndexError:
            name = input(f"无法读取主标题名，请手动输入,种子地址{url}\n请在此输入正确的主标题名：")
        print(f"成功记录主标题名 {name}")

    # 种子名称
        filename=""
        try:
            links = soup.find_all("a", class_="index")
            for link in links:
                href = link.get("href")
                if "download" in href:
                    torrent = link.text
                    filename=torrent.replace(".torrent","")
                    filename=filename.replace("[Shadow].","")
        except IndexError:
            filename= input(f"无法读取种子名称，请手动输入,种子地址{url}\n请在此输入正确的种子名称：")
        print(f"成功读取文件名称 {filename}")

        #副标题
        try:
            elements = soup.find_all("td", class_="rowfollow", valign="top", align="left")[0]
            texts_sdescr = [element.get_text() for element in elements]
            for small_descr in texts_sdescr:
               print(f"成功读取副标题名 {small_descr}")
        except IndexError:
            small_descr = input(f"无法读取副标题名，请手动输入,种子地址{url}\n请在此输入正确的副标题名：")


        #产地&年份
        kdescr = soup.find(id="kdescr")
        lines = kdescr.text.split("\n")
        country = ''
        try:
            for line in lines:
                if "◎产　　地　" in line:
                    country = line.split("◎产　　地　")[1]
            print(f"读取产地成功 {country}")
        except IndexError:
            country= input(f"无法确认产地，请手动输入,文件标题{name}\n请在此输入正确的产地（国家）：")


        madeyear=''
        try:
            match = re.search("◎年　　份　(\d+)", kdescr.text)
            if match:
                madeyear = match.group(1)
            else:
                year_match = re.search(r"\b(19\d{2}|20\d{2})\b", name)
                if year_match:
                    madeyear = year_match.group(0)
                    print(f"从文件名中提取年份成功 {madeyear}")
                else:
                    madeyear = input(f"无法确认年份，请手动输入,文件标题{name}\n请在此输入正确年份：")
        except IndexError:
            madeyear = input(f"无法确认年份，请手动输入,文件标题{name}\n请在此输入正确年份：")

        #标签
        try:
            elements = soup.find_all("td", class_="rowfollow", valign="top", align="left")[1]
            texts_tags = [element.get_text() for element in elements]
            tags = " ".join(texts_tags)
            print(f"读取标签成功 {tags}")
            if "mv" in tags.lower() or "体育" in tags or "音轨" in tags or "sport" in tags.lower() :
                print("当前尚未适配转载该类型资源，即将跳过本资源")
                continue
        except IndexError:
            tags = input(f"无法确认标签，请手动输入,资源链接{url}\n请在此输入正确的标签：")

        #确认完结
        if "complete" in name.lower() and "完结" in tags:
            complete = 1
        elif "complete" in name.lower() and not "完结" in tags:
            choice = input(f'标题包含Complete，但资源未勾选完结标签，请手动确认该资源是否完结\n输入1代表完结，输入0代表未完结: ')
            if choice == '1':
                complete = 1
            elif choice == '0':
                complete = 0
            else:
                print("无效的输入，请重新输入")
        elif not "complete" in name.lower() and "完结" in tags:
            choice = input(f'资源已勾选完结标签，但标题不包含Complete，请手动确认该资源是否完结\n输入1代表完结，输入0代表未完结: ')
            if choice == '1':
                complete = 1
                name = input(f"请在主标题中手动加入Complete,添加位置在季数之后，如 S01 Complete\n当前主标题{name}")
            elif choice == '0':
                complete = 0
            else:
                print("无效的输入，请重新输入")
        else:
            complete = 0

        #基本信息
        try:
            elements = soup.find_all("td", class_="rowfollow", valign="top", align="left")[2]
            texts_info = [element.get_text() for element in elements]
            info = " ".join(texts_info)
            print("获取基本信息成功")
            infolist = info.split()
            size = " ".join(infolist[1:3])
            type = infolist[4]
            medium = infolist[6]
            codec = infolist[8]
            audio = infolist[10]
            standard = infolist[12]
            print(f"资源体积 {size}")
            print(f"类型 {type}")
            if "电影" in type:
                type = "movie"
            elif "剧集" in type:
                type = "tvseries"
            elif "综艺" in type:
                type = "tvshow"
            elif "纪录" in type:
                type = "doc"
            elif "动画" in type:
                type = "anime"
            elif "音轨" in type:
                type = "music"
                print("检测到类型为音轨，当前尚未适配转载该类型资源，即将跳过本资源")
                continue
            elif "MV" in type:
                type = "mv"
                print("检测到类型为MV，当前尚未适配转载该类型资源，即将跳过本资源")
                continue
            elif "体育" in type:
                type = "sport"
                print("检测到类型为体育，当前尚未适配转载该类型资源，即将跳过本资源")
                continue
            else:
                type = "other"
                print("未检测到当前资源类型，即将跳过本资源")
                continue

            print(f"媒介 {medium}")
            print(f"编码 {codec}")
            print(f"音频编码 {audio}")
            print(f"清晰度 {standard}")
            print(f"制作组 {team}")
        except IndexError:
            print("无法获取基本信息")

    # 豆瓣
        douban = None
        try:
            dblinks = soup.find_all("a", href=lambda x: x and "douban" in x)
            douban = [(link.get("href"), link.get_text()) for link in dblinks]
            for douban in dblinks:
                douban = douban.get("href")
                print(f"成功获取豆瓣链接 {douban}")
        except IndexError:
            print("无法获取豆瓣链接")

        #IMDB
        imdb = ""
        tmdb_id = ""
        try:
            imdblinks = soup.find_all("a", href=lambda x: x and "imdb" in x)
            if imdblinks:
                imdb = [(link.get("href"), link.get_text()) for link in imdblinks]
                for imdb in imdblinks:
                    imdb = imdb.get("href")
                    print(f"成功获取IMDB链接 {imdb}")
                    imdb_split=imdb.split('/')
                    imdb_id=imdb_split[4]
                    print(f"正在通过IMDBID '{imdb_id}' 获取TMDBID")
                    tmdb_url = "https://api.themoviedb.org/3/find/"+imdb_id+"?api_key="+tmdb_api+"&external_source=imdb_id&include_adult=true&language=zh-CN"
                    print(tmdb_url)
                    try:
                        tmdb_res = requests.get(tmdb_url)
                        if tmdb_res.status_code == 200:
                            data = tmdb_res.json()
                            if data["movie_results"]:
                                tmdb_id = data["movie_results"][0]["id"]
                                tmdb_title = data["movie_results"][0]["title"]
                                print(f"TMDBID获取成功 {tmdb_id} ")
                                print(f"中文标题 {tmdb_title} ")
                            elif data["tv_results"]:
                                tmdb_id = data["tv_results"][0]["id"]
                                tmdb_title = data["tv_results"][0]["name"]
                                print(f"TMDBID获取成功 {tmdb_id} ")
                                print(f"中文标题 {tmdb_title} ")
                            elif data["tv_episode_results"]:
                                tmdb_id = data["tv_episode_results"][0]["id"]
                                tmdb_title = data["tv_episode_results"][0]["name"]
                                print(f"TMDBID获取成功 {tmdb_id} ")
                                print(f"中文标题 {tmdb_title} ")
                            else:
                                print("未成功获取TMDBID，尝试使用影片名称搜索")
                                if type == "movie":
                                    print("")
                                else:
                                    print("")
                        else:
                            print(f"TMDB请求失败 {tmdb_res.status_code}.")
                    except IndexError:
                        tmdb_id = ""
                        tmdb_title = ""
                        print("无法连接到tmdb")
                else:
                    imdb = ""
                    print("该资源暂无imdb链接")
        except Exception as e:
            print("无法获取IMDB链接")
        logger.info(f"第{counter}个资源读取完成")
        mkyaml(yamlinfo,counter,filename,name,small_descr,tags,team,type,audio,codec,medium,douban,imdb,country,madeyear,standard,tmdb_id,torrent)





utils/getinfo/info_transfer.py
Ethan930717/AutoTransferMachine
import re
import datetime
from loguru import logger

def mkyaml(yamlinfo,counter,filename,name,small_descr,tags,team,type,audio,codec,medium,douban,imdb,country,madeyear,standard,tmdb_id,torrent):
    #亚洲国家
    east_asia = ["中国大陆", "蒙古", "朝鲜", "韩国", "日本", "香港", "台湾", "澳门","中国" ] #仅作判定使用，无任何地缘政治因素
    southeast_asia = ["菲律宾", "越南", "老挝", "柬埔寨", "缅甸", "泰国", "马来西亚", "文莱", "新加坡", "印度尼西亚", "东帝汶"]
    south_asia = ["尼泊尔", "不丹", "孟加拉国", "印度", "巴基斯坦", "斯里兰卡","马尔代夫"]
    central_asia = ["哈萨克斯坦","吉尔吉斯斯坦","塔吉克斯坦","乌兹别克斯坦","土库曼斯坦"]
    west_asia = ["阿富汗", "伊拉克", "伊朗", "叙利亚", "约旦", "黎巴嫩", "以色列", "巴勒斯坦", "沙特阿拉伯", "巴林", "卡塔尔", "科威特", "阿拉伯联合酋长国", "阿联酋", "阿曼", "也门", "格鲁吉亚", "亚美尼亚", "阿塞拜疆", "土耳其", "塞浦路斯"]
    asia = set(east_asia + southeast_asia + south_asia + central_asia + west_asia)
    #欧美国家
    eu = ["澳大利亚", "芬兰", "瑞典", "挪威", "冰岛", "丹麦", "爱沙尼亚", "拉脱维亚", "立陶宛", "白俄罗斯", "俄罗斯", "乌克兰", "摩尔多瓦", "波兰", "捷克", "斯洛伐克", "匈牙利", "德国", "奥地利", "英国", "爱尔兰", "荷兰", "比利时", "卢森堡", "法国", "摩纳哥", "西班牙", "葡萄牙", "意大利", "梵蒂冈", "圣马力诺", "马耳他", "希腊", "阿尔巴尼亚", "保加利亚", "罗马尼亚", "加拿大", "美国", "墨西哥", "危地马拉", "伯利兹", "萨尔瓦多", "洪都拉斯", "尼加拉瓜", "哥斯达黎加", "巴拿马", "哥伦比亚", "委内瑞拉", "圭亚那", "苏里南", "厄瓜多尔", "秘鲁", "玻利维亚", "巴西", "智利", "阿根廷","乌拉圭","巴拉圭","古巴","海地","多米尼加共和国","牙买加","巴哈马","安提瓜和巴布达","圣基茨和尼维斯","多米尼克","圣卢西亚","圣文森特和格林纳丁斯","格林纳达","巴巴多斯"]
    #站点特判
    #碟粉非亚洲资源与动漫.年份大于五年
    current_year = datetime.date.today().year # 获取当前年份
    keep_year = abs(current_year - int(madeyear))
    if country in asia and not "anime" in type and keep_year > 4:
        discfan = '0'
        print(f"当前资源产地为{country},类型为{type},上映时间{keep_year}年\n符合碟粉发种要求")
    else:
        discfan = 'null'
        print(f"当前资源产地为{country},类型为{type},上映时间{keep_year}年\n不符合碟粉发种要求")

    if not 'anime' in type:
        ilolicon = 'null'
    else:
        ilolicon = '0'
    #白兔4K
    if not '2160' in standard or not '4k' in standard:
        hares = 'null'
    else:
        hares = '0'
    #freefarm大陆资源
    if not '大陆' in country:
        freefarm = '0'
    else:
        freefarm = 'null'
    #tccf纪录片
    if type == 'doc':
        tccf = "0"
    else:
        tccf = 'null'
    #猫H264/X264
    if "H264" in codec.upper():
        pter= "null"
    else:
        pter = '0'
    site=""
    site += f"    audience: null\n"
    site += f"    btschool: null\n"
    site += f"    carpt: 0\n"
    site += f"    cyanbug: 0\n"
    site += f"    dajiao: 0\n"
    site += f"    discfan: {discfan}\n"
    site += f"    dragonhd: 0\n"
    site += f"    freefarm: {freefarm}\n"
    site += f"    gtk: 0\n"
    site += f"    haidan: 0\n"
    site += f"    hares: {hares}\n"
    site += f"    hdarea: 0\n"
    site += f"    hddolby: 0\n"
    site += f"    hdfans: 0\n"
    site += f"    hdhome: 0\n"
    site += f"    hdmayi: 0\n"
    site += f"    hdpost: null\n"
    site += f"    hdpt: 0\n"
    site += f"    hdsky: null\n"
    site += f"    hdtime: 0\n"
    site += f"    hdu: 0\n"
    site += f"    hdvideo: 0\n"
    site += f"    hdzone: 0\n"
    site += f"    hhclub: null\n"
    site += f"    hitpt: 0\n"
    site += f"    hudbt: null\n"
    site += f"    icc: 0\n"
    site += f"    itzmx: null\n"
    site += f"    joyhd: 0\n"
    site += f"    kufei: 0\n"
    site += f"    mangguo: null\n"
    site += f"    mteam: null\n"
    site += f"    nanyang: 0\n"
    site += f"    okpt: 0\n"
    site += f"    oshen: 0\n"
    site += f"    piggo: 0\n"
    site += f"    ptcafe: 0\n"
    site += f"    ptchina: 0\n"
    site += f"    pter: {pter}\n"
    site += f"    pthome: 0\n"
    site += f"    ptlsp: 0\n"
    site += f"    ptsbao: null\n"
    site += f"    pttime: 0\n"
    site += f"    redleaves: 0\n"
    site += f"    rousi: 0\n"
    site += f"    soulvoice: 0\n"
    site += f"    ssd: null\n"
    site += f"    tccf: {tccf}\n"
    site += f"    ubits: 0\n"
    site += f"    wintersakura: 0\n"
    site += f"    ydy: 0\n"
    site += f"    yiptba: 0\n"
    site += f"    wuerpt: 0\n"
    site += f"    zhuque: 0\n"
    site += f"    zmpt: 0\n"
    site += f"    ilolicon: {ilolicon}\n"

    # 确定中文名
    cnname = ""
    cnname = filename.split(".")  # 以空格为分隔符分割字符串
    cnname = cnname[0]  # 取第一个元素作为中文名
    cnname = cnname[0:len(cnname)]  # 取整个字符串作为中文名（这一步其实可以省略）
    cnname = cnname.replace(":", " ")
    cnname = cnname.replace("：", " ")
    cnname = cnname.replace("’", " ")
    cnname = cnname.replace("”", " ")
    print(cnname)

    # 确定英文名
    enname=""
    if "2019" in name:
        en1 = name.split("2019")[0]
        enname = en1.replace(".", " ")
    elif "2020" in name:
        en1 = name.split("2020")[0]
        enname = en1.replace(".", " ")
    elif "19" in name:
        en1 = name.split("19")[0]
        enname = en1.replace(".", " ")
    elif "20" in name:
        en1 = name.split("20")[0]
        enname = en1.replace(".", " ")
    enname = enname.replace("'", " ")
    enname = enname.replace(":", " ")
    print(enname)

    #获取path序列
    au = f"{yamlinfo['basic']['workpath']}au.yaml"
    f = open(au, 'r',encoding='utf-8') # 以只读模式打开文件
    lines = f.readlines() # 读取所有行并存储在列表中
    f.close() # 关闭文件

    pattern = r'path\d+' # 定义正则表达式模式

    index = -1 # 初始化索引为-1，表示没有找到
    for i in range(len(lines)): # 遍历列表中的每个元素的索引
        if re.search(pattern, lines[i]): # 如果当前行包含"path(n)"
            index = i # 更新索引为当前值
    if index != -1: # 如果索引不等于-1，表示找到了
        line = lines[index] # 获取最后一个带有"path"的行的值
        match = re.search(r'\d+', line) # 使用正则表达式查找其中的数字
        if match: # 如果找到了数字
            pathnum = int(match.group()) + 1 # 提取数字并转换为整数
            print(f"已找到最大的path序列为{int(match.group())},正在将当前path序列设置为{pathnum}")
        else: # 如果没有找到数字
            pathnum = "1" # 将pathnum设为1
            print("未找到path序列，已将pathnum设为1")
    else: # 如果索引等于-1，表示没有找到
        pathnum = "1" # 将pathnum设为1
        print("未找到path序列，已将pathnum设为1")


    # 确认来源
    if "UHD" in name.upper() and "BLU" in name.upper() and "DIY" in name.upper():
        source = "UHD BLURAY DIY"
    elif "UHD" in name.upper() and "BLU" in name.upper():
        source = "UHD BLURAY"
    elif "BLURAY" in name.upper():
        source = "BLURAY"
    elif "UHD" in name.upper() and "TV" in name.upper() and "DIY" in name.upper():
        source = "UHD TV DIY"
    elif "UHD" in name.upper() and "TV" in name.upper():
        source = "UHD TV"
    elif "UHD" in name.upper():
        source = "UHD"
    elif "HDTV" in name.upper():
        source = "HDTV"
    elif "WEB" in name.upper():
        source = "WEBDL"
    elif "DVD" in name.upper():
        source = "DVD"
    elif "CD" in name.upper():
        source = "CD"
    elif "ENCODE" in name.upper():
        source = "ENCODE"
    else:
        source = "OTHER"

    #确认编码
    if "x265" in name and "10bit" in name:
        codec="x265 10bit"
    elif "x265" in name:
        codec="x265"
    elif "H265" in name and "10bit" in name and "HDR" in name:
        codec="H265 10bit HDR"
    elif "H265" in name and "10bit" in name:
        codec="H265 10bit"
    elif "H265" in name:
        codec="H265"
    elif "H264" in name:
        codec="H264"
    elif "AVC" in name:
        codec = "AVC"
    elif "x264" in name:
        codec = "x264"
    elif "HEVC" in name:
        codec = "HEVC"
    else:
        codec = input(f"无法确认视频格式，请手动输入,文件标题{name}")

    #确认音频
    if "DTS-HD" in name.upper() and "MA" in name.upper() and "1.0" in name.upper():
        audio = "DTS-HD MA 1.0"
    elif "DTS-HD" in name.upper() and "MA" in name.upper() and "2.0" in name.upper():
        audio = "DTS-HD MA 2.0"
    elif "DTS-HD" in name.upper() and "MA" in name.upper() and "5.1" in name.upper():
        audio = "DTS-HD MA 5.1"
    elif "DTS-HD" in name.upper() and "MA" in name.upper() and "7.1" in name.upper():
        audio = "DTS-HD MA 7.1"
    elif "TRUE" in name.upper() and "AutoTransferMachineOS" in name.upper() and "7.1" in name.upper():
        audio = "TrueHD AutoTransferMachineos 7.1"
    elif "TRUE" in name.upper() and "AutoTransferMachineOS" in name.upper():
        audio = "TrueHD AutoTransferMachineos"
    elif "TRUE" in name.upper() and "5.1" in name.upper():
        audio = "TrueHD 5.1"
    elif "TRUE" in name.upper():
        audio = "TrueHD"
    elif "AAC" in name.upper():
        audio = "AAC"
    elif "AC3" in name.upper():
        audio = "AC3"
    elif "AC3" in name.upper():
        audio = "AC3"
    elif "DDP" in name.upper() and "AutoTransferMachineOS" in name.upper() and "5.1" in name.upper():
        audio = "DDP5.1 AutoTransferMachineos"
    elif "DDP" in name.upper() and "5.1" in name.upper():
        audio = "DDP5.1"
    elif "DDP" in name.upper() and "2.0" in name.upper():
        audio = "DDP2.0"
    elif "DDP" in name.upper():
        audio = "DDP"
    elif "DD" in name.upper() and "2.0" in name.upper():
        audio = "DD2.0"
    elif "DD" in name.upper():
        audio = "DD"
    elif "FLAC" in name.upper():
        audio = "FLAC"
    else:
        audio = input(f"无法确认音频格式，请手动输入,文件标题{name}")

    text = ""
    text += f"  path{pathnum}:\n"
    text += f"    downloadpath: /download\n"
    text += f"    enable: 1\n"
    text += f"    collection: 1\n"
    text += f"    path: /media/{filename}\n"
    text += f"    uploadname: \"{name}\"\n"
    text += f"    filename: \"{torrent}\"\n"
    text += f"    chinesename: \"{cnname}\"\n"
    text += f"    englishname: \"{enname}\"\n"
    text += f"    small_descr: \"{small_descr}\"\n"
    text += f"    tags: {tags}\n"
    text += f"    sub: {team}\n"
    text += f"    type: {type}\n"
    text += f'    contenthead: \'[quote][b][color=#d98a91][size=3][font=Arial Black]转自[/size][size=5]{team}[/size][size=3]，感谢原作者发布[/color][/size][/font][/b][/quote]\'\n'
    text += f"    audio_format: {audio}\n"
    text += f"    video_format: {codec}\n"
    text += f"    medium: {medium}\n"
    text += f"    source: {source}\n"
    text += f"    doubanurl: {douban}\n"
    text += f"    screenshot: null\n"
    text += f"    from_url: null\n"
    text += f"    imdb_url: {imdb}\n"
    text += f"    tmdb_id: {tmdb_id}\n"
    text += f"{site}"
    logger.info(text)
    with open(au, "a+", encoding="utf-8") as f:
        f.write(text)
utils/getinfo/makeyaml.py
Ethan930717/AutoTransferMachine
import re
import os
import cloudscraper
from bs4 import BeautifulSoup
from requests.cookies import cookiejar_from_dict
import time
from loguru import logger
import sys
import shutil
import yaml
import csv
from utils.getinfo.torrent_download import download_torrent

def cookies_raw2jar(raw_cookies):
    cookie_dict = {}
    for cookie in raw_cookies.split(";"):
        key, value = cookie.split("=", 1)
        cookie_dict[key] = value
    return cookiejar_from_dict(cookie_dict)

def shadowflow_download(sitename, siteurl, sitecookie, sitepasskey, yamlinfo, start_time):
    row = 0
    scraper = cloudscraper.create_scraper()
    csv_filename = f"{sitename}_torrents.csv"
    file = open(csv_filename, mode='w', newline='', encoding='utf-8-sig')
    writer = csv.writer(file)
    writer.writerow(["标题", "体积", "做种人数", "发布时间", "详情链接", "下载链接", "站点", "cookie", "passkey"])
    try:
        pagenum = int(input('请输入本次需要爬取几页种子: '))
        if pagenum > 0:  # 如果输入是正整数
            print(f"您选择了爬取{pagenum}页种子")
    except ValueError:
        print('输入错误，请输入一个整数。')
    while True:

        outtag = input(
            f"请选择需要排除的资源关键字，可多选，无格式要求（默认排除禁转、限转资源，注意区分大小写) \n例：排除有国语粤语标签的动漫和综艺资源，则输入CD12 \n做种人数(seed)，体积(size)筛选请使用前后比较符，如0<seed<5则为排除做种人数小于5人的种子，10<size<100则表示排除体积在10GB-100GB之间的种子，可与关键字一同筛选）\n A.电影 B.剧集 C.综艺 D.动漫 E.纪录片 F.MV\n gy.国语 yy.粤语 zz.中字 diy.DIY wj.完结 fj.分集 db.杜比视界 hdr.HDR\n请输入排除项:")
        tags = []
        tags.append("禁转")
        tags.append("限转")
        if "A" in outtag:
            tags.append("电影")
        if "B" in outtag:
            tags.append("剧集")
        if "C" in outtag:
            tags.append("综艺")
        if "D" in outtag:
            tags.append("动漫")
        if "E" in outtag:
            tags.append("纪录片")
        if "F" in outtag:
            tags.append("MV")
        if "gy" in outtag:
            tags.append("国语")
        if "yy" in outtag:
            tags.append("粤语")
        if "zz" in outtag:
            tags.append("中字")
        if "diy" in outtag:
            tags.append("DIY")
        if "wj" in outtag:
            tags.append("完结")
        if "fj" in outtag:
            tags.append("分集")
        if "db" in outtag:
            tags.append("杜比视界")
        if "hdr" in outtag:
            tags.append("HDR")
        tags_str = " ".join(tags)
        # 解析输入，查找是否包含seed筛选条件
        seed_filter = None
        seedprint = ""
        if 'seed' in outtag:
            match = re.search(r'(\d+)\s*<\s*seed\s*<\s*(\d+)', outtag)
            if match:
                seed_min = int(match.group(1))
                seed_max = int(match.group(2))
                seed_filter = lambda x: seed_min <= int(x) < seed_max
                seedprint = f"做种人数在{seed_min}到{seed_max}之间,"

        # 解析输入，查找是否包含size筛选条件
        size_filter = None
        sizeprint = ""
        if 'size' in outtag:
            match = re.search(r'(\d+)\s*<\s*size\s*<\s*(\d+)', outtag)
            if match:
                size_min = int(match.group(1))
                size_max = int(match.group(2))
                size_filter = lambda x: size_min <= int(x) < size_max
                sizeprint = f"体积在{size_min}GB到{size_max}GB之间"
        download_ensure = input(f"选择完毕，本次将为您排除{tags_str},{seedprint}{sizeprint}的资源\n确认：Y \n重选： N \n")
        if download_ensure.lower() == "y":
            break
        elif download_ensure.lower() == "n":
            continue
        else:
            print("输入有误，请输入Y或者N")
    for page in range(pagenum):
        torrent_url = f"{siteurl}torrents.php?page={page}"
        r = scraper.get(torrent_url, cookies=cookies_raw2jar(sitecookie), timeout=30)
        soup = BeautifulSoup(r.content, "html.parser")
        if r.status_code == 200:
            # 查找id为torrents的表格元素
            table = soup.find("table", class_="torrents")
            if table:
                trs = table.find_all("tr")[1:]
                for tr in trs:
                    if any(x in tr.text for x in tags):
                        print(f"不符合筛选条件，跳过")
                        continue
                    else:
                        td_list = tr.find_all("td")
                        if len(td_list) >= 4:
                            seeders = td_list[-4].text
                        else:
                            continue
                        size = tr.find_all("td")[-5].text
                        size_pattern = re.search(r'(\d+\.\d+|\d+)', size)
                        size = float(size_pattern.group(1)) / 1024 if 'MB' in size else float(size_pattern.group(1))
                        # 将MB单位的体积转换为GB单位
                        if (seed_filter is None or seed_filter(seeders)) and (size_filter is None or size_filter(size)):
                            try:
                                embedded = tr.find("td", class_="embedded")
                                a = embedded.find("a", href=lambda x: "details" in x)
                                b = a["href"]
                                title = a["title"]
                                details = f"{siteurl}{b}"
                                pattern = "id=(\d+)&hit"
                                torrent_id = re.search(pattern, details)
                                if torrent_id:
                                    pass
                                else:
                                    print("未识别到种子ID")
                                download = details.replace("details", "download")
                                download = download.replace("hit=1", f"passkey={sitepasskey}")
                                seeders = tr.find_all("td")[-4].text
                                size = tr.find_all("td")[-5].text
                                uploadtime = tr.find_all("td")[-6].text
                                writer.writerow([title, size, seeders, uploadtime, details, download, sitename, sitecookie,sitepasskey])
                                logger.info(f'{title}获取成功')
                                row += 1
                            except IndexError:
                                continue
                        else:
                            print(f"不符合筛选条件，跳过")
            else:
                print("没东西了，停")
                break
        else:
            print("没东西了，停")
            continue

    file.close()
    end_time = time.time()
    execution_time = end_time - start_time
    logger.info(f"爬取结束，本次共读取到{row}个种子,耗时{execution_time}，请选择接下来的任务\n 1.批量打印种子链接 2.批量打印下载链接 3.跳过")
    # 移动文件到指定目录
    if os.path.exists(csv_filename):
        os.makedirs(yamlinfo['basic']['record_path'], exist_ok=True)
        shutil.move(csv_filename, os.path.join(yamlinfo['basic']['record_path'], csv_filename))
    else:
        print(f"文件 {csv_filename} 不存在!")

    # 打开CSV文件并读取数据
    csv_filepath = os.path.join(yamlinfo['basic']['record_path'], csv_filename)
    details_list = []
    download_list = []

    with open(csv_filepath, 'r', encoding='utf-8-sig') as file:
        reader = csv.reader(file)
        next(reader)  # 跳过标题行
        for row in reader:
            details_list.append(row[4])  # 假设详情在第5列，根据实际情况进行调整
            download_list.append(row[5])  # 假设下载URL在第6列，根据实际情况进行调整

    # 提示用户选择并打印相应的信息
    choice = input("请输入您的选择：")
    while True:
        if choice == "1":
            print("以下是所有的种子链接：")
            for detail in details_list:
                print(detail)
            break
        elif choice == "2":
            print("以下是所有的下载链接：")
            for download in download_list:
                print(download)
            break
        elif choice == "3":
            print("好的")
            break
        else:
            print("选择错误，请重新选择")
            choice = input("请输入您的选择：")
    #获取path序列
    while True:
        forsure = input(f"本次数据已保存在{yamlinfo['basic']['record_path']}/{sitename}_torrents.csv\n是否需要将Yaml模板中的torrent_file路径替换成本次生成的数据文件路径\nY.是，替换路径\nN.否，不需要替换\n默认不替换")
        if forsure.upper() == 'Y':
            au = f"{yamlinfo['basic']['workpath']}au.yaml"
            logger.info(f"检测到模板路径为{au}")
            with open(au, "r") as f:
                yamlinfo = yaml.load(f, Loader=yaml.FullLoader)
                yamlinfo["basic"]["torrent_list"] = f"{yamlinfo['basic']['record_path']}/{sitename}_torrents.csv"
                with open(au, "w") as f:
                    yaml.dump(yamlinfo, f)
            logger.info(f"修改完成，当前yaml模板的torrent_list为{yamlinfo['basic']['torrent_list']}")
            while True:
                dlsure = input(
                    f'是否需要将本次抓取到的资源种子下载到本地（下载路径为torrent_path，请确认配置文件中已正确配置该项\nY.是，下载\nN，否，不下载')
                if dlsure.upper() == "Y":
                    logger.info("开始下载")
                    return download_torrent(yamlinfo)
                elif dlsure.upper() == "N":
                    logger.info("未选择下载种子，即将结束本次任务")
                    sys.exit()
                else:
                    logger.info("选择错误，请重新选择")
                    continue
        elif forsure.upper() == 'N':
            logger.info('已选择不替换路径')
            while True:
                dlsure = input(f'是否需要将本次抓取到的资源种子下载到本地（选是则同步将种子上传到QB，默认添加后为暂停状态）\nY.是，下载\nN，否，不下载')
                if dlsure.upper() == "Y":
                    logger.info("开始下载")
                    return download_torrent(yamlinfo)
                elif dlsure.upper() == "N":
                    logger.info("未选择下载种子，即将结束本次任务")
                    sys.exit()
                else:
                    logger.info("选择错误，请重新选择")
                    continue
        else:
            logger.info("选择错误，请重新选择")
            continue
utils/getinfo/shadowflow_download.py
Ethan930717/AutoTransferMachine
import time
from loguru import logger
import sys
import shutil
import yaml
import urllib
import requests
import os
import logging
from qbittorrentapi import Client
import csv



def get_torrent(yamlinfo):
    from utils.getinfo.shadowflow_download import shadowflow_download
    start_time = time.time()
    choosesite = input(f"请选择你要获取信息的网站\n1.影 \n请输入序号:")
    if choosesite == "1":
        sitename = "shadowflow"
        logger.info('即将从影站获取种子信息')
    else:
        logger.info('未能识别当前选择的站点，退出脚本')
        sys.exit(0)
    siteurl = yamlinfo['site info'][sitename]['url']
    sitecookie = yamlinfo['site info'][sitename]['cookie']
    sitepasskey = yamlinfo['site info'][sitename]['passkey']
    shadowflow_download(sitename,siteurl,sitecookie,sitepasskey,yamlinfo,start_time)



def download_torrent(yamlinfo):
    logging.basicConfig(level=logging.ERROR, format="%(asctime)s - %(levelname)s - %(message)s",filename=f"{yamlinfo['basic']['record_path']}/torrent_download.log")
    csv_path = yamlinfo["basic"]["torrent_list"]
    file_path = f"{yamlinfo['basic']['torrent_path']}/"
    old_count = len([name for name in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, name))])
    logger.info(f'开始下载种子，当前种子文件夹中文件数量为{old_count}个')
    url_list = []

    try:
        client = Client(host=yamlinfo['qbinfo']['qburl'], username=yamlinfo['qbinfo']['qbwebuiusername'],
                        password=yamlinfo['qbinfo']['qbwebuipassword'])
    except:
        logger.warning(f'Qbittorrent登录失败')
    logger.info('正在登录Qbittorrent')
    try:
        client.auth_log_in()
    except:
        logger.warning(f"Qbittorrent信息错误，登录失败，\n当前设置的Qbittorent地址为{yamlinfo['qbinfo']['qburl']},用户名{yamlinfo['qbinfo']['qbwebuiusername']}，密码{yamlinfo['qbinfo']['qbwebuipassword']}，请检查")
    logger.info('成功登录Qbittorrent')

    with open(csv_path, 'r', encoding='utf-8') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader)
        for row in csvreader:
            download_url = row[5]
            url_list.append(download_url)
    counter = 0
    for url in url_list:
        with open(csv_path, 'r', encoding='utf-8') as csvfile:
            csvreader = csv.reader(csvfile)
            for _ in range(counter + 1):  # 跳到当前行
                next(csvreader)
            row = next(csvreader)
            passkey = row[8]  # 假设 passkey 在第9列 (列I)
        r = requests.get(url, params={"passkey": passkey})
        if r.status_code == 200:
            content_disposition = r.headers.get("Content-Disposition")
            if content_disposition:
                file_name = r.headers["Content-Disposition"].split(";")[-1].split("=")[-1].strip('"')
                file_name = urllib.parse.unquote(file_name)
                file_full_path = file_path + file_name
                with open(file_full_path, "wb") as f:
                    f.write(r.content)
                print(f"{file_name}种子文件已成功保存到本地")
                res = client.torrents_add(urls=url, is_skip_checking=False, is_paused=True)
                if res == "Ok.":
                    print(f"{file_name}添加Qbittorent成功")
                elif "fail" in res.lower():
                    print(f"{file_name}添加Qbittorent失败")
                elif "Torrent is already in the download list" in res:
                    print(f"{file_name}在Qbittorent中已存在")
            else:
                print("无法获取文件名,相关信息已记录在日志中，请查看record文件夹中的torrent_download.log")
                logging.error(f"无法获取文件名，下载失败：{url}")
        else:
            print(f"下载失败：{url}")
        counter += 1
    new_count = len([name for name in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, name))])
    logger.info(f'下载完成，本次共下载了{counter}个种子，实际下载成功了{new_count - old_count}个种子,本次任务结束')
    exit()








utils/getinfo/torrent_download.py
Ethan930717/AutoTransferMachine
import re
import json
from pathlib import Path
from typing import Optional
import requests
from loguru import logger
from bs4 import BeautifulSoup
from urllib.parse import urlparse

def url_to_domain(url):
     o = urlparse(url)
     domain = o.hostname
     return domain.split('.')[-2]

def get_token(url:str,cookie:str):
    headers={
    'cookie': cookie,
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'}
    try:
        response=requests.get(url=url,headers=headers)
    except Exception as r:
        logger.warning('获取token失败，原因: %s' %(r))
        return ''
    content=response.text
    soup=BeautifulSoup(content,'lxml')
    for link in soup.find_all("a"):
        links=link.get("href") 
        if 'auth_token' in links:
            return links[links.find('auth_token')+11:]
    return ''

def chevereto_api_upload(imgpath: str, url: str, api_key: str):
    img  = Path(imgpath)
    data = {'key': api_key}
    files = {'source': open(img, 'rb')}
    try:
        req = requests.post(f'{url}/api/1/upload', data=data, files=files)
    except Exception as r:
        logger.warning('requests 获取失败，原因: %s' %(r))
    try:
        res = req.json()
        logger.trace(res)
    except json.decoder.JSONDecodeError:
        res = {}
    if not req.ok:
        logger.trace(req.content)
        logger.warning(
            f"上传图片失败: HTTP {req.status_code}, reason: {req.reason} "
            f"{res['error'].get('message') if 'error' in res else ''}")
        return None
    if 'error' in res:
        logger.warning(f"上传图片失败: [{res['error'].get('code')}]{res['error'].get('message')}")
        return None
    if 'image' not in res or 'url' not in res['image']:
        logger.warning(f"图片直链获取失败")
        return None
    return res['image']['url']


def chevereto_cookie_upload(imgpath: str, url: str, cookie: str):
    auth_token=get_token(url,cookie)
    if auth_token=='':
        logger.warning('未找到auth_token')
        return None

    img  = Path(imgpath)
    headers = {'cookie': cookie}
    data = {'type': 'file', 'action': 'upload', 'nsfw': 0, 'auth_token': auth_token}
    files = {'source': open(img, 'rb')}

    try:
        req = requests.post(f'{url}/json', data=data, files=files, headers=headers)
    except Exception as r:
        logger.warning('requests 获取失败，原因: %s' %(r))
    try:
        res = req.json()
        logger.trace(res)
    except json.decoder.JSONDecodeError:
        res = {}
    if not req.ok:
        logger.warning(
            f"上传图片失败: HTTP {req.status_code}, reason: {req.reason} "
            f"{res['error'].get('message') if 'error' in res else ''}")
        return None
    if 'error' in res:
        logger.warning(f"上传图片失败: [{res['error'].get('code')}] {res['error'].get('context')} {res['error'].get('message')}")
        return None
    if 'status_code' in res and res.get('status_code') != 200:
        logger.warning(f"上传图片失败: [{res['status_code']}] {res.get('status_txt')}")
        return None 
    if 'image' not in res or 'url' not in res['image']:
        logger.warning(f"图片直链获取失败")
        return None
    return res['image']['url']

def chevereto_api_upload_files(imgpaths: list,url: str, api_key: str, form='img'):
    liststr=''
    imgnum=0
    domain=url_to_domain(url)
    for imgpath in imgpaths:
        imgnum=imgnum+1
        trynum=0
        success=0
        imgstr=''
        while success==0 and trynum<5:
            trynum=trynum+1
            try:
                imgstr=chevereto_api_upload(imgpath,url,api_key)
                success=1
            except Exception as r:
                success=0
                logger.warning(domain+'第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...原因: %s' %(r))
            if imgstr==None:
                success=0
                logger.warning(domain+'第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...')
        if success==1:
            if form.lower()=='img':
                liststr=liststr+imgstr+'\n'
            elif form.lower()=='bbcode':
                liststr=liststr+'[img]'+imgstr+'[/img]\n'
            else:
                liststr=liststr+imgstr+'\n'
            logger.info(domain+'第'+str(imgnum)+'张图片上传成功！')
        else:
            logger.warning(domain+'第'+str(imgnum)+'张图片'+imgpath+'上传失败')
    return liststr.strip()

def chevereto_cookie_upload_files(imgpaths: list,url: str, cookie: str, form='img'):
    liststr=''
    imgnum=0
    domain=url_to_domain(url)
    for imgpath in imgpaths:
        imgnum=imgnum+1
        trynum=0
        success=0
        imgstr=''
        while success==0 and trynum<5:
            trynum=trynum+1
            try:
                imgstr=chevereto_cookie_upload(imgpath,url,cookie)
                success=1
            except Exception as r:
                success=0
                logger.warning(domain+'第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...原因: %s' %(r))
            if imgstr==None:
                success=0
                logger.warning(domain+'第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...')
        if success==1:
            if form.lower()=='img':
                liststr=liststr+imgstr+'\n'
            elif form.lower()=='bbcode':
                liststr=liststr+'[img]'+imgstr+'[/img]\n'
            else:
                liststr=liststr+imgstr+'\n'
            logger.info(domain+'第'+str(imgnum)+'张图片上传成功！')
        else:
            logger.warning(domain+'第'+str(imgnum)+'张图片'+imgpath+'上传失败')
    return liststr.strip()

#p1="/Users/moyu/Downloads/在线视频十大品牌-视频app排行榜-视频网站排行榜-买购品牌网 (2).png"
#p2="/Users/moyu/Downloads/zhizhu.jpg"
#imgpaths=[p1,p2]
#key='chv_SVbN_71d381f1cefd83182c17337618060ed19f00232f809b12b6f1eeb8f5c5180714b1d0bb2b4b91f265dbbd0c4ea336eb840a637b92bdb7ba41c71c36c862a442a4'
#url='https://www.picgo.net/api/1/upload'
#print(chevereto_api_upload(p,url,key))
#print(chevereto_api_upload_files(imgpaths,url,key,'bbcode'))




#auth_token='5b22483f1d360d3aab9c51ff95e18e0e2fb3aaf2'
#url='https://s3.pterclub.com'
#cookie='KEEP_LOGIN=a4Np%3A575db23e5a8bb04e125711db411b9c18cee2c10dfa6e5ffce3be1d3a068c55c3c93f822a509746e5e84bdb71bc15b87bdf11e1a1361fda194cb5373fd9ff81fbaaef26119313e7a9b7e1aa96fde2032a64b451a87702ca42997bbdf1e7f8f11394991b795c%3A1658856793; PHPSESSID=t6usd4455j8dle6jr71oc6jpkm'
#p='/Users/moyu/Downloads/1.png'
#auth_token='2ff56e94fe9a5e817dfb5a20211df8677d1243f0'
#cookie='PHPSESSID=7a5tf1pcrpttglphd0rlid7rpq; AGREE_CONSENT=1; KEEP_LOGIN=CPT%3A11717c9cc52cbcd96397bd68d2178737bfd4839973ff561f4401af4c59ba84c4b30af45e5b8cb497b4d79e7bb5653f7b670f5bd6be833ae6dc122e63c63c54391e4782918be061dbbcf1776136dbe14c28040551e2730c59c358091cf6fc8625804a1d3647a19bc2%3A1658892099'
#url='https://jerking.empornium.ph'
#print(chevereto_cookie_upload(p,url,cookie,auth_token))






utils/img_upload/chevereto.py
Ethan930717/AutoTransferMachine
import os
import re
import random
from pathlib import Path
from typing import Optional, List
from string import ascii_letters, digits
import requests
from loguru import logger
from lxml.html import fromstring



def get_csrf_token(session) -> Optional[str]:
    req = session.get('https://imgbox.com')
    if req.ok:
        m = re.search(r"content=\"(.*?)\" name=\"csrf-token\"", req.text)
        if m:
            return m.groups()[0]
    return None


def get_token(session, csrf_token: str, gallery_title: Optional[str], allow_comment: bool = False) -> dict:
    headers = {
        'X-CSRF-Token': csrf_token,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
    }
    data = {
        "gallery": "true" if gallery_title is not None else "false",
        # TODO: need to test when gallery title is None
        "gallery_title": gallery_title,
        "comments_enabled": str(int(allow_comment)),
    }
    req = session.post("https://imgbox.com/ajax/token/generate", data=data, headers=headers, json=True)
    if req.ok and req.json().get("ok"):
        return req.json()
    return {}

def login(session, username, password, csrf_token):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
    }
    data = {
        "utf8": "✓",
        "authenticity_token": csrf_token,
        "user[login]": username,
        "user[password]": password
    }
    logger.info("正在登录imgbox...")
    req = session.post("https://imgbox.com/login", data=data, headers=headers)
    if len(req.history) and req.history[-1].status_code == 302:
        logger.info("登录成功")
        return
    logger.warning("登录失败，使用匿名模式上传")
        

def imgbox_upload_files(
    imgpaths: List[str],
    username: str = None,
    password: str = None,
    gallery_title: str = None,
    thumbnail_size: str = "300r",
    is_family_safe: bool = True,
    allow_comment: bool = False,
    form:str ="img",
) :
    for i in range(len(imgpaths)):
        imgpaths[i]=Path(imgpaths[i])
    session = requests.Session()
    csrf_token = get_csrf_token(session)
    if username and password:
        login(session, username, password, csrf_token)
    token = get_token(session, csrf_token, gallery_title, allow_comment)
    if not token:
        logger.warning("获取token失败")
        return []

    headers = {
        'X-CSRF-Token': csrf_token,
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
    }
    urls = []
    for count, img in enumerate(imgpaths):
        data = {
            "token_id": str(token.get("token_id")),
            "token_secret": token.get("token_secret"),
            "content_type": str(int(is_family_safe)),
            "thumbnail_size": thumbnail_size,
            "gallery_id": token.get("gallery_id"),
            "gallery_secret": token.get("gallery_secret"),
            "comments_enabled": str(int(allow_comment)),
        }
        files = {
            "files[]": open(img, "rb"),
        }
        req = session.post(
            "https://imgbox.com/upload/process",
            data=data,
            files=files,
            headers=headers,
        )

        if not req.ok:
            logger.trace(req.content)
            logger.warning(f"上传图片失败: HTTP {req.status_code}, reason: {req.reason}")
            return None
        elif req.json().get("error"):
            logger.trace(req.content)
            logger.warning(
                f"上传图片失败: Code {req.json()['error'].get('code')}, message: {req.json()['error]'].get('message')}"
            )
            return None
        logger.info(f"第{count+1}张截图上传成功")
        urls.append(req.json())

    logger.info(f"Imgbox图床链接：https://imgbox.com/upload/edit/{token.get('token_id')}/{token.get('token_secret')}")
    urlstr=''
    for url in urls:
        if 'img' in form.lower():
            urlstr=urlstr+url.get("files", [{}])[0].get("original_url")+'\n'
        elif 'bbcode' in form.lower():
            urlstr=urlstr+'[url='+url.get("files", [{}])[0].get("original_url")+'][img]'+url.get("files", [{}])[0].get("thumbnail_url")+'[/img][/url]\n'
        else:
            urlstr=urlstr+url.get("files", [{}])[0].get("original_url")+'\n'
    return urlstr






utils/img_upload/imgbox.py
Ethan930717/AutoTransferMachine
import os
from loguru import logger
from utils.img_upload.chevereto import chevereto_api_upload_files,chevereto_cookie_upload_files
from utils.img_upload.ptpimg import ptpimg_upload_files
from utils.img_upload.smms import smms_upload_files
from utils.img_upload.imgbox import imgbox_upload_files


def existitem(imgdata,item):
    if item in imgdata and not(imgdata[item]=='') and not imgdata[item]==None:
        return True
    return False

def createimgdict(imgdata):
    imgdict=dict()
    imghostlist=['ptpimg','picgo','smms','pter','imgbox','freeimage','kimoji']
    for item in imghostlist:
        imgdict[item]=False
    if existitem(imgdata,'ptpimg') and existitem(imgdata['ptpimg'],'apikey'):
        imgdict['ptpimg']=True
    if existitem(imgdata,'picgo') and existitem(imgdata['picgo'],'apikey') and existitem(imgdata['picgo'],'url') :
        imgdict['picgo']=True
    if existitem(imgdata,'smms') and existitem(imgdata['smms'],'apikey'):
        imgdict['smms']=True
    if existitem(imgdata,'pter')  and existitem(imgdata['pter'],'url') and existitem(imgdata['pter'],'cookie') :
        imgdict['pter']=True
    if existitem(imgdata,'kimoji')  and existitem(imgdata['kimoji'],'url') and existitem(imgdata['kimoji'],'cookie') :
        imgdict['kimoji']=True
    if existitem(imgdata,'freeimage')  and existitem(imgdata['freeimage'],'url') and existitem(imgdata['freeimage'],'cookie') :
        imgdict['freeimage']=True
    imgdict['imgbox']=True
    listnum=1
    seq=[]
    while (existitem(imgdata['seq'],(listnum))):
        seq.append(imgdata['seq'][(listnum)])
        listnum=listnum+1
    return imgdata,imgdict,seq

def img_upload_seq(imgdata,seq:list[str],imglist:list[str],form:str='img'):
    for i in range(len(seq)):
        res=img_upload(imgdata=imgdata,imglist=imglist,host=seq[i],form=form,fail=True)
        if not (res==''):
            return res

def img_upload(imgdata,imglist:list[str],host:str='',form:str='img',fail:bool=False,chevereto_url:str='',chevereto_apikey:str='',chevereto_cookie:str=''):
    imgdata,imgdict,seq=createimgdict(imgdata)
    success=True
    res=''
    if host=='':
    	host=seq[0]
    if 'ptpimg'in host.lower():
        host='ptpimg'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=ptpimg_upload_files(imgpaths=imglist,api_key=imgdata[host]['apikey'],form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'picgo' in host.lower():
        host='picgo'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=chevereto_api_upload_files(imgpaths=imglist,url=imgdata[host]['url'].strip('/'),api_key=imgdata[host]['apikey'],form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'smms' in host.lower():
        host='smms'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=smms_upload_files(imgpaths=imglist,api_key=imgdata[host]['apikey'],form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'pter' in host.lower():
        host='pter'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=chevereto_cookie_upload_files(imgpaths=imglist,url=imgdata[host]['url'].strip('/'), cookie=imgdata[host]['cookie'], form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'kimoji' in host.lower():
        host='kimoji'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=chevereto_cookie_upload_files(imgpaths=imglist,url=imgdata[host]['url'].strip('/'), cookie=imgdata[host]['cookie'], form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'imgbox' in host.lower():
        host='imgbox'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=imgbox_upload_files(imgpaths=imglist, form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'chd' in host.lower():
        host='chd'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=chevereto_cookie_upload_files(imgpaths=imglist,url=imgdata[host]['url'].strip('/'), cookie=imgdata[host]['cookie'], form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'freeimage' in host.lower():
        host='freeimage'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=chevereto_cookie_upload_files(imgpaths=imglist,url=imgdata[host]['url'].strip('/'), cookie=imgdata[host]['cookie'], form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'chevereto_api' in host.lower():
        host='chevereto_api'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if not (chevereto_url=='' or chevereto_apikey==''):
            res=chevereto_api_upload_files(imgpaths=imglist,url=chevereto_url,api_key=chevereto_apikey,form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    elif 'chevereto_cookie' in host.lower():
        host='chevereto_cookie'
        logger.info('正在尝试使用'+host+'上传图片,请稍等...')
        if not (chevereto_url=='' or chevereto_cookie==''):
            res=chevereto_cookie_upload_files(imgpaths=imglist,url=chevereto_url, cookie=chevereto_cookie, form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    else:
        host='ptpimg'
        logger.info('未找到该图床，正在尝试使用'+host+'上传图片,请稍等...')
        if imgdict[host]==True:
            res=ptpimg_upload_files(imgpaths=imglist,api_key=imgdata[host]['apikey'],form=form)
        else:
            success=False
            logger.warning('图床'+host+'配置信息缺失')
        if res=='':
            success=False
    if success:
        logger.info('上传成功！')
        return res
    else:
        logger.warning('上传失败！')
        if fail==False:
            return img_upload_seq(imgdata=imgdata,seq=seq,imglist=imglist,form=form)
        else:
            return ''

utils/img_upload/imgupload.py
Ethan930717/AutoTransferMachine
import json
from pathlib import Path
import requests
from urllib.parse import urlparse
from loguru import logger

def ptpimg_upload(imgpath: str, api_key: str):
    img  = Path(imgpath)
    data = {'api_key': api_key}
    files = {'file-upload[0]': open(img, 'rb')}
    try:
        req = requests.post('https://ptpimg.me/upload.php', data=data, files=files)
    except Exception as r:
        logger.warning('requests 获取失败，原因: %s' %(r))
        return None
    try:
        res = req.json()
    except json.decoder.JSONDecodeError:
        res = {}
    if not req.ok:
        logger.warning(req.content)
        logger.warning(f"上传图片失败: HTTP {req.status_code}, reason: {req.reason}")
        return None
    if len(res) < 1 or 'code' not in res[0] or 'ext' not in res[0]:
        logger.warning(f"图片直链获取失败")
        return None
    return f"https://ptpimg.me/{res[0].get('code')}.{res[0].get('ext')}"


def ptpimg_upload_files(imgpaths: list, api_key: str, form='img'):
    liststr=''
    imgnum=0
    for imgpath in imgpaths:
        imgnum=imgnum+1
        trynum=0
        success=0
        imgstr=''
        while success==0 and trynum<5:
            trynum=trynum+1
            try:
                imgstr=ptpimg_upload(imgpath,api_key)
                success=1
            except Exception as r:
                success=0
                logger.warning('PTPIMG第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，失败原因: %s\n正在重试...' %(r))
            if imgstr==None:
                success=0
                logger.warning('PTPIMG第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...')
        if success==1:
            if form.lower()=='img':
                liststr=liststr+imgstr+'\n'
            elif form.lower()=='bbcode':
                liststr=liststr+'[img]'+imgstr+'[/img]\n'
            else:
                liststr=liststr+imgstr+'\n'
            logger.info('PTPIMG第'+str(imgnum)+'张图片上传成功！')
        else:
            logger.warning('PTPIMG第'+str(imgnum)+'张图片'+imgpath+'上传失败')
    return liststr.strip()
    

#p1="/Users/moyu/Downloads/在线视频十大品牌-视频app排行榜-视频网站排行榜-买购品牌网 (2).png"
#p2="/Users/moyu/Downloads/zhizhu.jpg"
#imgpaths=[p1,p2]
#key='de2a51b1-d5fc-45d0-8429-9c53a0c36468'
#print(ptpimg_upload(p,key))
#print(ptpimg_upload_files(imgpaths,key,'bbcode'))






utils/img_upload/ptpimg.py
Ethan930717/AutoTransferMachine
import json
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
import requests
from loguru import logger

def smms_upload(imgpath: str, api_key: str):
    img  = Path(imgpath)
    headers = {'Authorization': api_key}
    files = {'smfile': open(img, 'rb'), 'format': 'json'}
    try:
        #req = requests.post('https://sm.ms/api/v2/upload', headers=headers, files=files)
        req = requests.post('https://smms.app/api/v2/upload', headers=headers, files=files)
    except Exception as r:
        logger.warning('requests 获取失败，原因: %s' %(r))
        return None
    try:
        res = req.json()
    except json.decoder.JSONDecodeError:
        logger.warning('返回结果获取失败')
        res = {}
    if not req.ok:
        logger.warning(
            f"上传图片失败: HTTP {req.status_code}, reason: {req.reason} "
            f"{res.get('msg') if 'msg' in res else ''}")
        return None
    if not res.get('success') and res.get('code') != 'image_repeated':
        logger.warning(f"上传图片失败: [{res.get('code')}]{res.get('message')}")
        return None
    if res.get('code') == 'image_repeated':
        return res.get('images')
    if 'data' not in res or 'url' not in res['data']:
        logger.warning(f"图片直链获取失败")
        return None
    return res['data']['url']

def smms_upload_files(imgpaths: list, api_key: str, form='img'):
    liststr=''
    imgnum=0
    for imgpath in imgpaths:
        imgnum=imgnum+1
        trynum=0
        success=0
        imgstr=''
        while success==0 and trynum<5:
            trynum=trynum+1
            try:
                imgstr=smms_upload(imgpath,api_key)
                success=1
            except Exception as r:
                success=0
                logger.warning('SMMS第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...原因: %s' %(r))
            if imgstr==None:
                success=0
                logger.warning('SMMS第'+str(imgnum)+'张图片'+imgpath+'第'+str(trynum)+'次上传失败，正在重试...')
        if success==1:
            if form.lower()=='img':
                liststr=liststr+imgstr+'\n'
            elif form.lower()=='bbcode':
                liststr=liststr+'[img]'+imgstr+'[/img]\n'
            else:
                liststr=liststr+imgstr+'\n'
            logger.info('SMMS第'+str(imgnum)+'张图片上传成功！')
        else:
            logger.warning('SMMS第'+str(imgnum)+'张图片'+imgpath+'上传失败')
    return liststr.strip()

#p1="/Users/moyu/Downloads/在线视频十大品牌-视频app排行榜-视频网站排行榜-买购品牌网 (2).png"
#p2="/Users/moyu/Downloads/zhizhu.jpg"
#imgpaths=[p1,p2]
#key='7ubkPohmLV4LcAUjB5FsDmI0DWvaPo28'
#print(smms_upload(p,key))
#print(smms_upload_files(imgpaths,key,'bbcode'))

utils/img_upload/smms.py
Ethan930717/AutoTransferMachine
# -*- coding: utf-8 -*-

import re
import requests
from bs4 import BeautifulSoup


class BookPageParse:
    def __init__(self, book_id:int = 0, book_url:str = '',cookie:str = ''):
        """
        初始化
        :param book_id:
        :param book_info_html:
        """

        if book_id==0 and book_url=='':
            raise Exception('豆瓣链接与豆瓣id至少输入一个')
        elif book_id==0:
            try:
                book_id=int(re.findall('/subject/(\d+)/',book_url)[0])
            except Exception as err:
                raise Exception('豆瓣链接填写错误')
            book_url='https://book.douban.com/subject/' + str(book_id)+'/'
        elif book_url.strip()=='':
            book_url='https://book.douban.com/subject/' + str(book_id)+'/'
        
        self.book_id = book_id
        self.book_url = book_url
        self.cookie = cookie

        user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53'
        headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Sec-Fetch-Dest': 'document' ,
                'Sec-Fetch-Mode': 'navigate' ,
                'Sec-Fetch-Site': 'none' ,
                'Sec-Fetch-User': '?1' ,
                'Upgrade-Insecure-Requests': '1' ,
                'User-Agent': user_agent,
                'sec-ch-ua': '"Microsoft Edge";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
                'sec-ch-ua-mobile': '?0' ,
                'sec-ch-ua-platform': '"macOS"',
            }
        book_info_html = requests.get(book_url,headers=headers,timeout=20).text
        self.book_info_html=book_info_html
        self.book_soup = BeautifulSoup(self.book_info_html, 'lxml')

    def _get_book_name(self):
        """
        得到书籍名称
        :return:
        """
        try:
            name = self.book_soup.find('span', property="v:itemreviewed").text
        except Exception as err:
            name = ''
        return name

    def _get_book_image_url(self):
        """
        得到书籍图片链接
        :return:
        """
        try:
            image_url = str(self.book_soup.find('img', rel='v:photo')['src'])
        except Exception as err:
            image_url = ''
        return image_url

    def _get_book_subtitle(self):
        """
        获取书籍副标题
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            subtitle_str = str(re.search(r'副标题:</span>.*<br/>', book_info).group())
            subtitle = subtitle_str.replace('副标题:</span>', '').replace('<br/>', '').replace(' ', '')
        except Exception as err:
            subtitle = ''
        return subtitle

    def _get_book_origin_name(self):
        """
        获取书籍原作名
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            origin_name_str = str(re.search(r'原作名:</span>.*<br/>', book_info).group())
            origin_name = origin_name_str.replace('原作名:</span>', '').replace('<br/>', '')
        except Exception as err:
            origin_name = ''
        return origin_name.strip()

    def _get_book_author(self):
        """
        得到图书作者信息
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            book_info = book_info.replace('\n', '').replace(' ', '').replace('\xa0', '')
            if '作者</span>:' in book_info:
                book_author_str = str(re.search(r'作者</span>:.*?<br/>', book_info).group())
            else:
                book_author_str = re.search(r'作者:</span>.*?<br/>', book_info).group()
            book_author_list = book_author_str.split('</a>')
            author_list = []
            for i in range(0, len(book_author_list) - 1):
                author_str = book_author_list[i]
                author_name = re.sub(r'.*>', '', author_str)
                author_href = ''
                if '/author/' in author_str:
                    author_href = str(re.findall(r'href=".*"', author_str)[0]).replace('href=', '').replace('"', '')
                    author_href = author_href.replace('https://book.douban.com', '')
                author = {
                    'name': author_name,
                    'href': author_href
                }
                author_list.append(author)
        except Exception as err:
            author_list = []
        return author_list

    def _get_book_translator(self):
        """
        得到书籍译者
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            book_info = book_info.replace('\n', '').replace(' ', '').replace('\xa0', '')
            if '译者</span>:' in book_info:
                book_translator_str = str(re.search('译者</span>:.*?<br/>', book_info).group())
            else:
                book_translator_str = re.search('译者:</span>.*?<br/>', book_info).group()
            book_translator_list = book_translator_str.split('</a>')
            translator_list = []
            for i in range(0, len(book_translator_list) - 1):
                translator_str = book_translator_list[i]
                translator_name = str(re.sub(r'.*>', '', translator_str))
                translator_href = ''
                if '/author/' in translator_str:
                    translator_href = str(re.findall(r'href=".*"', translator_str)[0]).replace('href=', '').replace('"',
                                                                                                                    '')
                    translator_href = translator_href.replace('https://book.douban.com', '')
                translator = {
                    'name': translator_name,
                    'href': translator_href
                }
                translator_list.append(translator)
        except Exception as err:
            translator_list = []
        return translator_list

    def _get_book_press(self):
        """
        得到图书出版社信息
        :return:
        """

        try:
            book_info = self.book_soup.find('div', id='info')
            pressinfo=book_info.find('span',class_='pl',text=re.compile("出版社"))
            press_text = pressinfo.findNextSibling('a').text
            press = press_text.replace('出版社:</span>', '').replace(' ', '').replace('<br/>', '')
        except Exception as err:
            press = ''
            
        try:
            href=pressinfo.findNextSibling('a').attrs['href']
        except Exception as err:
            href = ''

        press={
            'name': press.strip(),
            'href': href,
        }
        return press
    
    def _get_book_producers(self):
        """
        得到图书出品方信息
        :return:
        """
        try:
            book_info = self.book_soup.find('div', id='info')
            producersinfo=book_info.find('span',class_='pl',text=re.compile("出品方"))
            producers_text = producersinfo.findNextSibling('a').text
            href=producersinfo.findNextSibling('a').attrs['href']
            producers = producers_text.replace('出品方:</span>', '').replace(' ', '').replace('<br/>', '')
        except Exception as err:
            producers = ''

        try:
            href=producersinfo.findNextSibling('a').attrs['href']
        except Exception as err:
            href=''

        producers={
            'name': producers.strip(),
            'href': href,
        }

        return producers
    
    def _get_book_series(self):
        """
        得到图书出品方信息
        :return:
        """
        try:
            book_info = self.book_soup.find('div', id='info')
            seriesinfo=book_info.find('span',class_='pl',text=re.compile("丛书"))
            series_text = seriesinfo.findNextSibling('a').text
            series = series_text.replace('丛书:</span>', '').replace(' ', '').replace('<br/>', '')
        except Exception as err:
            series = ''
        
        try:
            href=seriesinfo.findNextSibling('a').attrs['href']
        except Exception as err:
            href=''

        series={
            'name': series.strip(),
            'href': href,
        }

        return series
    
    def _get_book_ISBN(self):
        """
        得到图书ISBN信息
        :return:
        """
        try:
            book_info = self.book_soup.find('div', id='info')
            isbninfo=book_info.find('span',class_='pl',text=re.compile("ISBN"))
            isbn=isbninfo.next_sibling.text.strip()
        except Exception as err:
            isbn = ''
        return isbn
    
    def _get_book_pack(self):
        """
        得到图书ISBN信息
        :return:
        """
        try:
            book_info = self.book_soup.find('div', id='info')
            packinfo=book_info.find('span',class_='pl',text=re.compile("装帧"))
            pack=packinfo.next_sibling.text.strip()
        except Exception as err:
            pack = ''
        return pack

    def _get_book_publish_year(self):
        """
        书籍出版年份
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            publish_year_str = str(re.search(r'出版年:</span>.*<br/>', book_info).group())
            publish_year_str = publish_year_str.replace('出版年:</span>', '').replace('<br/>', '').replace(' ', '')
            publish_year = re.sub('<a.*>', '', publish_year_str)
        except Exception as err:
            publish_year = ''
        return publish_year

    def _get_book_page_num(self):
        """
        得到书籍页面
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            page_num_str = str(re.search(r'页数:</span>.*<br/>', book_info).group())
            page_num_str = page_num_str.replace('页数:</span>', '').replace('<br/>', '').replace(' ', '')
            page_num = re.sub('<a.*>', '', page_num_str)
        except Exception as err:
            page_num = ''
        return page_num

    def _get_book_price(self):
        """
        得到书籍价格
        :return:
        """
        try:
            book_info = str(self.book_soup.find('div', id='info'))
            price_str = str(re.search(r'定价:</span>.*<br/>', book_info).group())
            price_str = price_str.replace('定价:</span>', '').replace('<br/>', '').replace(' ', '')
            price = re.sub('<a.*>', '', price_str)
        except Exception as err:
            price = ''
        return price

    def _get_book_content_abstract(self):
        """
        得到图书内容简介
        :return:
        """
        try:
            try:
                content_abstract = str(self.book_soup.find('span', class_='all hidden').text)
                content_abstract = content_abstract.replace(' ', '').replace('\n', '').replace('\u3000', '')
                content_abstract = str(re.sub('.*;}', '', content_abstract))
            except:
                content_abstract = str(self.book_soup.find_all('div', class_='intro')[0].text)
                content_abstract = content_abstract.replace(' ', '').replace('\n', '').replace('\u3000', '')
        except Exception as err:
            content_abstract = ''
        return content_abstract

    def _get_book_catalog(self):
        """
        得到图书目录
        :return:
        """
        try:
            try:
                catalog_id = 'dir_' + str(self.book_id) + '_full'
                catalog = str(self.book_soup.find('div', id=catalog_id).text)
                catalog = catalog.replace(' ', '')
            except:
                catalog_id = 'dir_' + str(self.book_id) + '_short'
                catalog = str(self.book_soup.find('div', id=catalog_id).text)
                catalog = catalog.replace(' ', '')
        except Exception as err:
            catalog = ''
        return catalog

    def _get_book_rating(self):
        """
        得到书籍评分
        :return:
        """
        try:
            average = str(self.book_soup.find('strong', property='v:average').text)
            reviews_count = str(self.book_soup.find('a', class_='rating_people').text)
            rating = {
                'average': average,
                'reviews_count': reviews_count
            }
        except Exception as err:
            rating = {
                'average': '',
                'reviews_count': ''
            }
        return rating

    def parse(self):
        """
        获取书籍信息
        :return:
        """
        name = self._get_book_name()  # 书籍名称
        image_url = self._get_book_image_url()  # 书籍图片链接
        subtitle = self._get_book_subtitle()  # 书籍副标题
        origin_name = self._get_book_origin_name()  # 原作名
        author = self._get_book_author()  # 书籍作者
        translator = self._get_book_translator()  # 书籍译者
        press = self._get_book_press()  # 书籍出版社
        publish_year = self._get_book_publish_year()  # 书籍出版年份
        price = self._get_book_price()  # 书籍价格
        page_num = self._get_book_page_num()  # 书籍页数
        content_abstract = self._get_book_content_abstract()  # 图书内容简介
        catalog = self._get_book_catalog()  # 图书目录
        rating = self._get_book_rating()  # 书籍评分
        isbn = self._get_book_ISBN() #ISBN
        producers = self._get_book_producers() #出品方
        series = self._get_book_series() #丛书
        pack = self._get_book_pack() #装帧

        book_info_json = {
            'id': self.book_id,
            'image_url': image_url,
            'name': name,
            'subtitle': subtitle,
            'author': author,
            'press': press,
            'producers': producers,
            'origin_name': origin_name,
            'translator': translator,
            'publish_year': publish_year,
            'page_num': page_num,
            'price': price,
            'pack' : pack,
            'series': series,
            'ISBN': isbn,
            'content_abstract': content_abstract,
            'catalog': catalog,
            'rating': rating
        }
        return book_info_json

    def info(self):
        data=self.parse()
        douban_info=''
        if (data['image_url']):
            imgurl=re.findall('img[0-9]\.doubanio\.com',data['image_url'])
            douban_info = douban_info+"[img]" + data['image_url'].replace(imgurl[0],'img9.doubanio.com') + "[/img]\n"
        if (data['name']):
            douban_info = douban_info+ "\n◎书\u3000\u3000名　" + data['name'];
        if (data['author']) :
            douban_info += "\n◎作\u3000\u3000者　" + data['author'][0]['name']
        if (data['press']) :
            douban_info += "\n◎出版\u3000社　" + data['press']['name']
        if (data['producers']) :
            douban_info += "\n◎出品\u3000方　" + data['producers']['name']
        if (data['origin_name']) :
            douban_info += "\n◎原作名称　" + data['origin_name']
        if (data['translator']) :
            douban_info += "\n◎译\u3000\u3000者　" + data['translator'][0]['name']
        if (data['publish_year']) :
            douban_info += "\n◎出版年月　" + data['publish_year']
        if (data['page_num']) :
            douban_info += "\n◎页\u3000\u3000数　" + str(data['page_num'])
        if (data['price']) :
            douban_info += "\n◎定\u3000\u3000价　" + data['price']
        if (data['pack']) :
            douban_info += "\n◎装\u3000\u3000帧　" + data['pack']
        if (data['series']) :
            douban_info += "\n◎从\u3000\u3000书　" + data['series']['name']
        if (data['ISBN']) :
            douban_info += "\n◎I S B N　 " + data['ISBN']
        if (data['price']) :
            douban_info += "\n◎定\u3000\u3000价　" + data['price']
        if (data['rating']) :
            douban_info += "\n◎豆瓣评分　" + str(data['rating']['average']) + "/10 from " + str(re.findall('\d+',data['rating']['reviews_count'])[0]) + " users";
        if (self.book_url) :
            douban_info += "\n◎豆瓣链接　" + self.book_url
        if (data['catalog']):
            douban_info += "\n◎目\u3000\u3000录　" + str(data['catalog'])
        if (data['content_abstract']) :
            douban_info += "\n\n◎简　　介　" + "\n\n " +(data['content_abstract'])
        else:
            douban_info += "\n\n◎简　　介　" + "\n\n 暂无相关剧情介绍"
        douban_info =douban_info+ "\n\n"
        self.douban_info=douban_info
        return douban_info


utils/mediafile/douban_book.py
Ethan930717/AutoTransferMachine
# -*- coding: utf-8 -*-

import re
import requests
from bs4 import BeautifulSoup
import json


class MoviePageParse:
    def __init__(self, movie_id:int = 0, movie_url:str = '',cookie:str = ''):
        """
        初始化
        :param movie_id:
        :param movie_info_html:
        """
        self.movie_id = movie_id
        self.movie_url = movie_url
        if movie_id==0 and movie_url=='':
            raise Exception('豆瓣链接与豆瓣id至少输入一个')
        elif movie_id==0:
            try:
                movie_id=int(re.findall('/subject/(\d+)/',movie_url)[0])
            except Exception as err:
                raise Exception('豆瓣链接填写错误')
            movie_url='https://movie.douban.com/subject/' + str(movie_id)+'/'
        elif movie_url.strip()=='':
            movie_url='https://movie.douban.com/subject/' + str(movie_id)+'/'
        else:
            movie_url='https://movie.douban.com/subject/' + str(movie_id)+'/'
        
        self.movie_id = movie_id
        self.movie_url = movie_url
        self.cookie = cookie

        user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53'
        headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                'Connection': 'keep-alive',
                'Cookie': cookie,
                'Sec-Fetch-Dest': 'document' ,
                'Sec-Fetch-Mode': 'navigate' ,
                'Sec-Fetch-Site': 'none' ,
                'Sec-Fetch-User': '?1' ,
                'Upgrade-Insecure-Requests': '1' ,
                'User-Agent': user_agent,
                'sec-ch-ua': '"Microsoft Edge";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
                'sec-ch-ua-mobile': '?0' ,
                'sec-ch-ua-platform': '"macOS"',
            }
        movie_info_html = requests.get(movie_url,headers=headers,timeout=20).text
        self.movie_info_html= movie_info_html
        self.film_soup = BeautifulSoup(self.movie_info_html, 'lxml')

    def _get_movie_name(self):
        """
        获取电影姓名
        :param film_soup:
        :return:
        """
        try:
            name = str(self.film_soup.find('span', property='v:itemreviewed').text)
        except Exception as err:
            name = ''
            #info span.pl:contains("又名")
        return name

    def _get_movie_names(self):
        """
        获取电影姓名
        :param film_soup:
        :return:
        """
        try:
            chinesename = self.film_soup.title.text.replace('(豆瓣)','').strip()
        except Exception as err:
            chinesename = ''
        
        try:
            originalTitle = self._get_movie_name().replace(chinesename,'').strip()
        except Exception as err:
            originalTitle = ''
        
        akaTitles=[]
        try:
            akaTitles=self.film_soup.find('span', class_='pl',text=re.compile("又名")).next_sibling.text.strip().split(' / ')
        except Exception as err:
            akaTitles = []

        if originalTitle=='':
            originalTitle=chinesename
            if len(akaTitles)>0:
                translatedTitle=akaTitles[0]
            else:
                translatedTitle=chinesename
        else:
            translatedTitle=chinesename
        
        

        names={
            'chinesename': chinesename,
            'originalTitle': originalTitle,
            'translatedTitle': translatedTitle,
            'akaTitles': akaTitles,
        }
        return names

    def _get_movie_imdb(self):
        """
        获取imdb
        :param film_soup:
        :return:
        """
        try:
            imdb=self.film_soup.find('span', class_='pl',text=re.compile("IMDb")).next_sibling.text.strip()
        except Exception as err:
            imdb = ''
        return imdb
    
    def _get_movie_imdbscore(self):
        """
        获取imdb分数
        :param film_soup:
        :return:
        """
        imdb=self._get_movie_imdb()
        if imdb.strip()=='':
            imdbrating={
                'rating': 0,
                'ratingCount': 0,
            }
            return imdbrating

        url='http://p.media-imdb.com/static-content/documents/v1/title/'+imdb+'/ratings%3Fjsonp=imdb.rating.run:imdb.api.title.ratings/data.json'
        user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53'
        headers={
            'referrer': 'http://p.media-imdb.com/',
            'User-Agent': user_agent,
        }
        r= requests.get(url,headers=headers,timeout=20)
        
        
        rating=0
        ratingCount=0

        try:
            data=r.text[16:-1]
            data2 = json.loads(data)
            rating=data2['resource']['rating']
            ratingCount=data2['resource']['ratingCount']
        except Exception as err:
            rating=0
            ratingCount=0

        imdbrating={
            'rating': rating,
            'ratingCount': ratingCount,
        }
        return imdbrating

    def _get_movie_year(self):
        """
        获取电影年份
        :param film_soup:
        :return:
        """
        try:
            year = str(self.film_soup.find('span', class_='year').text)
        except Exception as err:
            year = ''
        
        year=re.findall('\d\d\d\d',year)

        try:
            year = int(year[0])
        except Exception as err:
            year = 2022

        return year

    def _get_movie_image_url(self):
        """
        获取电影图片链接
        :return:
        """
        try:
            image_url = str(self.film_soup.find('img', title='点击看更多海报')['src'])
        except Exception as err:
            image_url = ''
        try:
            image_url='https://img9.doubanio.com/view/photo/l_ratio_poster/public/'+re.findall('(p\d+).',image_url)[0]+'.jpg'
        except Exception as err:
            image_url = ''
        #image_url=image_url.replace(re.findall('img[0-9]\.doubanio\.com',image_url)[0],'img9.doubanio.com')
        return image_url

    def _get_movie_directors(self):
        """
        获取电影导演信息
        :param film_soup:
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            directors = []
            directors_text = re.search(r'导演</span>: <span class="attrs">.*</span><br/>', film_info).group()
            directors_text = directors_text.replace('导演</span>: <span class="attrs">', '').replace('</span><br/>',
                                                                                                   '').replace(
                '</span>', '')
            directors_text_list = directors_text.split('</a>')
            while '' in directors_text_list:
                directors_text_list.remove('')
            for director in directors_text_list:
                director_name = re.sub(r'<a.*>', '', director).replace('/', '').replace(' ', '')
                if 'celebrity' in director:
                    director_href = re.search(r'href="/celebrity/\d{0,15}/"', director).group().replace('href=',
                                                                                                        '').replace('"',
                                                                                                                    '')
                else:
                    director_href = ''
                directors.append({'name': director_name, 'href': director_href})
        except Exception as err:
            directors = []

        return directors

    def _get_movie_writers(self):
        """
        获取电影编剧信息
        :param film_soup:
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            writers = []
            writers_text = re.search(r'编剧</span>: <span class="attrs">.*</span><br/>', film_info).group()
            writers_text = writers_text.replace('编剧</span>: <span class="attrs">', '').replace('</span><br/>',
                                                                                               '').replace(
                '</span>', '')
            writers_text_list = writers_text.split('</a>')
            while '' in writers_text_list:
                writers_text_list.remove('')
            for writer in writers_text_list:
                writer_name = re.sub(r'<a.*>', '', writer).replace('/', '').replace(' ', '')
                if 'celebrity' in writer:
                    writer_href = re.search(r'href="/celebrity/\d{0,15}/"', writer).group().replace('href=',
                                                                                                    '').replace('"', '')
                else:
                    writer_href = ''
                writers.append({'name': writer_name, 'href': writer_href})
        except Exception as err:
            writers = []

        return writers

    def _get_movie_actors(self):
        """
        获取电影演员信息
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            actors = []
            actors_text = re.search(r'主演</span>: <span class="attrs">.*</span><br/>', film_info).group()
            actors_text = actors_text.replace('主演</span>: <span class="attrs">', '').replace('</span><br/>',
                                                                                             '').replace(
                '</span>', '')
            actors_text_list = actors_text.split('</a>')
            while '' in actors_text_list:
                actors_text_list.remove('')
            for actor in actors_text_list:
                actor_name = re.sub(r'<a.*>', '', actor).replace('/', '').replace(' ', '')
                if 'celebrity' in actor:
                    actor_href = re.search(r'href="/celebrity/\d{0,15}/"', actor).group().replace('href=', '').replace(
                        '"', '')
                else:
                    actor_href = ''
                actors.append({'name': actor_name, 'href': actor_href})
        except Exception as err:
            actors = []
        return actors

    def _get_movie_genres(self):
        """
        获取电影类型
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            genres = []
            genres_text = re.search(r'类型:</span> .*<br/>', film_info).group()
            genres_text = genres_text.replace('类型:</span> ', '').replace('<br/>', '')
            genres_text_list = genres_text.split('</span>')
            while '' in genres_text_list:
                genres_text_list.remove('')
            for genre in genres_text_list:
                genre_name = re.sub(r'<span.*>', '', genre).replace('/', '').replace(' ', '')
                genres.append(genre_name)
        except Exception as err:
            genres = []

        return genres

    def _get_movie_countries(self):
        """
        获取电影制片国家/地区
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            countries_text = re.search(r'制片国家/地区:</span>.*<br/>', film_info).group()
            countries_text = countries_text.replace('制片国家/地区:</span>', '').replace('<br/>', '')
            countries = [country.replace(' ', '') for country in countries_text.split('/')]
        except Exception as err:
            countries = []

        return countries

    def _get_movie_languages(self):
        """
        获取电影语言
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            languages_text = re.search(r'语言:</span>.*<br/>', film_info).group()
            languages_text = languages_text.replace('语言:</span>', '').replace('<br/>', '')
            languages = [language.replace(' ', '') for language in languages_text.split('/')]
        except Exception as err:
            languages = []

        return languages

    def _get_movie_pubdates(self):
        """
        获取电影上映时间
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            pubdates = []
            try:
                release_text = re.search(r'上映日期:</span> .*<br/>', film_info).group()
                release_text = release_text.replace('上映日期:</span> ', '').replace('<br/>', '')
                pubdates_text_list = release_text.split('</span>')
            except:
                premiere_text = re.search(r'首播:</span>.*<br/>', film_info).group()
                premiere_text = premiere_text.replace('首播:</span> ', '').replace('<br/>', '')
                pubdates_text_list = premiere_text.split('</span>')
            while '' in pubdates_text_list:
                pubdates_text_list.remove('')
            for pubdate in pubdates_text_list:
                pubdate_name = re.sub(r'<span.*>', '', pubdate).replace('/', '').replace(' ', '')
                pubdates.append(pubdate_name)
        except Exception as err:
            pubdates = []
        return pubdates

    def _get_movie_episodes(self):
        """
        获取电影集数
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            episodes_text = re.search(r'集数:</span>.*<br/>', film_info).group()
            episodes_text = episodes_text.replace('集数:</span>', '').replace('<br/>', '').replace(' ', '')
            episodes = episodes_text
        except Exception as err:
            episodes = '1'
        return episodes

    def _get_movie_durations(self):
        """
        获取电影片长
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            durations = []
            durations_text = re.search(r'片长:</span> .*<br/>', film_info).group()
            durations_text = durations_text.replace('片长:</span> ', '').replace('<br/>', '')
            durations_text_list = durations_text.split('</span>')
            while '' in durations_text_list:
                durations_text_list.remove('')
            for duration in durations_text_list:
                duration_name = re.sub(r'<span.*>', '', duration).replace('/', '').replace(' ', '')
                durations.append(duration_name)
        except Exception as err:
            durations = []

        return durations

    def _get_movie_other_names(self):
        """
        获取电影其他名称
        :return:
        """
        try:
            film_info = str(self.film_soup.find('div', {'id': 'info'}))
            other_names = []
            other_names_text = re.search('又名:</span>.*<br/>', film_info).group()
            other_names_text = other_names_text.replace('又名:</span>', '').replace('<br/>', '')
            other_names_text_list = other_names_text.split('/')
            while '' in other_names_text_list:
                other_names_text_list.remove('')
            for other_name in other_names_text_list:
                name = other_name.replace('/', '')#.replace(' ', '')
                other_names.append(name)
        except Exception as err:
            other_names = []

        return other_names

    def _get_movie_summary(self):
        """
        获取电影简介
        :return:
        """
        try:
            try:
                # all content
                summary = str(self.film_soup.find('span', class_='all hidden').text)
            except Exception as err:
                # short content
                summary = str(self.film_soup.find('span', property='v:summary').text)
        except Exception as err:
            summary = ''
        return summary

    def _get_movie_rating(self):
        """
        获取电影评分
        :return:
        """
        try:
            average = str(self.film_soup.find('strong', property='v:average').text)
            reviews_count = str(self.film_soup.find('span', property='v:votes').text)
            rating = {
                'average': average,
                'reviews_count': reviews_count
            }
        except Exception as err:
            rating = {
                'average': '',
                'reviews_count': ''
            }
        return rating
    def _get_movie_awards(self):
        awards_url='https://movie.douban.com/subject/'+str(self.movie_id)+'/awards/'
        user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53'
        headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                'Connection': 'keep-alive',
                'Cookie': self.cookie,
                'Sec-Fetch-Dest': 'document' ,
                'Sec-Fetch-Mode': 'navigate' ,
                'Sec-Fetch-Site': 'none' ,
                'Sec-Fetch-User': '?1' ,
                'Upgrade-Insecure-Requests': '1' ,
                'User-Agent': user_agent,
                'sec-ch-ua': '"Microsoft Edge";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
                'sec-ch-ua-mobile': '?0' ,
                'sec-ch-ua-platform': '"macOS"',
            }
        r=requests.get(awards_url,headers=headers,timeout=20)
        award_soup = BeautifulSoup(r.text, 'lxml')
        awardlist=award_soup.find_all('div',class_='awards')
        awards=[]
        for awarditem in awardlist:
            title=awarditem.find('h2').text.replace('\n',' ').strip()
            contentlist=awarditem.find_all('ul',class_="award")
            content=[]
            for contentitem in contentlist:
                content.append(contentitem.text.replace('\n',' ').strip())
            tempitem={
                'title':title,
                'content':content,
            }
            awards.append(tempitem)
        return awards
    def parse(self):
        """
        获取电影信息（包含电视剧、综艺、动漫、纪录片、短片）
        :return:
        """
        #name = self._get_movie_name()  # 电影姓名
        names =self._get_movie_names()
        year=self._get_movie_year()
        image_url = self._get_movie_image_url()  # 电影图片链接
        directors = self._get_movie_directors()  # 电影导演
        writers = self._get_movie_writers()  # 电影编剧
        actors = self._get_movie_actors()  # 电影演员
        genres = self._get_movie_genres()  # 电影类型
        countries = self._get_movie_countries()  # 电影制片国家/地区
        languages = self._get_movie_languages()  # 电影语言
        pubdates = self._get_movie_pubdates()  # 电影上映时间
        episodes = self._get_movie_episodes()  # 电影集数
        durations = self._get_movie_durations()  # 电影片长
        other_names = self._get_movie_other_names()  # 电影其他名称
        summary = self._get_movie_summary()  # 电影简介
        rating = self._get_movie_rating()  # 电影评分
        imdb= self._get_movie_imdb()
        imdbrating=self._get_movie_imdbscore()
        awards = self._get_movie_awards()


        movie_info_json = {
            'id': self.movie_id,
            'image_url': image_url,
            'names': names,
            'year': year,
            'directors': directors,
            'writers': writers,
            'actors': actors,
            'genres': genres,
            'countries': countries,
            'languages': languages,
            'pubdates': pubdates,
            'episodes': episodes,
            'durations': durations,
            'other_names': other_names,
            'summary': summary,
            'rating': rating,
            'imdb': imdb,
            'imdbrating': imdbrating,
            'awards':awards,
        }
        return movie_info_json
    def info(self):
        data=self.parse()
        douban_info=''
        if (data['image_url']):
            imgurl=re.findall('img[0-9]\.doubanio\.com',data['image_url'])
            douban_info = douban_info+"[img]" + data['image_url'].replace(imgurl[0],'img9.doubanio.com') + "[/img]\n"
            #self.picture=data['pic']
        if (data['names']['translatedTitle']):
            douban_info = douban_info+ "\n◎译\u3000\u3000名　" + '/'.join([data['names']['translatedTitle']]+data['names']['akaTitles']);
        if (data['names']['originalTitle']) :
            douban_info += "\n◎片\u3000\u3000名　" + data['names']['originalTitle']
        if (data['year']):
            douban_info += "\n◎年\u3000\u3000代　" + str(data['year'])
        if (data['countries'] and len(data['countries']) > 0) :
            douban_info += "\n◎产\u3000\u3000地　" + " / ".join(data['countries'])
        if (data['genres'] and len(data['genres']) > 0):
            douban_info += "\n◎类\u3000\u3000别　" + " / ".join(data['genres'])
        if (data['languages'] and len(data['languages']) > 0) :
            douban_info += "\n◎语\u3000\u3000言　" + " / ".join(data['languages'])
        if (data['pubdates'] and len(data['pubdates']) > 0) :
            douban_info += "\n◎上映日期　" + " / ".join(data['pubdates'])     
        if (data['imdb'].strip()!='') :
            if (data['imdbrating']) :
                douban_info += "\n◎IMDb评分  " + str(data['imdbrating']['rating']) + "/10 from " + str(data['imdbrating']['ratingCount']) + " users"
            douban_info += "\n◎IMDb链接  https://www.imdb.com/title/" + data['imdb']+"/"
        if (data['rating']) :
            douban_info += "\n◎豆瓣评分　" + str(data['rating']['average']) + "/10 from " + str(data['rating']['reviews_count']) + " users";
        if (self.movie_url) :
            douban_info += "\n◎豆瓣链接　" + self.movie_url
        if (data['durations'] and len(data['durations']) > 0) :
            douban_info += "\n◎片　　长　" + " / ".join(data['durations'])
        if (data['episodes']) :
            douban_info += "\n◎集\u3000\u3000数　" + data['episodes']
        if (data['directors'] and len(data['directors']) > 0) :
            for i in range (len(data['directors'])):
                if i==0:
                    douban_info += "\n◎导　　演　" + (data['directors'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['directors'][i]['name'])

        if (data['writers'] and len(data['writers']) > 0) :
            for i in range (len(data['writers'])):
                if i==0:
                    douban_info += "\n◎编　　剧　" + (data['writers'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['writers'][i]['name'])

        if (data['actors'] and len(data['actors']) > 0) :
            for i in range (len(data['actors'])):
                if i==0:
                    douban_info += "\n◎主　　演　" + (data['actors'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['actors'][i]['name'])

        if ('tags' in data and data['tags'] and len(data['tags']) > 0) :
            douban_info += "\n\n\n◎标　　签　" + " | ".join(data['tags'])
       
        if (data['summary']) :
            douban_info += "\n\n◎简　　介　" + "\n\n " +(data['summary'])
        else:
            douban_info += "\n\n◎简　　介　" + "\n\n 暂无相关剧情介绍"

        if ('awards' in data and data['awards'] and len(data['awards']) > 0) :
            awardstr=''
            for item in data['awards']:
                awardstr=awardstr+"\n\n　　" + item['title'];
                for itemc in item['content']:
                    awardstr=awardstr+"\n　　" + itemc
            douban_info += "\n\n◎获奖情况　" + awardstr

        douban_info =douban_info+ "\n\n"
        self.douban_info=douban_info
        return douban_info



utils/mediafile/douban_movie.py
Ethan930717/AutoTransferMachine
import os
from loguru import logger
import time
import requests
import re
import json
import sys
from utils.mediafile.douban_book import *
from utils.mediafile.douban_movie import *

def getdoubaninfo(url:str='',cookie:str=''):
    if 'movie.douban.com' in url:
        if cookie.strip()=='':
            page_parse=MoviePageParse(movie_url=url)
        else:
            page_parse=MoviePageParse(movie_url=url,cookie=cookie)
    elif 'book.douban.com' in url:
        if cookie.strip()=='':
            page_parse=BookPageParse(book_url=url)
        else:
            page_parse=BookPageParse(book_url=url,cookie=cookie)
    else:
        raise Exception('豆瓣链接填写错误')
    print('\n'+page_parse.info())


def ptgen_douban_info(doubanurl):
    url='https://api.iyuu.cn/App.Movie.Ptgen?url='+doubanurl
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
    headers = {
            'user-agent': user_agent,
            'referer': url,
        }
    logger.info('正在获取豆瓣信息')
    try:
        r = requests.get(url,headers=headers,timeout=20)
    except Exception as r:
        logger.error('获取豆瓣信息失败，原因: %s' %(r))
        return 

    logger.info('获取豆瓣信息完毕，正在处理信息，请稍等...')
    
    try:
        info_json=r.json()
        logger.trace(info_json)
    except Exception as r:
        logger.warning('获取豆瓣信息转换json格式失败，原因: %s' %(r))
        return
    
    if not r.ok:
        logger.trace(r.content)
        logger.warning(
            f"获取豆瓣信息失败: HTTP {r.status_code}, reason: {r.reason} ")
        return 

    if 'data' not in info_json or 'format' not in info_json['data']:
        logger.warning(f"豆瓣信息获取失败")
        return 
    
    info=info_json['data']['format']
    info=info[0:info.find('<a')]
    
    imgurl=re.findall('img[0-9]\.doubanio\.com',info)
    if len(imgurl)>0:
        info=info.replace(imgurl[0],'img9.doubanio.com')
    return info

def doubaninfo(doubanurl):
    res=None
    trynum=0
    while res==None:
        trynum=trynum+1
        if trynum>10:
            print('获取失败')
            return 
        res=ptgen_douban_info(doubanurl)
        if res==None:
            time.sleep(3)
    print('\n'+res)
    return 





utils/mediafile/doubaninfo.py
Ethan930717/AutoTransferMachine
from progress.bar import IncrementalBar
from torf import Torrent
from pathlib import Path
import time
from loguru import logger
import os
def make_private_torrent(filepath: str, torrentname:str, tracker="https://announce.leaguehd.com/announce.php"):
    '''
    if os.path.isdir(filepath):
        logger.info('检测到路径制种，将先删除掉路径里面所有种子文件(torrent后缀)以及隐藏文件（.开头的文件）...')
        deletetorrent(filepath) 
    deletetorrent(os.path.dirname(torrentname))
    logger.info('即将开始制作种子...')
    '''
    torrent_path = Path(torrentname)
    path = Path(filepath)
    piece_size = 4 * 1024 * 1024
    private = True
    created_by = "ATM"
    source = "ATM"
    trytime=0
    filesize=0

    while filesize==0:
        trytime=trytime+1
        if trytime>10:
            logger.error('制作种子失败')
            return
        if trytime>1:
            logger.warning('第'+str(trytime-1)+'次制作种子失败')
        logger.info('正在第'+str(trytime)+'次制作种子:') 
        if torrent_path.exists():
            logger.info('已存在种子文件，正在删除'+torrentname)
            try:
                os.remove(torrent_path)
            except Exception as r:
                logger.error('删除种子发生错误: %s' %(r))
            
        if tracker:
            torrent = Torrent(path=str(path.absolute()), trackers=[tracker], piece_size=piece_size, private=private, created_by=created_by, source=source)
        else:
            torrent = Torrent(path=str(path.absolute()), piece_size=piece_size, private=private,  created_by=created_by)
        bar = IncrementalBar(message="制种中:", max=torrent.pieces,suffix="%(index)d/%(max)d [%(eta_td)s]")

        def cb(__torrent: Torrent, path: str, hashed_pieces: int, total_pieces: int):
            bar.next()

        torrent.generate(callback=cb, interval=0)
        torrent.write(str(torrent_path))
        bar.finish()
        filesizetime=0
        while filesize==0:
            filesizetime=filesizetime+1
            if filesizetime>5:
                break
            if os.path.exists(torrentname):
                filesize=os.path.getsize(torrentname)
            else:
                filesize=0
            if filesize==0:
                time.sleep(1)
    logger.info('已完成制作种子'+torrentname)
    return 
utils/mediafile/maketorrent.py
Ethan930717/AutoTransferMachine
from utils.pathinfo.pathinfo import findnum
from utils.pathinfo.pathinfo import findeps
import os
from loguru import logger
import time
import requests
import re
import json
import sys
from utils.img_upload.imgupload import img_upload
from utils.getinfo.info_transfer import getmediainfo
from doubaninfo.doubaninfo import getdoubaninfo
from utils.para_ctrl.readyaml import readyaml



def changename(path):
    if not 'win' in sys.platform:
        return path
    else:
        return '/cygdrive/'+path.replace('\\','/').replace(':','')


def get_video_duration(video_path: str):
    ext = os.path.splitext(video_path)[-1]
    if ext != '.mp4' and ext != '.avi' and ext != '.flv'and ext != '.ts'and ext != '.mkv':
        raise Exception('format not support')
    ffprobe_cmd = 'ffprobe -i "'+video_path+'" -show_entries format=duration -v quiet -of csv="p=0"'
    a=os.popen(ffprobe_cmd)
    duration_info = float(a.read())
    a.close()
    #duration_info = float(a.buffer.read().decode('utf-8'))
    return duration_info

def takescreenshot(file,screenshotaddress,screenshotnum,basic):
    '''
    para:
        file:视频文件
        duration:视频文件播放时长
        screenshotaddress:存放截图地址，截图后除了新截图其他文件会被清空
        screenshotnum:截图数量
    '''
    logger.info('正在对视频'+file+'截图'+str(screenshotnum)+'张并存入文件夹'+screenshotaddress)
    i=os.path.basename(file)
    if (os.path.isdir(file)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
        logger.error(file+'非视频文件,无法截图')
        raise ValueError (file+'非视频文件,无法截图')
    duration=get_video_duration(file)
    if abs(duration)<1e-9:
        logger.error(file+'视频文件播放时长过短,无法截图')
        raise ValueError (file+'视频文件播放时长过短,无法截图')
    #清空截图文件夹
    ls = os.listdir(screenshotaddress)
    for i in ls:
        c_path = os.path.join(screenshotaddress, i)
        if not (os.path.isdir(c_path)):
            os.remove(c_path)
    timestep=duration*1.0/(screenshotnum+3)
    firststep=timestep*2

    if basic['picture_format'].lower() == "png":
        picture_format = ".png"
    elif basic['picture_format'].lower() == "gif":
        picture_format = ".gif"
    elif basic['picture_format'].lower() == "bmp":
        picture_format = ".bmp"
    elif basic['picture_format'].lower() == "tiff":
        picture_format = ".tiff"
    else:
        picture_format = ".jpg"

    for i in range (screenshotnum):
        firststep=firststep+timestep
        if 'win32' in sys.platform:
            screenshotstr='ffmpeg -ss '+str(firststep)+' -i "'+file+'" -f image2 -y "'+os.path.join(screenshotaddress,str(i+1)+picture_format)+'"'
        else:
            screenshotstr='ffmpeg -ss '+str(firststep)+' -i "'+file+'" -frames:v 1 -f image2 -y "'+os.path.join(screenshotaddress,str(i+1)+picture_format)+'" &> /dev/null'
        #print(screenshotstr)
        os.system(screenshotstr)
    logger.info('截图完毕')




class mediafile(object):
    def __init__(self,mediapath,pathinfo,basic,imgdata):
        self.mediapath         =mediapath
        self.pathinfo          = pathinfo
        self.downloadpath      =pathinfo.downloadpath
        self.basic             =basic
        #self.address就是要被抓去info的资源文件路径
        #如果mediapath是文件夹，self.address就选里面最大的视频文件
        if os.path.isdir(self.mediapath):
            self.isdir=True
            maxsize=0
            ls = os.listdir(self.mediapath)
            for i in ls:
                c_path=os.path.join(self.mediapath, i)
                if (os.path.isdir(c_path)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
                    continue
                filesize=os.path.getsize(c_path)
                if filesize>maxsize:
                    self.address=c_path
                    maxsize=filesize

            if self.pathinfo.collection>=1 and 'zeroday_name' in self.pathinfo.infodict and self.pathinfo.infodict['zeroday_name']!=None and self.pathinfo.infodict['zeroday_name']!='':
                zeroday_path=os.path.join(self.pathinfo.path,self.pathinfo.infodict['zeroday_name'])
                if os.path.exists(zeroday_path):
                    ls = os.listdir(zeroday_path)
                    for i in ls:
                        c_path=os.path.join(zeroday_path, i)
                        if (os.path.isdir(c_path)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
                            continue
                        filesize=os.path.getsize(c_path)
                        if filesize>maxsize:
                            self.address=c_path
                            maxsize=filesize
        
        else:
            self.address           = mediapath
            self.isdir=False
        
        #种子目录
        self.topath            = ''
        self.screenshotaddress = basic['screenshot_path']
        self.torrentaddress    = basic['torrent_path'] #种子文件目录
        self.screenshotnum     = int(basic['picture_num'])
        self.tmdbapi           = basic['tmdb_api']
        self.imgdata           = imgdata
        
        self.path              = os.path.dirname(mediapath)
        
        self.mediatype         = pathinfo.type
        self.doubanurl         = pathinfo.doubanurl
        self.imdburl           = pathinfo.imdb_url
        self.imdbid            = pathinfo.imdb_id
        self.tmdbid            = pathinfo.tmdb_id
        self.tmdbname          = pathinfo.tmdb_name
        self.bgmurl            = pathinfo.bgm_url
        self.anidburl          = pathinfo.anidb_url
        self.from_url          = pathinfo.from_url
        self.transfer          = pathinfo.transfer
        self.complete          = pathinfo.complete
        self.filename          = os.path.basename(self.address)
        self.episodename       = findnum(self.filename)[0]
        self.episode           = int(self.episodename)

        self.sub               = self.pathinfo.sub
        self.englishname       = self.pathinfo.englishname
        self.chinesename       = self.pathinfo.chinesename

        self.audio_ch=0
        self.audio_jp=0
        self.audio_en=0
        self.audio_yue=0
        self.audio_num=0

        self.text_jp=0
        self.text_sc=0
        self.text_tc=0
        self.text_en=0
 
        if ('anime' in self.mediatype.lower() or 'tv' in self.mediatype.lower() or 'doc' in self.mediatype.lower() ):
            self.season            = self.pathinfo.season
            self.seasonnum         = self.pathinfo.seasonnum
            self.season_ch         = self.pathinfo.season_ch
            self.complete          = self.pathinfo.complete

        dlgroup           =['NaN-Raws','NaN Raws','NC-Raws','NC Raws','Lilith-Raws','Lilith Raws','ANi','Skymoon-Raws','Skymoon Raws','GMTeam','GM-Team','YingWEB']
        self.type              ='WEBRip'
        self.Video_Format      ='H264'
        
        if 'hdtvrip' in self.filename.lower() or 'hdtv-rip' in self.filename.lower() or 'tv-rip' in self.filename.lower() or 'tvrip' in self.filename.lower():
            self.type='HDTVRip'
            self.source='HDTVRip'
        elif 'hdtv' in self.filename.lower():
            self.type='HDTV'
            self.source ='HDTV'
        elif 'bdrip' in self.filename.lower() or 'bd-rip' in self.filename.lower():
            self.type='BDRip'
            self.source='BDRip'
        elif 'remux' in self.filename.lower():
            self.type='Remux'
            self.source = 'Remux'
        elif 'bluray' in self.filename.lower() or 'blu-ray' in self.filename.lower():
            self.type='Bluray'
            self.source = 'Bluray'
        elif 'dvdrip' in self.filename.lower() or 'dvd-rip' in self.filename.lower():
            self.type='DVDRip'
            self.source = 'DVDRip'
        elif 'dvd' in self.filename.lower() :
            self.type='DVD'
            self.source ='DVD'
        elif 'webdl' in self.filename.lower() or 'web-dl' in self.filename.lower() :
            self.type='WEB-DL'
            self.source ='WEB-DL'
        elif 'webrip' in self.filename.lower() or 'web-rip' in self.filename.lower():
            self.type='WEBRip'
            self.source = 'WEBRip'
        elif self.sub in dlgroup or ('WEB' in self.sub.upper() and not 'WEBRRP' in self.sub.upper() and not '爪爪' in self.pathinfo.exinfo):
            self.type='WEB-DL'
            self.source ='WEB-DL'


        self.getscreenshot_done=0
        self.getimgurl_done=0
        self.getmediainfo_done=0
        self.getptgen_done=0
        self.mktorrent_done=0
        self.getinfo_done=0


        self.language=''
        self.country=''
        self.year=2023

        #根据文件名判断内嵌字幕信息
        self.sublan=''
        jp=0
        sc=0
        tc=0
        if 'SC' in self.filename.upper() or 'CHS' in self.filename.upper() or 'GB' in self.filename.upper() or '简' in self.filename.upper() or '簡' in self.filename.upper():
            sc=1
        if 'TC' in self.filename.upper() or 'CHT' in self.filename.upper() or 'BIG5' in self.filename.upper() or '繁' in self.filename.upper():
            tc=1
        if 'JP' in self.filename.upper() or 'JAPANESE' in self.filename.upper() or '日' in self.filename.upper():
            jp=1
        
        if jp==0 and sc==0 and tc==1:
            self.sublan='[内嵌繁中]'
        elif jp==0 and sc==1 and tc==0:
            self.sublan='[内嵌简中]'
        elif jp==0 and sc==1 and tc==1:
            self.sublan='[内嵌简繁中字]'
        elif jp==1 and sc==0 and tc==0:
            self.sublan='[内嵌日字]'
        elif jp==1 and sc==0 and tc==1:
            self.sublan='[内嵌繁日双语]'
        elif jp==1 and sc==1 and tc==0:
            self.sublan='[内嵌简日双语]'
        elif jp==1 and sc==1 and tc==1:
            self.sublan='[内嵌简繁日双语]'
        else:
            self.sublan=''
        
        if jp+sc+tc>0:
            logger.info('根据文件名分析，字幕语言为'+self.sublan)
        else:
            logger.warning('无法根据文件名分析出字幕语言信息')



    def getscreenshot(self):
        if self.getscreenshot_done==0:
            takescreenshot(self.address,self.screenshotaddress,self.screenshotnum,self.basic)
            self.getscreenshot_done=1
    
    def getimgurl(self,server=''):
        if self.getimgurl_done==1:
            return self.screenshoturl
        '''
        0张图的特判
        '''
        if self.basic['picture_format'].lower() == "png":
            picture_format = ".png"
        elif self.basic['picture_format'].lower() == "gif":
            picture_format = ".gif"
        elif self.basic['picture_format'].lower() == "bmp":
            picture_format = ".bmp"
        elif self.basic['picture_format'].lower() == "tiff":
            picture_format = ".tiff"
        else:
            picture_format = ".jpg"

        if 'picture_num' in self.basic and int(self.basic['picture_num'])==0:
            self.screenshoturl=''
            self.getimgurl_done=1
            return ''
        self.getscreenshot()
        imgpaths=[]
        for i in range (self.screenshotnum):
            imgpaths.append(os.path.join(self.screenshotaddress,str(i+1)+picture_format))
        logger.info('正在将'+self.chinesename +'的第'+self.episodename+'集截图上传'+server+'图床,请稍等...')
        res=img_upload(imgdata=self.imgdata,imglist=imgpaths,host=server,form='bbcode')
        if res=='':
            print(self.chinesename+'上传图床失败,请自行上传图床：')
            temp='\n'
            res=''
            while not temp=='':
                temp=input('')
                res=res+temp+'\n'
        logger.info('成功获得图片链接：\n'+res)
        self.screenshoturl=res
        self.getimgurl_done=1
        return self.screenshoturl

    def dealsubtext(self,res):
        jp=0
        sc=0
        tc=0
        en=0
        a=res.split('\n\n')
        for item in a:
            if item.startswith('Text'):
                b=item.split('\n')
                for subitem in b:
                    if subitem.lower().startswith('language') or subitem.lower().startswith('title'):
                        if 'SC' in subitem.upper() or 'CHS' in subitem.upper() or 'GB' in subitem.upper() or '简' in subitem.upper() or '簡' in subitem.upper() or '中字' in self.pathinfo.tags:
                            sc=1
                        if 'TC' in subitem.upper() or 'CHT' in subitem.upper() or 'BIG5' in subitem.upper() or '繁' in subitem.upper() or '中字' in self.pathinfo.tags:
                            tc=1
                        if 'JP' in subitem.upper() or 'JA' in subitem.upper() or'JAPANESE' in subitem.upper() or '日' in subitem.upper():
                            jp=1
                        if 'EN' in subitem.upper() or 'ENGLISH' in subitem.upper() or '英' in subitem.upper():
                            en=1
        if en==0 and jp==0 and sc==0 and tc==1:
            self.sublan='[内封繁体中字]'
        elif en==0 and jp==0 and sc==1 and tc==0:
            self.sublan='[内封简体中字]'
        elif en==0 and jp==0 and sc==1 and tc==1:
            self.sublan='[内封简繁中字]'
        elif en==0 and jp==1 and sc==0 and tc==0:
            self.sublan='[内封日文字幕]'
        elif en==0 and jp==1 and sc==0 and tc==1:
            self.sublan='[内封繁日双语]'
        elif en==0 and jp==1 and sc==1 and tc==0:
            self.sublan='[内封简日双语]'
        elif en==0 and jp==1 and sc==1 and tc==1:
            self.sublan='[内封简繁日双语]'
        elif en==1 and jp==0 and sc==0 and tc==0:
            self.sublan='[内封英文字幕]'
        elif en==1 and jp==0 and sc==0 and tc==1:
            self.sublan='[内封繁英双语]'
        elif en==1 and jp==0 and sc==1 and tc==0:
            self.sublan='[内封简英双语]'
        elif en==1 and jp==0 and sc==1 and tc==1:
            self.sublan='[内封简繁英双语]'
        elif en==1 and jp==1 and sc==0 and tc==0:
            self.sublan='[内封日英双语]'
        elif en==1 and jp==1 and sc==0 and tc==1:
            self.sublan='[内封繁日英三语]'
        elif en==1 and jp==1 and sc==1 and tc==0:
            self.sublan='[内封简日英三语]'
        elif en==0 and jp==1 and sc==1 and tc==1:
            self.sublan='[内封简繁日英三语]'

        self.text_jp=jp
        self.text_sc=sc
        self.text_tc=tc
        self.text_en=en

        if jp+sc+tc+en>0:
            logger.info('根据mediainfo分析，字幕语言为'+self.sublan)
        else:
            logger.warning('无法根据mediainfo分析出字幕语言信息')

    def dealaudio(self,res):
        ch=0
        jp=0
        en=0
        yue=0
        a=res.split('\n\n')
        for item in a:
            if item.startswith('Audio'):
                b=item.split('\n')
                for subitem in b:
                    if subitem.lower().startswith('language') or subitem.lower().startswith('title'):

                        if 'CHINESE' in subitem.upper() or '中' in subitem.upper() or '国' in subitem.upper() or '国语' in self.pathinfo.tags or '国语' in self.pathinfo.small_descr:
                            ch=1
                            #logger.info('根据mediainfo音轨分析，语言为'+self.language)
                        if  'JAPANESE' in subitem.upper() or '日' in subitem.upper() or '日语' in self.pathinfo.tags or '日语' in self.pathinfo.small_descr:
                            jp=1
                            #logger.info('根据mediainfo音轨分析，语言为'+self.language)
                        if 'ENGLISH' in subitem.upper() or '英' in subitem.upper() or '英语' in self.pathinfo.tags or '英语' in self.pathinfo.small_descr:
                            en=1
                            #logger.info('根据mediainfo音轨分析，语言为'+self.language)
                        if 'CANTON' in subitem.upper() or '粤' in subitem.upper() or '粤语' in self.pathinfo.tags or '粤语' in self.pathinfo.small_descr:
                            yue=1

        '''
        if jp==0 and ch==0 and en==1:
            self.language='英语'
        elif jp==0 and ch==1 and en==0:
            self.language='国语'
        elif jp==0 and ch==1 and en==1:
            self.language='中英双语'
        elif jp==1 and ch==0 and en==0:
            self.language='日语'
        elif jp==1 and ch==0 and en==1:
            self.language='日英双语'
        elif jp==1 and ch==1 and en==0:
            self.language='中日双语'
        elif jp==1 and ch==1 and en==1:
            self.language='中英日三语'
        else:
            self.language=self.language
        '''
        if jp+ch+en+yue>0:
            self.language=''
            if ch==1:
                self.language=self.language+'国'
            if yue==1:
                self.language=self.language+'粤'
            if jp==1:
                self.language=self.language+'日'
            if en==1:
                self.language=self.language+'英'
        self.audio_num=jp+ch+en+yue
        self.audio_ch=ch
        self.audio_jp=jp
        self.audio_en=en
        self.audio_yue=yue

        if self.audio_num=='1':
            self.language=self.language+'语'
        elif self.audio_num=='2':
            self.language=self.language+'双语'
        elif self.audio_num=='3':
            self.language=self.language+'三语'
        elif self.audio_num=='4':
            self.language=self.language+'四语'

        if self.audio_num>0:
            logger.info('根据mediainfo音轨分析，语言为'+self.language)
        else:
            logger.warning('无法根据mediainfo分析出音轨语言信息')

    def getaudio(self):
        ch=0
        jp=0
        en=0
        yue=0
        infolist=self.mediainfo_json['media']['track']
        for item in infolist:
            if not '@type' in item:
                continue
            if item['@type'].lower()=='audio':
                if 'Title' in item :
                    if 'CHINESE' in item['Title'].upper() or '中' in item['Title'].upper() or 'CH' in item['Title'].upper() or 'ZH' in item['Title'].upper() or '国' in item['Title'].upper() or 'MANDARIN' in item['Title'].upper() or '国语' in self.pathinfo.small_descr:
                        ch=1
                    if  'JA' in item['Title'].upper() or 'JP' in item['Title'].upper() or '日' in item['Title'].upper():
                        jp=1
                    if 'EN' in item['Title'].upper() or '英' in item['Title'].upper():
                        en=1
                    if 'CANTON' in item['Title'].upper() or '粤' in item['Title'].upper() or '粤语' in self.pathinfo.small_descr:
                        yue=1
                elif 'Language' in item :
                    if 'CHINESE' in item['Language'].upper() or '中' in item['Language'].upper() or 'CH' in item['Language'].upper() or 'ZH' in item['Language'].upper() or '国' in item['Language'].upper() or '国语' in self.pathinfo.small_descr:
                        ch=1
                    if 'JA' in item['Language'].upper() or 'JP' in item['Language'].upper() or '日' in item['Language'].upper():
                        jp=1
                    if 'EN' in item['Language'].upper() or '英' in item['Language'].upper():
                        en=1
                    if 'CANTON' in item['Language'].upper() or '粤' in item['Language'].upper() or '粤语' in self.pathinfo.small_descr:
                        yue=1
        '''
        if jp==0 and ch==0 and en==1:
            self.language='英语'
        elif jp==0 and ch==1 and en==0:
            self.language='国语'
        elif jp==0 and ch==1 and en==1:
            self.language='中英双语'
        elif jp==1 and ch==0 and en==0:
            self.language='日语'
        elif jp==1 and ch==0 and en==1:
            self.language='日英双语'
        elif jp==1 and ch==1 and en==0:
            self.language='中日双语'
        elif jp==1 and ch==1 and en==1:
            self.language='中英日三语'
        else:
            self.language=self.language

        self.audio_ch=ch
        self.audio_jp=jp
        self.audio_en=en

        if jp+ch+en>0:
            logger.info('根据mediainfo音轨分析，语言为'+self.language)
        else:
            logger.warning('无法根据mediainfo分析出音轨语言信息')
        '''
        if jp+ch+en+yue>0:
            self.language=''
            if ch==1:
                self.language=self.language+'国'
            if yue==1:
                self.language=self.language+'粤'
            if jp==1:
                self.language=self.language+'日'
            if en==1:
                self.language=self.language+'英'
        self.audio_num=jp+ch+en+yue
        self.audio_ch=ch
        self.audio_jp=jp
        self.audio_en=en
        self.audio_yue=yue

        if self.audio_num=='1':
            self.language=self.language+'语'
        elif self.audio_num=='2':
            self.language=self.language+'双语'
        elif self.audio_num=='3':
            self.language=self.language+'三语'
        elif self.audio_num=='4':
            self.language=self.language+'四语'

        if self.audio_num>0:
            logger.info('根据mediainfo音轨分析，语言为'+self.language)
        else:
            logger.warning('无法根据mediainfo分析出音轨语言信息')

    def getsubtext(self):
        jp=0
        sc=0
        tc=0
        en=0
        infolist=self.mediainfo_json['media']['track']
        for item in infolist:
            if not '@type' in item:
                continue
            if item['@type'].lower()=='text':
                if 'Title' in item :
                    if 'TC' in item['Title'].upper() or 'CHT' in item['Title'].upper() or 'BIG5' in item['Title'].upper() or '繁' in item['Title'].upper():
                        tc=1
                    elif 'SC' in item['Title'].upper() or 'CHS' in item['Title'].upper() or 'GB' in item['Title'].upper() or '简' in item['Title'].upper() or '簡' in item['Title'].upper() or '中' in item['Title'].upper():
                        sc=1
                    elif 'JP' in item['Title'].upper() or 'JAPANESE' in item['Title'].upper() or '日' in item['Title'].upper():
                        jp=1
                    elif 'EN' in item['Title'].upper() or 'ENGLISH' in item['Title'].upper() or '英' in item['Title'].upper():
                        en=1
                elif 'Language' in item:
                    if 'TC' in item['Language'].upper() or 'CHT' in item['Language'].upper() or 'BIG5' in item['Language'].upper() or '繁' in item['Language'].upper():
                        tc=1
                    elif 'SC' in item['Language'].upper() or 'CHS' in item['Language'].upper() or 'GB' in item['Language'].upper() or '简' in item['Language'].upper() or '簡' in item['Language'].upper() or 'ZH' in item['Language'].upper():
                        sc=1
                    elif 'JP' in item['Language'].upper() or 'JA' in item['Language'].upper() or 'JAPANESE' in item['Language'].upper() or '日' in item['Language'].upper():
                        jp=1
                    elif 'EN' in item['Language'].upper() or 'ENGLISH' in item['Language'].upper() or '英' in item['Language'].upper():
                        en=1
        if en==0 and jp==0 and sc==0 and tc==1:
            self.sublan='[繁体中字]'
        elif en==0 and jp==0 and sc==1 and tc==0:
            self.sublan='[简体中字]'
        elif en==0 and jp==0 and sc==1 and tc==1:
            self.sublan='[简繁中字]'
        elif en==0 and jp==1 and sc==0 and tc==0:
            self.sublan='[日文字幕]'
        elif en==0 and jp==1 and sc==0 and tc==1:
            self.sublan='[繁日双语]'
        elif en==0 and jp==1 and sc==1 and tc==0:
            self.sublan='[简日双语]'
        elif en==0 and jp==1 and sc==1 and tc==1:
            self.sublan='[简繁日双语]'
        elif en==1 and jp==0 and sc==0 and tc==0:
            self.sublan='[英文字幕]'
        elif en==1 and jp==0 and sc==0 and tc==1:
            self.sublan='[繁英双语]'
        elif en==1 and jp==0 and sc==1 and tc==0:
            self.sublan='[简英双语]'
        elif en==1 and jp==0 and sc==1 and tc==1:
            self.sublan='[简繁英双语]'
        elif en==1 and jp==1 and sc==0 and tc==0:
            self.sublan='[日英双语]'
        elif en==1 and jp==1 and sc==0 and tc==1:
            self.sublan='[繁日英三语]'
        elif en==1 and jp==1 and sc==1 and tc==0:
            self.sublan='[简日英三语]'
        elif en==0 and jp==1 and sc==1 and tc==1:
            self.sublan='[简繁日英三语]'

        self.text_jp=jp
        self.text_sc=sc
        self.text_tc=tc
        self.text_en=en

        if jp+sc+tc+en>0:
            logger.info('根据mediainfo分析，字幕语言为'+self.sublan)
        else:
            logger.warning('无法根据mediainfo分析出字幕语言信息')

    def updatemediainfo(self,filepath=''):
        if os.path.isdir(self.topath):
            self.address=os.path.join(self.topath,os.path.basename(self.address))
        if not (filepath=='' or filepath==None):
            logger.info('检测到mediainfo模板文件正在应用...')
            a=os.popen('mediainfo --Inform=file://"'+filepath+'" "'+self.address+'"')
            res=a.buffer.read().decode('utf-8')
            self.mediainfo=res
            a.close()
            self.content=self.douban_info+"\n[quote=Mediainfo]\n"+self.mediainfo+"[/quote]\n"+self.screenshoturl
            if self.pathinfo.contenthead!='':
                self.content= self.pathinfo.contenthead+self.content
            
            if self.pathinfo.contenttail!='':
                self.content= self.content+self.pathinfo.contenttail
            #logger.info('使用模板后，mediainfo变更为:\n'+self.mediainfo)
        else:
            #logger.info('未检测到mediainfo模板文件,正在使用原版mediainfo...')
            a=os.popen('mediainfo "'+self.address+'"')
            res=a.buffer.read().decode('utf-8')
            a.close()
            ss=res.split('\n')
            for i in range(len(ss)):
                if ss[i].startswith('Complete name'):
                    ss[i]=':'.join([ss[i].split(':')[0],' '+self.filename])
            i=0
            while (i<len(ss)):
                if (ss[i].upper()).startswith('Unique'.upper()):
                    del(ss[i])
                    i=i-1
                i+=1
            res='\n'.join(ss)
            self.mediainfo=res
            self.content=self.douban_info+"\n[quote=Mediainfo]\n"+self.mediainfo+"[/quote]\n"+self.screenshoturl
            if self.pathinfo.contenthead!='':
                self.content= self.pathinfo.contenthead+self.content
            
            if self.pathinfo.contenttail!='':
                self.content= self.content+self.pathinfo.contenttail

    def getmediainfo(self):
        if self.getmediainfo_done==1:
            return self.mediainfo
        a=os.popen('mediainfo "'+self.address+'"')
        #res=a.read()
        res=a.buffer.read().decode('utf-8')
        a.close()
        #self.dealsubtext(res)
        #self.dealaudio(res)
        ss=res.split('\n')
        #ss[1]=':'.join([ss[1].split(':')[0],' '+self.filename])
        for i in range(len(ss)):
            if ss[i].startswith('Complete name'):
                ss[i]=':'.join([ss[i].split(':')[0],' '+self.filename])
        i=0
        while (i<len(ss)):
            if (ss[i].upper()).startswith('Unique'.upper()):
                del(ss[i])
                i=i-1
            i+=1

        self.mediainfo='\n'.join(ss)
        a=os.popen("mediainfo --Output=JSON \""+self.address+'"')
        #res_json=a.read()
        res_json=a.buffer.read().decode('utf-8')
        a.close()
        media_json=json.loads(res_json)

        self.mediainfo_json=media_json

        self.getsubtext()
        self.getaudio()

        self.Format            =media_json['media']['track'][0]['Format']
        self.FileSize          =int(media_json['media']['track'][0]['FileSize'].strip())
        self.duration          =float(media_json['media']['track'][0]['Duration'].strip())
        self.Video_Format      =media_json['media']['track'][1]['Format']
        self.Width             =int(media_json['media']['track'][1]['Width'].strip())
        self.Height            =int(media_json['media']['track'][1]['Height'].strip())
        self.BitDepth          =int(media_json['media']['track'][1]['BitDepth'].strip())
        self.Audio_Format      =media_json['media']['track'][2]['Format']


        #获取HDR信息


        #获取分辨率
        if 'Scan type' in media_json['media']['track'][1]:
            self.scan_type=media_json['media']['track'][1]['Scan type']
        else:
            self.scan_type=None
        self.Channels          =int(media_json['media']['track'][2]['Channels'].strip())
        self.standard_sel=None
        if not self.scan_type==None and ( 'inter' in self.scan_type.lower() or '隔行' in self.scan_type):
            if int(self.Height)>2160:
                self.standard_sel='8K'
            elif int(self.Height)>1080:
                self.standard_sel='2160i'
            elif int(self.Height)>720:
                self.standard_sel='1080i'
            elif int(self.Height)>480:
                self.standard_sel='720i'
            else:
                self.standard_sel='480i'
        else:
            if int(self.Height)>2160:
                self.standard_sel='8K'
            elif int(self.Height)>1080:
                self.standard_sel='2160p'
            elif int(self.Height)>720:
                self.standard_sel='1080p'
            elif int(self.Height)>480:
                self.standard_sel='720p'
            else:
                self.standard_sel='480p'

        text=self.mediainfo.lower()
        if ('webrip'in text) or ('web-rip' in text):
            self.type='WEBRip'
        if ('webdl'in text) or ('web-dl' in text):
            self.type='WEB-DL'

        if self.Video_Format == 'AVC':
            self.Video_Format = 'H264'
        if self.Video_Format == 'H264' and 'x264' in text:
            self.Video_Format = 'x264'

        if self.Video_Format == 'HEVC':
            self.Video_Format = 'H265'
        if self.Video_Format == 'H265' and 'x265' in text:
            self.Video_Format = 'x265'
        self.getmediainfo_done=1
        return self.mediainfo

    def dealwith_douban_info(self,infolist):
        self.picture=infolist[0].strip()
        for item in infolist:
            if '译\u3000\u3000名'in item:
                self.allName=item[5:].strip().split('/')
                self.small_descr=item[5:].strip()
            if '片\u3000\u3000名'in item:
                self.name=item[5:].strip()
            if '年\u3000\u3000代'in item:
                self.year=item[5:].strip()
                logger.info('根据豆瓣信息分析，年份为'+self.year)
            if '产\u3000\u3000地'in item:
                self.country=item[5:].strip()
                logger.info('根据豆瓣信息分析，地区为'+self.country)
            if '类\u3000\u3000别'in item:
                self.genre=item[5:].strip()
                logger.info('根据豆瓣信息分析，类别为'+self.genre)
            if '语\u3000\u3000言'in item:
                self.language=item[5:].strip()
                logger.info('根据豆瓣信息分析，语言为'+self.language)
            if '上映日期'in item:
                self.release=item[5:].strip()
                logger.info('根据豆瓣信息分析，上映日期为'+self.release)
            if '首\u3000\u3000播'in item:
                self.firstRelease=item[5:].strip()
                logger.info('根据豆瓣信息分析，首播为'+self.firstRelease)
            if '集\u3000\u3000数'in item:
                self.num=int(item[5:].strip())
                if not (self.complete==1 or self.complete==0):
                    if self.pathinfo.max>=self.num:
                        self.complete=0
                    else:
                        self.complete=0
                logger.info('根据豆瓣信息分析，总集数为'+str(self.num))
            if self.imdburl=='' and 'imdb'in item and '链接'in item and not((item[7:].strip()).endswith('//')):
                self.imdburl=item[7:].strip()
            if '片\u3000\u3000长'in item:
                self.runtime=item[5:].strip()
            if not (self.complete==1 or self.complete==0):
                self.complete=0
    def get_douban(self):
        if 'doubancookie' in self.basic and self.basic['doubancookie']!=None:
            get_success=0
            get_time=0
            while get_success==0:
                get_time+=1
                if get_time>5:
                    raise Exception('获取豆瓣info出错，请尝试能否正常打开豆瓣')
                try:
                    res_douban=getdoubaninfo(url=self.doubanurl,cookie=self.basic['doubancookie'],ret_val=True)
                    douban_dict=res_douban.parse()
                    get_success=1
                except Exception as r:
                    get_success=0
                    logger.warning('抓取豆瓣info错误，一秒后重试，原因: %s' %(r))
                    time.sleep(1)

        else:
            get_success=0
            get_time=0
            while get_success==0:
                get_time+=1
                if get_time>5:
                    raise Exception('获取豆瓣info出错，请尝试能否正常打开豆瓣')
                try:
                    res_douban=getdoubaninfo(url=self.doubanurl,ret_val=True)
                    douban_dict=res_douban.parse()
                    get_success=1
                except Exception as r:
                    get_success=0
                    logger.warning('抓取豆瓣info错误，一秒后重试，原因: %s' %(r))
                    time.sleep(1)
        

        self.douban_dict=douban_dict
        self.douban_info=res_douban.info()

        #if (douban_dict['names']['chinesename']):
        #    self.chinesename=douban_dict['names']['chinesename']
        if (douban_dict['names']['akaTitles']):
            self.allName='/'.join(douban_dict['names']['akaTitles'])
        if (douban_dict['year']):
            try:
                self.year=int(douban_dict['year'])
            except:
                logger.warning("douban_dict['year']转换数字出错,其内容为: "+str(douban_dict['year']))
                self.year=2023
        if (douban_dict['countries'] and len(douban_dict['countries']) > 0) :
            self.country=" / ".join(douban_dict['countries'])
        if (douban_dict['genres'] and len(douban_dict['genres']) > 0):
            self.genre=" / ".join(douban_dict['genres'])
        if (douban_dict['languages'] and len(douban_dict['languages']) > 0) :
            if self.language.strip()=='':
                self.language=" / ".join(douban_dict['languages'])
                logger.info('根据豆瓣信息分析，语言为'+self.language)
        if (douban_dict['pubdates'] and len(douban_dict['pubdates']) > 0) :
            self.release=" / ".join(douban_dict['pubdates'])
        if (douban_dict['imdb'].strip()!='') :
            self.imdbid=douban_dict['imdb']
            self.pathinfo.imdb_id=self.imdbid
            self.imdburl='https://www.imdb.com/title/'+self.imdbid+'/'
            self.pathinfo.imdb_url=self.imdburl
            logger.info('根据豆瓣信息分析，imdb链接为'+self.imdburl)
            base_url = "https://api.tmdb.org/3"
            if 'movie' in self.pathinfo.type.lower():
                search_url = base_url + "/search/movie"
            elif 'series' in self.pathinfo.type.lower():    
                search_url = base_url + "/search/tv"
            elif 'doc' in self.pathinfo.type.lower() and "完结" in self.pathinfo.tags:
                search_url = base_url + "/search/tv" 
            elif 'doc' in self.pathinfo.type.lower():
                search_url = base_url + "/search/movie"
            elif 'anime' in self.pathinfo.type.lower() and "完结" in self.pathinfo.tags:   
                search_url = base_url + "/search/tv" 
            elif 'anime' in self.pathinfo.type.lower():
                search_url = base_url + "/search/movie"                
            else:    
                search_url = base_url + "/search/multi"
            params = {
                "api_key": self.tmdbapi ,
                "language": "zh-CN",
                "query": self.englishname
            }
            response = requests.get(search_url, params=params)
            if response.status_code == 200:
                data = response.json()
                if data["results"]:
                    tmdbid = data["results"][0]["id"]
                    tmdbname = "".join([data["results"][0].get("name", ""), data["results"][0].get("title", "")])
                    if not tmdbname:
                        print(f"TMDB中未找到{self.englishname}") 
                        tmdbid = ""
                    # 输出TMDB ID
                    logger.info(f"已搜索到{tmdbname}在TMDB的ID为{tmdbid}")
                    self.tmdbid=str(tmdbid)
                    self.tmdbname=str(tmdbname)                   
                else:
                    # 输出没有结果的提示
                    logger.info(f"TMDB中未找到{self.englishname}")
                    self.tmdbid=""
                    self.tmdbname=""
                self.pathinfo.tmdb_id=self.tmdbid
                self.pathinfo.tmdb_name=self.tmdbname 
            else:
                # 输出请求失败的提示
                logger.info(f"Request failed with status code {response.status_code}.")
        if (douban_dict['episodes']) and  (not('movie' in self.mediatype.lower())):
            self.media_type='TV_series'
            try:
                self.num=int(douban_dict['episodes'])
                logger.info('根据豆瓣信息分析，总集数为'+str(self.num))
            except:
                self.num=1000000
                logger.info('豆瓣页面暂无集数数据')
            if not (self.complete==1 or self.complete==0):
                if self.pathinfo.max>=self.num:
                    self.complete=1
                else:
                    self.complete=0
            
        #没有获取到集数信息则默认为“未完结”
        if not (self.complete==1 or self.complete==0):
                self.complete=0
        self.getptgen_done=1

    def getptgen_douban_info(self):
        if self.getptgen_done==1:
            return
        url='https://api.iyuu.cn/App.Movie.Ptgen?url='+self.doubanurl
        user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
        headers = {
                'user-agent': user_agent,
                'referer': url,
            }
        logger.info('正在获取豆瓣信息')
        try:
            r = requests.get(url,headers=headers,timeout=20)
        except Exception as r:
            logger.error('获取豆瓣信息失败，原因: %s' %(r))
            return 

        logger.info('获取豆瓣信息完毕，正在处理信息，请稍等...')
        
        try:
            info_json=r.json()
            logger.trace(info_json)
        except Exception as r:
            logger.warning('获取豆瓣信息转换json格式失败，原因: %s' %(r))
            return
        
        if not r.ok:
            logger.trace(r.content)
            logger.warning(
                f"获取豆瓣信息失败: HTTP {r.status_code}, reason: {r.reason} ")
            return 

        if 'data' not in info_json or 'format' not in info_json['data']:
            logger.warning(f"豆瓣信息获取失败")
            return 
        
        info=info_json['data']['format']
        info=info[0:info.find('<a')]
        self.douban_info=info
        imgurl=re.findall('img[0-9]\.doubanio\.com',self.douban_info)
        if len(imgurl)>0:
            self.douban_info=self.douban_info.replace(imgurl[0],'img9.doubanio.com')
        infolist=info.split('◎')
        self.dealwith_douban_info(infolist)
        self.getptgen_done=1
        


    def getdoubaninfo(self):
        url='https://movieinfo.leaguehd.com/doubanAjax.php?url='+self.doubanurl
        user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
        headers = {
                'user-agent': user_agent,
                'referer': url,
            }
        logger.info('正在获取豆瓣信息，请稍等...')
        try:
            r = requests.get(url,headers=headers,timeout=20)
        except Exception as r:
            logger.warning('通过柠檬获取豆瓣信息失败，原因: %s' %(r))
            return

        logger.info('获取豆瓣信息完毕，正在处理信息，请稍等...')
        try:
            data=r.json()
        except Exception as r:
            logger.warning('通过柠檬获取豆瓣信息转换json格式失败，原因: %s' %(r))
            return

        douban_info=''
        if (data['pic']):
            imgurl=re.findall('img[0-9]\.doubanio\.com',data['pic'])
            douban_info = douban_info+"[img]" + data['pic'].replace(imgurl[0],'img9.doubanio.com') + "[/img]\n"
            #self.picture=data['pic']
        if (data['allName']):
            douban_info = douban_info+ "\n◎译\u3000\u3000名　" + '/'.join(data['allName']);
            self.name=data['allName'][0]
            self.allName='/'.join(data['allName'])
        if (data['name']) :
            douban_info += "\n◎片\u3000\u3000名　" + data['name']
            self.name=data['name']
        if (data['year']):
            douban_info += "\n◎年\u3000\u3000代　" + data['year']
            self.year=data['year']
            logger.info('根据豆瓣信息分析，年份为'+self.year)
        if (data['country'] and len(data['country']) > 0) :
            douban_info += "\n◎产\u3000\u3000地　" + " / ".join(data['country'])
            self.country=" / ".join(data['country'])
            logger.info('根据豆瓣信息分析，地区为'+self.country)
        if (data['genre'] and len(data['genre']) > 0):
            douban_info += "\n◎类\u3000\u3000别　" + " / ".join(data['genre'])
            self.genre=" / ".join(data['genre'])
            logger.info('根据豆瓣信息分析，类别为'+self.genre)
        if (data['language'] and len(data['language']) > 0) :
            douban_info += "\n◎语\u3000\u3000言　" + " / ".join(data['language'])
            self.language=" / ".join(data['language'])
            logger.info('根据豆瓣信息分析，语言为'+self.language)
        if (data['release'] and len(data['release']) > 0) :
            douban_info += "\n◎上映日期　" + " / ".join(data['release'])
            self.release=" / ".join(data['release'])
            logger.info('根据豆瓣信息分析，上映日期为'+self.release)
        if (data['firstRelease'] and len(data['firstRelease']) > 0) :
            douban_info += "\n◎首\u3000\u3000播　" + " / ".join(data['firstRelease'])
            self.firstRelease=" / ".join(data['firstRelease'])
            logger.info('根据豆瓣信息分析，首播为'+self.firstRelease)
        if (data['num']) :
            douban_info += "\n◎集\u3000\u3000数　" + data['num']
            self.media_type='TV_series'
            self.num=int(data['num'])
            if not (self.complete==1 or self.complete==0):
                if self.pathinfo.max>=self.num:
                    self.complete=1
                else:
                    self.complete=0
            logger.info('根据豆瓣信息分析，总集数为'+str(self.num))
        if (data['imdbRating']) :
            douban_info += "\n◎IMDb评分  " + data['imdbRating'] + "/10 from " + data['imdbVotes'] + " users"
        if (data['imdbUrl']) :
            douban_info += "\n◎IMDb链接  " + data['imdbUrl']
            self.imdburl=data['imdbUrl']
            self.pathinfo.imdb_url=data['imdbUrl']
            logger.info('根据豆瓣信息分析，imdb链接为'+data['imdbUrl'])
        if (data['rating']) :
            self.rating=data['rating']
            self.pathinfo.rating=data['rating']
            douban_info += "\n◎豆瓣评分　" + data['rating'] + "/10 from " + data['votes'] + " users";
        if (data['url']) :
            douban_info += "\n◎豆瓣链接　" + data['url']
        if (data['runtime'] and len(data['runtime']) > 0) :
            douban_info += "\n◎片　　长　" + " / ".join(data['runtime'])

        if (data['director'] and len(data['director']) > 0) :
            for i in range (len(data['director'])):
                if i==0:
                    douban_info += "\n◎导　　演　" + (data['director'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['director'][i]['name'])

        if (data['writer'] and len(data['writer']) > 0) :
            for i in range (len(data['writer'])):
                if i==0:
                    douban_info += "\n◎编　　剧　" + (data['writer'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['writer'][i]['name'])

        if (data['cast'] and len(data['cast']) > 0) :
            for i in range (len(data['cast'])):
                if i==0:
                    douban_info += "\n◎主　　演　" + (data['cast'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['cast'][i]['name'])

        if (data['tags'] and len(data['tags']) > 0) :
            douban_info += "\n\n\n◎标　　签　" + " | ".join(data['tags'])
        if (data['plot']) :
            douban_info=douban_info[0:douban_info.find('<a')]
            plotstr=data['plot']
            plotstr=plotstr[0:plotstr.find('<a')]
            douban_info += "\n\n◎简　　介　" + "\n\n " +(plotstr)
            self.douban_AutoTransferMachine = douban_info       
        if (data['awards'] and len(data['awards']) > 0) :
            awardstr=''
            for item in data['awards']:
                awardstr=awardstr+"\n\n　　" + item['title'];
                for itemc in item['content']:
                    awardstr=awardstr+"\n　　" + itemc
            douban_info += "\n\n◎获奖情况　" + awardstr

        douban_info =douban_info+ "\n\n"
        if not (self.complete==1 or self.complete==0):
            self.complete=0
        self.douban_info=douban_info
        self.getptgen_done=1

    def get_details_url(self):
        file = open(self.torrent_list, "r")
        url_list = file.readlines()
        file.close()
        getmediainfo(url_list)

    #寻找已有的种子文件
    def find_torrentfile(self):
        self.torrentpath=""
        logger.info(f"开始在{self.torrentaddress}中寻找种子文件{self.pathinfo.filename}")
        found = False
        for file in os.listdir(self.torrentaddress):
            file_path = os.path.join(self.torrentaddress, file)
            if os.path.isfile(file_path) and self.pathinfo.filename in file:
                self.torrentpath = f"{self.torrentaddress}/{self.pathinfo.filename}"
                logger.info(f"{self.torrentpath}已寻找到同名种子文件，开始转种")
                found = True
                break
        if not found:
            logger.info(f"没有找到同名种子文件，请手动确认,以下为当前文件夹下的所有文件{file_path}")

    def getfullinfo(self, tracker='https://announce.leaguehd.com/announce.php'):
        if self.getinfo_done==1:
            return

        trytime=0
        while not self.getptgen_done==1:
            logger.info('正在获取豆瓣信息...')
            trytime += 1
            if trytime>10:
                logger.error('获取豆瓣信息失败')
                raise Exception('获取豆瓣信息失败')
            self.get_douban()
            '''
            if self.getptgen_done<1:
                self.getptgen_douban_info()
            if self.getptgen_done<1:
                self.getdoubaninfo()
            '''
            if self.getptgen_done<1:
                time.sleep(3)

        self.getmediainfo()

        if self.pathinfo.year!='':
            self.year=self.pathinfo.year
        if self.pathinfo.video_type!='':
            self.type=self.pathinfo.video_type
        if self.pathinfo.video_format!='':
            self.Video_Format=self.pathinfo.video_format
        if self.pathinfo.audio_format!='':
            self.Audio_Format=self.pathinfo.audio_format
        if self.pathinfo.txt_info!='':
            self.sublan='['+self.pathinfo.txt_info+']'
        if self.pathinfo.audio_info!='':
            self.language=self.pathinfo.audio_info
        self.uploadname=self.pathinfo.uploadname #确定主标题
        self.small_descr=self.pathinfo.small_descr #确定副标题
        self.getimgurl()
        if self.pathinfo.screenshot!='':
            self.screenshoturl=self.pathinfo.screenshot+'\n'+self.screenshoturl
        self.content=self.douban_info+"\n[quote=Mediainfo]\n"+self.mediainfo+"[/quote]\n"+self.screenshoturl
        if self.pathinfo.contenthead!='':
            self.content= self.pathinfo.contenthead+self.content #简介礼节
        if self.pathinfo.contenttail!='':
            self.content= self.content+self.pathinfo.contenttail #简介末尾
        self.find_torrentfile()
        self.getinfo_done=1 #信息收集完成

    def print(self):
        self.getfullinfo()
        attr=['uploadname','small_descr','content','rating']
        for item in attr:
            exec('print("'+item+':"  ,self.'+item+'  )')



utils/mediafile/mediafile.py
Ethan930717/AutoTransferMachine
from utils.pathinfo.pathinfo import findnum
from utils.pathinfo.pathinfo import findeps
import os
from loguru import logger
import time
import requests
import re
import json
import sys
from utils.edittorrent.edittorrent import *
from utils.img_upload.imgupload import img_upload
from shutil import move
from doubaninfo.doubaninfo import getdoubaninfo
from progress.bar import IncrementalBar
from torf import Torrent
from pathlib import Path

def deletetorrent(delpath=''):
    if delpath == '':
        delpath = os.path.dirname(os.path.abspath(__file__))
    logger.info('正在清除此文件夹下所有种子文件:' + delpath)
    ls = os.listdir(delpath)
    for i in ls:
        c_path = os.path.join(delpath, i)
        if (os.path.isfile(c_path)) and (os.path.splitext(i)[1].lower() == ('.torrent') or i.startswith('.')):
            logger.info('正在删除文件:' + c_path + '...')
            os.remove(c_path)


def changename(path):
    if not 'win' in sys.platform:
        return path
    else:
        return '/cygdrive/' + path.replace('\\', '/').replace(':', '')


def mktorrent_win_temp(filepath, torrentname, tracker="https://announce.leaguehd.com/announce.php"):
    cwd = os.getcwd()
    newcwd = os.path.dirname(filepath)
    os.chdir(newcwd)
    if os.path.isdir(filepath):
        logger.info('检测到路径制种，将先删除掉路径里面所有种子文件(torrent后缀)以及隐藏文件（.开头的文件）...')
        deletetorrent(filepath)
    logger.info('即将开始制作种子...')
    if os.path.exists(torrentname):
        logger.info('已存在种子文件，正在删除' + torrentname)
        try:
            os.remove(torrentname)
        except Exception as r:
            logger.error('删除种子发生错误: %s' % (r))
    logger.info('正在制作种子:' + filepath)
    order = 'mktorrent -v -p -f -l 24 -a ' + tracker + ' -o \"' + changename(torrentname) + '\" \"' + os.path.basename(
        filepath) + '\"' + ''
    logger.info(order)
    os.system(order)
    logger.info('已完成制作种子' + torrentname)
    os.chdir(cwd)


def mktorrent_win(filepath, torrentname, tracker="https://announce.leaguehd.com/announce.php"):
    cwd = os.getcwd()
    newcwd = os.path.dirname(filepath)
    os.chdir(newcwd)
    if os.path.isdir(filepath):
        logger.info('检测到路径制种，将先删除掉路径里面所有种子文件(torrent后缀)以及隐藏文件（.开头的文件）...')
        deletetorrent(filepath)
    logger.info('即将开始制作种子...')
    if os.path.exists(torrentname):
        logger.info('已存在种子文件，正在删除' + torrentname)
        try:
            os.remove(torrentname)
        except Exception as r:
            logger.error('删除种子发生错误: %s' % (r))

    if os.path.isdir(filepath):
        new_filepath = os.path.join(os.path.dirname(filepath), 'AAABBBCCC')
        os.rename(filepath, new_filepath)
        logger.info('正在制作种子:' + filepath)
        order = 'mktorrent -v -p -l 24 -c "Made by Auto_Upload" -a ' + tracker + ' -o \"' + changename(
            torrentname) + '\" \"' + os.path.basename(new_filepath) + '\"' + ''
        # logger.info(order)

        trytime = 0
        filesize = 0
        res = ''
        while filesize == 0:

            trytime = trytime + 1
            if trytime > 10:
                logger.error('制作种子失败')
                break
            if trytime > 1:
                logger.warning('制作种子失败,失败原因:' + str(res))
                logger.info(order)
            logger.info('第' + str(trytime) + '次制作种子:')

            # os.system(order)
            if os.path.exists(torrentname):
                logger.info('已存在种子文件，正在删除' + torrentname)
                try:
                    os.remove(torrentname)
                except Exception as r:
                    logger.error('删除种子发生错误: %s' % (r))
            res = os.popen(order)
            temp = res
            res = res.buffer.read().decode('utf-8')
            temp.close()
            del (temp)
            if os.path.exists(torrentname):
                filesize = os.path.getsize(torrentname)
            else:
                filesize = 0

        os.rename(new_filepath, filepath)
        t = Torrent()
        t.load(torrentname)
        t.data[b"info"][b"name"] = str2bytes(os.path.basename(filepath))
        t.dump(torrentname)
    else:
        new_filepath = os.path.join(os.path.dirname(filepath), 'AAABBBCCC' + os.path.splitext(filepath)[-1])
        os.rename(filepath, new_filepath)
        logger.info('正在制作种子:' + filepath)
        order = 'mktorrent -v -p -l 24 -c "Made by Auto_Upload" -a ' + tracker + ' -o \"' + changename(
            torrentname) + '\" \"' + os.path.basename(new_filepath) + '\"' + ''

        # logger.info(order)

        trytime = 0
        filesize = 0
        res = ''
        while filesize == 0:
            trytime = trytime + 1
            if trytime > 10:
                logger.error('制作种子失败')
                break
            if trytime > 1:
                logger.warning('制作种子失败,失败原因:' + str(res))
                if os.path.exists(torrentname):
                    logger.info('已存在种子文件，正在删除' + torrentname)
                    try:
                        os.remove(torrentname)
                    except Exception as r:
                        logger.error('删除种子发生错误: %s' % (r))
                logger.info(order)
            logger.info('第' + str(trytime) + '次制作种子:')

            # os.system(order)
            res = os.popen(order)
            temp = res
            res = res.buffer.read().decode('utf-8')
            temp.close()
            del (temp)
            filesizetime = 0
            while filesize == 0:
                filesizetime = filesizetime + 1
                if filesizetime > 5:
                    break
                if os.path.exists(torrentname):
                    filesize = os.path.getsize(torrentname)
                else:
                    filesize = 0
                if filesize == 0:
                    time.sleep(1)

        os.rename(new_filepath, filepath)
        t = Torrent()
        t.load(torrentname)
        t.data[b"info"][b"name"] = str2bytes(os.path.basename(filepath))
        t.dump(torrentname)

    logger.info('已完成制作种子' + torrentname)
    os.chdir(cwd)


def mktorrent_old(filepath, torrentname, tracker="https://announce.leaguehd.com/announce.php"):
    if 'win32' in sys.platform:
        mktorrent_win(filepath, torrentname, tracker)
        return
    if os.path.isdir(filepath):
        logger.info('检测到路径制种，将先删除掉路径里面所有种子文件(torrent后缀)以及隐藏文件（.开头的文件）...')
        deletetorrent(filepath)
    deletetorrent(os.path.dirname(torrentname))
    logger.info('即将开始制作种子...')
    trytime = 0
    while os.path.exists(torrentname):
        trytime = trytime + 1
        if trytime > 5:
            logger.error('删除种子失败，制作种子失败')
            break
        logger.info('已存在种子文件，正在删除' + torrentname)
        try:
            os.rename(torrentname, torrentname + 'temp')
            os.remove(torrentname + 'temp')
        except Exception as r:
            logger.warning('删除种子发生错误: %s' % (r))

    logger.info('正在对下面路径制作种子:' + filepath)
    order = 'mktorrent -v -p -l 24 -c "Made by ATM" -a ' + tracker + ' -o \"' + torrentname + '\" \"' + filepath + '\"'
    # logger.info(order)
    trytime = 0
    filesize = 0
    while filesize == 0:
        trytime = trytime + 1
        if trytime > 10:
            logger.error('制作种子失败')
            break
        if trytime > 1:
            logger.warning('制作种子失败,失败原因:' + str(res))
            logger.info(order)
        logger.info('第' + str(trytime) + '次制作种子:')
        # os.system(order)
        if os.path.exists(torrentname):
            logger.info('已存在种子文件，正在删除' + torrentname)
            try:
                os.remove(torrentname)
            except Exception as r:
                logger.error('删除种子发生错误: %s' % (r))
        res = os.popen(order)
        temp = res
        res = res.buffer.read().decode('utf-8')
        temp.close()
        del (temp)
        filesizetime = 0
        while filesize == 0:
            filesizetime = filesizetime + 1
            if filesizetime > 5:
                break
            if os.path.exists(torrentname):
                filesize = os.path.getsize(torrentname)
            else:
                filesize = 0
            if filesize == 0:
                time.sleep(1)

    logger.info('已完成制作种子' + torrentname)


def mktorrent(filepath: str, torrentname: str, tracker="https://announce.leaguehd.com/announce.php"):
    if os.path.isdir(filepath):
        logger.info('检测到路径制种，将先删除掉路径里面所有种子文件(torrent后缀)以及隐藏文件（.开头的文件）...')
        deletetorrent(filepath)
    deletetorrent(os.path.dirname(torrentname))
    logger.info('即将开始制作种子...')
    torrent_path = Path(torrentname)
    path = Path(filepath)
    piece_size = 4 * 1024 * 1024
    private = True
    created_by = "ATM"
    source = "ATM"
    trytime = 0
    filesize = 0

    while filesize == 0:
        trytime = trytime + 1
        if trytime > 10:
            logger.error('制作种子失败')
            return
        if trytime > 1:
            logger.warning('第' + str(trytime - 1) + '次制作种子失败')
        logger.info('正在第' + str(trytime) + '次制作种子:')
        if torrent_path.exists():
            logger.info('已存在种子文件，正在删除' + torrentname)
            try:
                os.remove(torrent_path)
            except Exception as r:
                logger.error('删除种子发生错误: %s' % (r))

        if tracker:
            torrent = Torrent(path=str(path.absolute()), trackers=[tracker], piece_size=piece_size, private=private,
                              created_by=created_by, source=source)
        else:
            torrent = Torrent(path=str(path.absolute()), piece_size=piece_size, private=private, created_by=created_by)
        bar = IncrementalBar(message="制种中:", max=torrent.pieces, suffix="%(index)d/%(max)d [%(eta_td)s]")

        def cb(__torrent: Torrent, path: str, hashed_pieces: int, total_pieces: int):
            bar.next()

        torrent.generate(callback=cb, interval=0)
        torrent.write(str(torrent_path))
        bar.finish()
        filesizetime = 0
        while filesize == 0:
            filesizetime = filesizetime + 1
            if filesizetime > 5:
                break
            if os.path.exists(torrentname):
                filesize = os.path.getsize(torrentname)
            else:
                filesize = 0
            if filesize == 0:
                time.sleep(1)
    logger.info('已完成制作种子' + torrentname)
    return


def get_video_duration(video_path: str):
    ext = os.path.splitext(video_path)[-1]
    if ext != '.mp4' and ext != '.avi' and ext != '.flv' and ext != '.ts' and ext != '.mkv':
        raise Exception('format not support')
    ffprobe_cmd = 'ffprobe -i "' + video_path + '" -show_entries format=duration -v quiet -of csv="p=0"'
    a = os.popen(ffprobe_cmd)
    duration_info = float(a.read())
    a.close()
    # duration_info = float(a.buffer.read().decode('utf-8'))
    return duration_info


def takescreenshot(file,screenshotaddress,screenshotnum,basic):
    '''
    para:
        file:视频文件
        duration:视频文件播放时长
        screenshotaddress:存放截图地址，截图后除了新截图其他文件会被清空
        screenshotnum:截图数量
    '''
    logger.info('正在对视频'+file+'截图'+str(screenshotnum)+'张并存入文件夹'+screenshotaddress)
    i=os.path.basename(file)
    if (os.path.isdir(file)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
        logger.error(file+'非视频文件,无法截图')
        raise ValueError (file+'非视频文件,无法截图')
    duration=get_video_duration(file)
    if abs(duration)<1e-9:
        logger.error(file+'视频文件播放时长过短,无法截图')
        raise ValueError (file+'视频文件播放时长过短,无法截图')
    #清空截图文件夹
    ls = os.listdir(screenshotaddress)
    for i in ls:
        c_path = os.path.join(screenshotaddress, i)
        if not (os.path.isdir(c_path)):
            os.remove(c_path)
    timestep=duration*1.0/(screenshotnum+3)
    firststep=timestep*2

    if basic['picture_format'].lower() == "png":
        picture_format = ".png"
    elif basic['picture_format'].lower() == "gif":
        picture_format = ".gif"
    elif basic['picture_format'].lower() == "bmp":
        picture_format = ".bmp"
    elif basic['picture_format'].lower() == "tiff":
        picture_format = ".tiff"
    else:
        picture_format = ".jpg"

    for i in range (screenshotnum):
        firststep=firststep+timestep
        if 'win32' in sys.platform:
            screenshotstr='ffmpeg -ss '+str(firststep)+' -i "'+file+'" -f image2 -y "'+os.path.join(screenshotaddress,str(i+1)+picture_format)+'"'
        else:
            screenshotstr='ffmpeg -ss '+str(firststep)+' -i "'+file+'" -f image2 -y "'+os.path.join(screenshotaddress,str(i+1)+picture_format)+'" &> /dev/null'
        #print(screenshotstr)
        os.system(screenshotstr)
    logger.info('截图完毕')


class mediafile(object):
    def __init__(self, mediapath, pathinfo, basic, imgdata):
        self.mediapath = mediapath
        self.pathinfo = pathinfo
        self.downloadpath = pathinfo.downloadpath
        self.basic = basic
        # self.address就是要被抓去info的资源文件路径
        # 如果mediapath是文件夹，self.address就选里面最大的视频文件
        if os.path.isdir(self.mediapath):
            self.isdir = True
            maxsize = 0
            ls = os.listdir(self.mediapath)
            for i in ls:
                c_path = os.path.join(self.mediapath, i)
                if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                        os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                        os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                    continue
                filesize = os.path.getsize(c_path)
                if filesize > maxsize:
                    self.address = c_path
                    maxsize = filesize

            if self.pathinfo.collection >= 1 and 'zeroday_name' in self.pathinfo.infodict and self.pathinfo.infodict[
                'zeroday_name'] != None and self.pathinfo.infodict['zeroday_name'] != '':
                zeroday_path = os.path.join(self.pathinfo.path, self.pathinfo.infodict['zeroday_name'])
                if os.path.exists(zeroday_path):
                    ls = os.listdir(zeroday_path)
                    for i in ls:
                        c_path = os.path.join(zeroday_path, i)
                        if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                                os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == (
                                '.mkv') or os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[
                                    1].lower() == (
                                        '.ts'))):
                            continue
                        filesize = os.path.getsize(c_path)
                        if filesize > maxsize:
                            self.address = c_path
                            maxsize = filesize

        else:
            self.address = mediapath
            self.isdir = False

        # 种子目录
        self.topath = ''
        self.screenshotaddress = basic['screenshot_path']
        self.torrentaddress = basic['torrent_path']  # 种子文件目录
        self.screenshotnum = int(basic['picture_num'])
        self.tmdbapi = basic['tmdb_api']
        self.imgdata = imgdata

        self.path = os.path.dirname(mediapath)

        self.mediatype = pathinfo.type
        self.doubanurl = pathinfo.doubanurl
        self.imdburl = pathinfo.imdb_url
        self.imdbid = pathinfo.imdb_id
        self.tmdbid = pathinfo.tmdb_id
        self.tmdbname = pathinfo.tmdb_name
        self.bgmurl = pathinfo.bgm_url
        self.anidburl = pathinfo.anidb_url
        self.from_url = pathinfo.from_url
        self.transfer = pathinfo.transfer
        self.complete = pathinfo.complete
        self.filename = os.path.basename(self.address)
        self.episodename = findnum(self.filename)[0]
        self.episode = int(self.episodename)

        self.sub = self.pathinfo.sub
        self.englishname = self.pathinfo.englishname
        self.chinesename = self.pathinfo.chinesename

        self.audio_ch = 0
        self.audio_jp = 0
        self.audio_en = 0
        self.audio_yue = 0
        self.audio_num = 0

        self.text_jp = 0
        self.text_sc = 0
        self.text_tc = 0
        self.text_en = 0

        if ('anime' in self.mediatype.lower() or 'tv' in self.mediatype.lower() or 'doc' in self.mediatype.lower()):
            self.season = self.pathinfo.season
            self.seasonnum = self.pathinfo.seasonnum
            self.season_ch = self.pathinfo.season_ch
            self.complete = self.pathinfo.complete

        dlgroup = ['NaN-Raws', 'NaN Raws', 'NC-Raws', 'NC Raws', 'Lilith-Raws', 'Lilith Raws', 'ANi', 'Skymoon-Raws',
                   'Skymoon Raws', 'GMTeam', 'GM-Team']
        self.type = 'WEBRip'
        self.source = 'WEB-DL'
        self.Video_Format = 'H264'

        if 'hdtvrip' in self.filename.lower() or 'hdtv-rip' in self.filename.lower() or 'tv-rip' in self.filename.lower() or 'tvrip' in self.filename.lower():
            self.type='HDTVRip'
            self.source='HDTVRip'
        elif 'hdtv' in self.filename.lower():
            self.type='HDTV'
            self.source ='HDTV'
        elif 'bdrip' in self.filename.lower() or 'bd-rip' in self.filename.lower():
            self.type='BDRip'
            self.source='BDRip'
        elif 'remux' in self.filename.lower():
            self.type='Remux'
            self.source = 'Remux'
        elif 'bluray' in self.filename.lower() or 'blu-ray' in self.filename.lower():
            self.type='Bluray'
            self.source = 'Bluray'
        elif 'dvdrip' in self.filename.lower() or 'dvd-rip' in self.filename.lower():
            self.type='DVDRip'
            self.source = 'DVDRip'
        elif 'dvd' in self.filename.lower() :
            self.type='DVD'
            self.source ='DVD'
        elif 'webdl' in self.filename.lower() or 'web-dl' in self.filename.lower() :
            self.type='WEB-DL'
            self.source ='WEB-DL'
        elif 'webrip' in self.filename.lower() or 'web-rip' in self.filename.lower():
            self.type='WEBRip'
            self.source = 'WEBRip'
        elif self.sub in dlgroup or ('WEB' in self.sub.upper() and not 'WEBRRP' in self.sub.upper() and not '爪爪' in self.pathinfo.exinfo):
            self.type='WEB-DL'
            self.source ='WEB-DL'

        self.getscreenshot_done = 0
        self.getimgurl_done = 0
        self.getmediainfo_done = 0
        self.getptgen_done = 0
        self.mktorrent_done = 0
        self.getinfo_done = 0

        self.language = ''
        self.country = ''
        self.year = 2023

        # 根据文件名判断内嵌字幕信息
        self.sublan = ''
        jp = 0
        sc = 0
        tc = 0
        if 'SC' in self.filename.upper() or 'CHS' in self.filename.upper() or 'GB' in self.filename.upper() or '简' in self.filename.upper() or '簡' in self.filename.upper():
            sc = 1
        if 'TC' in self.filename.upper() or 'CHT' in self.filename.upper() or 'BIG5' in self.filename.upper() or '繁' in self.filename.upper():
            tc = 1
        if 'JP' in self.filename.upper() or 'JAPANESE' in self.filename.upper() or '日' in self.filename.upper():
            jp = 1

        if jp == 0 and sc == 0 and tc == 1:
            self.sublan = '[内嵌繁中]'
        elif jp == 0 and sc == 1 and tc == 0:
            self.sublan = '[内嵌简中]'
        elif jp == 0 and sc == 1 and tc == 1:
            self.sublan = '[内嵌简繁中字]'
        elif jp == 1 and sc == 0 and tc == 0:
            self.sublan = '[内嵌日字]'
        elif jp == 1 and sc == 0 and tc == 1:
            self.sublan = '[内嵌繁日双语]'
        elif jp == 1 and sc == 1 and tc == 0:
            self.sublan = '[内嵌简日双语]'
        elif jp == 1 and sc == 1 and tc == 1:
            self.sublan = '[内嵌简繁日双语]'
        else:
            self.sublan = ''

        if jp + sc + tc > 0:
            logger.info('根据文件名分析，字幕语言为' + self.sublan)
        else:
            logger.warning('无法根据文件名分析出字幕语言信息')

    def getscreenshot(self):
        if self.getscreenshot_done == 0:
            takescreenshot(self.address, self.screenshotaddress, self.screenshotnum,self.basic)
            self.getscreenshot_done = 1

    def getimgurl(self, server=''):
        if self.getimgurl_done == 1:
            return self.screenshoturl
        '''
        0张图的特判
        '''
        if 'picture_num' in self.basic and int(self.basic['picture_num']) == 0:
            self.screenshoturl = ''
            self.getimgurl_done = 1
            return ''
        self.getscreenshot()
        imgpaths = []

        if self.basic['picture_format'].lower() == "png":
            picture_format = ".png"
        elif self.basic['picture_format'].lower() == "gif":
            picture_format = ".gif"
        elif self.basic['picture_format'].lower() == "bmp":
            picture_format = ".bmp"
        elif self.basic['picture_format'].lower() == "tiff":
            picture_format = ".tiff"
        else:
            picture_format = ".jpg"

        for i in range(self.screenshotnum):
            imgpaths.append(os.path.join(self.screenshotaddress, str(i + 1) + picture_format))
        logger.info('正在将' + self.chinesename + '的第' + self.episodename + '集截图上传' + server + '图床,请稍等...')
        res = img_upload(imgdata=self.imgdata, imglist=imgpaths, host=server, form='bbcode')
        if res == '':
            print(self.chinesename + '上传图床失败,请自行上传图床：')
            temp = '\n'
            res = ''
            while not temp == '':
                temp = input('')
                res = res + temp + '\n'
        logger.info('成功获得图片链接：\n' + res)
        self.screenshoturl = res
        self.getimgurl_done = 1
        return self.screenshoturl

    def dealsubtext(self, res):
        jp = 0
        sc = 0
        tc = 0
        en = 0
        a = res.split('\n\n')
        for item in a:
            if item.startswith('Text'):
                b = item.split('\n')
                for subitem in b:
                    if subitem.lower().startswith('language') or subitem.lower().startswith('title'):
                        if 'SC' in subitem.upper() or 'CHS' in subitem.upper() or 'GB' in subitem.upper() or '简' in subitem.upper() or '簡' in subitem.upper() or '中字' in self.pathinfo.tags:
                            sc = 1
                        if 'TC' in subitem.upper() or 'CHT' in subitem.upper() or 'BIG5' in subitem.upper() or '繁' in subitem.upper() or '中字' in self.pathinfo.tags:
                            tc = 1
                        if 'JP' in subitem.upper() or 'JA' in subitem.upper() or 'JAPANESE' in subitem.upper() or '日' in subitem.upper():
                            jp = 1
                        if 'EN' in subitem.upper() or 'ENGLISH' in subitem.upper() or '英' in subitem.upper():
                            en = 1
        if en == 0 and jp == 0 and sc == 0 and tc == 1:
            self.sublan = '[内封繁体中字]'
        elif en == 0 and jp == 0 and sc == 1 and tc == 0:
            self.sublan = '[内封简体中字]'
        elif en == 0 and jp == 0 and sc == 1 and tc == 1:
            self.sublan = '[内封简繁中字]'
        elif en == 0 and jp == 1 and sc == 0 and tc == 0:
            self.sublan = '[内封日文字幕]'
        elif en == 0 and jp == 1 and sc == 0 and tc == 1:
            self.sublan = '[内封繁日双语]'
        elif en == 0 and jp == 1 and sc == 1 and tc == 0:
            self.sublan = '[内封简日双语]'
        elif en == 0 and jp == 1 and sc == 1 and tc == 1:
            self.sublan = '[内封简繁日双语]'
        elif en == 1 and jp == 0 and sc == 0 and tc == 0:
            self.sublan = '[内封英文字幕]'
        elif en == 1 and jp == 0 and sc == 0 and tc == 1:
            self.sublan = '[内封繁英双语]'
        elif en == 1 and jp == 0 and sc == 1 and tc == 0:
            self.sublan = '[内封简英双语]'
        elif en == 1 and jp == 0 and sc == 1 and tc == 1:
            self.sublan = '[内封简繁英双语]'
        elif en == 1 and jp == 1 and sc == 0 and tc == 0:
            self.sublan = '[内封日英双语]'
        elif en == 1 and jp == 1 and sc == 0 and tc == 1:
            self.sublan = '[内封繁日英三语]'
        elif en == 1 and jp == 1 and sc == 1 and tc == 0:
            self.sublan = '[内封简日英三语]'
        elif en == 0 and jp == 1 and sc == 1 and tc == 1:
            self.sublan = '[内封简繁日英三语]'

        self.text_jp = jp
        self.text_sc = sc
        self.text_tc = tc
        self.text_en = en

        if jp + sc + tc + en > 0:
            logger.info('根据mediainfo分析，字幕语言为' + self.sublan)
        else:
            logger.warning('无法根据mediainfo分析出字幕语言信息')

    def dealaudio(self, res):
        ch = 0
        jp = 0
        en = 0
        yue = 0
        a = res.split('\n\n')
        for item in a:
            if item.startswith('Audio'):
                b = item.split('\n')
                for subitem in b:
                    if subitem.lower().startswith('language') or subitem.lower().startswith('title'):

                        if 'CHINESE' in subitem.upper() or '中' in subitem.upper() or '国' in subitem.upper() or '国语' in self.pathinfo.tags or '国语' in self.pathinfo.small_descr:
                            ch = 1
                            # logger.info('根据mediainfo音轨分析，语言为'+self.language)
                        if 'JAPANESE' in subitem.upper() or '日' in subitem.upper() or '日语' in self.pathinfo.tags or '日语' in self.pathinfo.small_descr:
                            jp = 1
                            # logger.info('根据mediainfo音轨分析，语言为'+self.language)
                        if 'ENGLISH' in subitem.upper() or '英' in subitem.upper() or '英语' in self.pathinfo.tags or '英语' in self.pathinfo.small_descr:
                            en = 1
                            # logger.info('根据mediainfo音轨分析，语言为'+self.language)
                        if 'CANTON' in subitem.upper() or '粤' in subitem.upper() or '粤语' in self.pathinfo.tags or '粤语' in self.pathinfo.small_descr:
                            yue = 1

        '''
        if jp==0 and ch==0 and en==1:
            self.language='英语'
        elif jp==0 and ch==1 and en==0:
            self.language='国语'
        elif jp==0 and ch==1 and en==1:
            self.language='中英双语'
        elif jp==1 and ch==0 and en==0:
            self.language='日语'
        elif jp==1 and ch==0 and en==1:
            self.language='日英双语'
        elif jp==1 and ch==1 and en==0:
            self.language='中日双语'
        elif jp==1 and ch==1 and en==1:
            self.language='中英日三语'
        else:
            self.language=self.language
        '''
        if jp + ch + en + yue > 0:
            self.language = ''
            if ch == 1:
                self.language = self.language + '国'
            if yue == 1:
                self.language = self.language + '粤'
            if jp == 1:
                self.language = self.language + '日'
            if en == 1:
                self.language = self.language + '英'
        self.audio_num = jp + ch + en + yue
        self.audio_ch = ch
        self.audio_jp = jp
        self.audio_en = en
        self.audio_yue = yue

        if self.audio_num == '1':
            self.language = self.language + '语'
        elif self.audio_num == '2':
            self.language = self.language + '双语'
        elif self.audio_num == '3':
            self.language = self.language + '三语'
        elif self.audio_num == '4':
            self.language = self.language + '四语'

        if self.audio_num > 0:
            logger.info('根据mediainfo音轨分析，语言为' + self.language)
        else:
            logger.warning('无法根据mediainfo分析出音轨语言信息')

    def getaudio(self):
        ch = 0
        jp = 0
        en = 0
        yue = 0
        infolist = self.mediainfo_json['media']['track']
        for item in infolist:
            if not '@type' in item:
                continue
            if item['@type'].lower() == 'audio':
                if 'Title' in item:
                    if 'CHINESE' in item['Title'].upper() or '中' in item['Title'].upper() or 'CH' in item[
                        'Title'].upper() or 'ZH' in item['Title'].upper() or '国' in item[
                        'Title'].upper() or 'MANDARIN' in item['Title'].upper() or '国语' in self.pathinfo.small_descr:
                        ch = 1
                    if 'JA' in item['Title'].upper() or 'JP' in item['Title'].upper() or '日' in item['Title'].upper():
                        jp = 1
                    if 'EN' in item['Title'].upper() or '英' in item['Title'].upper():
                        en = 1
                    if 'CANTON' in item['Title'].upper() or '粤' in item[
                        'Title'].upper() or '粤语' in self.pathinfo.small_descr:
                        yue = 1
                elif 'Language' in item:
                    if 'CHINESE' in item['Language'].upper() or '中' in item['Language'].upper() or 'CH' in item[
                        'Language'].upper() or 'ZH' in item['Language'].upper() or '国' in item[
                        'Language'].upper() or '国语' in self.pathinfo.small_descr:
                        ch = 1
                    if 'JA' in item['Language'].upper() or 'JP' in item['Language'].upper() or '日' in item[
                        'Language'].upper():
                        jp = 1
                    if 'EN' in item['Language'].upper() or '英' in item['Language'].upper():
                        en = 1
                    if 'CANTON' in item['Language'].upper() or '粤' in item[
                        'Language'].upper() or '粤语' in self.pathinfo.small_descr:
                        yue = 1
        '''
        if jp==0 and ch==0 and en==1:
            self.language='英语'
        elif jp==0 and ch==1 and en==0:
            self.language='国语'
        elif jp==0 and ch==1 and en==1:
            self.language='中英双语'
        elif jp==1 and ch==0 and en==0:
            self.language='日语'
        elif jp==1 and ch==0 and en==1:
            self.language='日英双语'
        elif jp==1 and ch==1 and en==0:
            self.language='中日双语'
        elif jp==1 and ch==1 and en==1:
            self.language='中英日三语'
        else:
            self.language=self.language

        self.audio_ch=ch
        self.audio_jp=jp
        self.audio_en=en

        if jp+ch+en>0:
            logger.info('根据mediainfo音轨分析，语言为'+self.language)
        else:
            logger.warning('无法根据mediainfo分析出音轨语言信息')
        '''
        if jp + ch + en + yue > 0:
            self.language = ''
            if ch == 1:
                self.language = self.language + '国'
            if yue == 1:
                self.language = self.language + '粤'
            if jp == 1:
                self.language = self.language + '日'
            if en == 1:
                self.language = self.language + '英'
        self.audio_num = jp + ch + en + yue
        self.audio_ch = ch
        self.audio_jp = jp
        self.audio_en = en
        self.audio_yue = yue

        if self.audio_num == '1':
            self.language = self.language + '语'
        elif self.audio_num == '2':
            self.language = self.language + '双语'
        elif self.audio_num == '3':
            self.language = self.language + '三语'
        elif self.audio_num == '4':
            self.language = self.language + '四语'

        if self.audio_num > 0:
            logger.info('根据mediainfo音轨分析，语言为' + self.language)
        else:
            logger.warning('无法根据mediainfo分析出音轨语言信息')

    def getsubtext(self):
        jp = 0
        sc = 0
        tc = 0
        en = 0
        infolist = self.mediainfo_json['media']['track']
        for item in infolist:
            if not '@type' in item:
                continue
            if item['@type'].lower() == 'text':
                if 'Title' in item:
                    if 'TC' in item['Title'].upper() or 'CHT' in item['Title'].upper() or 'BIG5' in item[
                        'Title'].upper() or '繁' in item['Title'].upper():
                        tc = 1
                    elif 'SC' in item['Title'].upper() or 'CHS' in item['Title'].upper() or 'GB' in item[
                        'Title'].upper() or '简' in item['Title'].upper() or '簡' in item['Title'].upper() or '中' in \
                            item['Title'].upper():
                        sc = 1
                    elif 'JP' in item['Title'].upper() or 'JAPANESE' in item['Title'].upper() or '日' in item[
                        'Title'].upper():
                        jp = 1
                    elif 'EN' in item['Title'].upper() or 'ENGLISH' in item['Title'].upper() or '英' in item[
                        'Title'].upper():
                        en = 1
                elif 'Language' in item:
                    if 'TC' in item['Language'].upper() or 'CHT' in item['Language'].upper() or 'BIG5' in item[
                        'Language'].upper() or '繁' in item['Language'].upper():
                        tc = 1
                    elif 'SC' in item['Language'].upper() or 'CHS' in item['Language'].upper() or 'GB' in item[
                        'Language'].upper() or '简' in item['Language'].upper() or '簡' in item[
                        'Language'].upper() or 'ZH' in item['Language'].upper():
                        sc = 1
                    elif 'JP' in item['Language'].upper() or 'JA' in item['Language'].upper() or 'JAPANESE' in item[
                        'Language'].upper() or '日' in item['Language'].upper():
                        jp = 1
                    elif 'EN' in item['Language'].upper() or 'ENGLISH' in item['Language'].upper() or '英' in item[
                        'Language'].upper():
                        en = 1
        if en == 0 and jp == 0 and sc == 0 and tc == 1:
            self.sublan = '[繁体中字]'
        elif en == 0 and jp == 0 and sc == 1 and tc == 0:
            self.sublan = '[简体中字]'
        elif en == 0 and jp == 0 and sc == 1 and tc == 1:
            self.sublan = '[简繁中字]'
        elif en == 0 and jp == 1 and sc == 0 and tc == 0:
            self.sublan = '[日文字幕]'
        elif en == 0 and jp == 1 and sc == 0 and tc == 1:
            self.sublan = '[繁日双语]'
        elif en == 0 and jp == 1 and sc == 1 and tc == 0:
            self.sublan = '[简日双语]'
        elif en == 0 and jp == 1 and sc == 1 and tc == 1:
            self.sublan = '[简繁日双语]'
        elif en == 1 and jp == 0 and sc == 0 and tc == 0:
            self.sublan = '[英文字幕]'
        elif en == 1 and jp == 0 and sc == 0 and tc == 1:
            self.sublan = '[繁英双语]'
        elif en == 1 and jp == 0 and sc == 1 and tc == 0:
            self.sublan = '[简英双语]'
        elif en == 1 and jp == 0 and sc == 1 and tc == 1:
            self.sublan = '[简繁英双语]'
        elif en == 1 and jp == 1 and sc == 0 and tc == 0:
            self.sublan = '[日英双语]'
        elif en == 1 and jp == 1 and sc == 0 and tc == 1:
            self.sublan = '[繁日英三语]'
        elif en == 1 and jp == 1 and sc == 1 and tc == 0:
            self.sublan = '[简日英三语]'
        elif en == 0 and jp == 1 and sc == 1 and tc == 1:
            self.sublan = '[简繁日英三语]'

        self.text_jp = jp
        self.text_sc = sc
        self.text_tc = tc
        self.text_en = en

        if jp + sc + tc + en > 0:
            logger.info('根据mediainfo分析，字幕语言为' + self.sublan)
        else:
            logger.warning('无法根据mediainfo分析出字幕语言信息')

    def updatemediainfo(self, filepath=''):
        if os.path.isdir(self.topath):
            self.address = os.path.join(self.topath, os.path.basename(self.address))
        if not (filepath == '' or filepath == None):
            logger.info('检测到mediainfo模板文件正在应用...')
            a = os.popen('mediainfo --Inform=file://"' + filepath + '" "' + self.address + '"')
            res = a.buffer.read().decode('utf-8')
            self.mediainfo = res
            a.close()
            self.content = self.douban_info + "\n[quote=Mediainfo]\n" + self.mediainfo + "[/quote]\n" + self.screenshoturl
            if self.pathinfo.contenthead != '':
                self.content = self.pathinfo.contenthead + self.content

            if self.pathinfo.contenttail != '':
                self.content = self.content + self.pathinfo.contenttail
            # logger.info('使用模板后，mediainfo变更为:\n'+self.mediainfo)
        else:
            # logger.info('未检测到mediainfo模板文件,正在使用原版mediainfo...')
            a = os.popen('mediainfo "' + self.address + '"')
            res = a.buffer.read().decode('utf-8')
            a.close()
            ss = res.split('\n')
            for i in range(len(ss)):
                if ss[i].startswith('Complete name'):
                    ss[i] = ':'.join([ss[i].split(':')[0], ' ' + self.filename])
            i = 0
            while (i < len(ss)):
                if (ss[i].upper()).startswith('Unique'.upper()):
                    del (ss[i])
                    i = i - 1
                i += 1
            res = '\n'.join(ss)
            self.mediainfo = res
            self.content = self.douban_info + "\n[quote=Mediainfo]\n" + self.mediainfo + "[/quote]\n" + self.screenshoturl
            if self.pathinfo.contenthead != '':
                self.content = self.pathinfo.contenthead + self.content

            if self.pathinfo.contenttail != '':
                self.content = self.content + self.pathinfo.contenttail

    def getmediainfo(self):
        if self.getmediainfo_done == 1:
            return self.mediainfo
        a = os.popen('mediainfo "' + self.address + '"')
        # res=a.read()
        res = a.buffer.read().decode('utf-8')
        a.close()
        # self.dealsubtext(res)
        # self.dealaudio(res)
        ss = res.split('\n')
        # ss[1]=':'.join([ss[1].split(':')[0],' '+self.filename])
        for i in range(len(ss)):
            if ss[i].startswith('Complete name'):
                ss[i] = ':'.join([ss[i].split(':')[0], ' ' + self.filename])
        i = 0
        while (i < len(ss)):
            if (ss[i].upper()).startswith('Unique'.upper()):
                del (ss[i])
                i = i - 1
            i += 1

        self.mediainfo = '\n'.join(ss)
        a = os.popen("mediainfo --Output=JSON \"" + self.address + '"')
        # res_json=a.read()
        res_json = a.buffer.read().decode('utf-8')
        a.close()
        media_json = json.loads(res_json)

        self.mediainfo_json = media_json

        self.getsubtext()
        self.getaudio()

        self.Format = media_json['media']['track'][0]['Format']
        self.FileSize = int(media_json['media']['track'][0]['FileSize'].strip())
        self.duration = float(media_json['media']['track'][0]['Duration'].strip())
        self.Video_Format = media_json['media']['track'][1]['Format']
        self.Width = int(media_json['media']['track'][1]['Width'].strip())
        self.Height = int(media_json['media']['track'][1]['Height'].strip())
        self.BitDepth = int(media_json['media']['track'][1]['BitDepth'].strip())
        self.Audio_Format = media_json['media']['track'][2]['Format']

        #获取HDR信息
        if colour_primaries in media_json['media']['track'][1] or hdr_format in media_json['media']['track'][1]:
            if media_json['media']['track'][1]['colour_primaries'] == "BT.2020" or media_json['media']['track'][1]['hdr_format'] == "SMPTE ST 2094 App 4, Version 1, HDR10+ Profile A compatible":
                self.hdr_type = "HDR10+"
            elif media_json['media']['track'][1]['colour_primaries'] == "BT.2020" or media_json['media']['track'][1]['hdr_format'] == "SMPTE ST 2086, HDR10 compatible":
                self.hdr_type = "HDR10"
            elif media_json['media']['track'][1]['colour_primaries'] == "Display P3" or media_json['media']['track'][1]['hdr_format'] == "Dolby Vision, Version 1.0, dvhe.04.06, BL+RPU":
                self.hdr_type = "Dolby Vision"
            else:
                self.hdr_type = "SDR"
        else:
            self.hdr_type = None

        #获取分辨率
        if 'Scan type' in media_json['media']['track'][1]:
            self.scan_type = media_json['media']['track'][1]['Scan type']
        else:
            self.scan_type = None
        self.Channels = int(media_json['media']['track'][2]['Channels'].strip())
        self.standard_sel = None
        if not self.scan_type == None and ('inter' in self.scan_type.lower() or '隔行' in self.scan_type):
            if int(self.Height) > 2160:
                self.standard_sel = '8K'
            elif int(self.Height) > 1080:
                self.standard_sel = '2160i'
            elif int(self.Height) > 720:
                self.standard_sel = '1080i'
            elif int(self.Height) > 480:
                self.standard_sel = '720i'
            else:
                self.standard_sel = '480i'
        else:
            if int(self.Height) > 2160:
                self.standard_sel = '8K'
            elif int(self.Height) > 1080:
                self.standard_sel = '2160p'
            elif int(self.Height) > 720:
                self.standard_sel = '1080p'
            elif int(self.Height) > 480:
                self.standard_sel = '720p'
            else:
                self.standard_sel = '480p'

        text = self.mediainfo.lower()
        if ('webrip' in text) or ('web-rip' in text):
            self.type = 'WEBRip'
        if ('webdl' in text) or ('web-dl' in text):
            self.type = 'WEB-DL'

        if self.Video_Format == 'AVC':
            self.Video_Format = 'H264'
        if self.Video_Format == 'H264' and 'x264' in text:
            self.Video_Format = 'x264'

        if self.Video_Format == 'HEVC':
            self.Video_Format = 'H265'
        if self.Video_Format == 'H265' and 'x265' in text:
            self.Video_Format = 'x265'
        self.getmediainfo_done = 1
        return self.mediainfo

    def dealwith_douban_info(self, infolist):
        self.picture = infolist[0].strip()
        for item in infolist:
            if '译\u3000\u3000名' in item:
                self.allName = item[5:].strip().split('/')
                self.small_descr = item[5:].strip()
            if '片\u3000\u3000名' in item:
                self.name = item[5:].strip()
            if '年\u3000\u3000代' in item:
                self.year = item[5:].strip()
                logger.info('根据豆瓣信息分析，年份为' + self.year)
            if '产\u3000\u3000地' in item:
                self.country = item[5:].strip()
                logger.info('根据豆瓣信息分析，地区为' + self.country)
            if '类\u3000\u3000别' in item:
                self.genre = item[5:].strip()
                logger.info('根据豆瓣信息分析，类别为' + self.genre)
            if '语\u3000\u3000言' in item:
                self.language = item[5:].strip()
                logger.info('根据豆瓣信息分析，语言为' + self.language)
            if '上映日期' in item:
                self.release = item[5:].strip()
                logger.info('根据豆瓣信息分析，上映日期为' + self.release)
            if '首\u3000\u3000播' in item:
                self.firstRelease = item[5:].strip()
                logger.info('根据豆瓣信息分析，首播为' + self.firstRelease)
            if '集\u3000\u3000数' in item:
                self.num = int(item[5:].strip())
                if not (self.complete == 1 or self.complete == 0):
                    if self.pathinfo.max >= self.num:
                        self.complete = 0
                    else:
                        self.complete = 0
                logger.info('根据豆瓣信息分析，总集数为' + str(self.num))
            if self.imdburl == '' and 'imdb' in item and '链接' in item and not ((item[7:].strip()).endswith('//')):
                self.imdburl = item[7:].strip()
            if '片\u3000\u3000长' in item:
                self.runtime = item[5:].strip()
            if not (self.complete == 1 or self.complete == 0):
                self.complete = 0

    def get_douban(self):
        if 'doubancookie' in self.basic and self.basic['doubancookie'] != None:
            get_success = 0
            get_time = 0
            while get_success == 0:
                get_time += 1
                if get_time > 5:
                    raise Exception('获取豆瓣info出错，请尝试能否正常打开豆瓣')
                try:
                    res_douban = getdoubaninfo(url=self.doubanurl, cookie=self.basic['doubancookie'], ret_val=True)
                    douban_dict = res_douban.parse()
                    get_success = 1
                except Exception as r:
                    get_success = 0
                    logger.warning('抓取豆瓣info错误，一秒后重试，原因: %s' % (r))
                    time.sleep(1)

        else:
            get_success = 0
            get_time = 0
            while get_success == 0:
                get_time += 1
                if get_time > 5:
                    raise Exception('获取豆瓣info出错，请尝试能否正常打开豆瓣')
                try:
                    res_douban = getdoubaninfo(url=self.doubanurl, ret_val=True)
                    douban_dict = res_douban.parse()
                    get_success = 1
                except Exception as r:
                    get_success = 0
                    logger.warning('抓取豆瓣info错误，一秒后重试，原因: %s' % (r))
                    time.sleep(1)

        self.douban_dict = douban_dict
        self.douban_info = res_douban.info()

        # if (douban_dict['names']['chinesename']):
        #    self.chinesename=douban_dict['names']['chinesename']
        if (douban_dict['names']['akaTitles']):
            self.allName = '/'.join(douban_dict['names']['akaTitles'])
        if (douban_dict['year']):
            try:
                self.year = int(douban_dict['year'])
            except:
                logger.warning("douban_dict['year']转换数字出错,其内容为: " + str(douban_dict['year']))
                self.year = 2023
        if (douban_dict['countries'] and len(douban_dict['countries']) > 0):
            self.country = " / ".join(douban_dict['countries'])
        if (douban_dict['genres'] and len(douban_dict['genres']) > 0):
            self.genre = " / ".join(douban_dict['genres'])
        if (douban_dict['languages'] and len(douban_dict['languages']) > 0):
            if self.language.strip() == '':
                self.language = " / ".join(douban_dict['languages'])
                logger.info('根据豆瓣信息分析，语言为' + self.language)
        if (douban_dict['pubdates'] and len(douban_dict['pubdates']) > 0):
            self.release = " / ".join(douban_dict['pubdates'])
        if (douban_dict['imdb'].strip() != ''):
            self.imdbid = douban_dict['imdb']
            self.pathinfo.imdb_id = self.imdbid
            self.imdburl = 'https://www.imdb.com/title/' + self.imdbid + '/'
            self.pathinfo.imdb_url = self.imdburl
            logger.info('根据豆瓣信息分析，imdb链接为' + self.imdburl)
            base_url = "https://api.tmdb.org/3"
            if 'movie' in self.pathinfo.type.lower():
                search_url = base_url + "/search/movie"
            elif 'series' in self.pathinfo.type.lower():
                search_url = base_url + "/search/tv"
            elif 'doc' in self.pathinfo.type.lower() and "完结" in self.pathinfo.tags:
                search_url = base_url + "/search/tv"
            elif 'doc' in self.pathinfo.type.lower():
                search_url = base_url + "/search/movie"
            elif 'anime' in self.pathinfo.type.lower() and "完结" in self.pathinfo.tags:
                search_url = base_url + "/search/tv"
            elif 'anime' in self.pathinfo.type.lower():
                search_url = base_url + "/search/movie"
            else:
                search_url = base_url + "/search/multi"
            params = {
                "api_key": self.tmdbapi,
                "language": "zh-CN",
                "query": self.englishname
            }
            response = requests.get(search_url, params=params)
            if response.status_code == 200:
                data = response.json()
                if data["results"]:
                    tmdbid = data["results"][0]["id"]
                    tmdbname = "".join([data["results"][0].get("name", ""), data["results"][0].get("title", "")])
                    if not tmdbname:
                        print(f"TMDB中未找到{self.englishname}")
                        tmdbid = ""
                    # 输出TMDB ID
                    logger.info(f"已搜索到{tmdbname}在TMDB的ID为{tmdbid}")
                    self.tmdbid = str(tmdbid)
                    self.tmdbname = str(tmdbname)
                else:
                    # 输出没有结果的提示
                    logger.info(f"TMDB中未找到{self.englishname}")
                    self.tmdbid = ""
                    self.tmdbname = ""
                self.pathinfo.tmdb_id = self.tmdbid
                self.pathinfo.tmdb_name = self.tmdbname
            else:
                # 输出请求失败的提示
                logger.info(f"Request failed with status code {response.status_code}.")
        if (douban_dict['episodes']) and (not ('movie' in self.mediatype.lower())):
            self.media_type = 'TV_series'
            try:
                self.num = int(douban_dict['episodes'])
                logger.info('根据豆瓣信息分析，总集数为' + str(self.num))
            except:
                self.num = 1000000
                logger.info('豆瓣页面暂无集数数据')
            if not (self.complete == 1 or self.complete == 0):
                if self.pathinfo.max >= self.num:
                    self.complete = 1
                else:
                    self.complete = 0

        # 没有获取到集数信息则默认为“未完结”
        if not (self.complete == 1 or self.complete == 0):
            self.complete = 0
        self.getptgen_done = 1

    def getptgen_douban_info(self):
        if self.getptgen_done == 1:
            return
        url = 'https://api.iyuu.cn/App.Movie.Ptgen?url=' + self.doubanurl
        user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
        headers = {
            'user-agent': user_agent,
            'referer': url,
        }
        logger.info('正在获取豆瓣信息')
        try:
            r = requests.get(url, headers=headers, timeout=20)
        except Exception as r:
            logger.error('获取豆瓣信息失败，原因: %s' % (r))
            return

        logger.info('获取豆瓣信息完毕，正在处理信息，请稍等...')

        try:
            info_json = r.json()
            logger.trace(info_json)
        except Exception as r:
            logger.warning('获取豆瓣信息转换json格式失败，原因: %s' % (r))
            return

        if not r.ok:
            logger.trace(r.content)
            logger.warning(
                f"获取豆瓣信息失败: HTTP {r.status_code}, reason: {r.reason} ")
            return

        if 'data' not in info_json or 'format' not in info_json['data']:
            logger.warning(f"豆瓣信息获取失败")
            return

        info = info_json['data']['format']
        info = info[0:info.find('<a')]
        self.douban_info = info
        imgurl = re.findall('img[0-9]\.doubanio\.com', self.douban_info)
        if len(imgurl) > 0:
            self.douban_info = self.douban_info.replace(imgurl[0], 'img9.doubanio.com')
        infolist = info.split('◎')
        self.dealwith_douban_info(infolist)
        self.getptgen_done = 1

    def getdoubaninfo(self):
        url = 'https://movieinfo.leaguehd.com/doubanAjax.php?url=' + self.doubanurl
        user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
        headers = {
            'user-agent': user_agent,
            'referer': url,
        }
        logger.info('正在获取豆瓣信息，请稍等...')
        try:
            r = requests.get(url, headers=headers, timeout=20)
        except Exception as r:
            logger.warning('通过柠檬获取豆瓣信息失败，原因: %s' % (r))
            return

        logger.info('获取豆瓣信息完毕，正在处理信息，请稍等...')
        try:
            data = r.json()
        except Exception as r:
            logger.warning('通过柠檬获取豆瓣信息转换json格式失败，原因: %s' % (r))
            return

        douban_info = ''
        if (data['pic']):
            imgurl = re.findall('img[0-9]\.doubanio\.com', data['pic'])
            douban_info = douban_info + "[img]" + data['pic'].replace(imgurl[0], 'img9.doubanio.com') + "[/img]\n"
            # self.picture=data['pic']
        if (data['allName']):
            douban_info = douban_info + "\n◎译\u3000\u3000名　" + '/'.join(data['allName']);
            self.name = data['allName'][0]
            self.allName = '/'.join(data['allName'])
        if (data['name']):
            douban_info += "\n◎片\u3000\u3000名　" + data['name']
            self.name = data['name']
        if (data['year']):
            douban_info += "\n◎年\u3000\u3000代　" + data['year']
            self.year = data['year']
            logger.info('根据豆瓣信息分析，年份为' + self.year)
        if (data['country'] and len(data['country']) > 0):
            douban_info += "\n◎产\u3000\u3000地　" + " / ".join(data['country'])
            self.country = " / ".join(data['country'])
            logger.info('根据豆瓣信息分析，地区为' + self.country)
        if (data['genre'] and len(data['genre']) > 0):
            douban_info += "\n◎类\u3000\u3000别　" + " / ".join(data['genre'])
            self.genre = " / ".join(data['genre'])
            logger.info('根据豆瓣信息分析，类别为' + self.genre)
        if (data['language'] and len(data['language']) > 0):
            douban_info += "\n◎语\u3000\u3000言　" + " / ".join(data['language'])
            self.language = " / ".join(data['language'])
            logger.info('根据豆瓣信息分析，语言为' + self.language)
        if (data['release'] and len(data['release']) > 0):
            douban_info += "\n◎上映日期　" + " / ".join(data['release'])
            self.release = " / ".join(data['release'])
            logger.info('根据豆瓣信息分析，上映日期为' + self.release)
        if (data['firstRelease'] and len(data['firstRelease']) > 0):
            douban_info += "\n◎首\u3000\u3000播　" + " / ".join(data['firstRelease'])
            self.firstRelease = " / ".join(data['firstRelease'])
            logger.info('根据豆瓣信息分析，首播为' + self.firstRelease)
        if (data['num']):
            douban_info += "\n◎集\u3000\u3000数　" + data['num']
            self.media_type = 'TV_series'
            self.num = int(data['num'])
            if not (self.complete == 1 or self.complete == 0):
                if self.pathinfo.max >= self.num:
                    self.complete = 1
                else:
                    self.complete = 0
            logger.info('根据豆瓣信息分析，总集数为' + str(self.num))
        if (data['imdbRating']):
            douban_info += "\n◎IMDb评分  " + data['imdbRating'] + "/10 from " + data['imdbVotes'] + " users"
        if (data['imdbUrl']):
            douban_info += "\n◎IMDb链接  " + data['imdbUrl']
            self.imdburl = data['imdbUrl']
            self.pathinfo.imdb_url = data['imdbUrl']
            logger.info('根据豆瓣信息分析，imdb链接为' + data['imdbUrl'])
        if (data['rating']):
            self.rating = data['rating']
            self.pathinfo.rating = data['rating']
            douban_info += "\n◎豆瓣评分　" + data['rating'] + "/10 from " + data['votes'] + " users";
        if (data['url']):
            douban_info += "\n◎豆瓣链接　" + data['url']
        if (data['runtime'] and len(data['runtime']) > 0):
            douban_info += "\n◎片　　长　" + " / ".join(data['runtime'])

        if (data['director'] and len(data['director']) > 0):
            for i in range(len(data['director'])):
                if i == 0:
                    douban_info += "\n◎导　　演　" + (data['director'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['director'][i]['name'])

        if (data['writer'] and len(data['writer']) > 0):
            for i in range(len(data['writer'])):
                if i == 0:
                    douban_info += "\n◎编　　剧　" + (data['writer'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['writer'][i]['name'])

        if (data['cast'] and len(data['cast']) > 0):
            for i in range(len(data['cast'])):
                if i == 0:
                    douban_info += "\n◎主　　演　" + (data['cast'][i]['name'])
                else:
                    douban_info += "\n　　　　　  " + (data['cast'][i]['name'])

        if (data['tags'] and len(data['tags']) > 0):
            douban_info += "\n\n\n◎标　　签　" + " | ".join(data['tags'])
        if (data['plot']):
            douban_info = douban_info[0:douban_info.find('<a')]
            plotstr = data['plot']
            plotstr = plotstr[0:plotstr.find('<a')]
            douban_info += "\n\n◎简　　介　" + "\n\n " + (plotstr)
            self.douban_ATMOS = douban_info
        if (data['awards'] and len(data['awards']) > 0):
            awardstr = ''
            for item in data['awards']:
                awardstr = awardstr + "\n\n　　" + item['title'];
                for itemc in item['content']:
                    awardstr = awardstr + "\n　　" + itemc
            douban_info += "\n\n◎获奖情况　" + awardstr

        douban_info = douban_info + "\n\n"
        if not (self.complete == 1 or self.complete == 0):
            self.complete = 0
        self.douban_info = douban_info
        self.getptgen_done = 1


    def mktorrent(self, tracker='https://announce.leaguehd.com/announce.php'):
        # if self.mktorrent_done==1:
        #    return
        torrentpath = os.path.join(self.screenshotaddress, str(self.episode) + '.torrent')
        self.torrentpath = torrentpath
        mktorrent(self.topath, torrentpath, tracker=tracker)
        self.mktorrent_done = 1


    def gettorrent(self, tracker='https://announce.leaguehd.com/announce.php'):
        if not ('new_folder' in self.basic and self.basic['new_folder'] >= 1):
            self.mktorrent(tracker)
            return
        dirpath = os.path.dirname(self.topath)
        filelist = []
        if not os.path.exists(self.topath):
            os.makedirs(self.topath)
        else:
            ls = os.listdir(self.topath)
            for i in ls:
                c_path = os.path.join(self.topath, i)
                if i.startswith('.') and os.path.exists(c_path):
                    try:
                        os.remove(c_path)
                    except Exception as r:
                        logger.error('删除.开头文件"' + c_path + '"发生错误: %s' % (r))
                    continue
                if (os.path.isdir(c_path)):
                    if not os.path.exists(os.path.join(dirpath, i)):
                        newpath = move(c_path, dirpath)
                        filelist.append(newpath)
                    else:
                        logger.warning('由于文件' + c_path + '在里外文件夹均已存在,已改名为_temp')
                        try:
                            os.rename(c_path, c_path + '_temp')
                        except Exception as r:
                            logger.error('rename文件夹"' + c_path + '"发生错误: %s' % (r))
                        newpath = move(c_path + '_temp', dirpath)
                        filelist.append(newpath)
                else:
                    if not os.path.exists(os.path.join(dirpath, i)):
                        newpath = move(c_path, dirpath)
                        filelist.append(newpath)
                    else:
                        logger.warning('由于文件' + c_path + '在里外文件夹均已存在,已改名为_temp')
                        stem, suffix = os.path.splitext(c_path)
                        try:
                            os.rename(c_path, stem + '_temp' + suffix)
                            newpath = move(stem + '_temp' + suffix, dirpath)
                            filelist.append(newpath)
                        except Exception as r:
                            logger.error('rename temp文件"' + c_path + '"发生错误: %s' % (r))

        logger.info('检测到路径制种，将先删除掉路径里面所有种子文件(torrent后缀)以及隐藏文件（.开头的文件）...')
        deletetorrent(self.topath)
        if os.path.isdir(self.mediapath):
            ls = os.listdir(self.mediapath)
            for i in ls:
                c_path = os.path.join(self.mediapath, i)
                if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                        os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                        os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                    continue
                move(c_path, self.topath)
        else:
            move(self.mediapath, self.topath)

        self.mktorrent(tracker)

        for item in filelist:
            if os.path.exists(item):
                newpath = move(item, self.topath)
                if '_temp' in newpath and os.path.exists(newpath):
                    os.rename(newpath, newpath.replace('_temp', ''))
            else:
                logger.warning('文件 ' + item + ' 丢失')

    def getfullinfo(self, tracker='https://announce.leaguehd.com/announce.php'):
        if self.getinfo_done == 1:
            return
        trytime = 0
        while not self.getptgen_done == 1:
            logger.info('正在获取豆瓣信息...')
            trytime += 1
            if trytime > 10:
                logger.error('获取豆瓣信息失败')
                raise Exception('获取豆瓣信息失败')
            self.get_douban()
            '''
            if self.getptgen_done<1:
                self.getptgen_douban_info()
            if self.getptgen_done<1:
                self.getdoubaninfo()
            '''
            if self.getptgen_done < 1:
                time.sleep(3)

        self.getmediainfo()

        if self.pathinfo.year != '':
            self.year = self.pathinfo.year
        if self.pathinfo.medium != '':
            self.type = self.pathinfo.medium
        if self.pathinfo.source != '':
            self.source = self.pathinfo.source
        if self.pathinfo.video_format != '':
            self.Video_Format = self.pathinfo.video_format
        if self.pathinfo.audio_format != '':
            self.Audio_Format = self.pathinfo.audio_format
        if self.pathinfo.txt_info != '':
            self.sublan = '[' + self.pathinfo.txt_info + ']'
        if self.pathinfo.audio_info != '':
            self.language = self.pathinfo.audio_info


        self.uploadname = str(self.englishname) + ' ' + str(self.year)
        self.small_descr = self.chinesename.strip()

        medianame = self.uploadname
        if self.pathinfo.type == 'anime' or self.pathinfo.type == 'tv' or self.pathinfo.type == 'doc':
            self.uploadname = self.uploadname + ' ' + self.season
            # if int(self.seasonnum)>1:
            # self.small_descr=self.small_descr+' | '+self.season_ch.strip()
            medianame = self.uploadname
            if not self.isdir:
                self.uploadname = self.uploadname + 'E' + self.episodename
                self.small_descr = self.small_descr + ' | 第' + self.episodename + '集'
            elif self.pathinfo.collection == 2:
                eps_temp = findeps([self.mediapath])
                eps_temp.sort()
                if len(eps_temp) > 1:
                    self.uploadname = self.uploadname + 'E' + str(eps_temp[0]).zfill(2) + '-E' + str(
                        eps_temp[-1]).zfill(2)
                    self.small_descr = self.small_descr + ' | 第' + str(eps_temp[0]).zfill(2) + '-' + str(
                        eps_temp[-1]).zfill(2) + '集'
                else:
                    self.uploadname = self.uploadname + 'E' + self.episodename
                    self.small_descr = self.small_descr + ' | 第' + self.episodename + '集'
            elif self.complete == 1:
                self.uploadname = self.uploadname
                self.small_descr = self.small_descr + ' | 全 ' + str(self.pathinfo.max) + ' 集'
            else:
                self.uploadname = self.uploadname + 'E' + str(self.pathinfo.min).zfill(2) + '-E' + str(
                    self.pathinfo.max).zfill(2)
                self.small_descr = self.small_descr + ' | 第' + str(self.pathinfo.min).zfill(2) + '-' + str(
                    self.pathinfo.max).zfill(2) + '集'

        if self.douban_dict['directors']:
            self.small_descr = self.small_descr + ' | 导演: ' + self.douban_dict['directors'][0]['name'].strip()
            for i in range(min(len(self.douban_dict['directors']) - 1, 1)):
                self.small_descr = self.small_descr + ' / ' + self.douban_dict['directors'][i + 1]['name'].strip()

        if self.douban_dict['actors']:
            self.small_descr = self.small_descr + ' | 主演: ' + self.douban_dict['actors'][0]['name'].strip()
            for i in range(min(len(self.douban_dict['actors']) - 1, 4)):
                self.small_descr = self.small_descr + ' / ' + self.douban_dict['actors'][i + 1]['name'].strip()

        medianame = medianame + ' ' + self.standard_sel + ' ' + self.type + ' ' + self.Video_Format + ' ' + self.Audio_Format + '-' + self.sub
        while '  ' in medianame:
            medianame = medianame.replace('  ', ' ')
        medianame = medianame.replace(' ', '.')

        if 'new_folder' in self.basic and self.basic['new_folder'] == 1:
            if self.pathinfo.zeroday_name != '':
                self.topath = os.path.join(self.pathinfo.path, self.pathinfo.zeroday_name)
            else:
                self.topath = os.path.join(self.pathinfo.path, medianame)
                self.pathinfo.zeroday_name = medianame
                self.pathinfo.infodict['zeroday_name'] = medianame
        elif 'new_folder' in self.basic and self.basic['new_folder'] == 2:
            if self.pathinfo.zeroday_name != '':
                self.topath = os.path.join(self.pathinfo.path, self.pathinfo.zeroday_name)
            else:
                tempchinesename = self.chinesename.strip()
                while '  ' in tempchinesename:
                    tempchinesename = tempchinesename.replace('  ', ' ')
                tempchinesename = tempchinesename.replace(' ', '.')
                self.topath = os.path.join(self.pathinfo.path, tempchinesename + '.' + medianame)
                self.pathinfo.infodict['zeroday_name'] = tempchinesename + '.' + medianame
                self.pathinfo.zeroday_name = tempchinesename + '.' + medianame
                del (tempchinesename)
        else:
            self.topath = self.mediapath

        self.uploadname_ssd = self.uploadname + ' ' + self.type + ' ' + self.standard_sel + ' ' + self.Video_Format + ' ' + self.Audio_Format + (
                    self.audio_num > 1) * ('.' + str(self.audio_num) + 'Audio') + '-' + self.sub
        if self.pathinfo.complete == 1:
            self.uploadname = self.uploadname + ' Complete ' + self.standard_sel + ' ' + self.type + ' ' + self.Video_Format + ' ' + self.Audio_Format + (
                        self.audio_num > 1) * (' ' + str(self.audio_num) + 'Audio') + '-' + self.sub
        else:
            self.uploadname = self.uploadname + ' ' + self.standard_sel + ' ' + self.type + ' ' + self.Video_Format + ' ' + self.Audio_Format + (
                        self.audio_num > 1) * (' ' + str(self.audio_num) + 'Audio') + '-' + self.sub

        try:
            if self.language != '':
                self.small_descr = self.small_descr + ' [' + self.language + ']'
        except:
            logger.warning('未找到资源语言信息，默认为日语')
            self.small_descr = self.small_descr + ' [日语]'

        if not self.sublan == '':
            self.small_descr = self.small_descr + ' ' + self.sublan
        else:
            self.small_descr = self.small_descr + ' [无字幕]'
        self.small_descr = self.small_descr.replace('（', '(').replace('）', ')')

        if self.pathinfo.small_descr != '':
            self.small_descr = self.pathinfo.small_descr
        # logger.debug('副标题为'+self.small_descr)
        self.getimgurl()
        if self.pathinfo.screenshot != '':
            self.screenshoturl = self.pathinfo.screenshot + '\n' + self.screenshoturl
        self.content = self.douban_info + "\n[quote=Mediainfo]\n" + self.mediainfo + "[/quote]\n" + self.screenshoturl

        if self.pathinfo.contenthead != '':
            self.content = self.pathinfo.contenthead + self.content

        if self.pathinfo.contenttail != '':
            self.content = self.content + self.pathinfo.contenttail

        '''
        if 'new_folder' in self.basic and self.basic['new_folder']>=1:
            self.gettorrent(tracker)
        else:
            self.mktorrent(tracker)
        '''
        self.gettorrent(tracker)
        if not (self.complete == 1 or self.complete == 0):
            self.complete = 0
        self.getinfo_done = 1

    def print(self):
        self.getfullinfo()
        attr = ['uploadname', 'small_descr', 'content', 'rating']
        for item in attr:
            exec('print("' + item + ':"  ,self.' + item + '  )')

utils/mediafile/upload_mediafile.py
Ethan930717/AutoTransferMachine
from utils.para_ctrl.readyaml import readyaml
from utils.para_ctrl.readargs import readargs
from utils.para_ctrl.readyaml import write_yaml

import os
from loguru import logger
import csv
import urllib
def choose_function():
    print("请选择你想要执行的功能：")
    print(f"1. 自动转种模式(从本地抓取种子上传）")
    print(f"2. 发种模式(适用于发布自己的资源，自动制种，而不是转发其他资源)")
    print("3. 签到模式")
    print("4. 拉种模式")
    print("5. pathinfo模板转换")
    print("6. 自动截图并上传图床")
    print(f"脚本运行过程中，可使用ctrl+c退出,ctrl+z暂停,暂停过程中输入'fg'恢复运行")
    modechoice = input("请输入你的选择：")
    return modechoice

def read_para():
    args = readargs()
    modechoice=choose_function()
    iu=0#img upload
    su=0#sign
    ru=0#resources upload
    au_data  = readyaml(args.yaml_path)
    if 'basic' in au_data and 'workpath' in au_data['basic']:
        if not os.path.exists(au_data['basic']['workpath']):
            logger.info('检测到workpath目录并未创建，正在新建文件夹：'+au_data['basic']['workpath'])
            os.makedirs(au_data['basic']['workpath'])
        itemlist=['record_path','screenshot_path']
        for item in itemlist:
            if not item in au_data['basic']:
                au_data['basic'][item]=os.path.join(au_data['basic']['workpath'],item)
                if not os.path.exists(au_data['basic'][item]):
                    logger.info('检测到'+item+'目录并未创建，正在新建文件夹：'+au_data['basic'][item])
                    os.makedirs(au_data['basic'][item])

    au_data['yaml_path']=args.yaml_path
    write_yaml(au_data)
    if modechoice == "1":
        au_data['mod']='transfer'
    elif modechoice == "2":
        au_data['mod']='upload'
    elif modechoice == "3":
        au_data['mod']='sign'
    elif modechoice == "4":
        au_data['mod']='download'
    elif modechoice == "5":
        au_data['mod']='transinfo'
    else:
        logger.error('模式选择有误，请重试')
        raise ValueError('模式选择有误，请重试')

    if modechoice == "1":
        if not 'path info' in au_data or len(au_data['path info'])==0:
            logger.error('参数输入错误，发布资源请至少输入一个本地文件地址')
            raise ValueError ('参数输入错误，发布资源请至少输入一个本地文件地址')
        for item in au_data['path info']:
            if not 'path' in au_data['path info'][item] or au_data['path info'][item]['path']==None or au_data['path info'][item]['path']=='':
                logger.error('参数输入错误，'+item+'请至少输入一个本地文件地址')
                raise ValueError ('参数输入错误，'+item+'请至少输入一个本地文件地址')
            if 'type' in au_data['path info'][item] and not ( 'anime' in au_data['path info'][item]['type'].lower() or 'tv' in au_data['path info'][item]['type'].lower() or 'movie' in au_data['path info'][item]['type'].lower() or 'doc' in au_data['path info'][item]['type'].lower()):
                logger.error('参数输入错误，'+item+'的type类型暂不支持')
                raise ValueError ('参数输入错误，'+item+'的type类型暂不支持')
        if not 'qbinfo' in au_data:
            logger.error('参数输入错误，未找到qbinfo')
            raise ValueError ('参数输入错误，未找到qbinfo')
        if not 'start' in au_data['qbinfo'] or not (int(au_data['qbinfo']['start'])==1 or int(au_data['qbinfo']['start'])==0):
            au_data['qbinfo']['start']=0
            logger.warning('未找到qbinfo中的start(添加到qb的种子是否自动开始)参数,已设置为0(不自动开始)')

    return au_data




utils/para_ctrl/para_ctrl.py
Ethan930717/AutoTransferMachine
import argparse
import os


def readargs():
    mainpath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    yaml_path = os.path.join(mainpath,"au.yaml")
    parser = argparse.ArgumentParser(description='欢迎使用大胡开发的ATM自动转种机，如果你有意和我一起开发和测试本工具，欢迎你加入ATM研发群870081858')
    parser.add_argument('-yp','--yaml-path', type=str, help='指定你的au.yaml路径',required=True,default=yaml_path)
    args = parser.parse_args()
    return args

utils/para_ctrl/readargs.py
Ethan930717/AutoTransferMachine
import os
import yaml
from loguru import logger

def readyaml(file):
    newfile=file+'.bak'
    logger.info('正在读取yaml...')
    f=open(file, encoding='utf-8')
    audata = yaml.load(f, Loader=yaml.FullLoader)
    try:
        if (len(audata)<1):
            logger.warning('配置文件'+file+'数据少于一行，判断为数据缺失，已自动使用备份配置文件'+newfile)
            if os.path.exists(newfile):
                f=open(newfile, encoding='utf-8')
                audata = yaml.load(f, Loader=yaml.FullLoader)
            else:
                raise ValueError('配置文件'+file+'数据少于两行，判断为数据缺失，且未找到备份配置文件'+newfile+'请检查配置文件')

    except:
        logger.warning('配置文件'+file+'数据缺失，已自动使用备份配置文件'+newfile)
        f=open(newfile, encoding='utf-8')
        audata = yaml.load(f, Loader=yaml.FullLoader)

    f.close()
    logger.info('读取yaml完毕')
    #au_data['yaml_path']=file
    newfile=file+'.bak'
    write_yaml(audata,newfile)
    return audata
    
def write_yaml(au_data,file=''):
    mod =''
    if file=='' and 'yaml_path' in au_data:
        file=au_data.pop('yaml_path')
    if 'mod' in au_data    :
        mod =au_data.pop('mod')
    if file=='':
        logger.error('未找到yaml文件信息,无法写入文件')
        raise ValueError ('未找到yaml文件信息,无法写入文件')

    logger.info('正在更新yaml中，请勿中途终止程序。如果特殊原因终止程序导致yaml文件内容丢失，请前往au.yaml.bak文件内容中找回')
    f=open(file, "w", encoding='utf-8')
    f.write(yaml.dump(au_data, allow_unicode=True, sort_keys=False))
    f.close()
    logger.info('更新yaml完毕')

    if not file=='' and not '.bak' in file:
        au_data['yaml_path']=file
    if not mod=='':
        au_data['mod']=mod

utils/para_ctrl/readyaml.py
Ethan930717/AutoTransferMachine
import os
from loguru import logger
from urllib.parse import quote
from urllib.parse import unquote
import re
import requests
from utils.para_ctrl.readyaml import write_yaml
from shutil import move

def findnum(name):
    for i in range(2,0,-1):
        num=re.findall(r" ([0-9]{"+str(i)+"}) ",name)
        if len(num)!=0:
            sty=" "+num[0]+" "
            stz=" XX "
            stx=" "+num[0]+" "
            return num[0],sty,stz,stx
        num=re.findall(r"第([0-9]{"+str(i)+"})話",name)
        if len(num)!=0:
            sty='第'+num[0]+'話'
            stz="第XX話"
            stx='第'+num[0]+'話'
            return num[0],sty,stz,stx
        num=re.findall(r"第([0-9]{"+str(i)+"})话",name)
        if len(num)!=0:
            sty='第'+num[0]+'话'
            stz="第XX话"
            stx='第'+num[0]+'话'
            return num[0],sty,stz,stx
        num=re.findall(r"E([0-9]{"+str(i)+"})",name)
        if len(num)!=0:
            sty='第'+num[0]+'话'
            stz="第XX话"
            stx='第'+num[0]+'话'
            return num[0],sty,stz,stx
        num=re.findall(r"_([0-9]{"+str(i)+"})_",name)
        if len(num)!=0:
            sty='_'+num[0]+'_'
            stz="_XX_"
            stx='_'+num[0]+'_'
            return num[0],sty,stz,stx
        num=re.findall(r"\[([0-9]{"+str(i)+"})\D",name)
        if len(num)!=0:
            sty="\["+num[0]+"\]"
            stz="[XX]"
            stx="["+num[0]+"]"
            return num[0],sty,stz,stx
        num=re.findall(r"\D([0-9]{"+str(i)+"})\]",name)
        if len(num)!=0:
            sty="\["+num[0]+"\]"
            stz="[XX]"
            stx="["+num[0]+"]"
            return num[0],sty,stz,stx
        num=re.findall(r"-([0-9]{"+str(i)+"})\D",name)
        if len(num)!=0:
            sty='-'+num[0]
            stz="-XX"
            stx="-"+num[0]
            return num[0],sty,stz,stx
        num=re.findall(r"\D([0-9]{"+str(i)+"})\D",name)
        if len(num)!=0:
            sty=num[0]
            stz="XX"
            stx=num[0]
            return num[0],sty,stz,stx  
        num=re.findall(r"([0-9]{"+str(i)+"})",name)
        if len(num)!=0:
            sty=num[0]
            stz="XX"
            stx=num[0]
            return num[0],sty,stz,stx     
    return '-1','-1','XX','-1'

def finddoubanurl(name):
    logger.info('正在寻找 '+name+' 的豆瓣链接，请稍等...')
    url_encode_name = quote(name.replace(' ',''))
    url='https://www.douban.com/search?q='+url_encode_name
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
    headers = {
            'user-agent': user_agent,
            'referer': url,
            }
    r=requests.models.Response()
    try:
        r = requests.get(url,headers=headers,timeout=30)
    except:
        logger.warning('寻找豆瓣链接失败')
        
    for item in re.findall('/?url=(.*)%2F',r.text):
        item=unquote(item)
        if ('movie.douban.com'in item) and ('/subject/' in item or '/movie/' in item) :
            logger.info('已找到 '+name+' 的豆瓣链接为:\n'+item+'\n')
            res=input('请确认豆瓣链接正确性,如果正确回复y,否则回复正确的豆瓣链接:\n')
            if res.strip().lower()=='y':
                logger.info('已确认 '+name+' 的豆瓣链接为:'+item+'\n')
                return item
            else :
                logger.info('已确认 '+name+' 的豆瓣链接为:'+res+'\n')
                return res
    return ''

def findbgmurl(name):
    logger.info('正在寻找 '+name+' 的Bangumi链接，请稍等...')
    url_encode_name = quote(name)
    url='https://bgm.tv/subject_search/'+url_encode_name+'?cat=2'
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
    headers = {
            'user-agent': user_agent,
            'referer': url,
            }
    r = requests.get(url,headers=headers,timeout=30)
    ans=re.findall('href="/subject/(\d*)',r.text)
    if len(ans)>0:
        logger.info('已找到 '+name+' 的Bangumi链接为:\n'+'https://bgm.tv/subject/'+ans[0]+'\n')
        res=input('请确认Bangumi链接正确性,如果正确回复y,否则回复正确的Bangumi链接,若不需要则直接输入回车:\n')
        if res.strip().lower()=='y':
            logger.info('已确认 '+name+' 的Bangumi链接为:'+'https://bgm.tv/subject/'+ans[0]+'\n')
            return 'https://bgm.tv/subject/'+ans[0]
        else :
            logger.info('已确认 '+name+' 的Bangumi链接为:'+res+'\n')
            return res
    return ''

def findeps(pathlist):
    eps=[]
    for path in pathlist:
        if not os.path.exists(path):
            continue
        ls = os.listdir(path)
        ls.sort()
        for i in ls:
            c_path = os.path.join(path, i)
            if (os.path.isdir(c_path)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
                continue
            epnum=int(findnum(i)[0])
            if epnum==-1:
                logger.error(c_path+' 这个文件，文件名为:'+i+',没找到集数信息，请用户检查，如果确定是程序没有抽取成功请联系作者')
                raise ValueError (c_path+' 这个文件，文件名为:'+i+',没找到集数信息，请用户检查，如果确定是程序没有抽取成功请联系作者')
            if not epnum in eps:
                eps.append(epnum)
    eps.sort()
    return eps





class pathinfo(object):
    def updatepath(self,newpath):
        self.path=newpath
        if self.path[-1]=='\\' or self.path[-1]=='/':
            self.path=self.path[:-1]
        if ('anime' in self.type.lower() or 'tv' in self.type.lower() or 'doc' in self.type.lower()):
            if self.zeroday_name=='':
                self.eps=findeps([self.path])
            else:
                self.eps=findeps([self.path,os.path.join(self.path,self.zeroday_name)])
            if (len(self.eps)<1):
                #raise Exception('路径'+pathid+' : '+self.infodict['path']+'中没找到视频文件')
                logger.warning('路径'+self.pathid+' : '+self.infodict['path']+'中没找到任何视频文件,请检查或者联系开发者')
            if len(self.eps)>0:
                self.min=self.eps[0]
                self.max=self.eps[-1]
            else:
                self.min=10000
                self.max=-1000

    def __init__(self,pathid,infodict,sites,basic):
        self.pathid=pathid
        self.sites=[]
        self.exclusive=[]
        self.infodict=infodict
        self.max=1
        self.min=1
        #必须有的属性
        attr_must=['path','chinesename','englishname','sub']
        for item in attr_must:
            if not item in infodict or infodict[item]==None:
                logger.error('未识别'+pathid+' 中的'+item+'信息')
                raise ValueError ('未识别'+pathid+' 中的'+item+'信息')
            else:
                exec('self.'+item+'=infodict[item]')
                exec('self.exist_'+item+'=True')
        if self.path[-1]=='\\' or self.path[-1]=='/':
            self.path=self.path[:-1]
        
        #可有可无的属性,后面写入配置文件
        attr_disp=['type','collection','enable','doubanurl','complete']
        for item in attr_disp:
            if not item in infodict or infodict[item]==None:
                exec('self.'+item+'=""')
                exec('infodict[item]=None')
                exec('self.exist_'+item+'=False')
            else:
                exec('self.'+item+'=infodict[item]')
                exec('self.exist_'+item+'=True')

        #可有可无的属性,后面不写入配置文件
        attr_disp=['uploadname','video_type','video_format','audio_format','year','zeroday_name','exinfo','seasonnum','imdb_url','bgm_url','anidb_url','transfer','txt_info','audio_info','from_url','contenttail','contenthead','screenshot','small_descr','source','tags','medium','tmdb_id','imdb_id','tmdb_name',"filename"]
        for item in attr_disp:
            if not item in infodict or infodict[item]==None:
                exec('self.'+item+'=""')
                exec('self.exist_'+item+'=False')
            else:
                exec('self.'+item+'=infodict[item]')
                exec('self.exist_'+item+'=True')


        pathstr=os.path.basename(self.path)
        if (self.exist_chinesename and self.exist_englishname and self.exist_sub):
            if self.exinfo!='':
                self.exinfo='['+self.exinfo+']'
            if self.seasonnum=='':
                self.seasonnum=1
                self.season='S01'
            else:
                try:
                    self.seasonnum=int(self.seasonnum)
                    self.season='S'+str(self.seasonnum).zfill(2)
                except:
                    logger.error('季度输入错误')
                    raise ValueError (pathid+'季度输入错误')

        elif   (len(pathstr.split('-'))==4)  :

            path1=os.path.basename(self.path)
            if self.seasonnum!='':
                try:
                    self.seasonnum=int(self.seasonnum)
                    self.season='S'+str(self.seasonnum).zfill(2)
                except:
                    logger.error('季度输入错误')
                    raise ValueError (pathid+'季度输入错误')
            if self.sub=='':
                self.sub               = path1.split('-')[-1].strip()
                infodict['sub']=self.sub
            if self.englishname=='':
                self.englishname       = path1.split('-')[-2].strip()
                seasons=re.findall("S[0-9]{1,2}",self.englishname)
                if len(seasons)==0 and self.seasonnum=='':
                    self.season='S01'
                    self.seasonnum=1

                else:
                    if self.seasonnum=='':
                        self.seasonnum=int(seasons[0][1:])
                        self.season='S'+str(self.seasonnum).zfill(2)
                        infodict['seasonnum']=self.seasonnum
                    self.englishname=self.englishname.replace(self.season,'').strip()
                infodict['englishname']=self.englishname
            if self.chinesename=='':
                self.chinesename       =path1.split('-')[-3].strip()
                if len(re.findall("第.*季",self.chinesename))>0:
                    self.chinesename=self.chinesename.replace(re.findall("第.*季",self.chinesename)[0],'')
                    self.chinesename=self.chinesename.strip()
                infodict['chinesename']=self.chinesename
            if self.exinfo=='':
                self.exinfo            =re.findall('\[.*\]',pathstr.split('-')[0].strip())
                if len(self.exinfo)>0:
                    self.exinfo=self.exinfo[0]
                    infodict['exinfo']=self.exinfo
                else:
                    self.exinfo=''
            else:
                self.exinfo='['+self.exinfo+']'



        else:
            logger.error(pathid+' 信息异常，中文名，英文名，制作小组名有缺失，请补齐后重发')
            raise ValueError (pathid+' 信息异常，中文名，英文名，制作小组名有缺失，请补齐后重发')
        
        pathitem=self.chinesename

        if not self.exist_type:
            logger.warning('未识别路径'+infodict['path']+'的type（资源类型）信息')
            res=100
            while not(res>0 and res<4):
                res=input('请输入资源类型对应的数字:\n1.动漫 2.电视剧 3.电影 4.纪录片 5.综艺\n')
                try:
                    res=int(res)
                except:
                    res=100
                if not(res>0 and res<4):
                    logger.warning('输入有误，请重新输入')
            if res==1:
                self.type='anime'
                infodict['type']='anime'
            elif res==2:
                self.type='tvsereis'
                infodict['type']='tvsereis'
            elif res==3:
                self.type='movie'
                infodict['type']='movie'
            elif res==4:
                self.type='doc'
                infodict['type']='doc'
            elif res == 5:
                self.type = 'tvshow'
                infodict['type'] = 'tvshow'
            else:
                logger.error(pathid+' 中type(资源类型)输入错误')
                raise ValueError (pathid+' 中type(资源类型)输入错误')


        self.downloadpath=''
        if not 'downloadpath' in infodict or infodict['downloadpath']==None or infodict['downloadpath']=='':
            if (self.collection>0 or 'movie' in self.type.lower()) and ( (not 'new_folder' in basic) or str(basic['new_folder'])=='0' or basic['new_folder']==None or basic['new_folder']==''):
                self.downloadpath=os.path.dirname( self.path)
            else:
                self.downloadpath=self.path
        else:
            self.downloadpath=infodict['downloadpath']

        self.category=None
        if not 'category' in infodict or infodict['category']==None:
            self.category=None
        else:
            self.category=infodict['category']



        if self.exist_enable:
            try:
                self.enable =int(self.enable)
            except:
                logger.warning('未识别路径'+pathid+'的enable（资源是否发布）信息,已设置为0（不发）')
                self.enable =0
                infodict['enable']=0
            if not (self.enable==0 or self.enable==1):
                logger.warning('未识别路径'+pathid+'的enable（资源是否发布）信息,已设置为0（不发）')
                self.enable =0
                infodict['enable']=0
        else:
            logger.warning('未识别路径'+pathid+'的enable（资源是否发布）信息,已设置为0（不发）')
            self.enable =0
            infodict['enable']=0


        if self.exist_transfer:
            try:
                self.transfer =int(self.transfer)
            except:
                logger.warning('未识别路径'+pathid+'的transfer(资源是否为转载)信息,已设置为1（默认资源为转载）')
                self.transfer =1
                infodict['transfer']=1
            if not (self.transfer==0 or self.transfer==1):
                logger.warning('未识别路径'+pathid+'的transfer(资源是否为转载)信息,已设置为1（默认资源为转载）')
                self.transfer =1
                infodict['transfer']=1
        else:
            logger.warning('未识别路径'+pathid+'的transfer(资源是否为转载)信息,已设置为1（默认资源为转载）')
            self.transfer =1
            infodict['transfer']=1

        if self.transfer==1 and not self.exist_from_url:
            logger.warning('未识别路径'+pathid+'from_url(转载资源原链接)信息')
            self.from_url = 'https://mikanani.me/'
            infodict['from_url']='https://mikanani.me/'

        if self.exist_complete:
            try:
                self.complete =int(self.complete)
            except:
                logger.warning('未识别路径'+pathid+'的complete(资源是否为完结)信息,默认设置为0（未完结）')
                self.complete =-1
            if not (self.complete==0 or self.complete==1 or self.complete==-1):
                logger.warning('未识别路径'+pathid+'的complete(资源是否为完结)信息,默认设置为0（未完结）')
                self.complete =-1
        else:
            logger.warning('未识别路径'+pathid+'的complete(资源是否为完结)信息,默认设置为0（未完结）')
            self.complete =-1
            


        
        for siteitem in sites:
            if sites[siteitem].enable==0:
                continue
            self.sites.append(siteitem)
            if (not siteitem in infodict) or (infodict[siteitem]==None):
                logger.warning('未找到路径'+pathitem+'在'+siteitem+'的站点信息,已设置为不发')
                exec('self.'+siteitem+'_done=[]')
                exec('self.'+siteitem+'_max_done=10000')
                exec('self.'+siteitem+'_min_done=-1')
                infodict[siteitem]=None
            else:
                exec('self.'+siteitem+'_done='+'str(infodict[siteitem]).split(",")')
                exec('self.'+siteitem+'_max_done=-1')
                exec('self.'+siteitem+'_min_done=10000')
                for i in range(eval('len(self.'+siteitem+'_done)')):
                    #self.done[i]= int(self.done[i])
                    exec('self.'+siteitem+'_done[i]='+'int(self.'+siteitem+'_done[i])')
                    if eval('self.'+siteitem+'_done[i]>self.'+siteitem+'_max_done'):
                        exec('self.'+siteitem+'_max_done=self.'+siteitem+'_done[i]')
                    if eval('self.'+siteitem+'_done[i]<self.'+siteitem+'_min_done'):
                        exec('self.'+siteitem+'_min_done=self.'+siteitem+'_done[i]')
                exec('self.'+siteitem+'_done.sort()')
        
        if 'exclusive' in infodict and infodict['exclusive']!=None:
            self.exclusive=infodict['exclusive'].split(",")
            self.exclusive=[i.strip().lower() for i in self.exclusive]

        season_ch=''
        season_ch=season_ch+'第'
        if self.seasonnum==1:
            season_ch=season_ch+'一'
        elif self.seasonnum==2:
            season_ch=season_ch+'二'
        elif self.seasonnum==3:
            season_ch=season_ch+'三'
        elif self.seasonnum==4:
            season_ch=season_ch+'四'
        elif self.seasonnum==5:
            season_ch=season_ch+'五'
        elif self.seasonnum==6:
            season_ch=season_ch+'六'
        elif self.seasonnum==7:
            season_ch=season_ch+'七'
        elif self.seasonnum==8:
            season_ch=season_ch+'八'
        elif self.seasonnum==9:
            season_ch=season_ch+'九'
        elif self.seasonnum==10:
            season_ch=season_ch+'十'
        elif self.seasonnum==11:
            season_ch=season_ch+'十一'
        elif self.seasonnum==12:
            season_ch=season_ch+'十二'
        elif self.seasonnum==13:
            season_ch=season_ch+'十三'
        elif self.seasonnum==14:
            season_ch=season_ch+'十四'
        elif self.seasonnum==15:
            season_ch=season_ch+'十五'
        else:
            season_ch=season_ch+str(self.seasonnum)
        season_ch=season_ch+'季'
        self.season_ch=season_ch
        
        if ('anime' in self.type.lower() or 'tv' in self.type.lower() or 'doc' in self.type.lower()):

            if self.zeroday_name=='':
                self.eps=findeps([self.path])
            else:
                self.eps=findeps([self.path,os.path.join(self.path,self.zeroday_name)])
            if (len(self.eps)<1):
                #raise Exception('路径'+pathid+' : '+self.infodict['path']+'中没找到视频文件')
                logger.warning('路径'+pathid+' : '+self.infodict['path']+'中没找到任何视频文件,请检查或者联系开发者')
            if len(self.eps)>0:
                self.min=self.eps[0]
                self.max=self.eps[-1]
            else:
                self.min=10000
                self.max=-10000
            '''
            if (not self.exist_bgm_url) and 'anime' in self.type:
                if self.seasonnum>1:
                    self.bgm_url=findbgmurl(self.chinesename.strip()+' '+self.season_ch.strip())
                else:
                    self.bgm_url=findbgmurl(self.chinesename.strip())
                if self.bgm_url=='':
                    #logger.error('未找到 '+self.chinesename+' 对应的Bangumi地址。')
                    logger.warning('未找到 '+self.chinesename+' 对应的Bangumi地址。暂设置为空，如果需要请手动前往au.yaml设置')
                    infodict['bgm_url']=None
                else:
                    infodict['bgm_url']=self.bgm_url
            '''

        if (not self.exist_doubanurl):
            if ('anime' in self.type or 'tv' in self.type or 'doc' in self.type):
                if self.seasonnum>1:
                    self.doubanurl=finddoubanurl(self.chinesename.strip()+' '+self.season_ch.strip())
                else:
                    self.doubanurl=finddoubanurl(self.chinesename.strip())
            else:
                self.doubanurl=finddoubanurl(self.chinesename.strip())
            if self.doubanurl=='':
                logger.warning('未找到 '+self.chinesename+' 对应的豆瓣地址')
                res=input('未找到 '+self.chinesename+' 对应的豆瓣地址。请手动输入正确的豆瓣链接:\n')
                self.doubanurl=res
                infodict['doubanurl']=res
            else:
                infodict['doubanurl']=self.doubanurl
            

    def print(self):
        attr=['path','type','collection','enable','doubanurl','imdb_url','bgm_url','anidb_url','from_url','transfer','sub','englishname','chinesename','tmdb_id','imdb_id','tmdb_name']
        print('Path info:')
        for item in attr:
            exec('print("'+item+':"  ,self.'+item+'  )')
        

        series_attr=['season','seasonnum','eps','min','max']
        if (self.type=='anime' or self.type=='tv' or 'doc' in self.type.lower):
            for item in series_attr:
                exec('print("'+item+':"  ,self.'+item+'  )')
            for item in self.sites:
                exec('print("'+item+'_done:"  ,self.'+item+'_done  )')
                exec('print("'+item+'_min_done:"  ,self.'+item+'_min_done  )')
                exec('print("'+item+'_max_done:"  ,self.'+item+'_max_done  )')

        if ('anime' in self.type or 'tv' in self.type or 'doc' in self.type) :
            print('self.lack:',self.lack)
            if self.lack:
                print('self.lackeps:',self.lackeps)
        print('')


def findpathinfo(yamlinfo,sites):
    paths=yamlinfo['path info']
    pathlist=[]
    for item in paths:
        pathlist.append(pathinfo(item,paths[item],sites,yamlinfo['basic']))
    write_yaml(yamlinfo)
    #a=input('checkpath')
    return pathlist



utils/pathinfo/pathinfo.py
Ethan930717/AutoTransferMachine
import subprocess
import time
import qbittorrentapi
import os
screen_path = os.popen("which screen").read().strip()
query = subprocess.run([screen_path, "-Q", "-S", "fa", "select"], capture_output=True, text=True)
client = qbittorrentapi.Client(host=qbinfo['qburl'],username=qbinfo['qbwebuiusername'],password=qbinfo['qbwebuipassword'])
upload_max = 100 * 1024 * 1024  #达到100Mb/s后暂停发种
upload_min = 90 * 1024 * 1024   #小于90Mb/s后继续发种
paused = False # flag of paused status
while True:
    try:
        query.check_returncode()
        print(query.stdout)
        ps = subprocess.run(["ps", "-C", "AutoTransferMachine", "-o", "pid,stat"], capture_output=True, text=True)
        ps.check_returncode()
        lines = ps.stdout.split("\n")
        columns = lines[1].split()
        stat = columns[1]
        print(stat)
    except subprocess.CalledProcessError as e:
        print("子进程执行失败，错误信息如下：")
        print(e)
    current_upload = client.transfer.info.up_info_speed
    if current_upload >= upload_max:
        if "S" in stat: # 如果脚本在运行
            subprocess.run(["screen", "-X", "-S", "fa", "stuff", "^z"])
            print("达到最大上传速度，暂停发种")
            paused = True 
        else: # 如果脚本没有运行
            print("AutoTransferMachine处于暂停状态")
    elif current_upload < upload_min:
        if "T" in stat: # 如果脚本处于暂停状态
            subprocess.run(["screen", "-X", "-S", "fa", "stuff", "fg\n"])
            print("上传速度空闲，继续发种")
            paused = False # set paused flag to False
        else: 
            print("AutoTransferMachine处于运行状态")
    print("当前的实时上传速率为 " + str(round(current_upload / (1024 * 1024), 2)) + " MB/s")
    time.sleep(10)

utils/seed_machine/qb_control.py
Ethan930717/AutoTransferMachine
from loguru import logger
from utils.para_ctrl.readyaml import write_yaml
import os
from utils.pathinfo.pathinfo import findnum
from utils.mediafile.mediafile import mediafile
from utils.uploader.auto_upload import auto_upload
from shutil import move
from qbittorrentapi import Client
import time
import datetime
import shutil
import requests


def get_newhash(qbinfo):
    logger.info('正在查找最新发布的种子的hash...')
    logger.info('正在登录Qbittorrent WEBUI页面...')
    try:
        client = Client(host=qbinfo['qburl'],username=qbinfo['qbwebuiusername'],password=qbinfo['qbwebuipassword'])
    except Exception as r:
        logger.warning('Qbittorrent WEBUI登录失败，错误信息: %s' %(r))
        logger.warning('获取最新种子hash失败')
        return ''
    logger.info('正在登录Qbittorrent WEBUI账号..')
    try:
        client.auth_log_in()
    except Exception as r:
        logger.warning('Qbittorrent WEBUI信息错误，登录失败，请检查au.yaml文件里的url、用户名、密码，错误信息: %s' %(r))
        logger.warning('获取最新种子hash失败')
        return ''
    addtime=0
    torrentlist=client.torrents.info()
    for item in torrentlist:
        if item.added_on>addtime:
            addtime=item.added_on
            to=item
    return to._torrent_hash

def start_hash(qbinfo,hashlist):
    if hash=='':
        logger.warning('hash为空，并没有开始任何种子')
        return 
    logger.info('正在查找最新发布的种子的hash...')
    logger.info('正在登录Qbittorrent WEBUI页面...')
    try:
        client = Client(host=qbinfo['qburl'],username=qbinfo['qbwebuiusername'],password=qbinfo['qbwebuipassword'])
    except Exception as r:
        logger.warning('Qbittorrent WEBUI登录失败,错误信息: %s' %(r))
        return 
    logger.info('正在登录Qbittorrent WEBUI账号..')
    try:
        client.auth_log_in()
    except Exception as r:
        logger.warning('Qbittorrent WEBUI信息错误，登录失败，请检查au.yaml文件里的url、用户名、密码，错误信息: %s' %(r))
        return 
    for tohash in hashlist:
        try:
            client.torrents_resume(torrent_hashes=tohash)
        except Exception as r:
            logger.warning('开始种子发生错误,错误信息: %s' %(r))
    






def seedmachine_single(pathinfo,sites,pathyaml,basic,qbinfo,imgdata,hashlist):
    '''
    para:
        pathinfo
        sites 
        pathyaml 用于更新yaml中发布信息
        basic
        qbinfo  
    '''
    logger.info('正在发布路径'+pathinfo.path+'下资源')
    log_error=''
    log_succ=''
    logstr=''
    errorsite=''
    errornum=0
    succnum=0
    for pathep in pathinfo.eps:
        #判断此集有没有站点要发布,此集合收纳还没有发布过本集的站点
        site_upload=[]
        for siteitem in sites:
            #发布过此集的站点略过
            if sites[siteitem].enable==1 and not( eval('pathinfo.'+siteitem+'_max_done==10000')) and not eval('pathep in pathinfo.'+siteitem+'_done'):
                site_upload.append(sites[siteitem])

        #如果没有站点要发布就略过本集
        if len(site_upload)==0:
            continue
        

        ls = os.listdir(pathinfo.path)
        filepath=''
        for i in ls:
            c_path=os.path.join(pathinfo.path, i)
            if (os.path.isdir(c_path)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
                continue
            if int(findnum(i)[0])==pathep:
                filepath=c_path
                break
        move_suc=0
        move_newpath=''
        move_oldpath=''
        filelist=[]
        if filepath=='' and pathinfo.zeroday_name!='':
            zeroday_path=os.path.join(pathinfo.path,pathinfo.zeroday_name)
            ls = os.listdir(zeroday_path)
            filepath=''
            for i in ls:
                c_path=os.path.join(zeroday_path, i)
                if (os.path.isdir(c_path)) or (i.startswith('.')) or (not(  os.path.splitext(i)[1].lower()== ('.mp4') or os.path.splitext(i)[1].lower()== ('.mkv')  or os.path.splitext(i)[1].lower()== ('.avi') or os.path.splitext(i)[1].lower()== ('.ts')    )):
                    continue
                if int(findnum(i)[0])==pathep:
                    move_oldpath=os.path.dirname(c_path)
                    filepath=move(c_path,pathinfo.path)
                    move_newpath=filepath
                    move_suc=1
                    break
    
        if filepath=='':
            logger.error('未找到文件夹'+pathinfo.path+'下第'+str(pathep)+'集资源')
            raise ValueError ('未找到文件夹'+pathinfo.path+'下第'+str(pathep)+'集资源')

        #获取file全部信息
        file1=mediafile(filepath,pathinfo,basic,imgdata)
        if not pathinfo.imdb_url=='' and ((not 'imdb_url' in pathyaml) or pathyaml['imdb_url']==None):
            pathyaml['imdb_url']=pathinfo.imdb_url
        if file1.complete==1 and (not 'complete' in pathyaml or pathyaml['complete']==None or pathyaml['complete']==''):
            pathyaml['complete']=1
        
        
        logger.info('正在发布路径'+pathinfo.path+'下第'+str(pathep)+'集资源:'+filepath)
        logger.info('正在抓取资源信息,请稍后...')
        file1.getfullinfo()
        for siteitem in site_upload:
            if siteitem.enable==0:
                continue
            logger.info('正在'+siteitem.sitename+'站点发布路径'+pathinfo.chinesename+'第'+str(pathep)+'集资源')
            upload_success=False
            uploadtime=0
            #用模板获取mediainfo
            file1.updatemediainfo(siteitem.mediainfo_template_file)
            while upload_success==False and uploadtime<3:
                uploadtime=uploadtime+1
                logger.info('第'+str(uploadtime)+'次尝试发布')

                try:
                    upload_success,logstr=auto_upload(siteitem,file1,basic['record_path'],qbinfo,basic,hashlist)
                except Exception as r:
                    logger.warning('发布资源发生错误，错误信息: %s' %(r))
                    upload_success=False

                if not upload_success:
                    logger.warning(siteitem.sitename+'第'+str(uploadtime)+'次发布任务失败')
                    logger.warning(logstr)
                    #file1.mktorrent()
                    file1.find_torrentfile()

            if not upload_success:
                logger.warning(siteitem.sitename+'发布任务失败，本站暂停发种')
                siteitem.enable=0
                errornum=errornum+1
                log_error=log_error+str(errornum)+':\t'+siteitem.sitename+'   \t'+logstr+'\n'
                logger.warning(logstr)
                errorsite=errorsite+siteitem.sitename+logstr+'\n'
            elif '已存在' in  logstr:
                errornum=errornum+1
                log_error=log_error+str(errornum)+':\t'+siteitem.sitename+'   \t'+logstr+'\n'
                logger.warning(logstr)
                errorsite=errorsite+siteitem.sitename+logstr+'\n'
                #记录已发布的种子
                exec('pathinfo.'+siteitem.sitename+'_done.append(pathep)')
                exec('pathinfo.'+siteitem.sitename+'_done.sort()')
                exec('pathyaml["'+siteitem.sitename+'"]=",".join([str(i) for i in pathinfo.'+siteitem.sitename+'_done])')
            else:
                succnum=succnum+1
                log_succ=log_succ+str(succnum)+':\t'+siteitem.sitename+'   \t'+logstr+'\n'
                logger.info(logstr)
                #记录已发布的种子
                exec('pathinfo.'+siteitem.sitename+'_done.append(pathep)')
                exec('pathinfo.'+siteitem.sitename+'_done.sort()')
                exec('pathyaml["'+siteitem.sitename+'"]=",".join([str(i) for i in pathinfo.'+siteitem.sitename+'_done])')
                #deletetorrent(basic['screenshot_path'])
            #a=input('check')
            
        del(file1)
        if move_suc==1 and os.path.exists(move_newpath) and os.path.exists(move_oldpath):
            logger.info('正在尝试将文件：'+move_newpath+'移动回原位：'+move_oldpath)
            try:
                move_newpath=move(move_newpath,move_oldpath)
                move_suc=0
            except Exception as r:
                logger.warning('移动文件'+move_newpath+'到'+move_oldpath+'链接失败，原因: %s' %(r))
            
    logger.info('路径'+pathinfo.path+'下资源已全部发布完毕')
    return log_error,log_succ
    if errorsite=="":
        pushtext = pathinfo.chinesename + "发送完成，发送成功站点数"+str(succnum)+"个,无失败站点"
    else:
        pushtext = pathinfo.chinesename + "发送完成，发送成功站点数"+str(succnum)+"个,失败站点"+str(errornum)+"个:"+errorsite
    pushurl = "https://sc.ftqq.com/" + basic['serverchan_api'] + ".send?title=发种成功&desp=" + pushtext
    pushres = requests.get(pushurl)       



#发布合集
def seedmachine(pathinfo,sites,pathyaml,basic,qbinfo,imgdata,hashlist):
    '''
    para:
        pathinfo
        sites 
        pathyaml 用于更新yaml中发布信息
        basic
        qbinfo  
    '''
    logger.info('正在发布路径'+pathinfo.path+'下资源')
    log_error=''
    log_succ=''
    logstr=''
    errorsite=''
    errornum=0
    succnum=0
    site_upload=[]
    for siteitem in sites:
        #发布过此集的站点略过
        if sites[siteitem].enable==1 and not( eval('pathinfo.'+siteitem+'_max_done==10000')) and not eval('-1 in pathinfo.'+siteitem+'_done'):
            site_upload.append(sites[siteitem])

    #如果没有站点要发布就略过本集
    if len(site_upload)==0:
        logger.info('路径'+pathinfo.path+'下资源已全部发布完毕')
        return log_error,log_succ


    #获取file全部信息
    file1=mediafile(pathinfo.path,pathinfo,basic,imgdata)
    logger.info('正在抓取资源信息,请稍后...')
    file1.getfullinfo()
    if not pathinfo.imdb_url=='' and ((not 'imdb_url' in pathyaml) or pathyaml['imdb_url']==None):
        pathyaml['imdb_url']=pathinfo.imdb_url
    if file1.complete==1 and (not 'complete' in pathyaml or pathyaml['complete']==None or pathyaml['complete']==''):
        pathyaml['complete']=1
        

    logger.info('正在发布路径'+pathinfo.path+'下资源')
    

    for siteitem in site_upload:
        if siteitem.enable==0:
            continue
        logger.info('正在'+siteitem.sitename+'站点发布'+pathinfo.chinesename+'资源')
        upload_success=False
        uploadtime=0
        #用模板获取mediainfo
        file1.updatemediainfo(siteitem.mediainfo_template_file)
        while upload_success==False and uploadtime<3:
            uploadtime=uploadtime+1
            logger.info('第'+str(uploadtime)+'次尝试发布')


            upload_success,logstr=auto_upload(siteitem,file1,basic['record_path'],qbinfo,basic,hashlist)
            if not upload_success:
                logger.warning(siteitem.sitename+'第'+str(uploadtime)+'次发布任务失败')
                logger.warning(logstr)
                #file1.mktorrent()
                file1.find_torrentfile()

        if not upload_success:
            logger.warning(siteitem.sitename+'发布任务失败，本站暂停发种')
            siteitem.enable=0
            errornum=errornum+1
            log_error=log_error+str(errornum)+':\t'+siteitem.sitename+'  \t'+logstr+'\n'
            logger.warning(logstr)
            errorsite=errorsite+siteitem.sitename+logstr+'\n'
        elif '已存在' in  logstr:
            errornum=errornum+1
            log_error=log_error+str(errornum)+':\t'+siteitem.sitename+'   \t'+logstr+'\n'
            logger.warning(logstr)
            errorsite=errorsite+siteitem.sitename+logstr+'\n'
            #记录已发布的种子
            if not 'movie' in pathinfo.type.lower():
                for epitem in pathinfo.eps:
                    exec('pathinfo.'+siteitem.sitename+'_done.append('+str(epitem)+')')
                exec('pathinfo.'+siteitem.sitename+'_done=list(set('+'pathinfo.'+siteitem.sitename+'_done'+'))')
                exec('pathinfo.'+siteitem.sitename+'_done.sort()')
            if pathinfo.complete==1:
                exec('pathinfo.'+siteitem.sitename+'_done.append(-1)')
            exec('pathyaml["'+siteitem.sitename+'"]=",".join([str(i) for i in pathinfo.'+siteitem.sitename+'_done])')
        else:
            succnum=succnum+1
            log_succ=log_succ+str(succnum)+':\t'+siteitem.sitename+'   \t'+logstr+'\n'
            logger.info(logstr)
            #记录已发布的种子
            if not 'movie' in pathinfo.type.lower():
                for epitem in pathinfo.eps:
                    exec('pathinfo.'+siteitem.sitename+'_done.append('+str(epitem)+')')
                exec('pathinfo.'+siteitem.sitename+'_done=list(set('+'pathinfo.'+siteitem.sitename+'_done'+'))')
                exec('pathinfo.'+siteitem.sitename+'_done.sort()')
            if pathinfo.complete==1:
                exec('pathinfo.'+siteitem.sitename+'_done.append(-1)')
            exec('pathyaml["'+siteitem.sitename+'"]=",".join([str(i) for i in pathinfo.'+siteitem.sitename+'_done])')
            #deletetorrent(basic['screenshot_path'])
        #a=input('check')
            
    del(file1)  
    logger.info('路径'+pathinfo.path+'下资源已全部发布完毕')
    if errorsite=="":
        pushtext = pathinfo.chinesename + "发送完成，发送成功站点数"+str(succnum)+"个,无失败站点"
    else:
        pushtext = pathinfo.chinesename + "发送完成，发送成功站点数"+str(succnum)+"个,失败站点"+str(errornum)+"个:"+errorsite
    pushurl = "https://sc.ftqq.com/" + basic['serverchan_api'] + ".send?title=发种成功&desp=" + pushtext
    pushres = requests.get(pushurl)       
    return log_error,log_succ



def start_machine(pathlist,sites,yamlinfo):
    log_allsucc=''
    log_allerror=''
    hashlist=[]
    for path in pathlist:
        if path.enable==0:
            logger.info('路径'+path.path+'的enable被设置为0，已忽略')
            continue
        if (path.type=='anime' or path.type=='tv' or path.type=='doc') and path.collection==0:
            log_error,log_succ=seedmachine_single(path,sites,yamlinfo['path info'][path.pathid],yamlinfo['basic'],yamlinfo['qbinfo'],yamlinfo['image hosting'],hashlist)
        elif (path.type=='anime' or path.type=='tv' or path.type=='doc') and path.collection==2:
            log_error,log_succ=seedmachine_rest(path,sites,yamlinfo['path info'][path.pathid],yamlinfo['basic'],yamlinfo['qbinfo'],yamlinfo['image hosting'],hashlist)
        else:
            log_error,log_succ=seedmachine(path,sites,yamlinfo['path info'][path.pathid],yamlinfo['basic'],yamlinfo['qbinfo'],yamlinfo['image hosting'],hashlist)
        write_yaml(yamlinfo)
        if not log_succ=='':
            log_allsucc=log_allsucc+log_succ+'\n'
            logger.info(log_succ)
        print('\n')
        if not log_error=='':
            log_allerror=log_allerror+log_error+'\n'
            logger.error(log_error)

    if 'start' in yamlinfo['qbinfo'] and  yamlinfo['qbinfo']['start']==1:
        logger.info('检测到需要开始种子，正在开始种子...')
        try:
            start_hash(yamlinfo['qbinfo'],hashlist)
        except Exception as r:
            logger.warning('开始种子发生错误,错误信息: %s' %(r))



    print('\n\n以下种子已成功发布:')
    print('*'*100)
    #print(log_allsucc.strip())
    print('\033[1;35m'+log_allsucc.strip()+'\033[0m')
    print('*'*100+'\n\n')
    

    logger.trace('\n\n以下种子已成功发布:')
    logger.trace('*'*100)
    logger.trace(log_allsucc.strip())
    logger.trace('*'*100+'\n\n')

    print('以下种子发布失败:')
    print('&'*100)
    if log_allerror.strip()=='':
        print('\033[1;31;40m 无 \033[0m')
    else:
        print('\033[1;31;40m'+log_allerror.strip()+'\033[0m')
    #print(log_allerror.strip())
    print('&'*100+'\n\n')

    logger.trace('以下种子发布失败:')
    logger.trace('&'*100)
    logger.trace(log_allerror.strip())
    logger.trace('&'*100+'\n\n')



utils/seed_machine/seed_machine.py
Ethan930717/AutoTransferMachine
from loguru import logger
from utils.para_ctrl.readyaml import write_yaml
import os
from utils.pathinfo.pathinfo import findnum
from utils.mediafile.upload_mediafile import mediafile
from utils.uploader.auto_upload import auto_upload
from shutil import move
from qbittorrentapi import Client
import time
import datetime
import shutil
import requests
from utils.para_ctrl.readyaml import write_yaml


def get_newhash(qbinfo):
    logger.info('正在查找最新发布的种子的hash...')
    logger.info('正在登录Qbittorrent WEBUI页面...')
    try:
        client = Client(host=qbinfo['qburl'], username=qbinfo['qbwebuiusername'], password=qbinfo['qbwebuipassword'])
    except Exception as r:
        logger.warning('Qbittorrent WEBUI登录失败，错误信息: %s' % (r))
        logger.warning('获取最新种子hash失败')
        return ''
    logger.info('正在登录Qbittorrent WEBUI账号..')
    try:
        client.auth_log_in()
    except Exception as r:
        logger.warning('Qbittorrent WEBUI信息错误，登录失败，请检查au.yaml文件里的url、用户名、密码，错误信息: %s' % (r))
        logger.warning('获取最新种子hash失败')
        return ''
    addtime = 0
    torrentlist = client.torrents.info()
    for item in torrentlist:
        if item.added_on > addtime:
            addtime = item.added_on
            to = item
    return to._torrent_hash


def start_hash(qbinfo, hashlist):
    if hash == '':
        logger.warning('hash为空，并没有开始任何种子')
        return
    logger.info('正在查找最新发布的种子的hash...')
    logger.info('正在登录Qbittorrent WEBUI页面...')
    try:
        client = Client(host=qbinfo['qburl'], username=qbinfo['qbwebuiusername'], password=qbinfo['qbwebuipassword'])
    except Exception as r:
        logger.warning('Qbittorrent WEBUI登录失败,错误信息: %s' % (r))
        return
    logger.info('正在登录Qbittorrent WEBUI账号..')
    try:
        client.auth_log_in()
    except Exception as r:
        logger.warning('Qbittorrent WEBUI信息错误，登录失败，请检查au.yaml文件里的url、用户名、密码，错误信息: %s' % (r))
        return
    for tohash in hashlist:
        try:
            client.torrents_resume(torrent_hashes=tohash)
        except Exception as r:
            logger.warning('开始种子发生错误,错误信息: %s' % (r))


def seedmachine_single(pathinfo, sites, pathyaml, basic, qbinfo, imgdata, hashlist):
    '''
    para:
        pathinfo
        sites
        pathyaml 用于更新yaml中发布信息
        basic
        qbinfo
    '''
    logger.info('正在发布路径' + pathinfo.path + '下资源')
    log_error = ''
    log_succ = ''
    logstr = ''
    errorsite = ''
    errornum = 0
    succnum = 0
    for pathep in pathinfo.eps:

        # 判断此集有没有站点要发布,此集合收纳还没有发布过本集的站点
        site_upload = []
        for siteitem in sites:
            # 发布过此集的站点略过
            if sites[siteitem].enable == 1 and not (eval('pathinfo.' + siteitem + '_max_done==10000')) and not eval(
                    'pathep in pathinfo.' + siteitem + '_done'):
                site_upload.append(sites[siteitem])

        # 如果没有站点要发布就略过本集
        if len(site_upload) == 0:
            continue

        ls = os.listdir(pathinfo.path)
        filepath = ''
        for i in ls:
            c_path = os.path.join(pathinfo.path, i)
            if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                    os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                    os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                continue
            if int(findnum(i)[0]) == pathep:
                filepath = c_path
                break
        move_suc = 0
        move_newpath = ''
        move_oldpath = ''
        filelist = []
        if filepath == '' and pathinfo.zeroday_name != '':
            zeroday_path = os.path.join(pathinfo.path, pathinfo.zeroday_name)
            ls = os.listdir(zeroday_path)
            filepath = ''
            for i in ls:
                c_path = os.path.join(zeroday_path, i)
                if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                        os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                        os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                    continue
                if int(findnum(i)[0]) == pathep:
                    move_oldpath = os.path.dirname(c_path)
                    filepath = move(c_path, pathinfo.path)
                    move_newpath = filepath
                    move_suc = 1
                    break

        if filepath == '':
            logger.error('未找到文件夹' + pathinfo.path + '下第' + str(pathep) + '集资源')
            raise ValueError('未找到文件夹' + pathinfo.path + '下第' + str(pathep) + '集资源')

        # 获取file全部信息
        file1 = mediafile(filepath, pathinfo, basic, imgdata)
        if not pathinfo.imdb_url == '' and ((not 'imdb_url' in pathyaml) or pathyaml['imdb_url'] == None):
            pathyaml['imdb_url'] = pathinfo.imdb_url
        if file1.complete == 1 and (
                not 'complete' in pathyaml or pathyaml['complete'] == None or pathyaml['complete'] == ''):
            pathyaml['complete'] = 1

        logger.info('正在发布路径' + pathinfo.path + '下第' + str(pathep) + '集资源:' + filepath)
        logger.info('正在抓取资源信息,请稍后...')
        file1.getfullinfo()
        for siteitem in site_upload:
            if siteitem.enable == 0:
                continue
            logger.info(
                '正在' + siteitem.sitename + '站点发布路径' + pathinfo.chinesename + '第' + str(pathep) + '集资源')
            upload_success = False
            uploadtime = 0
            # 用模板获取mediainfo
            file1.updatemediainfo(siteitem.mediainfo_template_file)
            while upload_success == False and uploadtime < 1:
                uploadtime = uploadtime + 1
                logger.info('第' + str(uploadtime) + '次尝试发布')

                try:
                    upload_success, logstr = auto_upload(siteitem, file1, basic['record_path'], qbinfo, basic, hashlist)
                except Exception as r:
                    logger.warning('发布资源发生错误，错误信息: %s' % (r))
                    upload_success = False

                if not upload_success:
                    logger.warning(siteitem.sitename + '第' + str(uploadtime) + '次发布任务失败')
                    logger.warning(logstr)
                    # file1.mktorrent()
                    file1.gettorrent()

            if not upload_success:
                logger.warning(siteitem.sitename + '发布任务失败，本站暂停发种')
                siteitem.enable = 0
                errornum = errornum + 1
                log_error = log_error + str(errornum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
                logger.warning(logstr)
                errorsite = errorsite + siteitem.sitename +logstr+'\n'
            elif '已存在' in logstr:
                errornum = errornum + 1
                log_error = log_error + str(errornum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
                logger.warning(logstr)
                errorsite = errorsite + siteitem.sitename +logstr+'\n'
                # 记录已发布的种子
                exec('pathinfo.' + siteitem.sitename + '_done.append(pathep)')
                exec('pathinfo.' + siteitem.sitename + '_done.sort()')
                exec(
                    'pathyaml["' + siteitem.sitename + '"]=",".join([str(i) for i in pathinfo.' + siteitem.sitename + '_done])')
            else:
                succnum = succnum + 1
                log_succ = log_succ + str(succnum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
                logger.info(logstr)
                # 记录已发布的种子
                exec('pathinfo.' + siteitem.sitename + '_done.append(pathep)')
                exec('pathinfo.' + siteitem.sitename + '_done.sort()')
                exec(
                    'pathyaml["' + siteitem.sitename + '"]=",".join([str(i) for i in pathinfo.' + siteitem.sitename + '_done])')
                # deletetorrent(basic['screenshot_path'])
            # a=input('check')

        del (file1)
        if move_suc == 1 and os.path.exists(move_newpath) and os.path.exists(move_oldpath):
            logger.info('正在尝试将文件：' + move_newpath + '移动回原位：' + move_oldpath)
            try:
                move_newpath = move(move_newpath, move_oldpath)
                move_suc = 0
            except Exception as r:
                logger.warning('移动文件' + move_newpath + '到' + move_oldpath + '链接失败，原因: %s' % (r))

    logger.info('路径' + pathinfo.path + '下资源已全部发布完毕')
    return log_error, log_succ


# 发布剩余合集
def seedmachine_rest(pathinfo, sites, pathyaml, basic, qbinfo, imgdata, hashlist):
    # 把没发布的集数转移到新建文件夹内
    log_error = ''
    log_succ = ''
    errorsite = ''
    logstr = ''
    # 1.将没有发布过的资源移到新路径path_new
    path_old = pathinfo.path
    path_new = os.path.join(pathinfo.path, os.path.basename(pathinfo.path))
    for siteitem in sites:
        # 发布过此集的站点略过
        if sites[siteitem].enable != 1 or (eval('pathinfo.' + siteitem + '_max_done==10000')):
            continue
        # 收集需要发布的合集
        eps = []
        for pathep in pathinfo.eps:
            if not eval('pathep in pathinfo.' + siteitem + '_done'):
                eps.append(int(pathep))
        if len(eps) <= 0:
            logger.info('正在' + siteitem + '站点发布路径' + path_old + '下无未发布分集,已跳过')
            continue

        # 新建文件夹
        try:
            os.mkdir(path_new)
        except Exception as r:
            logger.warning('新建文件夹发生错误,错误信息: %s' % (r))
            log_error = log_error + '路径' + path_old + '新建子文件夹' + path_new + '发生错误\n'
            if os.path.exists(path_new):
                logger.warning('路径 ' + path_old + ' 内已存在文件夹 ' + path_new + '请更改此文件夹命名\n')
            continue

        ls = os.listdir(path_old)
        for i in ls:
            c_path = os.path.join(path_old, i)
            if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                    os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                    os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                continue
            if int(findnum(i)[0]) in eps:
                shutil.move(c_path, path_new)
        if pathinfo.zeroday_name != '' and pathinfo.zeroday_name != None and os.path.exists(
                os.path.join(path_old, pathinfo.zeroday_name)):
            path_file = os.path.join(path_old, pathinfo.zeroday_name)
            ls = os.listdir(path_file)
            for i in ls:
                c_path = os.path.join(path_file, i)
                if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                        os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                        os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                    continue
                if int(findnum(i)[0]) in eps:
                    shutil.move(c_path, path_new)
        # 2.将path_new按照合集发布
        if pathinfo.path != path_new:
            pathinfo.updatepath(path_new)
        logger.info('正在' + siteitem + '站点发布路径' + path_old + '下没发布过的资源合集，分别为：' + str(eps))

        errornum = 0
        succnum = 0
        siteitem = sites[siteitem]
        # 获取file全部信息
        file1 = mediafile(path_new, pathinfo, basic, imgdata)
        logger.info('正在抓取资源信息,请稍后...')
        file1.getfullinfo()
        if not pathinfo.imdb_url == '' and ((not 'imdb_url' in pathyaml) or pathyaml['imdb_url'] == None):
            pathyaml['imdb_url'] = pathinfo.imdb_url
        if file1.complete == 1 and (
                not 'complete' in pathyaml or pathyaml['complete'] == None or pathyaml['complete'] == ''):
            pathyaml['complete'] = 1
        # 用模板获取mediainfo
        file1.updatemediainfo(siteitem.mediainfo_template_file)

        # 3.把文件返回原位

        dst_path = path_old
        if ('new_folder' in basic) and (str(basic['new_folder']) == '1' or str(basic['new_folder']) == '2'):
            dst_path = os.path.join(path_old, os.path.basename(file1.topath))
        if not os.path.exists(dst_path):
            os.mkdir(dst_path)
        ls = os.listdir(file1.topath)
        for i in ls:
            c_path = os.path.join(file1.topath, i)
            if (os.path.isdir(c_path)) or (i.startswith('.')) or (not (
                    os.path.splitext(i)[1].lower() == ('.mp4') or os.path.splitext(i)[1].lower() == ('.mkv') or
                    os.path.splitext(i)[1].lower() == ('.avi') or os.path.splitext(i)[1].lower() == ('.ts'))):
                continue
            shutil.move(c_path, dst_path)
            # 4.删除path_new文件夹
        shutil.rmtree(path_new)

        upload_success = False
        uploadtime = 0

        while upload_success == False and uploadtime < 1:
            uploadtime = uploadtime + 1
            logger.info('第' + str(uploadtime) + '次尝试发布')
            upload_success, logstr = auto_upload(siteitem, file1, basic['record_path'], qbinfo, basic, hashlist)
            if not upload_success:
                logger.warning(siteitem.sitename + '第' + str(uploadtime) + '次发布任务失败')
                logger.warning(logstr)
                # file1.mktorrent()
                file1.gettorrent()
        if not upload_success:
            logger.warning(siteitem.sitename + '发布任务失败，本站暂停发种')
            siteitem.enable = 0
            errornum = errornum + 1
            log_error = log_error + str(errornum) + ':\t' + siteitem.sitename + '  \t' + logstr + '\n'
            errorsite = errorsite + siteitem.sitename +logstr+'\n'
            logger.warning(logstr)
        elif '已存在' in logstr:
            errornum = errornum + 1
            log_error = log_error + str(errornum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
            errorsite = errorsite + siteitem.sitename +logstr+'\n'
            logger.warning(logstr)
            # 记录已发布的种子
            for epitem in eps:
                exec('pathinfo.' + siteitem.sitename + '_done.append(' + str(epitem) + ')')
            exec('pathinfo.' + siteitem.sitename + '_done=list(set(' + 'pathinfo.' + siteitem.sitename + '_done' + '))')
            exec('pathinfo.' + siteitem.sitename + '_done.sort()')
            exec(
                'pathyaml["' + siteitem.sitename + '"]=",".join([str(i) for i in pathinfo.' + siteitem.sitename + '_done])')
        else:
            succnum = succnum + 1
            log_succ = log_succ + str(succnum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
            logger.info(logstr)
            # 记录已发布的种子
            for epitem in eps:
                exec('pathinfo.' + siteitem.sitename + '_done.append(' + str(epitem) + ')')
            exec('pathinfo.' + siteitem.sitename + '_done=list(set(' + 'pathinfo.' + siteitem.sitename + '_done' + '))')
            exec('pathinfo.' + siteitem.sitename + '_done.sort()')
            exec(
                'pathyaml["' + siteitem.sitename + '"]=",".join([str(i) for i in pathinfo.' + siteitem.sitename + '_done])')
            # deletetorrent(basic['screenshot_path'])
        # a=input('check')

        del (file1)
        logger.info(siteitem.sitename + '站点,路径' + path_old + '下资源合集发布完毕，分别为：' + str(eps))

    return log_error, log_succ


# 发布合集
def seedmachine(pathinfo, sites, pathyaml, basic, qbinfo, imgdata, hashlist):
    '''
    para:
        pathinfo
        sites
        pathyaml 用于更新yaml中发布信息
        basic
        qbinfo
    '''
    logger.info('正在发布路径' + pathinfo.path + '下资源')
    log_error = ''
    log_succ = ''
    logstr = ''
    errorsite = ''
    errornum = 0
    succnum = 0
    site_upload = []
    for siteitem in sites:
        # 发布过此集的站点略过
        if sites[siteitem].enable == 1 and not (eval('pathinfo.' + siteitem + '_max_done==10000')) and not eval(
                '-1 in pathinfo.' + siteitem + '_done'):
            site_upload.append(sites[siteitem])

    # 如果没有站点要发布就略过本集
    if len(site_upload) == 0:
        logger.info('路径' + pathinfo.path + '下资源已全部发布完毕')
        return log_error, log_succ

    # 获取file全部信息
    file1 = mediafile(pathinfo.path, pathinfo, basic, imgdata)
    logger.info('正在抓取资源信息,请稍后...')
    file1.getfullinfo()
    if not pathinfo.imdb_url == '' and ((not 'imdb_url' in pathyaml) or pathyaml['imdb_url'] == None):
        pathyaml['imdb_url'] = pathinfo.imdb_url
    if file1.complete == 1 and (
            not 'complete' in pathyaml or pathyaml['complete'] == None or pathyaml['complete'] == ''):
        pathyaml['complete'] = 1

    logger.info('正在发布路径' + pathinfo.path + '下资源')

    for siteitem in site_upload:
        if siteitem.enable == 0:
            continue
        logger.info('正在' + siteitem.sitename + '站点发布' + pathinfo.chinesename + '资源')
        upload_success = False
        uploadtime = 0
        # 用模板获取mediainfo
        file1.updatemediainfo(siteitem.mediainfo_template_file)
        while upload_success == False and uploadtime < 1:
            uploadtime = uploadtime + 1
            logger.info('第' + str(uploadtime) + '次尝试发布')

            upload_success, logstr = auto_upload(siteitem, file1, basic['record_path'], qbinfo, basic, hashlist)
            if not upload_success:
                logger.warning(siteitem.sitename + '第' + str(uploadtime) + '次发布任务失败')
                logger.warning(logstr)
                # file1.mktorrent()
                file1.gettorrent()

        if not upload_success:
            logger.warning(siteitem.sitename + '发布任务失败，本站暂停发种')
            siteitem.enable = 0
            errornum = errornum + 1
            log_error = log_error + str(errornum) + ':\t' + siteitem.sitename + '  \t' + logstr + '\n'
            logger.warning(logstr)
            errorsite = errorsite + siteitem.sitename +logstr+'\n'
        elif '已存在' in logstr:
            errornum = errornum + 1
            log_error = log_error + str(errornum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
            logger.warning(logstr)
            errorsite = errorsite + siteitem.sitename +logstr+'\n'
            # 记录已发布的种子
            if not 'movie' in pathinfo.type.lower():
                for epitem in pathinfo.eps:
                    exec('pathinfo.' + siteitem.sitename + '_done.append(' + str(epitem) + ')')
                exec(
                    'pathinfo.' + siteitem.sitename + '_done=list(set(' + 'pathinfo.' + siteitem.sitename + '_done' + '))')
                exec('pathinfo.' + siteitem.sitename + '_done.sort()')
            if pathinfo.complete == 1:
                exec('pathinfo.' + siteitem.sitename + '_done.append(-1)')
            exec(
                'pathyaml["' + siteitem.sitename + '"]=",".join([str(i) for i in pathinfo.' + siteitem.sitename + '_done])')
        else:
            succnum = succnum + 1
            log_succ = log_succ + str(succnum) + ':\t' + siteitem.sitename + '   \t' + logstr + '\n'
            logger.info(logstr)
            # 记录已发布的种子
            if not 'movie' in pathinfo.type.lower():
                for epitem in pathinfo.eps:
                    exec('pathinfo.' + siteitem.sitename + '_done.append(' + str(epitem) + ')')
                exec(
                    'pathinfo.' + siteitem.sitename + '_done=list(set(' + 'pathinfo.' + siteitem.sitename + '_done' + '))')
                exec('pathinfo.' + siteitem.sitename + '_done.sort()')
            if pathinfo.complete == 1:
                exec('pathinfo.' + siteitem.sitename + '_done.append(-1)')
            exec(
                'pathyaml["' + siteitem.sitename + '"]=",".join([str(i) for i in pathinfo.' + siteitem.sitename + '_done])')
            # deletetorrent(basic['screenshot_path'])
        # a=input('check')

    del (file1)
    logger.info('路径' + pathinfo.path + '下资源已全部发布完毕')
    if errorsite == "":
        pushtext = pathinfo.chinesename + "发送完成，发送成功站点数" + str(succnum) + "个,无失败站点"
    else:
        pushtext = pathinfo.chinesename + "发送完成，发送成功站点数" + str(succnum) + "个,失败站点" + str(
            errornum) + "个:" + errorsite
    pushurl = "https://sc.ftqq.com/" + basic['serverchan_api'] + ".send?title=发种成功&desp=" + pushtext
    pushres = requests.get(pushurl)
    return log_error, log_succ


def startupload_machine(pathlist, sites, yamlinfo):
    log_allsucc = ''
    log_allerror = ''
    hashlist = []
    for path in pathlist:
        if path.enable == 0:
            logger.info('路径' + path.path + '的enable被设置为0，已忽略')
            continue
        if (path.type == 'anime' or path.type == 'tv' or path.type == 'doc') and path.collection == 0:
            log_error, log_succ = seedmachine_single(path, sites, yamlinfo['path info'][path.pathid], yamlinfo['basic'],
                                                     yamlinfo['qbinfo'], yamlinfo['image hosting'], hashlist)
        elif (path.type == 'anime' or path.type == 'tv' or path.type == 'doc') and path.collection == 2:
            log_error, log_succ = seedmachine_rest(path, sites, yamlinfo['path info'][path.pathid], yamlinfo['basic'],
                                                   yamlinfo['qbinfo'], yamlinfo['image hosting'], hashlist)
        else:
            log_error, log_succ = seedmachine(path, sites, yamlinfo['path info'][path.pathid], yamlinfo['basic'],
                                              yamlinfo['qbinfo'], yamlinfo['image hosting'], hashlist)
        write_yaml(yamlinfo)
        if not log_succ == '':
            log_allsucc = log_allsucc + log_succ + '\n'
            logger.info(log_succ)
        print('\n')
        if not log_error == '':
            log_allerror = log_allerror + log_error + '\n'
            logger.error(log_error)

    if 'start' in yamlinfo['qbinfo'] and yamlinfo['qbinfo']['start'] == 1:
        logger.info('检测到需要开始种子，正在开始种子...')
        try:
            start_hash(yamlinfo['qbinfo'], hashlist)
        except Exception as r:
            logger.warning('开始种子发生错误,错误信息: %s' % (r))

    print('\n\n以下种子已成功发布:')
    print('*' * 100)
    # print(log_allsucc.strip())
    print('\033[1;35m' + log_allsucc.strip() + '\033[0m')
    print('*' * 100 + '\n\n')

    logger.trace('\n\n以下种子已成功发布:')
    logger.trace('*' * 100)
    logger.trace(log_allsucc.strip())
    logger.trace('*' * 100 + '\n\n')

    print('以下种子发布失败:')
    print('&' * 100)
    if log_allerror.strip() == '':
        print('\033[1;31;40m 无 \033[0m')
    else:
        print('\033[1;31;40m' + log_allerror.strip() + '\033[0m')
    # print(log_allerror.strip())
    print('&' * 100 + '\n\n')

    logger.trace('以下种子发布失败:')
    logger.trace('&' * 100)
    logger.trace(log_allerror.strip())
    logger.trace('&' * 100 + '\n\n')



utils/seed_machine/seedupload_machine.py
Ethan930717/AutoTransferMachine
from loguru import logger
import json
import os.path

class site(object):
    def __init__(self,sitename,sitedict):
        self.sitename   = sitename
        self.exist_url   = False
        self.exist_cookie=False
        self.exist_passkey=False
        self.uplver =1
        self.enable =0
        self.check = False
        self.mediainfo_template_file=''
        self.passkey=''
        self.token='' #zhuque站点token
        self.torrentkey='' #zhuque站点torrentkey

        try:
            self.uplver =int(sitedict['uplver'])
        except:
            logger.warning(sitename+'站点匿名发布uplver信息填错错误，已设置为1:默认匿名发布')
            self.uplver =1
            sitedict['uplver']=1
        if not (self.uplver==0 or self.uplver==1):
            logger.warning(sitename+'站点匿名发布uplver信息填错错误，已设置为1:默认匿名发布')
            self.uplver =1
            sitedict['uplver']=1

        if 'mediainfo_template_file' in sitedict and sitedict['mediainfo_template_file']!= None and sitedict['mediainfo_template_file'].strip()!='':
            if os.path.exists(sitedict['mediainfo_template_file']):
                self.mediainfo_template_file=sitedict['mediainfo_template_file']
            else:
                raise Exception(sitename+'站点的mediainfo模板文件不存在')
        else:
            self.mediainfo_template_file=''


        try:
            self.enable =int(sitedict['enable'])
        except:
            logger.warning(sitename+'站点enable信息填错错误，已设置为0:关闭')
            self.enable =0
            sitedict['enable']=0

        if not (self.enable==0 or self.enable==1):
            logger.warning(sitename+'站点匿名发布enable信息填错错误，已设置为0:关闭')
            self.enable =0
            sitedict['enable']=0

        if 'url' in sitedict :
            self.url=sitedict['url']
            self.exist_url=True
        else:
            self.url=''
            self.exist_url=False


        if 'cookie' in sitedict :
            self.cookie=sitedict['cookie']
            self.exist_cookie=True
        else:
            self.cookie=''
            self.exist_cookie=False

        if 'passkey' in sitedict :
            self.passkey=sitedict['passkey']
            self.exist_passkey=True
        else:
            self.passkey=''
            self.exist_passkey=False

        if 'check' in sitedict :
            if str(sitedict['check']=='1'):
                self.check=True
            else:
                self.check=False

        if sitename=='zhuque':
            if 'torrentkey' in sitedict :
                self.torrentkey=sitedict['torrentkey']
            else:
                logger.warning('zhuque站点缺少torrentkey，将会导致无法做种')

        if self.enable==1 and not self.exist_cookie:
            logger.error('未找到'+sitename+' 站点的cookie信息')
            raise ValueError ('未找到'+sitename+' 站点的cookie信息')


    def print(self):
        print('Site info:')
        print('sitename:'  ,self.sitename  )
        print('enable:'    ,self.enable    )
        print('url:'       ,self.url       )
        print('loginurl:'  ,self.loginurl  )
        print('uploadurl:' ,self.uploadurl )
        sitename = self.sitename
        if self.exist_url:
            url = self.url
            print('url:',self.url)
        else:
            print('站点地址:未设置或未识别')
        if self.exist_cookie:
            cookies = self.cookie
            print('cookie:',self.cookie)
        else:
            print('cookiefile:未设置或未识别')
        if self.exist_passkey:
            passkey = self.passkey
            print('passkey:',self.passkey)
        else:
            print('passkey:未设置或未识别')
        fromsite(url,cookie,passkey,sitename)
        print('')

def makesites(siteinfo):
    sites=dict()
    for item in siteinfo:
        sites[item]=site(item,siteinfo[item])
    return sites









utils/site/site.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def audience_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower() and '完结' in file1.pathinfo.tags:
        select_type='402'
    elif 'anime' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'                 
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='408'                                    
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')         
    elif 'UHD' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='15'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')                              
    else:
        medium_sel='11'
        logger.info('未识别到媒介信息，不选择媒介')

   


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')              
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  


    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='26'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='21'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='23'
    elif 'AC3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='25'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='24'
    else:
        audiocodec_sel='6'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='10'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    #选择制作组
    if 'audies' in file1.sub.lower():
        team_sel='19'
    elif 'ade' in file1.sub.lower():
        team_sel='21'
    elif 'adweb' in file1.sub.lower():
        team_sel='20'
    elif 'adaudio' in file1.sub.lower():
        team_sel='23'
    elif 'adebook' in file1.sub.lower():
        team_sel='24'
    elif 'admusic' in file1.sub.lower():
        team_sel='25'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)


    tags=list(set(tags))
    if 'anime' in file1.pathinfo.type.lower():
        tags.append('dh')
    if '国' in file1.language or '中' in file1.language or '国语' in file1.pathinfo.tags:
        tags.append('gy')
    if '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan or '中字' in file1.pathinfo.tags:
        tags.append('zz')
    if file1.transfer==0:
        tags.append('yc')
    if '完结' in file1.pathinfo.tags :
        tags.append('wj')
    if '杜比' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags:
        tags.append('db')
    if 'DIY' in file1.pathinfo.tags:
        tags.append('diy')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append('hdrm')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append('hdr10')             
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'


    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "douban_id": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+"[Mediainfo]"+file1.mediainfo+"[/Mediainfo]"+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/audience_upload.py
Ethan930717/AutoTransferMachine
from utils.uploader.piggo_upload import piggo_upload
from utils.uploader.hdsky_upload import hdsky_upload
from utils.uploader.audience_upload import audience_upload
from utils.uploader.ssd_upload import ssd_upload
from utils.uploader.pter_upload import pter_upload
from utils.uploader.hhclub_upload import hhclub_upload
from utils.uploader.hdpt_upload import hdpt_upload
from utils.uploader.wintersakura_upload import wintersakura_upload
from utils.uploader.carpt_upload import carpt_upload
from utils.uploader.hdfans_upload import hdfans_upload
from utils.uploader.hares_upload import hares_upload
from utils.uploader.zmpt_upload import zmpt_upload
from utils.uploader.hdvideo_upload import hdvideo_upload
from utils.uploader.redleaves_upload import redleaves_upload
from utils.uploader.mteam_upload import mteam_upload
from utils.uploader.zhuque_upload import zhuque_upload
from utils.uploader.dajiao_upload import dajiao_upload
from utils.uploader.pandapt_upload import pandapt_upload
from utils.uploader.rousi_upload import rousi_upload
from utils.uploader.ptlsp_upload import ptlsp_upload
from utils.uploader.okpt_upload import okpt_upload
from utils.uploader.yiptba_upload import yiptba_upload
from utils.uploader.mangguo_upload import mangguo_upload
from utils.uploader.wuerpt_upload import wuerpt_upload
from utils.uploader.btschool_upload import btschool_upload
from utils.uploader.freefarm_upload import freefarm_upload
from utils.uploader.discfan_upload import discfan_upload
from utils.uploader.dragonhd_upload import dragonhd_upload
from utils.uploader.cyanbug_upload import cyanbug_upload
from utils.uploader.hdarea_upload import hdarea_upload
from utils.uploader.hdhome_upload import hdhome_upload
from utils.uploader.hddolby_upload import hddolby_upload
from utils.uploader.hdmayi_upload import hdmayi_upload
from utils.uploader.hdtime_upload import hdtime_upload
from utils.uploader.hdu_upload import hdu_upload
from utils.uploader.hdzone_upload import hdzone_upload
from utils.uploader.hitpt_upload import hitpt_upload
from utils.uploader.hudbt_upload import hudbt_upload
from utils.uploader.haidan_upload import haidan_upload
from utils.uploader.icc_upload import icc_upload
from utils.uploader.itzmx_upload import itzmx_upload
from utils.uploader.joyhd_upload import joyhd_upload
from utils.uploader.nanyang_upload import nanyang_upload
from utils.uploader.oshen_upload import oshen_upload
from utils.uploader.pttime_upload import pttime_upload
from utils.uploader.pthome_upload import pthome_upload
from utils.uploader.ptsbao_upload import ptsbao_upload
from utils.uploader.soulvoice_upload import soulvoice_upload
from utils.uploader.ubits_upload import ubits_upload
from utils.uploader.ptchina_upload import ptchina_upload
from utils.uploader.ydy_upload import ydy_upload
from utils.uploader.gtk_upload import gtk_upload
from utils.uploader.ptcafe_upload import ptcafe_upload
from utils.uploader.kufei_upload import kufei_upload
from utils.uploader.tccf_upload import tccf_upload
from utils.uploader.hdpost_upload import hdpost_upload
from utils.uploader.ilolicon_upload import ilolicon_upload
from utils.uploader.shadowflow_upload import shadowflow_upload
from utils.uploader.kimoji_upload import kimoji_upload
def auto_upload(siteitem,file,record_path,qbinfo,basic,hashlist):
    return eval(siteitem.sitename+'_upload(siteitem,file,record_path,qbinfo,basic,hashlist)')
utils/uploader/auto_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def btschool_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为动漫')      
    elif 'show' in file1.pathinfo.type.lower():
        select_type='412'
        logger.info('已成功填写类型为综艺')           
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='409'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='410'
        logger.info('已成功填写类型为体育')       
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='415'
        logger.info('已成功填写类型为其他')          

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD/DVDR')   
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD/HDCD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')       
    else:
        medium_sel='11'
        logger.info('未识别到媒介信息，已选择Others')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择others')  
    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'AC3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AAC' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='1'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='6'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

    


    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "imdbid" : file1.imdburl,
            "doubanid": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "anonymous": uplver,
            "visible": "1",
            "span[]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/btschool_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def carpt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为动漫')       
    elif 'show' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为综艺')          
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')         
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')               
    elif 'music' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='407'
        logger.info('已成功填写类型为其他')          

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为DVD/DVDR')   
    elif 'CD' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为CD/HDCD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为REMUX')       
    else:
        medium_sel='6'
        logger.info('未识别到媒介信息，已选择Others')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='6'
        logger.info('未识别到视频编码信息，已选择others')  
    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='7'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'AC3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    else:
        audiocodec_sel='9'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='5'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    #选择制作组
    if 'CARPT' in file1.sub.upper():
        team_sel='1'
    elif 'WIKI' in file1.sub.upper():
        team_sel='2'
    elif 'CMCT' in file1.sub.upper():
        team_sel='3'
    elif 'M-TEAM' in file1.sub.upper() or 'MTEAM' in file1.sub.upper():
        team_sel='4'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)
    
    if 'carpt' in file1.sub.lower():
        tags.append(3)
        logger.info('已选择官方')
    if 'carpt' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR标签')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': 'carpt.net',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'cookie': siteinfo.cookie,
        'origin': 'https://carpt.net',
        'referer': 'https://carpt.net/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
        
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/carpt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def cyanbug_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                 
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                  
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR')
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD')
    elif 'BD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为MiniBD')
    elif 'TRACK' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为TRACK')          
    else:
        medium_sel='12'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为MPEG-4')  
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and '7.1' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'DTS-HD' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='0'
    logger.info('已成功选择分辨率')
    

    #选择标签
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(8)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     
    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/cyanbug_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def dajiao_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='415'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='417'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
    else:
        select_type='405'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')            
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR')
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为HD DVD')  
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')                                    
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，不选择媒介')




    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选择other')  

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())
        


    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='6'
    elif '2160' in file1.standard_sel:
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'        
    elif '480' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择制作组
    if 'DJWEB' in file1.sub.upper():
        team_sel='1'
    elif 'DJTV' in file1.sub.upper():
        team_sel='2'
    elif 'DJZB' in file1.sub.upper():
        team_sel='3'
    elif 'CatEDU' in file1.sub.upper():
        team_sel='6'
    elif 'Zaxyzit' in file1.sub.upper():
        team_sel='8'
    else:
        team_sel='7'
    logger.info('制作组已成功选择为'+file1.sub)
    

    if 'dajiao' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')
    if 'doc' in file1.pathinfo.type.lower() and '国家地理' in file1.pathinfo.small_descr:
        tags.append(18)
    if 'doc' in file1.pathinfo.type.lower() and '探索' in file1.pathinfo.small_descr:
        tags.append(20)
    if 'doc' in file1.pathinfo.type.lower() and '历史' in file1.pathinfo.small_descr:
        tags.append(21)
    if 'doc' in file1.pathinfo.type.lower() and 'CCTV' in file1.pathinfo.small_descr:
        tags.append(8)
    if 'doc' in file1.pathinfo.type.lower() and 'NHK' in file1.pathinfo.small_descr:
        tags.append(19)
    if 'doc' in file1.pathinfo.type.lower() and 'BBC' in file1.pathinfo.small_descr:
        tags.append(17)
    if 'doc' in file1.pathinfo.type.lower() and '美食' in file1.pathinfo.small_descr:
        tags.append(12)
    if 'doc' in file1.pathinfo.type.lower() and ('人文' in file1.pathinfo.small_descr or '社会' in file1.pathinfo.small_descr):
        tags.append(11)
    if 'doc' in file1.pathinfo.type.lower() and ('动物' in file1.pathinfo.small_descr or '自然' in file1.pathinfo.small_descr):
        tags.append(23)
    if 'doc' in file1.pathinfo.type.lower() and '医' in file1.pathinfo.small_descr:
        tags.append(10) 
    if 'doc' in file1.pathinfo.type.lower() and ('人物' in file1.pathinfo.small_descr or '传记' in file1.pathinfo.small_descr):
        tags.append(16)
    if 'doc' in file1.pathinfo.type.lower() and ('军事' in file1.pathinfo.small_descr or '太空' in file1.pathinfo.small_descr or '宇宙' in file1.pathinfo.small_descr):
        tags.append(22) 
    if 'doc' in file1.pathinfo.type.lower() and ('运动' in file1.pathinfo.small_descr or '探险' in file1.pathinfo.small_descr):
        tags.append(14)                                                                     


    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/dajiao_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def discfan_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='419'
        logger.info('已成功填写类型为动漫')
    elif 'show' in file1.pathinfo.type.lower():
        select_type='416'
        logger.info('已成功填写类型为综艺')                  
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='411'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower() and '大陆' in file1.country:
        select_type='401'
        logger.info('已成功填写类型为中国大陆')
    elif 'movie' in file1.pathinfo.type.lower() and '香港' in file1.country:
        select_type='404'
        logger.info('已成功填写类型为中国香港')  
    elif 'movie' in file1.pathinfo.type.lower() and '台湾' in file1.country:
        select_type='405'
        logger.info('已成功填写类型为中国台湾')
    elif 'movie' in file1.pathinfo.type.lower() and '泰国' in file1.country:
        select_type='402'
        logger.info('已成功填写类型为泰国')
    elif 'movie' in file1.pathinfo.type.lower() and '日本' in file1.country:
        select_type='403'
        logger.info('已成功填写类型为日本')
    elif 'movie' in file1.pathinfo.type.lower() and '韩国' in file1.country:
        select_type='406'
        logger.info('已成功填写类型为韩国')                          
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='413'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='414'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='417'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='414'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='410'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        source_sel='9'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        source_sel='2'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        source_sel='3'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        source_sel='10'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        source_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        source_sel='131'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        source_sel='4'
        logger.info('已成功选择媒介为DVD')      
    else:
        source_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择标签
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
    if '粤' in file1.language:
        tags.append(8)
        logger.info('已选择粤语')
    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel[4]": source_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/discfan_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def dragonhd_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')  
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                 
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='411'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                 
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')       
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其他')          

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为DVD/DVDR')   
    elif 'CD' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为CD/HDCD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为REMUX')       
    else:
        medium_sel='8'
        logger.info('未识别到媒介信息，已选择Other')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为VC1')          
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='23'
        logger.info('已成功选择编码为VP9')          
    else:
        codec_sel='21'
        logger.info('未识别到视频编码信息，已选择Other')  

    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='14'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='3'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='5'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='5'
    elif '720' in file1.standard_sel:
        standard_sel='6'
    elif 'SD' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='0'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

        #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'BEITAI' in file1.sub.upper():
        team_sel='4'
    elif 'FRDS' in file1.sub.upper():
        team_sel='4'
    elif 'CMCT' in file1.sub.upper():
        team_sel='4'
    elif 'LEAGUE' in file1.sub.upper():
        team_sel='4'                                
    else:
        team_sel='8'
    logger.info('制作组已成功选择为'+file1.sub)    

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': 'www.dragonhd.xyz',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'cookie': siteinfo.cookie,
        'origin': 'https://www.dragonhd.xyz',
        'referer': 'https://www.dragonhd.xyz/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)

utils/uploader/dragonhd_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def freefarm_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')    
    elif 'show' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为综艺')              
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                  
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='428'
        logger.info('已成功填写类型为其它')   
       
    #选择地区    
    if '香港' in file1.country:
        source_sel='36'
        logger.info('已成功填写地区为中国香港')
    elif '台湾' in file1.country:
        source_sel='37'
        logger.info('已成功填写地区为中国台湾')
    elif '马来西亚' in file1.country or '新加坡' in file1.country or '泰国' in file1.country:
        source_sel='42'
        logger.info('已成功填写地区为其他')
    elif '日本' in file1.country:
        source_sel='40'
        logger.info('已成功填写地区为日本')
    elif '韩国' in file1.country:
        source_sel='39'
        logger.info('已成功填写地区为韩国')
    elif '印度' in file1.country:
        source_sel='41'
        logger.info('已成功填写地区为印度')
    else:
        source_sel='38'
        logger.info('已成功填写地区为欧美')



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为DVDR')
    elif 'DVD' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为DVD')
    elif 'BD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为MiniBD')
    elif 'TRACK' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为TRACK')          
    else:
        medium_sel='21'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='4'
        logger.info('已成功选择编码为x264')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='3'
        logger.info('已成功选择编码为x265')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='1'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为MPEG-4')  
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='8'
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为MPEG-4')         
    elif 'MVC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为MVC')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='14'
        logger.info('未识别到视频编码信息，已选择Other')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='13'
    elif 'DTS' in file1.Audio_Format.upper() and '7.1' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='21'
    else:
        audiocodec_sel='22'
    logger.info('已成功选择音频编码')


    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='2'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='3'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='5'
    elif '720' in file1.standard_sel:
        standard_sel='6'
    elif 'SD' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='14'
    logger.info('已成功选择分辨率')

        #选择制作组
    if 'FFCD' in file1.sub.upper():
        team_sel='4'
    elif 'FFTV' in file1.sub.upper():
        team_sel='6'
    elif 'FFWEB' in file1.sub.upper():
        team_sel='3'
    else:
        team_sel='14'
    logger.info('制作组已成功选择为'+file1.sub)
    

    #选择标签
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     
    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "source_sel[4]": source_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "team_sel[4]": team_sel,            
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/freefarm_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def gtk_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')       
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')    
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                 
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='411'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='401'
        logger.info('已成功填写类型为其它')          
        





    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='0'
        logger.info('已成功选择媒介为WEB-DL')             
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR')  
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为HDDVD')
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')                            
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为AV1')     
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='8'
        logger.info('已成功选择编码为VP9')               
    else:
        codec_sel='0'
        logger.info('未识别到视频编码信息，不选择')  



    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='6'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')
    

    #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'MYSILU' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'MARK' in file1.sub.upper():
        team_sel='7'
    elif 'MTEAM' in file1.sub.upper():
        team_sel='8'
    elif 'CMCT' in file1.sub.upper():
        team_sel='6'
    elif 'FRDS' in file1.sub.upper():
        team_sel='9'
    elif 'PTHOME' in file1.sub.upper():
        team_sel='10'
    elif 'BEAST' in file1.sub.upper():
        team_sel='11'
    else:
        team_sel='5'    
    logger.info('制作组已成功选择为Other')

    #选择标签
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel": medium_sel,
            "standard_sel": standard_sel,
            "codec_sel": codec_sel,
            "uplver": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/gtk_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def haidan_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')  
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')         
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                 
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper():
        medium_sel='9'
        tags.append(7)
        logger.info('已选择原盘标签')
        logger.info('已成功选择媒介为UHD-BLURAY')         
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        tags.append(7)
        logger.info('已选择原盘标签')
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')         
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='11'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='11'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='13'
        logger.info('已成功选择编码为MPEG-4')             
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='13'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='1'
        logger.info('未识别到视频编码信息，不选择')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '540' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='2'
    logger.info('已成功选择分辨率')
    


    #选择标签
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(16)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(15)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if '粤' in file1.language:
        tags.append(10)
        logger.info('已选择粤语标签')
    if not file1.language=='' and not '国' in file1.language and not '中' in file1.language and not '粤' in file1.language:
        tags.append(11)
        logger.info('已选择外语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(3)
        logger.info('已选择中字标签')
     

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "durl": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "season": file1.pathinfo.seasonnum,
            "episode": "0",
            "team_suffix": file1.pathinfo.sub,
            "preview-pics": file1.screenshoturl,
            "nfo-string": file1.mediainfo,
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.pathinfo.contenttail,
            "type": select_type,
            "medium_sel": medium_sel,
            "standard_sel": standard_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "uplver": uplver,
            "tag_list[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0 
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/haidan_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hares_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='415'
    else:
        select_type='415'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='5'
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
    elif 'BLU' in file1.type.upper():
        medium_sel='2'
    elif 'ENCODE' in file1.type.upper():
        medium_sel='4'
    elif 'tv' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        medium_sel='6'
    elif 'HDTV' in file1.type.upper():
        medium_sel='8'
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
    else:
        medium_sel='4'
    logger.info('已成功填写来源为'+file1.type)


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='8'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')  
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为MPEG-4')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')          
    elif 'AV1' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为AV1')    
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')        
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选择other')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='5'
    elif '2160' in file1.standard_sel:
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '1440' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            processing_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            processing_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            processing_sel='7'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            processing_sel='7'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            processing_sel='9'
            logger.info('国家信息已选择'+file1.country)
        else:
            processing_sel='10'
            logger.info('未找到资源国家信息，已选择其他')
    else:
        processing_sel='10'
        logger.info('未找到资源国家信息，已默认其他')

    #选择制作组
    if 'HARESWEB' in file1.sub.upper():
        team_sel='2'
    elif 'HARESTV' in file1.sub.upper():
        team_sel='3'
    elif 'HARES' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='4'
    elif 'HDS' in file1.sub.upper():
        team_sel='5'
    elif 'WIKI' in file1.sub.upper():
        team_sel='6'
    elif 'CMCT' in file1.sub.upper():
        team_sel='8'
    elif 'BEAST' in file1.sub.upper():
        team_sel='9'
    elif 'HDC' in file1.sub.upper():
        team_sel='10'
    elif 'FRDS' in file1.sub.upper():
        team_sel='11'
    elif 'PTER' in file1.sub.upper():
        team_sel='12'
    elif 'BHD' in file1.sub.upper():
        team_sel='13'
    elif 'PTH' in file1.sub.upper():
        team_sel='14'
    else:
        team_sel='15'
    logger.info('制作组已成功选择为'+file1.sub)
    
    if 'hare' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if 'HARES' in file1.sub.upper():
        tags.append(3)
        logger.info('已选择官方')
    if file1.pathinfo.transfer==0:
        tags.append(4)
        logger.info('已选择原创')
    if '国' in file1.language or '中' in file1.language:
        tags.append(6)
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append(7)
        logger.info('已选择粤语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(9)
        logger.info('已选择中字')
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.complete==0:
        tags.append(16)
        logger.info('已选择追更')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(14)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(13)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(15)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(11)
        logger.info('已选择DIY标签')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "pt_gen[douban][link]": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info.replace(''.join(re.findall('\[img\]https://img9\.douban.*p\d*.jpg\[/img\]',file1.douban_info)),'')+'\n'+file1.pathinfo.contenttail,
            "technical_info" : file1.mediainfo,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "processing_sel" : processing_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }
    if len(re.findall(r'\[img\](.*)\[/img\]',file1.douban_info))>0:
        other_data["url_poster"] = re.findall(r'\[img\](.*)\[/img\]',file1.douban_info)[0]
    else:
        return False,fileinfo+'未找到豆瓣简介中的海报图链接,无法填写海报信息'
    shots=file1.screenshoturl.replace('[img]','').replace('[/img]','').strip()
    if shots!='':
        other_data["screenshots"] = shots
    else:
        return False,fileinfo+'检测到用户设置为不截图，但是白兔强制要求资源截图'
    if file1.doubanurl!=None and file1.doubanurl!='':
        other_data["pt_gen[douban][link]"]= file1.doubanurl
    if file1.imdburl!=None and file1.imdburl!='':
        other_data["pt_gen[imdb][link]"] = file1.imdburl
    if file1.bgmurl!=None and file1.bgmurl!='':
        other_data["pt_gen[bangumi][link]"] = file1.bgmurl
    
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hares_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdarea_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')       
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')           
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='300'
        logger.info('已成功填写类型为Movie UHD-4K')
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='401'
        logger.info('已成功填写类型为Movie Blu-Ray')
    elif 'movie' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='415'
        logger.info('已成功填写类型为Movie REMUX')
    elif 'movie' in file1.pathinfo.type.lower() and 'WEB' in file1.type.upper():
        select_type='412'
        logger.info('已成功填写类型为Movie WEB-DL')
    elif 'movie' in file1.pathinfo.type.lower() and 'DVD' in file1.type.upper():
        select_type='414'
        logger.info('已成功填写类型为Movie DVD') 
    elif 'movie' in file1.pathinfo.type.lower() and 'HDTV' in file1.type.upper():
        select_type='413'
        logger.info('已成功填写类型为Movie HDTV')  
    elif 'movie' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='410'
        logger.info('已成功填写类型为Movie 1080p')
    elif 'movie' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='411'
        logger.info('已成功填写类型为Movie 720p')                       
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='410'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR') 
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD') 
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='1'
        logger.info('已成功选择编码为MPEG-4')  
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    else:
        audiocodec_sel='0'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='0'
    logger.info('已成功选择分辨率')
    


    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "uplver": uplver,
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': 'hdarea.club',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'cookie': siteinfo.cookie,
        'origin': 'https://hdarea.club',
        'referer': 'https://hdarea.club/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.0.0',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdarea_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdatmos_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        tags.append(12)
        logger.info('已选择动画标签')
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'

    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择来源
    if 'WEB' in file1.type.upper():
        source_sel='2'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper():
        source_sel='6'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'BLU' in file1.type.upper():
        source_sel='6'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        source_sel='1'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        source_sel='3'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        source_sel='5'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper() and 'HD' in file1.type.upper():
        source_sel='7'
        logger.info('已成功选择媒介为DVD')  
    elif 'DVD' in file1.type.upper():
        source_sel='8'
        logger.info('已成功选择媒介为DVD')
    elif 'CD' in file1.type.upper():
        source_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'MINI' in file1.type.upper():
        source_sel='4'
        logger.info('已成功选择媒介为MINIBD')   
    elif 'CD' in file1.type.upper():
        source_sel='9'
        logger.info('已成功选择媒介为TRACK')       
    else:
        source_sel='12'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'MINI' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MINIBD')   
    elif 'DVD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为TRACK')       
    else:
        medium_sel='13'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-4') 
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')      
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择Others')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='20'
    elif 'DTS-HD' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper() :
        audiocodec_sel='12'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'DD' in file1.Audio_Format.upper() and '5.1' in file1.Audio_Format.upper():
        audiocodec_sel='23'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'DSD' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    else:
        audiocodec_sel='21'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='15'
    elif '2160' in file1.standard_sel:
        standard_sel='10'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='11'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='12'
    elif '720' in file1.standard_sel:
        standard_sel='13'
    elif 'SD' in file1.standard_sel:
        standard_sel='14'
    else:
        standard_sel='16'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

    #选择处理
    if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
        processing_sel='3'
    elif '美国' in file1.country:
        processing_sel='4'
    elif '日本' in file1.country:
        processing_sel='5'
    elif '韩国' in file1.country:
        processing_sel='6'
    elif '德国' in file1.country:
        processing_sel='8'
    elif not '新加坡' in file1.country and not '马来西亚' in file1.country and not '泰国' in file1.country:
        processing_sel='9'
    else:
        processing_sel='9'

    team_sel='22'
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "source_sel[8]": medium_sel,
            "team_sel[8]": team_sel,
            "medium_sel[8]": medium_sel,
            "standard_sel[8]": standard_sel,
            "codec_sel[8]": codec_sel,
            "audiocodec_sel[8]": audiocodec_sel,
            "processing_sel[8]": processing_sel,
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdatmos_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hddolby_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')  
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')               
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为Movie')                       
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'WEBRIP' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为WEBRIP')  
    elif 'WEB' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为DVDR') 
    elif 'DVD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为DVD') 
    elif 'CD' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='11'
        logger.info('未识别到媒介信息，选择other')

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')          
    elif 'AV1' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为AV1')    
    elif 'VP9' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为VP9')        
    else:
        codec_sel='7'
        logger.info('未识别到视频编码信息，选择other')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    else:
        audiocodec_sel='12'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif '4320' in file1.standard_sel or '8K' in file1.standard_sel :
        standard_sel='6'
    else:
        standard_sel='5'
    logger.info('已成功选择分辨率')

    #选择标签
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append('hdrm')
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append('hdr10')
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append('db')
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append('diy')
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language or '国语' in file1.pathinfo.tags:
        tags.append('gy')
        logger.info('已选择国语标签')
    if '粤' in file1.language or '粤语' in file1.pathinfo.tags:
        tags.append('yy')
        logger.info('已选择粤语标签')
    if '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan or '中字' in file1.pathinfo.tags:
        tags.append('zz')
        logger.info('已选择中字标签')
     

    tags=list(set(tags))
    tags.sort()

    


    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "uplver": uplver,
            "tags[]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
        

    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hddolby_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdfans_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='417'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='416'
    elif 'tv' in file1.pathinfo.type.lower() :
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='403'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='418'
    else:
        select_type='410'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为WEB-DL')
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='18'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='19'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper():
        medium_sel='17'
        logger.info('已成功选择媒介为UHD-BLURAY')
    elif 'ENCODE' in file1.type.upper() and '2160' in file1.standard_sel:
        medium_sel='20'
        logger.info('已成功选择媒介为原盘压制')
    elif 'ENCODE' in file1.type.upper() and '1080' in file1.standard_sel:
        medium_sel='24'
        logger.info('已成功选择媒介为原盘压制')
    elif 'ENCODE' in file1.type.upper() and '720' in file1.standard_sel:
        medium_sel='25'
        logger.info('已成功选择媒介为原盘压制')
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='22'
        logger.info('已成功选择媒介为BLURAY DIY')
    elif 'REMUX' in file1.type.upper():
        medium_sel='23'
        logger.info('已成功选择媒介为BLURAY')
    elif 'HDTV' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为HDTV')
    elif 'DVD' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为DVD')
    else:
        medium_sel='10'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='4'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为MPEG-2')
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为MPEG-4')
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为XVID')
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='14'
        logger.info('已成功选择编码为AV1')
    else:
        codec_sel='13'
        logger.info('未识别到视频编码信息，不选择')

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='11'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='21'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'MPEG' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    else:
        audiocodec_sel='18'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())
    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='1'
    elif '2160' in file1.standard_sel:
        standard_sel='2'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='3'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='4'
    elif '720' in file1.standard_sel:
        standard_sel='5'
    elif '480' in file1.standard_sel:
        standard_sel='6'
    else:
        standard_sel='7'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            processing_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            processing_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            processing_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            processing_sel='8'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            processing_sel='7'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            processing_sel='6'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            processing_sel='10'
            logger.info('国家信息已选择'+file1.country)
        else:
            processing_sel='9'
            logger.info('未找到资源国家信息，已默认日本')
    else:
        processing_sel='6'
        logger.info('未找到资源国家信息，已默认日本')

    #选择制作组
    if 'hdfans' in file1.sub.lower():
        team_sel='9'
    elif 'chd' in file1.sub.lower():
        team_sel='1'
    elif 'hdc' in file1.sub.lower():
        team_sel='2'
    elif 'ttg' in file1.sub.lower():
        team_sel='19'
    elif 'wiki' in file1.sub.lower():
        team_sel='3'
    elif 'beast' in file1.sub.lower():
        team_sel='4'
    elif 'cmct' in file1.sub.lower():
        team_sel='5'
    elif 'frds' in file1.sub.lower():
        team_sel='6'
    elif 'hdsky' in file1.sub.lower():
        team_sel='7'
    elif 'ourbits' in file1.sub.lower():
        team_sel='17'
    elif 'pter' in file1.sub.lower():
        team_sel='20'
    elif 'league' in file1.sub.lower():
        team_sel='26'
    elif 'hdhome' in file1.sub.lower():
        team_sel='18'
    elif 'pthome' in file1.sub.lower():
        team_sel='16'
    elif 'tlf' in file1.sub.lower():
        team_sel='8'
    elif 'btn' in file1.sub.lower() or 'ntb' in file1.sub.lower():
        team_sel='32'
    elif 'hares' in file1.sub.lower():
        team_sel='28'
    elif 'audiences' in file1.sub.lower():
        team_sel='29'
    elif 'epsilon' in file1.sub.lower():
        team_sel='30'
    elif 'framestor' in file1.sub.lower():
        team_sel='31'
    else:
        team_sel='27'
    logger.info('制作组已成功选择为'+file1.sub)

    if 'hdfan' in file1.sub.lower():
        tags.append(3)
        logger.info('已选择官方')
    if 'hdfan' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append(10)
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(9)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')



    tags=list(set(tags))
    tags.sort()

    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),


    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info" : file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "standard_sel[4]": standard_sel,
            "processing_sel[4]" : processing_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0

    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdfans_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdhome_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='501'
        logger.info('已成功填写类型为anime Blu-Ray')
    elif 'anime' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='454'
        logger.info('已成功填写类型为anime Blu-Ray')
    elif 'anime' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='448'
        logger.info('已成功填写类型为anime REMUX')
    elif 'anime' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='447'
        logger.info('已成功填写类型为anime 1080p')
    elif 'anime' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='446'
        logger.info('已成功填写类型为anime 720p')  
    elif 'anime' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='449'
        logger.info('已成功填写类型为anime 2160p')        
    elif 'tv' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='502'
        logger.info('已成功填写类型为tv Blu-Ray')
    elif 'tv' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='453'
        logger.info('已成功填写类型为tv Blu-Ray')
    elif 'tv' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='437'
        logger.info('已成功填写类型为tv REMUX')
    elif 'tv' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='436'
        logger.info('已成功填写类型为tv 1080p')
    elif 'tv' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='435'
        logger.info('已成功填写类型为tv 1080i')
    elif 'tv' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='434'
        logger.info('已成功填写类型为tv 720p')  
    elif 'tv' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='438'
        logger.info('已成功填写类型为tv 2160p')  
    elif 'show' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='452'
        logger.info('已成功填写类型为show Blu-Ray')
    elif 'show' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='430'
        logger.info('已成功填写类型为show REMUX')
    elif 'show' in file1.pathinfo.type.lower() and '1080i' in file1.standard_sel.lower():
        select_type='428'
        logger.info('已成功填写类型为show 1080i')
    elif 'show' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='429'
        logger.info('已成功填写类型为show 1080p')
    elif 'show' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='427'
        logger.info('已成功填写类型为show 720p')  
    elif 'show' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='431'
        logger.info('已成功填写类型为show 2160p')                   
    elif 'movie' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='499'
        logger.info('已成功填写类型为Movie UHD-4K')
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='450'
        logger.info('已成功填写类型为Movie Blu-Ray')
    elif 'movie' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='415'
        logger.info('已成功填写类型为Movie REMUX')
    elif 'movie' in file1.pathinfo.type.lower() and '2160p' in file1.standard_sel.lower():
        select_type='416'
        logger.info('已成功填写类型为Movie 2160p')
    elif 'movie' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='414'
        logger.info('已成功填写类型为Movie 1080p')
    elif 'movie' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='413'
        logger.info('已成功填写类型为Movie 720p')                     
    elif 'doc' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='500'
        logger.info('已成功填写类型为doc Blu-Ray')
    elif 'doc' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='451'
        logger.info('已成功填写类型为doc Blu-Ray')
    elif 'doc' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='421'
        logger.info('已成功填写类型为doc REMUX')
    elif 'doc' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='420'
        logger.info('已成功填写类型为doc 1080p')
    elif 'doc' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='419'
        logger.info('已成功填写类型为doc 720p')  
    elif 'doc' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='422'
        logger.info('已成功填写类型为doc 2160p')         
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='441'
        logger.info('已成功填写类型为MV')           
    elif 'sport' in file1.pathinfo.type.lower() and '1080' in file1.standard_sel:
        select_type='443'
        logger.info('已成功填写类型为体育1080')
    elif 'sport' in file1.pathinfo.type.lower() and '720' in file1.standard_sel:
        select_type='443'
        logger.info('已成功填写类型为体育1080')    
    elif 'sport' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel:
        select_type='504'
        logger.info('已成功填写类型为体育2160')           
    elif 'music' in file1.pathinfo.type.lower():
        select_type='442'
        logger.info('已成功填写类型为体育720')          
    else:
        select_type='450'
        logger.info('已成功填写类型为其它')          
        


    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='7'
        logger.info('已成功选择来源为WEB-DL')  
    elif 'UHD' in file1.source.upper():
        source_sel='9'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY')               
    elif 'HDTV' in file1.source.upper():
        source_sel='4'
        logger.info('已成功选择来源为HDTV')        
    elif 'DVD' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为DVD')     
    else:
        source_sel='8'
        logger.info('未识别到来源信息，选择other')


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR') 
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为VC1')            
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选other')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and '7.1' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    else:
        audiocodec_sel='0'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif 'SD' in file1.standard_sel:
        standard_sel='5'
    elif '4320' in file1.standard_sel or '8K' in file1.standard_sel:
        standard_sel='10'
    else:
        standard_sel='0'
    logger.info('已成功选择分辨率')
    
    #选择处理
    if 'ENCODE' in file1.type.upper():
        processing_sel='2'
    else:
        processing_sel='1'

    #选择标签
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append('hdrm')
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append('hdr10')
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append('db')
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append('diy')
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append('gy')
        logger.info('已选择国语标签')
    if '粤' in file1.language:
        tags.append('yy')
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append('zz')
        logger.info('已选择中字标签')
     

    tags=list(set(tags))
    tags.sort()

    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "source_sel": source_sel,
            "standard_sel": standard_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "processing_sel": processing_sel,
            "uplver": uplver,
            "tags[]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdhome_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdmayi_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')     
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')             
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为Movie')                      
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='401'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为DVDR') 
    elif 'DVD' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为DVD') 
    elif 'BD' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为MiniBD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='4'
        logger.info('未识别到媒介信息，选择other')

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='4'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='5'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为VC1')          
    elif 'AV1' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为AV1')    
    elif 'VP9' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为VP9')        
    else:
        codec_sel='7'
        logger.info('未识别到视频编码信息，选择other')  



    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='2'
    logger.info('已成功选择分辨率')

    #选择标签
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(15)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')
    if '国' in file1.language and '英' in file1.language:
        tags.append(13)
        logger.info('已选择国英双语标签')
    elif '中' in file1.language and '英' in file1.language:
        tags.append(13)
        logger.info('已选择国英双语标签')             
    elif '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')

    if '粤' in file1.language:
        tags.append(9)
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan) and '英' in file1.sublan:
        tags.append(12)
        logger.info('已选择中英字幕')
    elif not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     

    tags=list(set(tags))
    tags.sort()

    


    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdmayi_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper
from bs4 import BeautifulSoup

def get_token(cookie):
    headers = {
            'host': 'pt.hdpost.top',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cookie': cookie,
            'origin': 'https://pt.hdpost.top',
            'referer': 'https://pt.hdpost.top/upload/2',
            'sec-ch-ua': '"Microsoft Edge";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.0.0',
    }
    scraper=cloudscraper.create_scraper()
    r = scraper.get('https://pt.hdpost.top',headers=headers)
    soup = BeautifulSoup (r.text, "lxml")
    res=soup.find_all('meta',{'name':'_token'})
    if len(res)<=0:
        return ''
    if not 'content' in res[0].attrs:
        return ''
    return res[0].attrs['content']
    
def hdpost_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename
    #选择类别
    if 'anime' in file1.pathinfo.type.lower() and file1.pathinfo.complete==1:
        select_type='2'
        imdb_id=file1.pathinfo.imdb_id
    elif 'anime' in file1.pathinfo.type.lower():
        select_type='1'
        imdb_id=file1.pathinfo.imdb_id
    elif 'doc' in file1.pathinfo.type.lower() and file1.pathinfo.complete==1:
        select_type='2'
        imdb_id=file1.pathinfo.imdb_id
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='1'
        imdb_id=file1.pathinfo.imdb_id
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='2'
        imdb_id=file1.pathinfo.imdb_id
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='1'       
    elif 'mv' in file1.pathinfo.type.lower() or 'music' in file1.pathinfo.type.lower():
        select_type='3'
        imdb_id=file1.pathinfo.imdb_id    
    else:
        select_type='1'
        imdb_id=""
    url = siteinfo.url
    post_url = f"{url}post/{select_type}"

    #选择规格
    if 'WEBRIP' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为WEBRIP')  
    elif 'WEB' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为WEB-DL')            
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为HDTV')        
    elif 'FLAC' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为FLAC')      
    else:
        medium_sel='3'
        logger.info('未识别到媒介信息，已选择Others')


    #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='2'
    elif '4320' in file1.standard_sel:
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='3'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='4'
    elif '720' in file1.standard_sel:
        standard_sel='5'
    elif 'SD' in file1.standard_sel:
        standard_sel='8'
    else:
        standard_sel='10'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

    
    if siteinfo.uplver==1:
        uplver='1'
    else:
        uplver='0'

    torrent_file = file1.torrentpath
    file_tup = ("torrent", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
    token=get_token(siteinfo.cookie)
    other_data = {
            "_token": token,
            "nfo": "",
            "torrent-cover": "",
            "torrent-banner": "",
            "name": file1.pathinfo.tmdb_name+file1.uploadname,
            "mediainfo": file1.mediainfo,
            "season_number" : file1.pathinfo.seasonnum,
            "episode_number": "0",
            "tmdb": file1.pathinfo.tmdb_id,
            "imdb": imdb_id,
            "tvdb": "0",
            "mal": "0",
            "igdb": "0",
            "keywords": "",
            "isPreviewEnabled": "0",
            "category_id": select_type,
            "type_id": medium_sel,
            "resolution_id": standard_sel,
            "description": file1.screenshoturl,
            "anonymous": uplver,
            "bdinfo": "",
            "stream": "0",
            "sd": "0",
            "internal": "0",
            "personal_release": "0",
            "mod_queue_opt_in": "0",
            "free": "1",
            "post": "true",
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': 'pt.hdpost.top',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryEVG6BHsXWq0Ddoi',
        'cookie': siteinfo.cookie,
        'origin': 'https://pt.hdpost.top',
        'referer': 'https://pt.hdpost.top/upload/2',
        'sec-ch-ua': '"Microsoft Edge";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.0.0',
        'x-csrf-token': content,        
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdpost_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdpt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    post_url = "https://hdpt.xyz/takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        tags.append(18)
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
    elif 'cartoon' in file1.pathinfo.type.lower():
        select_type='412'
        tags.append(18)
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择媒介
    if 'WEBRIP' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR') 
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD') 
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，选择other')
   


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'AV1' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为AV1')    
    elif 'VP9' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VP9')  
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')       
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选择other')  

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='5'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
   #选择处理
    if 'ENCODE' in file1.type.upper():
        processing_sel='2'
    else:
        processing_sel='1'

    #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'MYSILU' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'HDH' in file1.sub.upper():
        team_sel='7'
    elif 'OURTV' in file1.sub.upper():
        team_sel='8'
    elif 'NGB' in file1.sub.upper():
        team_sel='9'
    elif 'U2' in file1.sub.upper():
        team_sel='10'
    elif 'LHD' in file1.sub.upper():
        team_sel='11'
    elif 'CHDBITS' in file1.sub.upper():
        team_sel='12'
    elif 'PTER' in file1.sub.upper():
        team_sel='13'
    elif 'CMCT' in file1.sub.upper():
        team_sel='14'
    elif 'FRDS' in file1.sub.upper():
        team_sel='15'
    elif 'HARES' in file1.sub.upper():
        team_sel='16'
    elif 'HDPT' in file1.sub.upper():
        team_sel='18'
    else:
        team_sel='17'
    logger.info('制作组已成功选择为'+file1.sub)
    
    if 'hdpt' in file1.sub.lower():
        tags.append(3)
        logger.info('已选择官方')
    if file1.pathinfo.transfer==0:
        tags.append(21)
        logger.info('已选择原创')
    if 'hdpt' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if '粤' in file1.language:
        tags.append(20)
        logger.info('已选择粤语标签')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(15)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(16)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(17)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')


    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "standard_sel": standard_sel,
            "processing_sel" : processing_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdpt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdsky_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='411'
        else:
            select_type='413'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='412'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择来源 
    if file1.type=='WEB-DL':
        medium_sel='11'
    elif 'rip' in file1.type.lower() or file1.type=='bluray'  :
        medium_sel='7'
    elif file1.type=='HDTV':
        medium_sel='5'
    elif file1.type=='remux':
        medium_sel='3'
    else:
        medium_sel='7'
    logger.info('已成功选择质量为'+file1.type)
   


    #选择编码
    if file1.Video_Format=='H264':
        codec_sel='1'
    elif file1.Video_Format=='x264':
        codec_sel='10'
    elif file1.Video_Format=='H265':
        codec_sel='12'
    elif file1.Video_Format=='x265':
        codec_sel='13'
    else:
        codec_sel='1'
    logger.info('已成功选择编码为'+file1.Video_Format)

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA:X 7.1' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'DTS-HDMA' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'TRUEHD AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HD HR' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'AC3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'DSD' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'Dolby Digital Plus Dolby AutoTransferMachineos' in file1.Audio_Format.upper():
        audiocodec_sel='21'
    elif 'Dolby Digital Plus' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    #选择制作组
    if 'HDSKY' in file1.sub.upper():
        team_sel='6'
        tags.append(12)
    elif 'HDS3D' in file1.sub.upper():
        team_sel='28'
        tags.append(12)
    elif 'HDSTV' in file1.sub.upper():
        team_sel='9'
        tags.append(12)
    elif 'HDSWEB' in file1.sub.upper() and file1.pathinfo.collection>=1:
        team_sel='35'
        tags.append(12)
    elif 'HDSWEB' in file1.sub.upper():
        team_sel='31'
        tags.append(12)
    elif 'HDSPAD' in file1.sub.upper():
        team_sel='18'
        tags.append(12)
    elif 'HDSCD' in file1.sub.upper():
        team_sel='22'
        tags.append(12)
    elif 'hdspecial' in file1.sub.lower():
        team_sel='34'
        tags.append(12)
    elif 'BMDRU' in file1.sub.upper():
        team_sel='30'
        tags.append(12)
    elif 'AREA11' in file1.sub.upper():
        team_sel='25'
        tags.append(12)
    elif 'HDSAB' in file1.sub.upper():
        team_sel='36'
        tags.append(12)
    elif 'HDS' in file1.sub.upper():
        team_sel='1'
        tags.append(12)
    elif file1.transfer==0:
        team_sel='24'
    elif file1.transfer==1:
        team_sel='27'
    else:
        team_sel='27'
    logger.info('制作组已成功选择为'+file1.sub)
    
    if 'hdsky' in file1.pathinfo.exclusive :
        tags.append(2)
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
    if file1.transfer==0:
        tags.append(14)
    tags=list(set(tags))
    tags.sort()
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "url_douban": file1.doubanurl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "option_sel[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    

    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdsky_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdtime_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        tags.append(18)
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='424'    
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
    elif 'cartoon' in file1.pathinfo.type.lower():
        select_type='412'
        tags.append(18)
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择来源
    if 'movie' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        source_sel='81'
        logger.info('已成功选择来源为电影-REMUX')  
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        source_sel='80'
        logger.info('已成功选择来源为电影-DIY原盘')        
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        source_sel='79'
        logger.info('已成功选择来源为电影-BLURAY原盘')        
    elif 'movie' in file1.pathinfo.type.lower() and '10bit' in file1.Video_Format.lower():
        source_sel='3'
        logger.info('已成功选择来源为电影-10bit')
    elif 'movie' in file1.pathinfo.type.lower() and '1080' in file1.standard_sel:
        source_sel='6'
        logger.info('已成功选择来源为电影-1080')       
    elif 'movie' in file1.pathinfo.type.lower() and '720' in file1.standard_sel:
        source_sel='5'
        logger.info('已成功选择来源为电影-720')          
    elif 'anime' in file1.pathinfo.type.lower() and '10bit' in file1.Video_Format.lower():
        source_sel='83'
        logger.info('已成功选择来源为动漫-10bit')
    elif 'anime' in file1.pathinfo.type.lower() and "完结" in file1.pathinfo.tags:
        source_sel='66'
        logger.info('已成功选择来源为动漫完结')    
    elif 'anime' in file1.pathinfo.type.lower():
        source_sel='67'
        logger.info('已成功选择来源为动漫剧场版')                       
    elif 'tv' in file1.pathinfo.type.lower() and '大陆' in file1.country:
        source_sel='23'
        logger.info('已成功选择来源为大陆剧集')
    elif 'tv' in file1.pathinfo.type.lower() and ('香港' in file1.country or '台湾' in file1.country):
        source_sel='24'
        logger.info('已成功选择来源为港台剧集')           
    elif 'tv' in file1.pathinfo.type.lower() and '美国' in file1.country:
        source_sel='25'
        logger.info('已成功选择来源为美剧') 
    elif 'tv' in file1.pathinfo.type.lower() and '日本' in file1.country:
        source_sel='26'
        logger.info('已成功选择来源为日剧')  
    elif 'tv' in file1.pathinfo.type.lower() and '韩国' in file1.country:
        source_sel='27'
        logger.info('已成功选择来源为韩剧') 
    elif 'tv' in file1.pathinfo.type.lower():
        source_sel='70'
        logger.info('已成功选择来源为其他剧集')    
    elif 'show' in file1.pathinfo.type.lower():
        source_sel='15'
        logger.info('已成功选择来源为综艺综合')        
    else:
        source_sel='49'
        logger.info('已成功选择来源为其它') 



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='0'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR') 
    elif 'DVD' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为DVD') 
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，选择other')
   


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format and '10bit' in file1.Video_Format.lower():
        codec_sel='12'
        logger.info('已成功选择编码为x264-10bit')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为x264')        
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='12'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='12'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'AV1' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为AV1')    
    elif 'VP9' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VP9')  
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')       
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选择other')  



    #选择制作组
    if 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'beAst' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'HDTime' in file1.sub.upper():
        team_sel='6'
    elif 'PADTime' in file1.sub.upper():
        team_sel='7'
    elif 'CMCT' in file1.sub.upper():
        team_sel='8'
    elif 'CHDBITS' in file1.sub.upper():
        team_sel='2'
    elif 'CMCT' in file1.sub.upper():
        team_sel='4'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)
    

    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')

    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')


    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,            
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info.replace(''.join(re.findall('\[img\]https://img9\.douban.*p\d*.jpg\[/img\]',file1.douban_info)),'')+'\n'+file1.pathinfo.contenttail,
            "technical_info" : file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "source_sel[4]": source_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdtime_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdu_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')  
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                 
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为Movie')                     
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='411'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'DVD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD')  
    elif 'tv' in file1.pathinfo.type.lower() and 'WEB' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为WEB-DL TV')
    elif 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')   
    elif 'tv' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='16'
        logger.info('已成功选择媒介为TV UHD-REMUX')
    elif 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='15'
        logger.info('已成功选择媒介为UHD-REMUX')
    elif 'tv' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为REMUX TV')
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'UHD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHDBLURAY')           
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'tv' in file1.pathinfo.type.lower() and 'ENCODE' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为ENCODETV')
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')           
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD') 
    elif 'CD' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，选择other')

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='16'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='14'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='14'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='14'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='18'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'AV1' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为AV1')    
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')        
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选择other')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'DTS' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'MPEG' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    else:
        audiocodec_sel='13'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')

    #选择处理
    if '大陆' in file1.country:
        processing_sel='1'
    elif '香港' in file1.country or '台湾' in file1.country:
        processing_sel='2'
    elif '日本' in file1.country:
        processing_sel='4'
    elif '韩国' in file1.country:
        processing_sel='5'
    elif '印度' in file1.country:
        processing_sel='6'
    elif '泰国' in file1.country or '越南' in file1.country or '柬埔寨' in file1.country or '缅甸' in file1.country or '马来西亚' in file1.country or '新加坡' in file1.country or '印度尼西亚' in file1.country or '菲律宾' in file1.country or '文莱' in file1.country or '东帝汶' in file1.country or '印尼' in file1.country :
        processing_sel='4'
    else:
        processing_sel='2'

    #选择制作组
    if 'HDU' in file1.sub.upper():
        team_sel='2'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)
    


    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "processing_sel": processing_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdu_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdvideo_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='24'
        logger.info('已成功选择来源为WEB-DL')         
    elif 'UHD' in file1.source.upper():
        source_sel='23'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper():
        source_sel='22'
        logger.info('已成功选择来源为BLURAY')         
    elif 'DVD' in file1.source.upper():
        source_sel='25'
        logger.info('已成功选择来源为DVD')         
    elif 'HDTV' in file1.source.upper():
        source_sel='26'
        logger.info('已成功选择来源为HDTV')         
    elif 'CD' in file1.source.upper():
        source_sel='27'
        logger.info('已成功选择来源为CD')         
    else:
        source_sel='28'
        logger.info('已成功选择来源为其它') 

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为WEB-DL')               
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='16'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel='18'
        logger.info('已成功选择媒介为DVD')  
    elif 'CD' in file1.type.upper():
        medium_sel='20'
        logger.info('已成功选择媒介为CD')          
    else:
        medium_sel='19'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='8'
        logger.info('已成功选择编码为VC1')          
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为AV1')    
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为VP9')       
    else:
        codec_sel='11'
        logger.info('未识别到视频编码信息，选择other')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='21'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='5'
    elif '2160' in file1.standard_sel:
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='8'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='9'
    elif '720' in file1.standard_sel:
        standard_sel='10'
    elif '480' in file1.standard_sel:
        standard_sel='11'
    else:
        standard_sel='8'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择制作组
    if 'HDVWEB' in file1.sub.upper():
        team_sel='1'
    elif 'HDVMV' in file1.sub.upper():
        team_sel='2'
    else:
        team_sel='4'
    logger.info('制作组已成功选择为'+file1.sub)
    
    if 'HDV' in file1.sub.upper():
        tags.append(3)
        logger.info('已选择官方')
    if 'hdvideo' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language or '国' in file1.pathinfo.tags:
        tags.append(5)
        logger.info('已选择国语')
    if '粤' in file1.language or '粤' in file1.pathinfo.tags:
        tags.append(10)
        logger.info('已选择粤语')
    if '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan or '中' in file1.pathinfo.tags:
        tags.append(6)
        logger.info('已选择中字')
    if '完结' in  file1.pathinfo.tags:
        tags.append(17)
        logger.info('已选择完结')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(20)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(11)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(12)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(22)
        logger.info('已选择DIY标签')    

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel[4]": source_sel,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdvideo_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hdzone_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='501'
        logger.info('已成功填写类型为anime Blu-Ray')
    elif 'anime' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='454'
        logger.info('已成功填写类型为anime Blu-Ray')
    elif 'anime' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='448'
        logger.info('已成功填写类型为anime REMUX')
    elif 'anime' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='447'
        logger.info('已成功填写类型为anime 1080p')
    elif 'anime' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='446'
        logger.info('已成功填写类型为anime 720p')  
    elif 'anime' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='449'
        logger.info('已成功填写类型为anime 2160p') 
    elif 'show' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='452'
        logger.info('已成功填写类型为show Blu-Ray')
    elif 'show' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='430'
        logger.info('已成功填写类型为show REMUX')
    elif 'show' in file1.pathinfo.type.lower() and '1080i' in file1.standard_sel.lower():
        select_type='428'
        logger.info('已成功填写类型为show 1080i')
    elif 'show' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='429'
        logger.info('已成功填写类型为show 1080p')
    elif 'show' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='427'
        logger.info('已成功填写类型为show 720p')  
    elif 'show' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='431'
        logger.info('已成功填写类型为show 2160p')            
    elif 'tv' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='502'
        logger.info('已成功填写类型为tv Blu-Ray')
    elif 'tv' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='453'
        logger.info('已成功填写类型为tv Blu-Ray')
    elif 'tv' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='437'
        logger.info('已成功填写类型为tv REMUX')
    elif 'tv' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='436'
        logger.info('已成功填写类型为tv 1080p')
    elif 'tv' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='435'
        logger.info('已成功填写类型为tv 1080i')
    elif 'tv' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='434'
        logger.info('已成功填写类型为tv 720p')  
    elif 'tv' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='438'
        logger.info('已成功填写类型为tv 2160p')          
    elif 'movie' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='499'
        logger.info('已成功填写类型为Movie UHD-4K')
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='450'
        logger.info('已成功填写类型为Movie Blu-Ray')
    elif 'movie' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='415'
        logger.info('已成功填写类型为Movie REMUX')
    elif 'movie' in file1.pathinfo.type.lower() and '2160p' in file1.standard_sel.lower():
        select_type='416'
        logger.info('已成功填写类型为Movie 2160p')
    elif 'movie' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='414'
        logger.info('已成功填写类型为Movie 1080p')
    elif 'movie' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='413'
        logger.info('已成功填写类型为Movie 720p')               
     
    elif 'doc' in file1.pathinfo.type.lower() and 'UHD' in file1.type.upper():
        select_type='500'
        logger.info('已成功填写类型为doc Blu-Ray')
    elif 'doc' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='451'
        logger.info('已成功填写类型为doc Blu-Ray')
    elif 'doc' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_type='421'
        logger.info('已成功填写类型为doc REMUX')
    elif 'doc' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_type='420'
        logger.info('已成功填写类型为doc 1080p')
    elif 'doc' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_type='419'
        logger.info('已成功填写类型为doc 720p')  
    elif 'doc' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel.lower():
        select_type='422'
        logger.info('已成功填写类型为doc 2160p')         
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='441'
        logger.info('已成功填写类型为MV')           
    elif 'sport' in file1.pathinfo.type.lower() and '1080' in file1.standard_sel:
        select_type='443'
        logger.info('已成功填写类型为体育1080')
    elif 'sport' in file1.pathinfo.type.lower() and '720' in file1.standard_sel:
        select_type='443'
        logger.info('已成功填写类型为体育1080')    
    elif 'sport' in file1.pathinfo.type.lower() and '2160' in file1.standard_sel:
        select_type='504'
        logger.info('已成功填写类型为体育2160')           
    elif 'music' in file1.pathinfo.type.lower():
        select_type='442'
        logger.info('已成功填写类型为体育720')          
    else:
        select_type='450'
        logger.info('已成功填写类型为其它')          

    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='7'
        logger.info('已成功选择来源为WEB-DL')  
    elif 'UHD' in file1.source.upper():
        source_sel='9'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY')               
    elif 'HDTV' in file1.source.upper():
        source_sel='4'
        logger.info('已成功选择来源为HDTV')        
    elif 'DVD' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为DVD')     
    else:
        source_sel='8'
        logger.info('未识别到来源信息，选择other')

    #选择媒介
    if 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR') 
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')         
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为VC1')            
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选other')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif 'SD' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='2'
    logger.info('已成功选择分辨率')
    
    #选择处理
    if 'ENCODE' in file1.type.upper():
        processing_sel='2'
    else:
        processing_sel='1'


    #选择制作组
    if 'HDZONE' in file1.sub.upper():
        team_sel='1'
    elif 'HDZTV' in file1.sub.upper():
        team_sel='3'
    elif 'HDZ' in file1.sub.upper():
        team_sel='2'
    elif 'TTG' in file1.sub.upper():
        team_sel='6'
    elif 'METAM' in file1.sub.upper():
        team_sel='7'                        
    else:
        team_sel='11'
    logger.info('制作组已成功选择为'+file1.sub)        

    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel": source_sel,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "processing_sel": processing_sel,
            "team_sel": team_sel,            
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hdzone_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hhclub_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
    else:
        select_type='405'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择来源
    if 'web' in file1.type.lower():
        source_sel='6'
    elif (file1.type=='bluray' or 'bd' in file1.type.lower()) and '2160' in file1.standard_sel:
        source_sel='1'
    elif file1.type=='bluray' or 'bd' in file1.type.lower():
        source_sel='1'
    elif 'dvd' in file1.type.lower()  :
        source_sel='3'
    elif file1.type=='HDTV':
        source_sel='4'
    elif file1.type=='remux':
        source_sel='1'
    else:
        source_sel='6'
    logger.info('已成功填写来源为'+file1.type)

    #选择媒介
    if 'web' in file1.type.lower() and 'dl' in file1.type.lower():
        medium_sel='10'
    elif (file1.type=='bluray') and '2160' in file1.standard_sel:
        medium_sel='1'
    elif file1.type=='bluray':
        medium_sel='1'
    elif 'rip' in file1.type.lower() and  'web' in file1.type.lower():
        medium_sel='7'
    elif 'rip' in file1.type.lower() and 'dvd' in file1.type.lower():
        medium_sel='6'
    elif 'rip' in file1.type.lower()  :
        medium_sel='7'
    elif 'HDTV' in file1.type.upper() and '2160' in file1.standard_sel:
        medium_sel='5'
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
    elif 'remux' in file1.type.lower():
        medium_sel='3'
    elif 'dvd' in file1.type.lower():
        medium_sel='7'
    else:
        medium_sel='19'
    logger.info('已成功选择媒介为'+file1.type)


    #选择编码
    if file1.Video_Format=='H264':
        codec_sel='1'
    elif file1.Video_Format=='x264':
        codec_sel='1'
    elif file1.Video_Format=='H265':
        codec_sel='6'
    elif file1.Video_Format=='x265':
        codec_sel='6'
    else:
        codec_sel='6'
    logger.info('已成功选择编码为'+file1.Video_Format)

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'TRUEHD AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='1'
    elif '2160' in file1.standard_sel:
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='2'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            processing_sel='8'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            processing_sel='6'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            processing_sel='7'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            processing_sel='9'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            processing_sel='9'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            processing_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            processing_sel='9'
            logger.info('国家信息已选择'+file1.country)
        else:
            processing_sel='9'
            logger.info('未找到资源国家信息，已选择其他')
    else:
        processing_sel='4'
        logger.info('未找到资源国家信息，已默认日本')

    #选择制作组
    if 'HHWEB' in file1.sub.upper():
        team_sel='1'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)
    
    if 'HHWEB' in file1.sub.upper():
        tags.append(2)
        tags.append(3)
        tags.append(4)
    if 'WEB' in file1.type:
        tags.append(4)
        logger.info('已选择WEB')
    if 'hhclub' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    '''
    if '粤' in file1.language:
        tags.append(10)
        logger.info('已选择粤语')
    '''
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel" : source_sel,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "processing_sel" : processing_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hhclub_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def hitpt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='416'
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='413'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='415'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='415'
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)



    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='9'
        logger.info('已成功选择来源为WEB-DL')        
    elif 'UHD' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY')         
    elif 'ENCODE' in file1.source.upper():
        source_sel='2'
        logger.info('已成功选择来源为ENCODE')         
    elif 'HDTV' in file1.source.upper():
        source_sel='4'
        logger.info('已成功选择来源为HDTV')         
    elif 'DVD' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为DVD')         
    else:
        source_sel='8'
        logger.info('已成功选择来源为其它')

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  



     #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel.lower():
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    #选择制作组
    if 'BEAST' in file1.sub.upper():
        team_sel='14'
    elif 'MTEAM' in file1.sub.upper():
        team_sel='16'
    elif 'HIT' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='13'
    elif 'CMCT' in file1.sub.upper():
        team_sel='5'
    elif 'CHD' in file1.sub.upper():
        team_sel='8'
    elif 'HDWING' in file1.sub.upper():
        team_sel='6'
    else:
        team_sel='4'
    logger.info('制作组已成功选择为'+file1.sub)

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath

    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "doubanLink": file1.doubanurl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel": source_sel,
            "codec_sel": codec_sel,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
        

    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hitpt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import requests
from requests.adapters import HTTPAdapter
import socket
import certifi
import ssl
from ssl import create_default_context
import cloudscraper


def hudbt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'movie' in file1.pathinfo.type.lower():
        if '大陆' in file1.country:
            select_type='401'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            select_type='413'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            select_type='413'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            select_type='415'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            select_type='415'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            select_type='415'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            select_type='414'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            select_type='414'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            select_type='414'
            logger.info('国家信息已选择'+file1.country)
        elif '马来西亚' in file1.country:
            select_type='414'
            logger.info('国家信息已选择'+file1.country)
        elif '泰国' in file1.country:
            select_type='414'
            logger.info('国家信息已选择'+file1.country)
        elif '新加坡' in file1.country:
            select_type='414'
            logger.info('国家信息已选择'+file1.country)
        else:
            select_type='415'
            logger.info('未找到资源国家信息，已选择欧美')
    if 'show' in file1.pathinfo.type.lower():
        if '大陆' in file1.country:
            select_type='403'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            select_type='419'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            select_type='419'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            select_type='421'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            select_type='421'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            select_type='421'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            select_type='420'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            select_type='420'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            select_type='420'
            logger.info('国家信息已选择'+file1.country)
        elif '马来西亚' in file1.country:
            select_type='420'
            logger.info('国家信息已选择'+file1.country)
        elif '泰国' in file1.country:
            select_type='420'
            logger.info('国家信息已选择'+file1.country)
        elif '新加坡' in file1.country:
            select_type='420'
            logger.info('国家信息已选择'+file1.country)
        else:
            select_type='421'
            logger.info('未找到资源国家信息，已选择欧美')
    elif 'tv' in file1.pathinfo.type.lower():
        if '大陆' in file1.country:
            select_type='402'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            select_type='417'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            select_type='417'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            select_type='418'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            select_type='418'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            select_type='418'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            select_type='416'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            select_type='416'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            select_type='416'
            logger.info('国家信息已选择'+file1.country)
        elif '马来西亚' in file1.country:
            select_type='416'
            logger.info('国家信息已选择'+file1.country)
        elif '泰国' in file1.country:
            select_type='416'
            logger.info('国家信息已选择'+file1.country)
        elif '新加坡' in file1.country:
            select_type='416'
            logger.info('国家信息已选择'+file1.country)
        else:
            select_type='418'
            logger.info('未找到资源国家信息，已选择欧美')
    elif 'anime' in file1.pathinfo.type.lower() and '完结' in file1.pathinfo.tags:
        select_type='405'
    elif 'anime' in file1.pathinfo.type.lower():
        select_type='428'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='406'
    else:
        select_type='433'
    logger.info('已成功填写类型为'+file1.pathinfo.type)



    #选择分辨率
    if '2160' in file1.standard_sel:
        standard_sel='7'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath

    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "standard_sel": standard_sel,
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    headers = {
        'host': 'hudbt.hust.edu.cn',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'aache-control': 'max-age=0',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
         #'content-length': '499686',
        'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryfhTMBNBVOA7pufqF',
        'cookie': siteinfo.cookie,
        'origin': 'https://hudbt.hust.edu.cn',
        'referer': 'https://hudbt.hust.edu.cn/upload.php',
        'Sec-ch-ua': '"Microsoft Edge";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'Sec-ch-ua-mobile': '?0',
        'Sec-ch-ua-platform': '"Windows"',
        'Sec-fetch-dest': 'document',
        'Sec-fetch-mode': 'navigate',
        'Sec-fetch-site': 'same-origin',
        'Sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.0.0',
    } 
    
    success_upload=0
    try_upload=0
    ctx = ssl.create_default_context(cafile="/usr/local/share/ca-certificates/_.hust.edu.cn.crt")
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            ctx = create_default_context()
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out, cert="/usr/local/share/ca-certificates/_.hust.edu.cn.crt")
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/hudbt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def icc_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')  
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                      
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')  
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR') 
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD') 
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')       
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，选择other')

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'VC1' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为VC1')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')                       
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，选择other')  



    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '8K' in file1.standard_sel:
        standard_sel='7'
    elif '2K' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')

        #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'MYSILU' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)

    #选择标签

    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')          
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if '粤' in file1.language:
        tags.append(11)
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan) and '英' in file1.sublan:
        tags.append(10)
        logger.info('已选择中英字幕')
    elif not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     

    tags=list(set(tags))
    tags.sort()

    


    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/icc_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ilolicon_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型(只选择anime)
    select_type='405'




    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'MINI' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MINIBD')   
    elif 'TRACK' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为TRACK')       
    else:
        medium_sel='11'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='9'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='8'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为MPEG-4') 
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为VP-9')           
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择Others')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif "TRUE" in file1.Audio_Format.upper() and 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DD' in file1.Audio_Format.upper() and "5.1" in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'ALAC' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    else:
        audiocodec_sel='14'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='7'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')   
    if "ENCODE" in file1.type.upper():
        tags.append(9)
        logger.info('已选择RAW')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ilolicon_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def itzmx_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_type='401'
        logger.info('已成功填写类型为电影')                      
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为MV')                    
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='401'
        logger.info('已成功填写类型为其它')          
        




    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='3'
    elif '1080' in file1.standard_sel.lower():
        standard_sel='1'
    elif '720' in file1.standard_sel:
        standard_sel='2'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')

        #选择制作组
    team_sel='1'
    logger.info('制作组已成功选择为other')

    

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/itzmx_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def joyhd_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='414'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        




    #子类型
    if 'movie' in file1.pathinfo.type.lower() and '10bit' in file1.Video_Format:
        select_source='5'
        logger.info('已成功填写类型为Movie 10bit') 
    elif 'movie' in file1.pathinfo.type.lower() and 'WEB' in file1.type.upper():
        select_source='4'
        logger.info('已成功填写类型为Movie WEBDL') 
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_source='55'
        logger.info('已成功填写类型为Movie BLURAY')  
    elif 'movie' in file1.pathinfo.type.lower() and 'DVD' in file1.type.upper():
        select_source='79'
        logger.info('已成功填写类型为Movie DVD')         
    elif 'movie' in file1.pathinfo.type.lower() and 'HDTV' in file1.type.upper():
        select_source='80'
        logger.info('已成功填写类型为Movie HDTV')
    elif 'movie' in file1.pathinfo.type.lower() and 'ENCODE' in file1.type.upper():
        select_source='81'
        logger.info('已成功填写类型为Movie BDRIP')
    elif 'movie' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_source='57'
        logger.info('已成功填写类型为Movie REMUX')
    elif 'movie' in file1.pathinfo.type.lower() and '2160p' in file1.standard_sel.lower():
        select_source='82'
        logger.info('已成功填写类型为Movie 2160p')
    elif 'movie' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_source='6'
        logger.info('已成功填写类型为Movie 1080p')
    elif 'movie' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_source='7'
        logger.info('已成功填写类型为Movie 720p')               

    elif 'show' in file1.pathinfo.type.lower():
        select_source='15'
        logger.info('已成功填写类型为综艺综合')   

    elif 'tv' in file1.pathinfo.type.lower() and '大陆' in file1.country:
        select_source='23'
        logger.info('已成功填写类型为中国大陆')
    elif 'tv' in file1.pathinfo.type.lower() and '香港' in file1.country:
        select_source='24'
        logger.info('已成功填写类型为中国香港')  
    elif 'tv' in file1.pathinfo.type.lower() and '台湾' in file1.country:
        select_source='24'
        logger.info('已成功填写类型为中国台湾')
    elif 'tv' in file1.pathinfo.type.lower() and '泰国' in file1.country:
        select_source='70'
        logger.info('已成功填写类型为泰国')
    elif 'tv' in file1.pathinfo.type.lower() and '日本' in file1.country:
        select_source='26'
        logger.info('已成功填写类型为日本')
    elif 'tv' in file1.pathinfo.type.lower() and '韩国' in file1.country:
        select_source='27'
        logger.info('已成功填写类型为韩国')  
    elif 'tv' in file1.pathinfo.type.lower() and '美国' in file1.country:
        select_source='25'
        logger.info('已成功填写类型为美国')    
    elif 'tv' in file1.pathinfo.type.lower():
        select_source='70'
        logger.info('已成功填写类型为其他剧集')   


    elif 'anime' in file1.pathinfo.type.lower() and '完结' in file1.pathinfo.tags:
        select_source='66'
        logger.info('已成功填写类型为动漫完结')
    elif 'anime' in file1.pathinfo.type.lower():
        select_source='67'
        logger.info('已成功填写类型为动漫剧场版')

    elif 'doc' in file1.pathinfo.type.lower() and '国家地理' in file1.pathinfo.small_descr:
        select_source='34'
        logger.info('已成功填写类型为纪录片国家地理')
    elif 'doc' in file1.pathinfo.type.lower() and '探索' in file1.pathinfo.small_descr:
        select_source='35'
        logger.info('已成功填写类型为纪录片探索')
    elif 'doc' in file1.pathinfo.type.lower() and '历史' in file1.pathinfo.small_descr:
        select_source='40'
        logger.info('已成功填写类型为纪录片历史')
    elif 'doc' in file1.pathinfo.type.lower() and 'CCTV' in file1.pathinfo.small_descr:
        select_source='37'
        logger.info('已成功填写类型为纪录片CCTV')
    elif 'doc' in file1.pathinfo.type.lower() and 'NHK' in file1.pathinfo.small_descr:
        select_source='77'
        logger.info('已成功填写类型为纪录片国NHK')
    elif 'doc' in file1.pathinfo.type.lower() and 'BBC' in file1.pathinfo.small_descr:
        select_source='39'
        logger.info('已成功填写类型为纪录片BBC')
    elif 'doc' in file1.pathinfo.type.lower():
        select_source='41'
        logger.info('已成功填写类型为纪录片其他')

        
    elif 'mv' in file1.pathinfo.type.lower():
        select_source='60'
        logger.info('已成功填写类型为MV')           
    elif 'sport' in file1.pathinfo.type.lower():
        select_source='22'
        logger.info('已成功填写类型为体育')        
    elif 'music' in file1.pathinfo.type.lower():
        select_source='60'
        logger.info('已成功填写类型为体育720')          
    else:
        select_source='45'
        logger.info('已成功填写类型为其它')         



    #选择制作组
    if 'JOYHD' in file1.sub.upper():
        team_sel='1'
    elif 'IFT' in file1.sub.upper():
        team_sel='2'
    elif 'HDWING' in file1.sub.upper():
        team_sel='6'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'CMCT' in file1.sub.upper():
        team_sel='10'
    elif 'CHD' in file1.sub.upper():
        team_sel='8'
    elif 'BEAST' in file1.sub.upper():
        team_sel='7'
    elif 'MTEAM' in file1.sub.upper():
        team_sel='9'
    elif 'HDTIME' in file1.sub.upper():
        team_sel='11'
    elif 'SPARK' in file1.sub.upper():
        team_sel='12'
    elif 'IHQ' in file1.sub.upper():
        team_sel='15'
    else:
        team_sel='13'
    logger.info('制作组已成功选择为'+file1.sub)

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "imdburl": file1.imdburl,
            "dburl": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel": select_source,
            "team_sel": team_sel,
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/joyhd_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper


def kimoji_upload(siteinfo, file1, record_path, qbinfo, basic, hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    time_out = 40
    if (file1.pathinfo.type == 'anime' or file1.pathinfo.type == 'tv') and file1.pathinfo.collection == 0:
        fileinfo = file1.chinesename + '在' + siteinfo.sitename + '第' + file1.episodename + '集'
    else:
        fileinfo = file1.chinesename + '在' + siteinfo.sitename

    # 选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type = '405'
        tags.append(14)
    elif 'show' in file1.pathinfo.type.lower():
        select_type = '403'
    elif 'tv' in file1.pathinfo.type.lower():
        select_type = '402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type = '401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type = '404'
    elif 'music' in file1.pathinfo.type.lower() or 'mv' in file1.pathinfo.type.lower() :
        select_type = '406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type = '407'
    else:
        select_type = '401'
    logger.info('已成功填写类型为' + file1.pathinfo.type)

    # 选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel = '6'
        logger.info('已成功选择媒介为WEB-DL')
    elif 'UHD' in file1.type.upper():
        medium_sel = '10'
        logger.info('已成功选择媒介为UHD-BLURAY')
    elif 'BLU' in file1.type.upper():
        medium_sel = '1'
        logger.info('已成功选择媒介为BLURAY')
    elif 'ENCODE' in file1.type.upper():
        medium_sel = '7'
        logger.info('已成功选择媒介为ENCODE')
    elif 'HDTV' in file1.type.upper():
        medium_sel = '5'
        logger.info('已成功选择媒介为HDTV')
    elif 'REMUX' in file1.type.upper():
        medium_sel = '11'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel = '3'
        logger.info('已成功选择媒介为DVD')
    elif 'CD' in file1.type.upper():
        medium_sel = '8'
        logger.info('已成功选择媒介为CD')
    elif 'MINI' in file1.type.upper():
        medium_sel = '4'
        logger.info('已成功选择媒介为CD')
    elif 'TRACK' in file1.type.upper():
        medium_sel = '9'
        logger.info('已成功选择媒介为CD')
    else:
        medium_sel = '12'
        logger.info('未识别到媒介信息，不选择媒介')

    # 选择编码
    if '264' in file1.Video_Format or 'AVC' in file1.Video_Format.upper():
        codec_sel = '1'
        logger.info('已成功选择编码为H264/AVC')
    elif '265' in file1.Video_Format.upper() or 'HEVC' in file1.Video_Format.upper():
        codec_sel = '6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel = '4'
        logger.info('已成功选择编码为MPEG')
    elif 'MVC' in file1.Video_Format.upper():
        codec_sel = '10'
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel = '3'
    elif 'VC' in file1.Video_Format.upper():
     codec_sel = '2'
    elif 'VP' in file1.Video_Format.upper():
     codec_sel = '7'
    elif 'AV' in file1.Video_Format.upper():
      codec_sel = '8'
    elif 'PRO' in file1.Video_Format.upper():
      codec_sel = '9'
    else:
        codec_sel = '5'
        logger.info('未识别到视频编码信息，不选择')

        # 选择音频编码
    if file1.Audio_Format.upper() == 'AAC':
        audiocodec_sel = '6'
    elif 'DTS' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper() and '7' in file1.Audio_Format.upper():
        audiocodec_sel = '9'
    elif 'DTS' in file1.Audio_Format.upper() and 'HD' in file1.Audio_Format.upper():
        audiocodec_sel = '8'
    elif 'DTS' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel = '15'
    elif 'TRUE' in file1.Audio_Format.upper() and 'ATMOS' in file1.Audio_Format.upper():
        audiocodec_sel = '10'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel = '11'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel = '12'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel = '1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel = '2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel = '4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel = '14'
    elif 'AC3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel = '13'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel = '3'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel = '5'
    else:
        audiocodec_sel = '7'
    logger.info('已成功选择音频编码为' + file1.Audio_Format.upper())

    # 选择分辨率
    if '8K' in file1.standard_sel or '4320' in file1.standard_sel:
        standard_sel = '5'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel = '6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel = '1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel = '2'
    elif '720' in file1.standard_sel:
        standard_sel = '3'
    else:
        standard_sel = '1'
    logger.info('已成功选择分辨率为' + file1.standard_sel)


    if '国' in file1.language or '中' in file1.language or '国语' in file1.pathinfo.tags:
        tags.append(5)
    if '粤' in file1.language or '粤语' in file1.pathinfo.tags:
        tags.append(12)
    if '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan or '中字' in file1.pathinfo.tags:
        tags.append(6)
    if '完结' in file1.pathinfo.tags:
        tags.append(13)
    if '杜比' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags:
        tags.append(11)
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
    if 'MYTVS' in file1.pathinfo.uploadname.upper():
        tags.append(1)
    if 'NF' in file1.pathinfo.uploadname or 'NETFLIX' in file1.pathinfo.uploadname.upper():
        tags.append(8)
    tags = list(set(tags))
    tags.sort()

    if siteinfo.uplver == 1:
        uplver = 'yes'
    else:
        uplver = 'no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),

    other_data = {
        "name": file1.uploadname,
        "small_descr": file1.small_descr + file1.pathinfo.exinfo,
        "url": file1.imdburl,
        "douban_id": file1.doubanurl,
        "color": "0",
        "font": "0",
        "size": "0",
        "descr": file1.pathinfo.contenthead + '\n' + file1.douban_info + '\n' + "[Mediainfo]" + file1.mediainfo + "[/Mediainfo]" + '\n' + file1.screenshoturl + '\n' + file1.pathinfo.contenttail,
        "type": select_type,
        "medium_sel": medium_sel,
        "codec_sel": codec_sel,
        "audiocodec_sel": audiocodec_sel,
        "standard_sel": standard_sel,
        "team_sel": team_sel,
        "uplver": uplver,
        "tags[]": tags,
    }

    scraper = cloudscraper.create_scraper()
    success_upload = 0
    try_upload = 0
    while success_upload == 0:
        try_upload += 1
        if try_upload > 5:
            return False, fileinfo + ' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie), data=other_data, files=file_tup,
                             timeout=time_out)
            success_upload = 1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' % (r))
            success_upload = 0

    return afterupload(r, fileinfo, record_path, siteinfo, file1, qbinfo, hashlist)
utils/uploader/kimoji_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def kufei_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')      
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')             
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                 
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')         
    elif 'audio' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='401'
        logger.info('已成功填写类型为电影')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为WEB-DL')               
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD无中文')       
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为BLURAY DIY')
    elif 'BLU' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='18'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为DVD/DVDR')   
    elif 'CD' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为CD/HDCD')    
    else:
        medium_sel='16'
        logger.info('未识别到媒介信息，已选择Others')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='4'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为MPEG')
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为MPEG')            
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='8'
        logger.info('已成功选择编码为XVID')
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为AV')             
    else:
        codec_sel='10'
        logger.info('未识别到视频编码信息，已选择others')  


    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='5'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    else:
        standard_sel='7'
    logger.info('已成功选择分辨率')

   #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'MYSILU' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    else:
        team_sel='5'

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='18'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper() and 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='24'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'TAA' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择标签
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '完结' in file1.pathinfo.tags:
        tags.append(12)
        logger.info('已选择完结标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
    if '英' in file1.language:
        tags.append(8)
        logger.info('已选择英语标签')
     
    
    tags=list(set(tags))
    tags.sort()
        
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/kufei_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def mangguo_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'       
        logger.info('已成功填写类型为动漫')
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                  
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                  
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为音乐')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为学习')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
        logger.info('已成功填写类型为电子书')          
    else:
        select_type='410'
        logger.info('已成功填写类型为其它')          
        




    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='7'
        logger.info('已成功选择来源为WEB-DL')          
    elif 'UHD' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为UHD-BLURAY')         
    elif 'BLU' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY')         
    elif 'ENCODE' in file1.source.upper():
        source_sel='6'
        logger.info('已成功选择来源为ENCODE')         
    elif 'HDTV' in file1.source.upper():
        source_sel='4'
        logger.info('已成功选择来源为HDTV')         
    elif 'REMUX' in file1.source.upper():
        source_sel='6'
        logger.info('已成功选择来源为REMUX')
    elif 'HD' in file1.source.upper() and 'DVD' in file1.source.upper():
        source_sel='2'
        logger.info('已成功选择来源为HD DVD')
    elif 'DVD' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为DVD')
    elif 'SACD' in file1.source.upper():
        source_sel='9'
        logger.info('已成功选择来源为SACD') 
    elif 'CD' in file1.source.upper():
        source_sel='8'
        logger.info('已成功选择来源为CD')      
    else:
        source_sel='6'
        logger.info('已成功选择来源为其它') 


    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel[4]": source_sel,
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/mangguo_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def mteam_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='402'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '480' in file1.standard_sel:
            select_type='403'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        if 'remux' in file1.type.lower():
            select_type='439'
        elif 'dvd' in file1.type.lower() and 'iso' in file1.type.lower():
            select_type='420'
        elif 'blu' in file1.type.lower() or 'bdmv' in file1.type.lower() or 'iso' in file1.type.lower():
            select_type='421'
        elif '1080' in file1.standard_sel:
            select_type='419'            
        else:
            select_type='419'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='434'
    else:
        select_type='405'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='16'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='16'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='16'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='15'
        logger.info('已成功选择编码为MPEG')
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')                     
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')
    elif 'FLAC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为FLAC') 
    elif 'DTS' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为DTS')
    elif 'AC' in file1.Video_Format.upper() and '3' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为AC3')
    elif 'AAC' in file1.Video_Format.upper():
        codec_sel='18'
        logger.info('已成功选择编码为DTS')                                              
    else:
        codec_sel='1'
        logger.info('未识别到视频编码信息，已选择others')  

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='6'
    elif '2160' in file1.standard_sel:
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            processing_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            processing_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            processing_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            processing_sel='6'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            processing_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            processing_sel='6'
            logger.info('国家信息已选择'+file1.country)
        else:
            processing_sel='6'
            logger.info('未找到资源国家信息，已选择其他')
    else:
        processing_sel='4'
        logger.info('未找到资源国家信息，已默认日本')

    #选择制作组
    if 'MTeam' in file1.sub.upper():
        team_sel='9'
    elif 'LowPower-Raws' in file1.sub.upper():
        team_sel='22'
    else:
        team_sel='0'
    logger.info('制作组已成功选择为'+file1.sub)

    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            
    other_data = {
            "type": select_type,
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "codec_sel": codec_sel,
            "standard_sel": standard_sel,
            "processing_sel" : processing_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            }
    headers = {
        'authority': 'kp.m-team.cc',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        'cookie': siteinfo.cookie,
        'origin': 'https://kp.m-team.cc',
        'referer': 'https://kp.m-team.cc/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
    }
    if '国' in file1.language or '中' in file1.language:
        other_data['l_dub']='yes'
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        other_data['l_sub']='yes'
        logger.info('已选择中字')
    scraper=cloudscraper.create_scraper()
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
        
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/mteam_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def nanyang_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为动漫') 
    elif 'anime' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为综艺')        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                      
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='411'
        logger.info('已成功填写类型为其它')          
        
    

  

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "dburl": file1.doubanurl, 
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/nanyang_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def okpt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='409'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='409'
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')                
    elif 'UHD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHD-BLURAY')  
        tags.append(9)
        logger.info('已选择原盘标签')                 
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')     
        tags.append(9)
        logger.info('已选择原盘标签')             
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')  
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD')   
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')                  
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='14'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='13'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='0'
        logger.info('已成功选择编码为MPEG-2')   
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='0'
        logger.info('已成功选择编码为MPEG-4')        
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='0'
        logger.info('已成功选择编码为XVID')
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为VP9')    
    elif 'DIVX' in file1.Video_Format.upper():
        codec_sel='0'
        logger.info('已成功选择编码为DIVX')              
    else:
        codec_sel='0'
        logger.info('未识别到视频编码信息，不选择')  


#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='0'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'TAA' in file1.Audio_Format.upper():
        audiocodec_sel='0'
    else:
        audiocodec_sel='0'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='7'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='6'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='8'
    logger.info('已成功选择分辨率')


    #选择制作组

    if 'AUDIES' in file1.sub.upper():
        team_sel='5'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'CMCT' in file1.sub.upper():
        team_sel='7'
    elif 'FRDS' in file1.sub.upper():
        team_sel='3'
    elif 'HARES' in file1.sub.upper():
        team_sel='12'
    elif 'HDC' in file1.sub.upper():
        team_sel='11'
    elif 'HDH' in file1.sub.upper():
        team_sel='10'
    elif 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'HH' in file1.sub.upper():
        team_sel='6'
    elif 'LEAGUE' in file1.sub.upper():
        team_sel='15'
    elif 'OURBITS' in file1.sub.upper():
        team_sel='9'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'PTER' in file1.sub.upper():
        team_sel='8'        
    else:
        team_sel='14'    
    logger.info('制作组已成功选择为Other')    
    

    
    if 'okpt' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append(21)
        logger.info('已选择粤语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(8)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')          
        

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/okpt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def oshen_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='0'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD/DVDR') 
    elif 'DVDR' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDDVD')   
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD/HDCD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')       
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，已选择Encode')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择others')  


    #选择分辨率
    if '2160' in file1.standard_sel or '4k' in file1.standard_sel.lower():
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)


    #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'MYSILU' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'CMCT' in file1.sub.upper():
        team_sel='6'
    elif 'HDTIME' in file1.sub.upper():
        team_sel='8'
    elif 'SCSG' in file1.sub.upper():
        team_sel='7'
    elif 'PTHOME' in file1.sub.upper():
        team_sel='9'
    elif 'OSHEN' in file1.sub.upper():
        team_sel='10'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)


    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)

    
    tags=list(set(tags))
    tags.sort()
    

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/oshen_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def pandapt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        tags.append(12)
        logger.info('已选择动画标签')          
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'TV' in file1.pathinfo.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为UHD-BLURAY REMUX')           
    elif 'UHD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')  
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD') 
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为HDDVD')            
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')                  
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为MPEG-2')   
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-4')        
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为VP9')             
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  


#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='7'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'MP2' in file1.Audio_Format.upper():
        audiocodec_sel='17'        
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    else:
        audiocodec_sel='16'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='6'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')
    


    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            source_sel='7'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            source_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            source_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '新加坡' in file1.country:
            source_sel='8'
            logger.info('国家信息已选择'+file1.country)
        elif '马来西亚' in file1.country:
            source_sel='8'
            logger.info('国家信息已选择'+file1.country)
        elif '泰国' in file1.country:
            source_sel='8'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            source_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            source_sel='9'
            logger.info('国家信息已选择'+file1.country)
        else:
            source_sel='1'
            logger.info('未找到资源国家信息，已选择其他')
    else:
        source_sel='6'
        logger.info('未找到资源国家信息，选择其他')

    #选择制作组

    if 'BEITAI' in file1.sub.upper():
        team_sel='11'
    elif 'DGB' in file1.sub.upper():
        team_sel='12'
    elif 'GBWEB' in file1.sub.upper():
        team_sel='13'
    elif 'CATEDU' in file1.sub.upper():
        team_sel='15'
    elif 'LEAGUEWEB' in file1.sub.upper():
        team_sel='16'
    elif 'LEAGUENF' in file1.sub.upper():
        team_sel='17'
    elif 'LHD' in file1.sub.upper():
        team_sel='18'      
    else:
        team_sel='5'    
    logger.info('制作组已成功选择为Other')            
    
    if 'pandapt' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language or '国' in file1.pathinfo.tags:
        tags.append(5)
        logger.info('已选择国语')
    if '粤' in file1.language or '粤' in file1.pathinfo.tags:
        tags.append(13)
        logger.info('已选择粤语')
    if '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan or '中' in file1.pathinfo.tags:
        tags.append(6)
        logger.info('已选择中字')
    if file1.pathinfo.complete==1:
        tags.append(10)
        logger.info('已选择完结')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(9)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')        
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(8)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')          

    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "nfo": "0",            
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "source_sel[4]": source_sel,
            "team_sel[4]": team_sel,            
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': 'pandapt.net',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'cookie': siteinfo.cookie,
        'origin': 'https://pandapt.net',
        'referer': 'https://pandapt.net/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/pandapt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def piggo_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择来源

    if 'WEB' in file1.source.upper():
        source_sel='7'
        logger.info('已成功选择来源为WEB-DL')  
    elif 'UHD' in file1.source.upper() and 'DIY' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为UHD-BLURAY DIY')         
    elif 'UHD' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper() and 'DIY' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY DIY') 
    elif 'BLU' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY')         
    elif 'ENCODE' in file1.source.upper():
        source_sel='6'
        logger.info('已成功选择来源为ENCODE')         
    elif 'HDTV' in file1.source.upper():
        source_sel='5'
        logger.info('已成功选择来源为HDTV')         
    elif 'REMUX' in file1.source.upper():
        source_sel='6'
        logger.info('已成功选择来源为REMUX')
    elif 'DVD' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为DVD')
    elif 'DVD' in file1.source.upper() and 'HD' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为HDDVD')
    elif 'TV' in file1.source.upper():
        source_sel='5'
        logger.info('已成功选择来源为DVD')              
    else:
        source_sel='6'
        logger.info('已成功选择来源为其它') 

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')         
    elif 'UHD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')      
    elif 'DVDR' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为DVDR')        
    elif 'DVD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为HDDVD')
    elif 'BD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为MiniBD')
    elif 'TRACK' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为TRACK')         
    else:
        medium_sel='8'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DOLBY' in file1.Audio_Format.upper() and 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='10'
        tags.append(12)
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='6'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='3'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')

    #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'MYSILU' in file1.sub.upper():
        team_sel='3'
    elif 'WIKI' in file1.sub.upper():
        team_sel='4'
    elif 'BEITAI' in file1.sub.upper():
        team_sel='11'
        tags.append(22)
    elif 'DGB' in file1.sub.upper():
        team_sel='12'
        tags.append(24)
    else:
        team_sel='5'
    logger.info('已成功选择制作组')
    
    #选择画质
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        processing_sel='4' 
    elif 'HDR10+' in file1.pathinfo.tags:
        processing_sel='3'      
    elif 'HDR10' in file1.pathinfo.tags:
        processing_sel='2' 
    else:
        processing_sel='1' 


    #选择标签
    if '完结' in file1.pathinfo.tags or file1.pathinfo.complete == 1:
        tags.append(13)
        logger.info('已选择完结标签')

    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10+标签')

    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(9)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')
    if ( '国' in file1.language or '中' in file1.language) and '英' in file1.language: 
        tags.append(21)
        logger.info('已选择中英标签')            
    elif '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'    


    torrent_file = file1.torrentpath

    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            
    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "source_sel[4]": source_sel,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "processing_sel[4]": processing_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }
    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/piggo_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ptcafe_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')       
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')     
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')     
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        




    #选择来源
    if '大陆' in file1.country:
        source_sel='1'
    elif '香港' in file1.country or '台湾' in file1.country:
        source_sel='2'
    elif '日本' in file1.country:
        source_sel='4'
    elif '韩国' in file1.country:
        source_sel='5'
    elif '印度' in file1.country:
        source_sel='6'
    elif '新加坡' in file1.country or '马来西亚' in file1.country or '泰国' in file1.country:
        source_sel='7'
    else:
        source_sel='3'

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为UHD-BLURAY REMUX')   
    elif 'UHD' in file1.type.upper() and 'TV' in file1.pathinfo.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为UHD-BLURAY REMUX')           
    elif 'UHD' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为REMUX')  
    elif 'DVD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为DVD')   
    elif 'CD' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为CD')         
    else:
        medium_sel='13'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='4'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='1'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为MPEG-2')   
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为MPEG-4')        
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='8'
        logger.info('已成功选择编码为XVID')
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为VP9')    
    elif 'DIVX' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为DIVX')              
    else:
        codec_sel='11'
        logger.info('未识别到视频编码信息，不选择')  


#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='8'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'TAA' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    else:
        audiocodec_sel='16'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='1'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='2'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='3'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif 'SD' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='6'
    logger.info('已成功选择分辨率')
    

    #选择制作组
    if 'ADE' in file1.sub.upper():
        team_sel='1'
    elif 'ADWEB' in file1.sub.upper():
        team_sel='2'
    elif 'AUDIES' in file1.sub.upper():
        team_sel='3'
    elif 'BEITAI' in file1.sub.upper():
        team_sel='4'
        tags.append(10)
        logger.info('已选择备胎标签')   
    elif 'CAFETV' in file1.sub.upper():
        team_sel='5'
    elif 'CAFEWEB' in file1.sub.upper():
        team_sel='6'
    elif 'CHDBITS' in file1.sub.upper():
        team_sel='8'
    elif 'CHD' in file1.sub.upper():
        team_sel='7'
    elif 'CMCT' in file1.sub.upper():
        team_sel='9'
    elif 'DREAM' in file1.sub.upper():
        team_sel='10'
    elif 'FRDS' in file1.sub.upper():
        team_sel='11'
    elif 'HARES' in file1.sub.upper():
        team_sel='12'
    elif 'HARESTV' in file1.sub.upper():
        team_sel='13'
    elif 'HARESWEB' in file1.sub.upper():
        team_sel='14'
    elif 'HDCTV' in file1.sub.upper():
        team_sel='15'
    elif 'HDHOME' in file1.sub.upper():
        team_sel='17'
    elif 'HDHTV' in file1.sub.upper():
        team_sel='18'
    elif 'HDH' in file1.sub.upper():
        team_sel='16'
    elif 'HDSKY' in file1.sub.upper():
        team_sel='20'
    elif 'HDS' in file1.sub.upper():
        team_sel='19'
    elif 'HHWEB' in file1.sub.upper():
        team_sel='21'
    elif 'LEAGUEWEB' in file1.sub.upper():
        team_sel='22'
    elif 'MTEAM' in file1.sub.upper() or 'M-TEAM' in file1.sub.upper():
        team_sel='23'
    elif 'NTB' in file1.sub.upper():
        team_sel='24'
    elif 'OURBITS' in file1.sub.upper():
        team_sel='25'
    elif 'PTCAFE' in file1.sub.upper():
        team_sel='26'
    elif 'QHSTUDIO' in file1.sub.upper():
        team_sel='27'
    elif 'SAKURAWEB' in file1.sub.upper():
        team_sel='28'
    elif 'WIKI' in file1.sub.upper():
        team_sel='29'
    else:
        team_sel='30'    
    logger.info('制作组已成功选择为Other')

    #选择标签
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(12)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(11)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(13)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(7)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(9)
        logger.info('已选择中字标签')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "source_sel[4]": source_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ptcafe_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ptchina_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower() and "完结" in file1.pathinfo.tags:
        select_type='402'
        logger.info('已成功填写类型为电视剧')
    elif 'anime' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电视剧')  
    elif 'show' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为电视剧')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')               
    else:
        select_type='401'
        logger.info('已成功填写类型为其它')          
        





    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='9'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')         
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为BLURAY DIY')
    elif 'BLU' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为HDTV')           
    else:
        medium_sel='13'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='4'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为MPEG-2') 
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='12'
        logger.info('已成功选择编码为MPEG-4')               
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为VC1')  
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='13'
        logger.info('已成功选择编码为XVID')
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='14'
        logger.info('已成功选择编码为AV1')                     
    else:
        codec_sel='15'
        logger.info('未识别到视频编码信息，不选择')  

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='19'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='21'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='23'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    else:
        audiocodec_sel='24'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel.upper():
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='3'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='4'
    elif '2K' in file1.standard_sel.upper():
        standard_sel='2'
    else:
        standard_sel='6'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

    #选择处理
    if '大陆' in file1.country:
        processing_sel='1'
    elif '美国' in file1.country:
        processing_sel='2'
    elif '美国' in file1.country:
        processing_sel='8'
    elif '英国' in file1.country:
        processing_sel='2'
    elif '香港' in file1.country:
        processing_sel='9'
    elif '台湾' in file1.country:
        processing_sel='10'
    elif '泰国' in file1.country:
        processing_sel='12'
    elif '新加坡' in file1.country:
        processing_sel='12'
    elif '马来西亚' in file1.country:
        processing_sel='12'
    elif '日本' in file1.country:
        processing_sel='12'
    elif '韩国' in file1.country:
        processing_sel='12'
    else:
        processing_sel='11'




    #选择制作组
    if 'PTCHINA' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'HDC' in file1.sub.upper():
        team_sel='3'
    elif 'TTG' in file1.sub.upper():
        team_sel='4'
    elif 'WIKI' in file1.sub.upper():
        team_sel='5'
    elif 'BEAST' in file1.sub.upper():
        team_sel='21'
    elif 'CMCT' in file1.sub.upper():
        team_sel='22'
    elif 'FRDS' in file1.sub.upper():
        team_sel='23'
    elif 'HDS' in file1.sub.upper():
        team_sel='24'
    elif 'OURBITS' in file1.sub.upper():
        team_sel='25'
    elif 'PTER' in file1.sub.upper():
        team_sel='26'
    elif 'LEMONHD' in file1.sub.upper() or 'LEAGUE' in file1.sub.upper():
        team_sel='27'
    elif 'HDH' in file1.sub.upper():
        team_sel='28'
    elif 'PTH' in file1.sub.upper():
        team_sel='29'
    elif 'AUD' in file1.sub.upper():
        team_sel='30'
    elif 'HARE' in file1.sub.upper():
        team_sel='31'
    elif 'BTN' in file1.sub.upper() or 'NTB' in file1.sub.upper():
        team_sel='32'
    elif 'EPS' in file1.sub.upper():
        team_sel='33'
    elif 'FRA' in file1.sub.upper():
        team_sel='34'
    else:
        team_sel='35'    
    logger.info('制作组已成功选择为Other')




    #选择标签

    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "processing_sel[4]": processing_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ptchina_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def pter_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='403'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='405'        
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'music' in file1.pathinfo.type.lower() and 'video' in file1.pathinfo.type.lower():
        select_type='418'        
    elif 'music' in file1.pathinfo.type.lower():
        select_type='406'                
    else:
        select_type='412'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择来源 
    if 'WEB' in file1.type.upper():
        source_sel='5'
        logger.info('已成功选择来源为WEB-DL')         
    elif 'UHD' in file1.type.upper():
        source_sel='1'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        source_sel='2'
        logger.info('已成功选择来源为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        source_sel='6'
        logger.info('已成功选择来源为ENCODE')         
    elif 'HDTV' in file1.type.upper():
        source_sel='4'
        logger.info('已成功选择来源为HDTV')         
    elif 'REMUX' in file1.type.upper():
        source_sel='3'
        logger.info('已成功选择来源为REMUX')
    elif 'DVD' in file1.type.upper():
        source_sel='7'
        logger.info('已成功选择来源为DVD')
    elif 'FLAC' in file1.Audio_Format.upper():
        source_sel='8'
        logger.info('已成功选择来源为FLAC')                             
    else:
        source_sel='15'
        logger.info('已成功选择来源为其它') 

    
    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            team_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            team_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            team_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            team_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            team_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            team_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '俄' in file1.country:
            team_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '瑞' in file1.country:
            team_sel='4'
            logger.info('国家信息已选择'+file1.country)                 
        elif '韩国' in file1.country:
            team_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            team_sel='6'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            team_sel='7'
            logger.info('国家信息已选择'+file1.country)
        else:
            team_sel='4'
            logger.info('未找到资源国家信息，选择欧美')
    else:
        team_sel='4'
        logger.info('未找到资源国家信息，选择欧美')


    jinzhuan = 'no'
    guoyu    = 'no'
    zhongzi  = 'no'
    pr       = 'no'
    guanfang = 'no'
    uplver   = 'no'
    if 'audience' in file1.pathinfo.exclusive :
        jinzhuan = 'yes'
    if '国' in file1.language or '中' in file1.language or '国' in file1.pathinfo.tags:
        guoyu    = 'yes'
    if '粤' in file1.language or '粤' in file1.pathinfo.tags:
        yueyu    = 'yes'        
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan) or '中' in file1.pathinfo.tags:
        zhongzi  = 'yes'
    if '英' in file1.sublan:
        ensub  = 'yes'        
    if 'PTER' in file1.sub.upper():
        guanfang = 'yes'
    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'

        

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            
    
    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "douban": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+"[hide=Mediainfo]"+file1.mediainfo+"[/hide]"+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "type": select_type,
            "source_sel": source_sel,
            "team_sel": team_sel,
            }
    buttomlist=["uplver","jinzhuan","guoyu","zhongzi","pr","guanfang"]
    for item in buttomlist:
        if eval(item+"=='yes'"):
            exec('other_data["'+item+'"]="yes"')
            

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/pter_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def pthome_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
    elif 'tv' in file1.pathinfo.type.lower() :
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower() or 'music' in file1.pathinfo.type.lower():
        select_type='408'
        tags.append('mv')    
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')        
    elif 'UHD' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为UHD-BLURAY')  
    elif 'ENCODE' in file1.type.upper():
        medium_sel='15'
        logger.info('已成功选择媒介为ENCODE')           
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为BLURAY DIY')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY DIY')  
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')         
    else:
        medium_sel='11'
        logger.info('未识别到媒介信息，不选择媒介')    


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')            
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')                 
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='19'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='18'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='21'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='23'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='24'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())
    #选择分辨率
    if '8K' in file1.standard_sel.upper() or '4320' in file1.standard_sel:
        standard_sel='10'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel.upper():
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='11'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    #选择制作组
    team_sel='5'
    logger.info('制作组已成功选择为Other')
    
 
    if '国' in file1.language or '中' in file1.language:
        tags.append('gy')
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append('yy')
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append('zz')
        logger.info('已选择中字')
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append('hdrm')
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append('hdr10')
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append('db')
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append('diy')
        logger.info('已选择DIY标签')            


    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "douban_id": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/pthome_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ptlsp_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        tags.append(12)
        logger.info('已选择动画标签')
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        tags.append(8)
        logger.info('已选择音乐标签')
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        tags.append(17)
        logger.info('已选择体育标签')
    elif 'music' in file1.pathinfo.type.lower():
        select_type='411'
        tags.append(8)
        logger.info('已选择动画标签')
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD') 
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'MINI' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MINIBD')   
    elif 'TRACK' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为TRACK')       
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为MPEG-4') 
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为MPEG-2')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为VP-9')           
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择Others')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='6'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(14)
        logger.info('已选择HDR10+标签')
    if 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(13)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append(21)
        logger.info('已选择粤语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if not file1.sublan=='' and ('英' in file1.sublan):
        tags.append(20)
        logger.info('已选择英字')        
    if file1.pathinfo.complete==1:
        tags.append(19)
        logger.info('已选择完结')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ptlsp_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper
import requests

def ptsbao_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='414'
        logger.info('已成功填写类型为MV')                 
    elif 'music' in file1.pathinfo.type.lower():
        select_type='414'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        




    #子类型
    if 'movie' in file1.pathinfo.type.lower() and 'DIY' in file1.pathinfo.tags:
        select_source='93'
        logger.info('已成功填写类型为Movie DIY') 
    elif 'movie' in file1.pathinfo.type.lower() and 'WEB' in file1.type.upper():
        select_source='4'
        logger.info('已成功填写类型为Movie WEBDL') 
    elif 'movie' in file1.pathinfo.type.lower() and 'BLU' in file1.type.upper():
        select_source='55'
        logger.info('已成功填写类型为Movie BLURAY')  
    elif 'movie' in file1.pathinfo.type.lower() and 'DVD' in file1.type.upper():
        select_source='79'
        logger.info('已成功填写类型为Movie DVD')         
    elif 'movie' in file1.pathinfo.type.lower() and 'HDTV' in file1.type.upper():
        select_source='94'
        logger.info('已成功填写类型为Movie HDTV')
    elif 'movie' in file1.pathinfo.type.lower() and 'REMUX' in file1.type.upper():
        select_source='88'
        logger.info('已成功填写类型为Movie REMUX')
    elif 'movie' in file1.pathinfo.type.lower() and '2160p' in file1.standard_sel.lower():
        select_source='92'
        logger.info('已成功填写类型为Movie 2160p')
    elif 'movie' in file1.pathinfo.type.lower() and '1080p' in file1.standard_sel.lower():
        select_source='3'
        logger.info('已成功填写类型为Movie 1080p')
    elif 'movie' in file1.pathinfo.type.lower() and '720' in file1.standard_sel.lower():
        select_source='91'
        logger.info('已成功填写类型为Movie 720p')               

    elif 'show' in file1.pathinfo.type.lower():
        select_source='15'
        logger.info('已成功填写类型为综艺综合')   

    elif 'tv' in file1.pathinfo.type.lower() and '大陆' in file1.country:
        select_source='23'
        logger.info('已成功填写类型为中国大陆')
    elif 'tv' in file1.pathinfo.type.lower() and '香港' in file1.country:
        select_source='24'
        logger.info('已成功填写类型为中国香港')  
    elif 'tv' in file1.pathinfo.type.lower() and '台湾' in file1.country:
        select_source='24'
        logger.info('已成功填写类型为中国台湾')
    elif 'tv' in file1.pathinfo.type.lower() and '泰国' in file1.country:
        select_source='70'
        logger.info('已成功填写类型为泰国')
    elif 'tv' in file1.pathinfo.type.lower() and '日本' in file1.country:
        select_source='26'
        logger.info('已成功填写类型为日本')
    elif 'tv' in file1.pathinfo.type.lower() and '韩国' in file1.country:
        select_source='27'
        logger.info('已成功填写类型为韩国')  
    elif 'tv' in file1.pathinfo.type.lower() and '美国' in file1.country:
        select_source='25'
        logger.info('已成功填写类型为美国') 
    elif 'tv' in file1.pathinfo.type.lower() and '英国' in file1.country:
        select_source='90'
        logger.info('已成功填写类型为美国')    
    elif 'tv' in file1.pathinfo.type.lower():
        select_source='70'
        logger.info('已成功填写类型为其他剧集')   


    elif 'anime' in file1.pathinfo.type.lower() and '完结' in file1.pathinfo.tags:
        select_source='66'
        logger.info('已成功填写类型为动漫完结')
    elif 'anime' in file1.pathinfo.type.lower():
        select_source='67'
        logger.info('已成功填写类型为动漫剧场版')

    elif 'doc' in file1.pathinfo.type.lower() and '国家地理' in file1.pathinfo.small_descr:
        select_source='34'
        logger.info('已成功填写类型为纪录片国家地理')
    elif 'doc' in file1.pathinfo.type.lower() and '探索' in file1.pathinfo.small_descr:
        select_source='35'
        logger.info('已成功填写类型为纪录片探索')
    elif 'doc' in file1.pathinfo.type.lower() and '历史' in file1.pathinfo.small_descr:
        select_source='40'
        logger.info('已成功填写类型为纪录片历史')
    elif 'doc' in file1.pathinfo.type.lower() and 'CCTV' in file1.pathinfo.small_descr:
        select_source='37'
        logger.info('已成功填写类型为纪录片CCTV')
    elif 'doc' in file1.pathinfo.type.lower() and 'NHK' in file1.pathinfo.small_descr:
        select_source='77'
        logger.info('已成功填写类型为纪录片NHK')
    elif 'doc' in file1.pathinfo.type.lower() and 'BBC' in file1.pathinfo.small_descr:
        select_source='39'
        logger.info('已成功填写类型为纪录片BBC')
    elif 'doc' in file1.pathinfo.type.lower() and 'Netflix' in file1.pathinfo.small_descr:
        select_source='95'
        logger.info('已成功填写类型为网飞')
    elif 'doc' in file1.pathinfo.type.lower():
        select_source='41'
        logger.info('已成功填写类型为纪录片其他')

        
    elif 'mv' in file1.pathinfo.type.lower():
        select_source='49'
        logger.info('已成功填写类型为MV')                   
    else:
        select_source='68'
        logger.info('已成功填写类型为其它')         

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')         
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY DIY')          
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为DVD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')         
    else:
        medium_sel='9'
        logger.info('未识别到媒介信息，不选择媒介')    


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')            
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')  
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为VP9')
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')                  
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'MP2' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel.upper() or '4320' in file1.standard_sel:
        standard_sel='6'
    if '2K' in file1.standard_sel.upper():
        standard_sel='7'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel.upper():
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='1'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='6'
    logger.info('已成功选择分辨率为'+file1.standard_sel)


    #选择处理
    if 'ENCODE' in file1.type.upper():
        processing_sel='2'
    elif 'REMUX' in file1.type.upper():
        processing_sel='1'
    elif 'BLU' in file1.type.upper():
        processing_sel='5'
    else:
        processing_sel='3'
    

    #选择制作组
    if 'FFANSBD' in file1.sub.upper():
        team_sel='8'
    elif 'OPS' in file1.sub.upper():
        team_sel='11'
    elif 'FFANSWEB' in file1.sub.upper():
        team_sel='12'
    elif 'FFANSTV' in file1.sub.upper():
        team_sel='13'
    elif 'HQC' in file1.sub.upper():
        team_sel='10'
    elif 'TTG' in file1.sub.upper():
        team_sel='3'
    elif 'HDC' in file1.sub.upper():
        team_sel='6'
    elif 'HDS' in file1.sub.upper():
        team_sel='9'
    elif 'CMCT' in file1.sub.upper():
        team_sel='4'
    elif 'FRDS' in file1.sub.upper():
        team_sel='5'
    elif 'FFANSDVD' in file1.sub.upper():
        team_sel='14'
    elif 'FHDMV' in file1.sub.upper():
        team_sel='15'
    elif '19977' in file1.sub.upper():
        team_sel='17'
    elif 'QHSTUIDIO' in file1.sub.upper():
        team_sel='18'
    elif 'FFANSAIENCE' in file1.sub.upper():
        team_sel='19'
    elif 'SGXT' in file1.sub.upper():
        team_sel='20'
    else:
        team_sel='7'    
    logger.info('制作组已成功选择为Other')
    
    k4  = 'no'
    zz  = 'no'
    hdr = 'no'
    yp  = 'no'
    diy = 'no'
    uplver   = 'no'    
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        zz = 'yes'
    if 'HDR10' in file1.pathinfo.tags:
        hdr = 'yes'
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel.upper():
        k4 = 'yes'
    if 'BLU' in file1.type.upper():
        yp = 'yes'
    if 'DIY' in file1.pathinfo.tags:
        diy = 'yes'
    if siteinfo.uplver==1:
        uplver='yes'


    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "upload": "8381589",
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "imdburl": file1.imdburl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel": select_source,
            "team_sel": team_sel,
            "medium_sel": medium_sel,
            "standard_sel": standard_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "cite_torrent": "",
            "chinese_name": "",
            "english_name": "",
            "releasedate": "",
            "release_time": "",             
            "processing_sel": processing_sel,
            "uplver": uplver,
            }
    buttomlist=["uplver","k4","zz","hdr","yp","diy"]
    for item in buttomlist:
        if eval(item+"=='yes'"):
            exec('other_data["'+item+'"]="yes"')            


    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ptsbao_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def pttime_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='431'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='490'
        logger.info('已成功填写类型为其它')          
        

    #选择标签

    if '国' in file1.language or '中' in file1.language:
        tags.append('gy')
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append('yue')
        logger.info('已选择粤语')
    if '韩' in file1.language:
        tags.append('hy')
        logger.info('已选择韩语')
    if '日' in file1.language:
        tags.append('yue')
        logger.info('已选择日语')
    if '英' in file1.language:
        tags.append('yy')
        logger.info('已选择英语')
    if '印' in file1.language:
        tags.append('ydy')
        logger.info('已选择印语')
    if not file1.sublan=='' and not '国' in file1.language and not '中' in file1.language and not '粤' in file1.language and not '韩' in file1.language and not '日' in file1.language and not '英' in file1.language and not '印' in file1.language:
        tags.append('wy')
        logger.info('已选择其他语种')


    if '英' in file1.sublan and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append('zy')
        logger.info('已选择中英双字')
    elif '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan:
        tags.append('zz')
        logger.info('已选择中字')
    elif '英' in file1.sublan:
        tags.append('yz')
        logger.info('已选择中字')
    elif not file1.sublan=='':
        tags.append('qt')
        logger.info('已选择其他字幕')

    elif 'HDR10' in file1.pathinfo.tags:
        tags.append('hdr')
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append('dbsj')
        logger.info('已选择杜比视界标签')
    if 'blu' in file1.type.lower():
        tags.append('dwj')
        logger.info('已选择原盘标签') 
    if '2160' in file1.standard_sel or '4k' in file1.standard_sel.lower():
        tags.append('sk')
        logger.info('已选择4K标签')     

    
    tags=list(set(tags))
    tags.sort()
    

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "dburl": file1.doubanurl, 
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "anonymous": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/pttime_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def redleaves_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD/DVDR')   
    elif 'CD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为CD/HDCD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')       
    else:
        medium_sel='6'
        logger.info('未识别到媒介信息，已选择Other')



     #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'AC' in file1.Video_Format.lower() and '3' in file1.Video_Format:
        codec_sel='12'
        logger.info('已成功选择编码为AC3')               
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'VP' in file1.Video_Format.upper():
        codec_sel='13'
        logger.info('已成功选择编码为VP9') 
    elif 'AAC' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为AAC') 
    elif 'MP3' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为MP3') 
    elif 'WAV' in file1.Video_Format.upper():
        codec_sel='8'
        logger.info('已成功选择编码为WAV') 
    elif 'FLAC' in file1.Video_Format.upper():
        codec_sel='6'
        logger.info('已成功选择编码为FLAC')  
    elif 'DTS' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为DTS')  
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')                                                           
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择Other')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'TRUEHD AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'LPCM' in file1.Audio_Format.upper() or 'WAV' in file1.Audio_Format.upper() :
        audiocodec_sel='14'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='19'                
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'WMA' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'MPEG-4' in file1.Audio_Format.upper() or 'MPEG4' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'SBC' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'AptX' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='6'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择地区
    if not file1.country=='':
        if '大陆' in file1.country:
            processing_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            processing_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            processing_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '德国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '俄国' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '瑞' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '芬兰' in file1.country:
            processing_sel='3'
            logger.info('国家信息已选择'+file1.country)                                                  
        elif '韩国' in file1.country:
            processing_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            processing_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            processing_sel='6'
            logger.info('国家信息已选择'+file1.country)
        else:
            processing_sel='6'
            logger.info('未找到资源国家信息，已选择其他')
    else:
        processing_sel='6'
        logger.info('未找到资源国家信息，已选择其他')

        #选择制作组
    if 'PTER' in file1.sub.upper():
        team_sel='26'
    elif 'GBWEB' in file1.sub.upper():
        team_sel='10'
        tags.append(24)
        logger.info('已选择丐帮')         
    elif 'DGB' in file1.sub.upper():
        team_sel='8'
        tags.append(24)
        logger.info('已选择丐帮')         
    elif 'BEITAI' in file1.sub.upper():
        team_sel='6'
        tags.append(21)
        logger.info('已选择备胎')        
    elif 'FRDS' in file1.sub.upper():
        team_sel='12'
    elif 'VCB' in file1.sub.upper():
        team_sel='27'                               
    else:
        team_sel='0'
    logger.info('制作组已成功选择为'+file1.sub)      

    #选择标签
    if 'RL' in file1.sub.upper():
        tags.append(3)
        logger.info('已选择官方')
    if 'RL' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if '粤' in file1.language:
        tags.append(18)
        logger.info('已选择粤语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY') 
    if '杜比' in file1.pathinfo.tags or 'DV' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags :
        tags.append(17)
        logger.info('已选择Dovi') 
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR')                        

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[5]": medium_sel,
            "codec_sel[5]": codec_sel,
            "audiocodec_sel[5]": audiocodec_sel,
            "standard_sel[5]": standard_sel,
            "processing_sel[5]" : processing_sel,
            "team_sel[5]" : team_sel,            
            "uplver": uplver,
            "tags[]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/redleaves_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def rousi_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='415'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='402'
        else:
            select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='406'
    else:
        select_type='405'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    source_sel='24'
    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='24'
    elif 'UHD' in file1.source.upper():
        source_sel='23'
    elif 'BLU' in file1.source.upper():
        source_sel='22'
    elif 'ENCODE' in file1.source.upper():
        source_sel='24'
    elif 'dvd' in file1.type.lower():
        source_sel='25'
    elif 'ENCODE' in file1.source.upper():
        source_sel='22'
    elif 'HDTV' in file1.source.upper():
        source_sel='26'
    elif 'REMUX' in file1.source.upper():
        source_sel='22'
    else:
        source_sel='28'


    #选择媒介
    if 'web' in file1.type.lower() and 'dl' in file1.type.lower():
        medium_sel='10'
    elif (file1.type=='bluray') and '2160' in file1.standard_sel:
        medium_sel='1'
    elif file1.type=='bluray':
        medium_sel='1'
    elif 'rip' in file1.type.lower() and  'dvd' in file1.type.lower():
        medium_sel='6'
    elif 'rip' in file1.type.lower()  :
        medium_sel='7'
    elif 'HDTV' in file1.type.upper() and '2160' in file1.standard_sel:
        medium_sel='5'
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
    elif 'remux' in file1.type.lower():
        medium_sel='3'
    elif 'dvd' in file1.type.lower():
        medium_sel='2'
    else:
        medium_sel='10'
    logger.info('已成功填写来源为'+file1.type)



    #选择编码
    if file1.Video_Format=='H264':
        codec_sel='1'
    elif file1.Video_Format=='x264':
        codec_sel='1'
    elif file1.Video_Format=='H265':
        codec_sel='6'
    elif file1.Video_Format=='x265':
        codec_sel='6'
    else:
        codec_sel='1'
    logger.info('已成功选择编码为'+file1.Video_Format)

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'TRUEHD AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='6'
    elif '2160' in file1.standard_sel:
        standard_sel='6'
        tags.append(18)
        logger.info('已选择4K')
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='8'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择制作组
    if 'DJWEB' in file1.sub.upper():
        team_sel='1'
    elif 'DJTV' in file1.sub.upper():
        team_sel='2'
    elif 'DJZB' in file1.sub.upper():
        team_sel='3'
    elif 'CatEDU' in file1.sub.upper():
        team_sel='6'
    elif 'Zaxyzit' in file1.sub.upper():
        team_sel='8'
    else:
        team_sel='7'
    logger.info('制作组已成功选择为'+file1.sub)
    

    if 'rousi' in file1.pathinfo.exclusive :
        tags.append(1)
        logger.info('已选择禁转')
    if 'ROUSI' in file1.sub.upper():
        tags.append(3)
        logger.info('已选择官方')
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if not file1.sublan=='' and '英' in file1.sublan:
        tags.append(14)
        logger.info('已选择英字')
    if '粤' in file1.language:
        tags.append(15)
        logger.info('已选择粤语')
    if 'ROUSIWEB' in file1.sub.upper():
        tags.append(13)
        logger.info('已选择RousiWeb')
    if 'ROUSIWEB' in file1.sub.upper():
        tags.append(13)
        logger.info('已选择RousiWeb')
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(11)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')    


    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/rousi_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def shadowflow_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='504'
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='502'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='501'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='505'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='503'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='506'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='507'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='508'
    else:
        select_type='509'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择来源 
    if 'remux' in file1.type.lower():
        medium_sel='4'
    elif 'bdrip' in file1.type.lower():
        medium_sel='6'
    elif file1.type=='WEB-DL':
        medium_sel='7'
    elif 'webrip' in file1.type.lower():
        medium_sel='8'
    elif file1.type=='HDTV':
        medium_sel='5'
    elif 'tvrip' in file1.type.lower():
        medium_sel='9'
    elif 'dvdrip' in file1.type.lower():
        medium_sel='10'
    elif 'dvd' in file1.type.lower():
        medium_sel='3'
    else:
        medium_sel='12'
    logger.info('已成功选择质量为'+file1.type)



    #选择编码
    if file1.Video_Format=='H264':
        codec_sel='2'
    elif file1.Video_Format=='x264':
        codec_sel='2'
    elif file1.Video_Format=='H265':
        codec_sel='1'
    elif file1.Video_Format=='x265':
        codec_sel='1'
    else:
        codec_sel='2'
    logger.info('已成功选择编码为'+file1.Video_Format)

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='5'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'TRUEHD AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    else:
        audiocodec_sel='10'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='1'
    elif '2160' in file1.standard_sel:
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif '480' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='2'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择地区
    if file1.country!='' :
        if '大陆' in file1.country:
            source_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            source_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            source_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            source_sel='6'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            source_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            source_sel='7'
            logger.info('国家信息已选择'+file1.country)
        else:
            source_sel='99'
            logger.info('未找到资源国家信息，已选择Other')
    else:
        source_sel='5'
    logger.info('未找到资源国家信息，已默认日本')

    if file1.pathinfo.collection==1 and file1.pathinfo.complete==1:
        pack='yes'
    else:
        pack='no'
    
    if 'yingweb' in file1.pathinfo.exclusive:
        exclusive='yes'
    else:
        exclusive='no'

    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname.replace('  ',' ').replace(' ','.'),
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.doubanurl,
            "url_vimages": file1.screenshoturl.replace('[img]','').replace('[/img]',''),
            "Media_BDInfo": file1.mediainfo,
            "color": "0",
            "font": "0",
            "size": "0",
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "source_sel" : source_sel,
            "uplver": uplver,
            "exclusive": exclusive,
            "pack": pack,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/shadowflow_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def soulvoice_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'study' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为教学')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='409'
        logger.info('已成功填写类型为其它')          
        

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为UHD')
    elif 'BLU' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVDR' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为DVD/DVDR') 
    elif 'DVDR' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为HDDVD')   
    elif 'CD' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为CD/HDCD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为REMUX')       
    else:
        medium_sel='12'
        logger.info('未识别到媒介信息，已选择Encode')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为H265/HEVC')                   
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择others')  


    #选择分辨率
    if '2160' in file1.standard_sel or '4k' in file1.standard_sel.lower():
        standard_sel='3'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='4'
    logger.info('已成功选择分辨率为'+file1.standard_sel)


    #选择制作组
    if 'HDS' in file1.sub.upper():
        team_sel='1'
    elif 'CHD' in file1.sub.upper():
        team_sel='2'
    elif 'FRDS' in file1.sub.upper():
        team_sel='3'
    elif 'CMCT' in file1.sub.upper():
        team_sel='4'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)


    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
    if '完结' in file1.pathinfo.tags:
        tags.append(8)
    if '杜比' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags.upper():
        tags.append(12)
    
    tags=list(set(tags))
    tags.sort()
    

    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "codec_sel[4]": codec_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/soulvoice_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ssd_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='504'
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='502'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='501'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='505'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='503'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='506'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='507'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='508'
    else:
        select_type='509'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择来源 
    if 'remux' in file1.type.lower():
        medium_sel='4'
    elif 'bdrip' in file1.type.lower():
        medium_sel='6'
    elif file1.type=='WEB-DL':
        medium_sel='7'
    elif 'webrip' in file1.type.lower():
        medium_sel='8'
    elif file1.type=='HDTV':
        medium_sel='5'
    elif 'tvrip' in file1.type.lower():
        medium_sel='9'
    elif 'dvdrip' in file1.type.lower():
        medium_sel='10'
    elif 'dvd' in file1.type.lower():
        medium_sel='3'
    else:
        medium_sel='12'
    logger.info('已成功选择质量为'+file1.type)



    #选择编码
    if file1.Video_Format=='H264':
        codec_sel='2'
    elif file1.Video_Format=='x264':
        codec_sel='2'
    elif file1.Video_Format=='H265':
        codec_sel='1'
    elif file1.Video_Format=='x265':
        codec_sel='1'
    else:
        codec_sel='2'
    logger.info('已成功选择编码为'+file1.Video_Format)

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='5'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'TRUEHD AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'DTS:X' in file1.Audio_Format.upper() or 'DTS-X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'M4A' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    else:
        audiocodec_sel='10'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='1'
    elif '2160' in file1.standard_sel:
        standard_sel='1'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='2'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='3'
    elif '720' in file1.standard_sel:
        standard_sel='4'
    elif '480' in file1.standard_sel:
        standard_sel='5'
    else:
        standard_sel='2'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    
    #选择地区
    if file1.country!='' :
        if '大陆' in file1.country:
            source_sel='1'
            logger.info('国家信息已选择'+file1.country)
        elif '香港' in file1.country:
            source_sel='2'
            logger.info('国家信息已选择'+file1.country)
        elif '台湾' in file1.country:
            source_sel='3'
            logger.info('国家信息已选择'+file1.country)
        elif '美国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '英国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '法国' in file1.country:
            source_sel='4'
            logger.info('国家信息已选择'+file1.country)
        elif '韩国' in file1.country:
            source_sel='6'
            logger.info('国家信息已选择'+file1.country)
        elif '日本' in file1.country:
            source_sel='5'
            logger.info('国家信息已选择'+file1.country)
        elif '印度' in file1.country:
            source_sel='7'
            logger.info('国家信息已选择'+file1.country)
        else:
            source_sel='99'
            logger.info('未找到资源国家信息，已选择Other')
    else:
        source_sel='5'
    logger.info('未找到资源国家信息，已默认日本')

    if file1.pathinfo.collection==1 and file1.pathinfo.complete==1:
        pack='yes'
    else:
        pack='no'
    
    if 'ssd' in file1.pathinfo.exclusive:
        exclusive='yes'
    else:
        exclusive='no'

    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname.replace('  ',' ').replace(' ','.'),
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.doubanurl,
            "url_vimages": file1.screenshoturl.replace('[img]','').replace('[/img]',''),
            "Media_BDInfo": file1.mediainfo,
            "color": "0",
            "font": "0",
            "size": "0",
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "source_sel" : source_sel,
            "uplver": uplver,
            "exclusive": exclusive,
            "pack": pack,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ssd_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def tccf_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'doc' in file1.pathinfo.type.lower():
        select_type='624'
        logger.info('已成功填写类型为纪录片')   
    else:
        select_type='0'
        logger.info('已成功填写类型为纪录片')        
        
    #选择次类型
    source_sel='14'   

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='9'      
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
    elif 'REMUX' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为REMUX')           
    elif 'ENCODE' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为DVD/DVDR')     
    else:
        medium_sel='8'
        logger.info('未识别到媒介信息，已选择Others')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='8'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='8'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择others')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
        logger.info('已选择音频编码为AAC')  
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='8'
        logger.info('已选择音频编码为DTS.HDMA')  
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='9'
        logger.info('已选择音频编码为TrueHD AutoTransferMachineos')  
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='9'
        logger.info('已选择音频编码为TrueHD')  
    elif 'DTS:X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
        logger.info('已选择音频编码为DTS:X')  
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
        logger.info('已选择音频编码为FLAC')  
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
        logger.info('已选择音频编码为APE')  
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='5'
        logger.info('已选择音频编码为MP3')  
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='4'
        logger.info('已选择音频编码为DD')  
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='4'
        logger.info('已选择音频编码为DD')  
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
        logger.info('已选择音频编码为DTS')  
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='11'
        logger.info('已选择音频编码为WAV')  
    elif 'AAC' in file1.Audio_Format.upper():
        audiocodec_sel='6'
        logger.info('已选择音频编码为AAC')  
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='10'
        logger.info('已选择音频编码为LPCM') 
    else:
        audiocodec_sel='7'
        logger.info('未查询到音频编码，已选择音频编码为Others')  
    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')

   #选择制作组
    if 'TLF' in file1.sub.upper():
        team_sel='2'
    elif 'BMDRU' in file1.sub.upper():
        team_sel='3'
    elif 'CATEDU' in file1.sub.upper():
        team_sel='4'
    elif 'MADFOX' in file1.sub.upper():
        team_sel='5'
    else:
        team_sel='7'
    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "source_sel": source_sel,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            "tags[]": tags,
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': 'et8.org',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'cookie': 'c_secure_uid=NzM1MDE%3D; c_secure_pass=05e0bd3a6d27c02a24fc4b012d355334; c_secure_ssl=eWVhaA%3D%3D; c_secure_tracker_ssl=eWVhaA%3D%3D; c_secure_login=bm9wZQ%3D%3D',
        'origin': 'https://et8.org',
        'referer': 'https://et8.org/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/tccf_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ubits_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')                 
    elif 'music' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='408'
        logger.info('已成功填写类型为其它')          
        





    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为WEB-DL')              
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')         
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为HDTV')            
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')   
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR')     
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD')
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD')
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')           
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，不选择媒介')    


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='8'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='7'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2')            
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')  
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')                  
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='11'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel.upper():
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

    #选择标签
    if '2160' in file1.standard_sel and 'HDR10+' in file1.pathinfo.tags:
        tags.append(10)
        logger.info('已选择4K HDR10+标签')
    elif '2160' in file1.standard_sel and 'HDR10' in file1.pathinfo.tags:
        tags.append(9)
        logger.info('已选择4K HDR10标签')
    elif '2160' in file1.standard_sel:
        tags.append(7)
        logger.info('已选择4K SDR标签')

    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(8)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if '粤' in file1.language:
        tags.append(11)
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')
     
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ubits_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
from qbittorrentapi import Client
import time
import datetime
import os
import sys
import re
import qbittorrentapi
from http.cookies import SimpleCookie
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs


def afterupload(r, fileinfo, record_path, siteinfo, file1, qbinfo, hashlist):
    global downloadurl
    if r.status_code == 200:
        logger.info('已发布成功')
    elif r.status_code == 400 and siteinfo.sitename == 'zhuque' and 'code' in r.json() and 'TORRENT_ALREADY_UPLOAD' in \
            r.json()['code']:
        return True, fileinfo + '种子发布失败,失败原因:种子已存在'
    elif siteinfo.sitename == 'zhuque' and r.status_code == 400 and 'code' in r.json():
        logger.warning(
            '发布种子发生错误，错误代码:' + str(r.status_code) + ' ,错误信息:' + str(r.reason) + '站点返回信息:' +
            r.json()['code'])
        return True, fileinfo + ' 站点发布种子发生错误，错误代码:' + str(r.status_code) + ' ,错误信息:' + str(r.reason)
    elif siteinfo.sitename == 'zhuque' and 'code' in r.json():
        logger.warning(
            '发布种子发生错误，错误代码:' + str(r.status_code) + ' ,错误信息:' + str(r.reason) + '站点返回信息:' +
            r.json()['code'])
        return False, fileinfo + ' 发布种子发生错误，错误代码:' + str(r.status_code) + ' ,错误信息:' + str(r.reason)
    else:
        logger.warning('发布种子发生错误，错误代码:' + str(r.status_code) + ' ,错误信息:' + str(r.reason))
        return False, fileinfo + ' 发布种子发生错误，错误代码:' + str(r.status_code) + ' ,错误信息:' + str(r.reason)
    if siteinfo.sitename == 'zhuque':
        String_url = 'https://zhuque.in/torrent/info/' + str(r.json()['data']['id'])
    else:
        String_url = finduploadurl(r)
    if siteinfo.sitename == 'zhuque':
        if siteinfo.torrentkey == '':
            return True, fileinfo + '种子发布成功,但是做种失败，失败原因:未设置zhuque站点torrentkey.' + ',当前网址:' + String_url
        downloadurl = 'https://zhuque.in/api/torrent/download/' + str(
            r.json()['data']['id']) + '/' + siteinfo.torrentkey
    elif siteinfo.sitename == 'hdarea' or siteinfo.sitename == 'hdzone' or siteinfo.sitename == 'hitpt' or siteinfo.sitename == 'hudbt' or siteinfo.sitename == 'itzmx' or siteinfo.sitename == 'joyhd' or siteinfo.sitename == 'audience' or siteinfo.sitename == 'ilolicon' or siteinfo.sitename == 'zmpt':
        downloadurl = String_url.replace("details", "download")
        downloadurl = f"{downloadurl}&passkey={siteinfo.passkey}"
    elif siteinfo.sitename == 'haidan':
        parsed_url = urlparse(downloadurl)  # 解析 URL
        query = parsed_url.query  # 获取 query 参数
        params = parse_qs(query)  # 解析 query 参数
        try:
            torrent_id = params["torrent_id"][0]  # 获取 torrent_id 的值
        except KeyError:  # 捕获 KeyError 异常
            torrent_id = "0"  # 使用一个默认值
        downloadurl = f"https://www.haidan.video/download.php?id={torrent_id}&passkey={siteinfo.passkey}"
    else:
        downloadurl = finddownloadurl(r)
    if downloadurl == '已存在':
        return True, fileinfo + '种子发布失败,失败原因:种子' + downloadurl
    recordupload(os.path.join(record_path, siteinfo.sitename + '_torrent.csv'), file1, String_url, downloadurl)
    if downloadurl != '':
        res = qbseed(url=downloadurl, filepath=file1.downloadpath, qbinfo=qbinfo, category=file1.pathinfo.category,
                     hashlist=hashlist)
        if res:
            return True, fileinfo + '种子发布成功,种子链接:' + downloadurl + ',当前网址:' + String_url
        else:
            return True, fileinfo + '种子发布成功,但是添加种子失败,请手动添加种子，种子链接:' + downloadurl + ',当前网址:' + String_url

    else:
        logger.warning('正在记录错误的请求返回值')
        errorfile = os.path.join(record_path, 'errorhtml.html')
        f = open(errorfile, 'w', encoding='utf-8')
        f.write(r.text)
        f.close()
        return False, fileinfo + '未找到下载链接,当前网址:' + String_url + ' ,请求的返回值已保存至:' + errorfile


def cookies_raw2jar(raw: str) -> dict:
    """
    Arrange Cookies from raw using SimpleCookies
    """
    if not raw:
        raise ValueError("The Cookies is not allowed to be empty.")
    cookie = SimpleCookie(raw)
    return {key: morsel.value for key, morsel in cookie.items()}


def recordupload(torrent_file, file1, String_url, downloadurl):
    logger.info('正在记录发布的资源到' + torrent_file)
    if not os.path.exists(torrent_file):
        if 'win32' in sys.platform:
            f = open(torrent_file, 'w+', encoding='utf-8-sig', errors='ignore')
        else:
            f = open(torrent_file, 'w+', encoding='utf-8-sig')

        f.write('中文名,集数,发布日期,资源链接,资源下载链接\n0\n')
        f.close()

    if 'win32' in sys.platform:
        with open(torrent_file, 'r', encoding='utf-8-sig', errors='ignore') as f1:
            list1 = f1.readlines()
    else:
        with open(torrent_file, 'r') as f1:
            list1 = f1.readlines()
    while list1[-1].strip() == '':
        a = list1.pop(-1)
        del (a)

    try:
        num = int(list1[-1].replace(',', '').strip())
        a = list1.pop(-1)
        del (a)
    except:
        num = 0
    if len(list1) > 0:
        list1[-1] = list1[-1].strip() + '\n'

    now = datetime.datetime.now()

    filestr = ''.join(list1)
    newstr = ''

    newstr = newstr + file1.chinesename.replace(',', ' ') + ','
    if not (
            'anime' in file1.pathinfo.type.lower() or 'tv' in file1.pathinfo.type.lower()) or file1.pathinfo.collection == 0:
        newstr = newstr + file1.episodename.zfill(2) + ','
    else:
        newstr = newstr + '第' + str(file1.pathinfo.min).zfill(2) + '-' + str(file1.pathinfo.max).zfill(2) + '集 合集,'
    newstr = newstr + str(now.year) + str(now.month).zfill(2) + str(now.day).zfill(2) + ','
    newstr = newstr + str(String_url) + ','
    newstr = newstr + str(downloadurl) + '\n'

    logger.debug(newstr)

    filestr = filestr + newstr + str(num + 1) + '\n'
    if 'win32' in sys.platform:
        f = open(torrent_file, 'w+', encoding='utf-8-sig', errors='ignore')
    else:
        f = open(torrent_file, 'w+', encoding='utf-8-sig')
    f.write(filestr)
    f.close()
    logger.info('记录完毕')


def finduploadurl(res):
    logger.info('正在寻找发布页面链接')
    String_url = res.url
    if not ('&uploaded' in String_url):
        logger.warning(String_url + '未找到发布页面网址')
        return '未找到发布页面网址'
    String_url = String_url.split('&uploaded')[0]
    return String_url


def finddownloadurl(res):
    logger.info('正在寻找页面下载链接')
    o = urlparse(res.url)
    o = o.scheme + '://' + o.hostname + '/download.php?'
    # 白兔特判
    if 'hare' in o:
        link = re.findall('(https://club\.hares\.top/download\.php\?downhash=.*)\</p', res.text)
        if len(link) > 0:
            return link[0]
        else:
            if '已存在' in res.text:
                logger.warning('该种子已存在')
                return '已存在'
            logger.warning('未找到下载链接')
            return ''
    # 白兔特判结束
    soup = BeautifulSoup(res.text, 'lxml')
    for a in soup.find_all('a', href=True):
        link = ''
        try:
            link = a['href']
        except:
            # logger.warning('该a标签未找到href属性')
            logger.trace('该a标签未找到href属性')
        if o in link:
            logger.info('成功获得下载链接' + link)
            return link

    for a in soup.find_all('a', href=True):
        link = ''
        try:
            link = a['href']
        except:
            logger.warning('该a标签未找到href属性')
        if len(re.findall(r'download.php\?id=[0-9]+&', link)) > 0:
            o = urlparse(res.url)
            if link.startswith('download.php'):
                link = o.scheme + '://' + o.hostname + '/' + link
            logger.info('成功获得下载链接' + link)
            return link

    logger.warning('未找到下载链接')
    if '已存在' in res.text:
        logger.warning('该种子已存在')
        return '已存在'
    return ''


def qbseed(url, filepath, qbinfo, is_skip_checking=True, is_paused=False, category=None, hashlist=[]):
    logger.info('正在添加资源到Qbittorrent,请稍等...')

    is_paused = False
    try:
        client = Client(host=qbinfo['qburl'], username=qbinfo['qbwebuiusername'], password=qbinfo['qbwebuipassword'])
    except:
        logger.warning('Qbittorrent WEBUI登录失败,将种子添加到QB任务失败')
        return False

    logger.info('正在登录Qbittorrent WEBUI')
    try:
        client.auth_log_in()
    except:
        logger.warning('Qbittorrent WEBUI信息错误，登录失败，请检查au.yaml文件里的url、用户名、密码')
        return False
    logger.info('成功登录Qbittorrent WEBUI')
    try:
        tor_num = len(client.torrents_info())
    except Exception as err:
        tor_num = 0
    tor_num_new = tor_num
    trynum = 0
    while tor_num_new == tor_num:
        trynum = trynum + 1
        if trynum > 12:
            logger.warning('添加种子失败,种子下载链接为:' + url + '   请自行手动添加')
            return True
        logger.info('正在第' + str(trynum) + '次添加种子')
        try:
            res = client.torrents_add(urls=url, save_path=filepath, is_skip_checking=is_skip_checking,
                                      is_paused=is_paused, use_auto_torrent_management=None, category=category)
        except Exception as r:
            logger.warning('添加种子进入qb出错，错误信息: %s' % (str(r)[:50]))
            continue
            # raise ValueError ('添加种子进入qbittorrent出错，程序结束')
        if 'Ok' in res:
            logger.info('返回值显示成功添加种子')
        else:
            logger.warning('添加种子失败，返回值为:' + str(res)[:50])
        time.sleep(1)
        try:
            tor_num_new = len(client.torrents_info())
        except Exception as r:
            tor_num_new = tor_num
            logger.warning('计算种子数量出错，错误信息: %s' % (str(r)[:50]))
        if tor_num_new == tor_num:
            time.sleep(5)
            try:
                tor_num_new = len(client.torrents_info())
            except Exception as r:
                tor_num_new = tor_num
                logger.warning('计算种子数量出错，错误信息: %s' % (str(r)[:50]))

    logger.info('已经成功添加种子')
    addtime = 0
    to = None
    try:
        torrentlist = client.torrents.info()
    except Exception as r:
        torrentlist = []
        logger.warning('获取种子信息出错，错误信息: %s' % (str(r)[:50]))
    for item in torrentlist:
        if item.added_on > addtime:
            addtime = item.added_on
            to = item
    if type(to) != qbittorrentapi.torrents.TorrentDictionary:
        logger.warning('未找到最新的种子')
        return True
    if not to._torrent_hash in hashlist:
        hashlist.append(to._torrent_hash)

    return True
utils/uploader/upload_tools.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def wintersakura_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower() and '完结' in file1.pathinfo.tags:
        select_type='423'
    elif 'anime' in file1.pathinfo.type.lower():
        select_type='422'             
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'        
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection>=1:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='414'
        else:
            select_type='414'
    elif 'tv' in file1.pathinfo.type.lower() and file1.pathinfo.collection==0:
        if '大陆' in file1.country or '香港' in file1.country or '台湾' in file1.country:
            select_type='414'
        else:
            select_type='414'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='410'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
    else:
        select_type='409'
    logger.info('已成功填写类型为'+file1.pathinfo.type)


    #选择媒介
    if 'WEBRIP' in file1.type.upper():
        medium_sel='25'
        logger.info('已成功选择媒介为WEB-DL')
    elif 'WEB' in file1.type.upper():
        medium_sel='21'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')                
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为UHD-BLURAY')
        tags.append(22)
        logger.info('已选择原盘')                 
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为BLURAY-DIY')
    elif 'BLU' in file1.type.upper() and():
        medium_sel='12'
        logger.info('已成功选择媒介为BLURAY') 
        tags.append(22)
        logger.info('已选择原盘')                           
    elif 'ENCODE' in file1.type.upper():
        medium_sel='15'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='16'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='14'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='17'
        logger.info('已成功选择媒介为DVD')      
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')



    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='8'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='6'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='9'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='7'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='9'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='11'
        logger.info('已成功选择编码为MPEG-2')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='10'
        logger.info('已成功选择编码为VC1')          
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='16'
        logger.info('已成功选择编码为AV1')       
    else:
        codec_sel='13'
        logger.info('未识别到视频编码信息，已选择Others')  

    #选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='19'
    elif 'DTS' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='9'        
    elif 'DTS' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'DTS' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='22'
    elif 'DDP' in file1.Audio_Format.upper() and 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='26'                             
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='11'        
    elif 'TRUEHD' in file1.Audio_Format.upper():
        audiocodec_sel='12'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='15'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='16'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='17'
    elif 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='25'        
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='20'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='13'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='23'
    elif 'DSD' in file1.Audio_Format.upper():
        audiocodec_sel='24'
    elif 'AAC' in file1.Audio_Format.upper():
        audiocodec_sel='19'        
    else:
        audiocodec_sel='0'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='6'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif '480' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)

         #选择制作组
    if 'PTER' in file1.sub.upper():
        team_sel='8'
    elif 'TJUPT' in file1.sub.upper():
        team_sel='17'        
    elif 'CMCT' in file1.sub.upper():
        team_sel='6'         
    elif 'TTG' in file1.sub.upper():
        team_sel='15'       
    elif 'FRDS' in file1.sub.upper():
        team_sel='7'
    elif 'MTEAM' in file1.sub.upper():
        team_sel='13'
    elif 'HDC' in file1.sub.upper():
        team_sel='14'   
    elif 'HDS' in file1.sub.upper():
        team_sel='1'   
    elif 'CHD' in file1.sub.upper():
        team_sel='2'   
    elif 'BHD' in file1.sub.upper():
        team_sel='9'                                                                  
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)      
    
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY') 
    if '杜比' in file1.pathinfo.tags or 'DV' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags :
        tags.append(11)
        logger.info('已选择Dovi') 
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(10)
        logger.info('已选择HDR10+')       
    elif 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10+')
    elif '特效' in file1.pathinfo.tags:
        tags.append(9)
        logger.info('已选择HDR10+')              
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字')
    if '粤' in file1.language:
        tags.append(12)
        logger.info('已选择粤语')    

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "team_sel[4]": team_sel,            
            "audiocodec_sel[4]": audiocodec_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/wintersakura_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def wuerpt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫')      
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')             
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                 
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')   
    elif 'opera' in file1.pathinfo.type.lower():
        select_type='410'
        logger.info('已成功填写类型为戏曲')        
    elif 'audio' in file1.pathinfo.type.lower():
        select_type='408'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='401'
        logger.info('已成功填写类型为电影')          
        


    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and "中字" not in file1.pathinfo.tags:
        medium_sel='15'
        logger.info('已成功选择媒介为4K原盘中字')         
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD无中文')
    elif 'BLU' in file1.type.upper() and "中字" not in file1.pathinfo.tags:
        medium_sel='14'
        logger.info('已成功选择媒介为2K原盘中字')          
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='12'
        logger.info('已成功选择媒介为BLURAY DIY')
    elif 'BLU' in file1.type.upper() and 'REMUX' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='11'
        logger.info('已成功选择媒介为BLURAY无中文')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为HDTV')        
    elif 'DVD' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVD/DVDR')   
    elif 'CD' in file1.type.upper():
        medium_sel='8'
        logger.info('已成功选择媒介为CD/HDCD')
    elif '8K' in file1.type.upper():
        medium_sel='13'
        logger.info('已成功选择媒介为8K')       
    else:
        medium_sel='9'
        logger.info('未识别到媒介信息，已选择Others')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='13'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='11'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='13'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='14'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='12'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='1'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，已选择others')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
        logger.info('已选择音频编码为AAC')  
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='4'
        logger.info('已选择音频编码为DTS.HDMA')  
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='10'
        logger.info('已选择音频编码为TrueHD AutoTransferMachineos')  
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='12'
        logger.info('已选择音频编码为TrueHD')  
    elif 'DTS:X' in file1.Audio_Format.upper():
        audiocodec_sel='3'
        logger.info('已选择音频编码为DTS:X')  
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
        logger.info('已选择音频编码为FLAC')  
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
        logger.info('已选择音频编码为APE')  
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
        logger.info('已选择音频编码为MP3')  
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='6'
        logger.info('已选择音频编码为DD')  
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='6'
        logger.info('已选择音频编码为DD')  
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
        logger.info('已选择音频编码为DTS')  
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='11'
        logger.info('已选择音频编码为WAV')  
    elif 'AAC' in file1.Audio_Format.upper():
        audiocodec_sel='13'
        logger.info('已选择音频编码为AAC')  
    elif 'LPCM' in file1.Audio_Format.upper():
        audiocodec_sel='14'
        logger.info('已选择音频编码为LPCM') 
    else:
        audiocodec_sel='7'
        logger.info('未查询到音频编码，已选择音频编码为Others')  
    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='7'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    else:
        standard_sel='6'
    logger.info('已成功选择分辨率')
    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url" : file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "standard_sel": standard_sel,
            "uplver": uplver,
            "tags[]": tags,
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'authority': '52pt.site',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        #'content-length': '6820',
        'cookie': siteinfo.cookie,
        'origin': 'https://52pt.site',
        'referer': 'https://52pt.site/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/wuerpt_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def ydy_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='422'
        logger.info('已成功填写类型为其他')
    elif 'show' in file1.pathinfo.type.lower():
        select_type='422'
        logger.info('已成功填写类型为其他')                
    elif 'tv' in file1.pathinfo.type.lower() and "BLU" in file1.type.upper():
        select_type='424'
        logger.info('已成功填写类型为剧集BLURAY')          
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='421'
        logger.info('已成功填写类型为剧集HD')                   
    elif 'movie' in file1.pathinfo.type.lower() and "BLU" in file1.type.upper():
        select_type='420'
        logger.info('已成功填写类型为电影BLURAY')          
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='423'
        logger.info('已成功填写类型为电影HD')                  
    else:
        select_type='422'
        logger.info('已成功填写类型为其它')    

    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='5'
        logger.info('已成功选择来源为WEB-DL')     
    elif 'UHD' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper():
        source_sel='2'
        logger.info('已成功选择来源为BLURAY')         
    elif 'ENCODE' in file1.source.upper():
        source_sel='7'
        logger.info('已成功选择来源为ENCODE')         
    elif 'HDTV' in file1.source.upper():
        source_sel='3'
        logger.info('已成功选择来源为HDTV')         
    elif 'DVD' in file1.source.upper():
        source_sel='4'
        logger.info('已成功选择来源为DVD')         
    else:
        source_sel='8'
        logger.info('已成功选择来源为其它') 
      
        





    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='0'
        logger.info('已成功选择媒介为WEB-DL')           
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')         
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='5'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='5'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG-2' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-2') 
    elif 'MPEG-4' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG-4')               
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')  
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')
    elif 'AV' in file1.Video_Format.upper():
        codec_sel='5'
        logger.info('已成功选择编码为AV1')                     
    else:
        codec_sel='5'
        logger.info('未识别到视频编码信息，不选择')  

#选择音频编码
    if file1.Audio_Format.upper()=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'MA' in file1.Audio_Format.upper():
        audiocodec_sel='9'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'HR' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'DTS-HD' in file1.Audio_Format.upper() and 'X' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='10'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='8'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'PCM' in file1.Audio_Format.upper():
        audiocodec_sel='0'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='0'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    else:
        audiocodec_sel='0'
    logger.info('已成功选择音频编码为'+file1.Audio_Format.upper())

    #选择分辨率
    if '2160' in file1.standard_sel or '4K' in file1.standard_sel.upper():
        standard_sel='4'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '2K' in file1.standard_sel.upper():
        standard_sel='3'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)





    #选择制作组
    team_sel='9'    
    logger.info('制作组已成功选择为Other')



    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "nfo": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel": medium_sel,
            "standard_sel": standard_sel,
            "codec_sel": codec_sel,
            "audiocodec_sel": audiocodec_sel,
            "team_sel": team_sel,
            "uplver": uplver,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/ydy_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper

def yiptba_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    tags=[]
    time_out=40
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        select_type='405'
        logger.info('已成功填写类型为动漫') 
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'
        logger.info('已成功填写类型为综艺')                
    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
        logger.info('已成功填写类型为剧集')          
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
        logger.info('已成功填写类型为电影')                   
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='404'
        logger.info('已成功填写类型为纪录片')          
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='406'
        logger.info('已成功填写类型为MV')          
    elif 'sport' in file1.pathinfo.type.lower():
        select_type='407'
        logger.info('已成功填写类型为体育')          
    elif 'music' in file1.pathinfo.type.lower():
        select_type='411'
        logger.info('已成功填写类型为音乐')          
    else:
        select_type='405'
        logger.info('已成功填写类型为其它')          
        




    #选择来源
    if 'WEB' in file1.source.upper():
        source_sel='23'
        logger.info('已成功选择来源为WEB-DL')  
    elif 'UHD' in file1.source.upper() and 'DIY' in file1.source.upper():
        source_sel='17'
        logger.info('已成功选择来源为UHD-BLURAY DIY')         
    elif 'UHD' in file1.source.upper():
        source_sel='16'
        logger.info('已成功选择来源为UHD-BLURAY')        
    elif 'BLU' in file1.source.upper() and 'DIY' in file1.source.upper():
        source_sel='19'
        logger.info('已成功选择来源为BLURAY DIY') 
    elif 'BLU' in file1.source.upper():
        source_sel='1'
        logger.info('已成功选择来源为BLURAY')         
    elif 'ENCODE' in file1.source.upper():
        source_sel='22'
        logger.info('已成功选择来源为ENCODE')         
    elif 'HDTV' in file1.source.upper():
        source_sel='4'
        logger.info('已成功选择来源为HDTV')         
    elif 'REMUX' in file1.source.upper():
        source_sel='20'
        logger.info('已成功选择来源为REMUX')         
    else:
        source_sel='6'
        logger.info('已成功选择来源为其它') 

    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='0'
        logger.info('已成功选择媒介为WEB-DL')        
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='17'
        logger.info('已成功选择媒介为UHD-BLURAY DIY')         
    elif 'UHD' in file1.type.upper():
        medium_sel='16'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel='19'
        logger.info('已成功选择媒介为BLURAY DIY') 
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')        
    else:
        medium_sel='0'
        logger.info('未识别到媒介信息，不选择媒介')


    #选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')
    elif 'x' in file1.Video_Format.lower() and '264' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')     
    elif 'AVC' in file1.Video_Format:
        codec_sel='1'
        logger.info('已成功选择编码为H264/AVC')                
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel='18'
        logger.info('已成功选择编码为H265/HEVC')
    elif 'x' in file1.Video_Format.lower() and '265' in file1.Video_Format:
        codec_sel='18'
        logger.info('已成功选择编码为H265/HEVC')    
    elif 'HEVC' in file1.Video_Format.upper():
        codec_sel='18'
        logger.info('已成功选择编码为H265/HEVC')                
    elif 'MPEG' in file1.Video_Format.upper():
        codec_sel='4'
        logger.info('已成功选择编码为MPEG')          
    elif 'VC' in file1.Video_Format.upper():
        codec_sel='2'
        logger.info('已成功选择编码为VC1')          
    elif 'XVID' in file1.Video_Format.upper():
        codec_sel='3'
        logger.info('已成功选择编码为XVID')          
    else:
        codec_sel='0'
        logger.info('未识别到视频编码信息，不选择')  


    #选择音频编码
    if file1.Audio_Format=='AAC':
        audiocodec_sel='6'
    elif 'DTS-HDMA' in file1.Audio_Format.upper() or 'DTS-HD MA' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'AutoTransferMachineOS' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'TRUE' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'FLAC' in file1.Audio_Format.upper():
        audiocodec_sel='1'
    elif 'APE' in file1.Audio_Format.upper():
        audiocodec_sel='2'
    elif 'MP3' in file1.Audio_Format.upper():
        audiocodec_sel='4'
    elif 'EAC3' in file1.Audio_Format.upper() or 'EAC-3' in file1.Audio_Format.upper() or 'DDP' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'AC3' in file1.Audio_Format.upper() or 'AC-3' in file1.Audio_Format.upper() or 'DD' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'DTS' in file1.Audio_Format.upper():
        audiocodec_sel='3'
    elif 'WAV' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'OGG' in file1.Audio_Format.upper():
        audiocodec_sel='5'
    elif 'OPUS' in file1.Audio_Format.upper():
        audiocodec_sel='7'
    elif 'AAC' in file1.Audio_Format.upper():
        audiocodec_sel='6'
    else:
        audiocodec_sel='7'
    logger.info('已成功选择音频编码')

    #选择分辨率
    if '8K' in file1.standard_sel :
        standard_sel='17'
    elif '2160' in file1.standard_sel or '4K' in file1.standard_sel :
        standard_sel='16'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='2'
    elif '720' in file1.standard_sel:
        standard_sel='3'
    elif 'SD' in file1.standard_sel:
        standard_sel='4'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率')
    
    #选择处理
    if 'ENCODE' in file1.type.upper():
        processing_sel='2'
    else:
        processing_sel='1'

    #选择标签
    if 'HDR10+' in file1.pathinfo.tags:
        tags.append(22)
        logger.info('已选择HDR10+标签')
    elif 'HDR10' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '杜比' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(21)
        logger.info('已选择杜比视界标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')            
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
        logger.info('已选择国语标签')
    if '粤' in file1.language:
        tags.append(19)
        logger.info('已选择粤语标签')
    if not file1.sublan=='' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(6)
        logger.info('已选择中字标签')

    
    tags=list(set(tags))
    tags.sort()
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,
            "pt_gen": file1.doubanurl,
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.pathinfo.contenthead+'\n'+file1.douban_info+'\n'+file1.screenshoturl+'\n'+file1.pathinfo.contenttail,
            "technical_info": file1.mediainfo,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "source_sel[4]": source_sel,
            "standard_sel[4]": standard_sel,
            "codec_sel[4]": codec_sel,
            "audiocodec_sel[4]": audiocodec_sel,
            "processing_sel[4]": processing_sel,
            "uplver": uplver,
            "tags[4][]": tags,
            }

    scraper=cloudscraper.create_scraper()
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0
    
    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/yiptba_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper
from bs4 import BeautifulSoup


def get_token(cookie):
    headers = {
        'authority': 'zhuque.in',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cookie': cookie,
        'origin': 'https://zhuque.in',
        'referer': 'https://zhuque.in/torrent/upload',
        'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54',
    }
    scraper = cloudscraper.create_scraper()
    r = scraper.get('https://zhuque.in/index', headers=headers)
    soup = BeautifulSoup(r.text, 'lxml')
    res = soup.find_all('meta', {'name': 'x-csrf-token'})
    if len(res) <= 0:
        return ''
    if not 'content' in res[0].attrs:
        return ''
    return res[0].attrs['content']


def zhuque_upload(siteinfo, file1, record_path, qbinfo, basic, hashlist):
    url = siteinfo.url
    post_url = f"{url}api/torrent/upload"
    tags = []
    time_out = 40
    if (file1.pathinfo.type == 'anime' or file1.pathinfo.type == 'tv') and file1.pathinfo.collection == 0:
        fileinfo = file1.chinesename + '在' + siteinfo.sitename + '第' + file1.episodename + '集'
    else:
        fileinfo = file1.chinesename + '在' + siteinfo.sitename

    # 选择类型
    if 'anime' in file1.pathinfo.type.lower() and "完结" in file1.pathinfo.tags:
        select_type = '503'
        tmdbtype = "1"
    elif 'anime' in file1.pathinfo.type.lower():
        select_type = '503'
        tmdbtype = "0"
    elif 'doc' in file1.pathinfo.type.lower() and "完结" in file1.pathinfo.tags:
        select_type = '503'
        tmdbtype = "1"
    elif 'doc' in file1.pathinfo.type.lower():
        select_type = '503'
        tmdbtype = "0"
    elif 'show' in file1.pathinfo.type.lower():
        select_type = '504'
        tmdbtype = "1"
    elif 'tv' in file1.pathinfo.type.lower():
        select_type = '502'
        tmdbtype = "1"
    elif 'movie' in file1.pathinfo.type.lower():
        select_type = '501'
        tmdbtype = "0"
    else:
        select_type = '599'
        tmdbtype = "0"
    logger.info('已成功填写类型为' + file1.pathinfo.type)

    # 填写TMDB评分
    tmdbid = file1.pathinfo.tmdb_id
    logger.info('TMDBID为' + str(file1.pathinfo.tmdb_id))

    # 选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel = '309'
    elif 'UHD' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel = '302'
    elif 'UHD' in file1.type.upper():
        medium_sel = '301'
    elif 'BLU' in file1.type.upper() and 'DIY' in file1.type.upper():
        medium_sel = '303'
    elif 'BLU' in file1.type.upper():
        medium_sel = '304'
    elif 'REMUX' in file1.type.upper():
        medium_sel = '305'
    elif 'HDTV' in file1.type.upper() and '2160' in file1.standard_sel:
        medium_sel = '307'
    elif 'HDTV' in file1.type.upper():
        medium_sel = '308'
    elif 'ENCODE' in file1.type.upper():
        medium_sel = '306'
    else:
        medium_sel = '399'
    logger.info('已成功选择媒介为' + file1.type)

    # 选择编码
    if 'H' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel = '101'
    elif 'X' in file1.Video_Format.upper() and '264' in file1.Video_Format:
        codec_sel = '103'
    elif 'X' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel = '104'
    elif 'H' in file1.Video_Format.upper() and '265' in file1.Video_Format:
        codec_sel = '102'
    else:
        codec_sel = '105'
    logger.info('已成功选择编码为' + file1.Video_Format)

    # 选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel = '499'
    elif '2160' in file1.standard_sel:
        standard_sel = '404'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel = '403'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel = '402'
    elif '720' in file1.standard_sel:
        standard_sel = '401'
    elif '480' in file1.standard_sel:
        standard_sel = '499'
    else:
        standard_sel = '499'
    logger.info('已成功选择分辨率为' + file1.standard_sel)

    if 'ZHUQUE' in file1.sub.upper():
        tags.append(601)
        logger.info('已选择官方')
    if 'zhuque' in file1.pathinfo.exclusive:
        tags.append(602)
        logger.info('已选择禁转')
    if '国' in file1.language or '中' in file1.language:
        tags.append(603)
        logger.info('已选择国语')
    if not file1.sublan == '' and ('简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan):
        tags.append(604)
        logger.info('已选择中字')
    if '杜比' in file1.pathinfo.tags or 'DV' in file1.pathinfo.tags or 'Dolby' in file1.pathinfo.tags or 'DOLBY' in file1.pathinfo.tags:
        tags.append(611)
        logger.info('已选择Dovi')
    if 'HDR' in file1.pathinfo.tags:
        tags.append(613)
        logger.info('已选择HDR')

    tags = list(set(tags))
    tags.sort()
    tags = [str(titem) for titem in tags]
    if siteinfo.uplver == 1:
        uplver = 'true'
    else:
        uplver = 'false'

    torrent_file = file1.torrentpath
    file_tup = ("torrent", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
    token = get_token(siteinfo.cookie)
    if token == '' and siteinfo.token == '':
        return False, fileinfo + ' 发布种子发生错误,错误信息:朱雀缺少站点token信息，请联系站点/莫与解决'
    elif token == '':
        token = siteinfo.token
    headers = {
        'authority': 'zhuque.in',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cookie': siteinfo.cookie,
        'origin': 'https://zhuque.in',
        'referer': 'https://zhuque.in/torrent/upload',
        'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54',
        'x-csrf-token': token,
    }
    other_data = {
        "title": file1.uploadname,
        "subtitle": file1.small_descr + file1.pathinfo.exinfo,
        "screenshot": file1.screenshoturl.replace('[img]', '').replace('[/img]', ''),
        "mediainfo": file1.mediainfo,
        "category": select_type,
        "medium": medium_sel,
        "videoCoding": codec_sel,
        "resolution": standard_sel,
        "anonymous": uplver,
        "tags": ','.join(tags),
        "tmdbtype": tmdbtype,
        "tmdbid": tmdbid,
        "note": '转自' + file1.pathinfo.sub + ',感谢原作者发布',
    }
    scraper = cloudscraper.create_scraper()
    success_upload = 0
    try_upload = 0
    while success_upload == 0:
        try_upload += 1
        if try_upload > 5:
            return False, fileinfo + ' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = scraper.post(post_url, headers=headers, data=other_data, files=file_tup, timeout=time_out)
            success_upload = 1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' % (r))
            success_upload = 0

    return afterupload(r, fileinfo, record_path, siteinfo, file1, qbinfo, hashlist)
utils/uploader/zhuque_upload.py
Ethan930717/AutoTransferMachine
from loguru import logger
import requests
import time
import os
from utils.uploader.upload_tools import *
import re
import cloudscraper


def zmpt_upload(siteinfo,file1,record_path,qbinfo,basic,hashlist):
    url = siteinfo.url
    post_url = f"{url}takeupload.php"
    time_out=40
    tags=[]
    if (file1.pathinfo.type=='anime' or file1.pathinfo.type=='tv') and file1.pathinfo.collection==0:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename+'第'+file1.episodename+'集'
    else:
        fileinfo=file1.chinesename+'在'+siteinfo.sitename


    #选择类型
    if 'anime' in file1.pathinfo.type.lower():
        if not file1.country=='':
            if '大陆' in file1.country:
                select_type='417'
                logger.info('国家信息已选择'+file1.country)
            elif '香港' in file1.country:
                select_type='417'
                logger.info('国家信息已选择'+file1.country)
            elif '台湾' in file1.country:
                select_type='417'
                logger.info('国家信息已选择'+file1.country)
            elif '美国' in file1.country:
                select_type='420'
                logger.info('国家信息已选择'+file1.country)
            elif '英国' in file1.country:
                select_type='420'
                logger.info('国家信息已选择'+file1.country)
            elif '法国' in file1.country:
                select_type='420'
                logger.info('国家信息已选择'+file1.country)
            elif '韩国' in file1.country:
                select_type='419'
                logger.info('国家信息已选择'+file1.country)
            elif '日本' in file1.country:
                select_type='418'
                logger.info('国家信息已选择'+file1.country)
            elif '印度' in file1.country:
                select_type='421'
                logger.info('国家信息已选择'+file1.country)
            else:
                select_type='421'
                logger.info('未找到资源国家信息，已选择其他')
        else:
            select_type='418'
    elif 'show' in file1.pathinfo.type.lower():
        select_type='403'            

    elif 'tv' in file1.pathinfo.type.lower():
        select_type='402'
    elif 'movie' in file1.pathinfo.type.lower():
        select_type='401'
    elif 'doc' in file1.pathinfo.type.lower():
        select_type='422'
    elif 'mv' in file1.pathinfo.type.lower():
        select_type='423'
    elif 'music' in file1.pathinfo.type.lower():
        select_type='423'
    else:
        select_type='401'
    logger.info('已成功填写类型为'+file1.pathinfo.type)



    #选择媒介
    if 'WEB' in file1.type.upper():
        medium_sel='10'
        logger.info('已成功选择媒介为WEB-DL')               
    elif 'UHD' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为UHD-BLURAY')        
    elif 'BLU' in file1.type.upper():
        medium_sel='1'
        logger.info('已成功选择媒介为BLURAY')         
    elif 'ENCODE' in file1.type.upper():
        medium_sel='7'
        logger.info('已成功选择媒介为ENCODE')        
    elif 'HDTV' in file1.type.upper():
        medium_sel='5'
        logger.info('已成功选择媒介为HDTV')        
    elif 'REMUX' in file1.type.upper():
        medium_sel='3'
        logger.info('已成功选择媒介为REMUX')
    elif 'DVDR' in file1.type.upper():
        medium_sel='6'
        logger.info('已成功选择媒介为DVDR')   
    elif 'DVD' in file1.type.upper():
        medium_sel='2'
        logger.info('已成功选择媒介为DVD')
    elif 'BD' in file1.type.upper():
        medium_sel='4'
        logger.info('已成功选择媒介为MiniBD')           
    else:
        medium_sel='7'
        logger.info('未识别到媒介信息，不选择媒介')    

    #选择分辨率
    if '8K' in file1.standard_sel:
        standard_sel='9'
    elif '2160' in file1.standard_sel:
        standard_sel='5'
    elif '1080p' in file1.standard_sel.lower():
        standard_sel='1'
    elif '1080i' in file1.standard_sel.lower():
        standard_sel='1'
    elif '720' in file1.standard_sel:
        standard_sel='8'
    elif '480' in file1.standard_sel:
        standard_sel='7'
    else:
        standard_sel='1'
    logger.info('已成功选择分辨率为'+file1.standard_sel)
    

    #选择制作组
    if 'ZmPT' in file1.sub.upper():
        team_sel='6'
    elif 'ZmWeb' in file1.sub.upper():
        team_sel='7'
    else:
        team_sel='5'
    logger.info('制作组已成功选择为'+file1.sub)

    if 'zmpt' in file1.pathinfo.exclusive :
        tags.append(1)
    if 'ZMPT' in file1.sub.upper() or 'ZMWEB' in file1.sub.upper():
        tags.append(3)
    if '国' in file1.language or '中' in file1.language:
        tags.append(5)
    if '简' in file1.sublan or '繁' in file1.sublan or '中' in file1.sublan or '中' in file1.pathinfo.tags:
        tags.append(6)
    if 'HDR' in file1.pathinfo.tags:
        tags.append(7)
        logger.info('已选择HDR10标签')
    if '完结' in file1.pathinfo.tags:
        tags.append(12)
        logger.info('已选择完结标签')
    if 'DIY' in file1.pathinfo.tags:
        tags.append(4)
        logger.info('已选择DIY标签')   
    
    
    if siteinfo.uplver==1:
        uplver='yes'
    else:
        uplver='no'

    torrent_file = file1.torrentpath
    file_tup = ("file", (os.path.basename(torrent_file), open(torrent_file, 'rb'), 'application/x-bittorrent')),
            

    other_data = {
            "name": file1.uploadname,
            "small_descr": file1.small_descr+file1.pathinfo.exinfo,
            "url": file1.imdburl,            
            "pt_gen": file1.doubanurl,
            "price": "",
            "color": "0",
            "font": "0",
            "size": "0",
            "descr": file1.content,
            "type": select_type,
            "medium_sel[4]": medium_sel,
            "standard_sel[4]": standard_sel,
            "team_sel[4]": team_sel,
            "codec_sel[4]": "7",
            "uplver": uplver,
            "tags[4][]": tags,
            }
    scraper=cloudscraper.create_scraper()
    headers = {
        'host': 'zmpt.cc',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'max-age=0',
        'cookie': siteinfo.cookie,
        'origin': 'https://zmpt.cc',
        'referer': 'https://zmpt.cc/upload.php',
        'sec-ch-ua': '"Microsoft Edge";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.0.0',
    } 
    
    success_upload=0
    try_upload=0
    while success_upload==0:
        try_upload+=1
        if try_upload>5:
            return False,fileinfo+' 发布种子发生请求错误,请确认站点是否正常运行'
        logger.info('正在发布种子')
        try:
            r = requests.post(post_url, headers=headers,cookies=cookies_raw2jar(siteinfo.cookie),data=other_data, files=file_tup,timeout=time_out)
            success_upload=1
        except Exception as r:
            logger.warning('发布种子发生错误: %s' %(r))
            success_upload=0

    return afterupload(r,fileinfo,record_path,siteinfo,file1,qbinfo,hashlist)
utils/uploader/zmpt_upload.py
Ethan930717/AutoTransferMachine