From 4aa1c22c25b3cabd25da94d9a4aee18ba05f959b Mon Sep 17 00:00:00 2001 From: ikun Date: Fri, 20 Sep 2024 20:02:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/check.py | 36 +++++++++++++++++++----------------- common/get_manifest_info.py | 2 +- common/init_text.py | 2 +- common/main_func.py | 22 +++++++++++++--------- common/manifest_down.py | 13 ++++++------- common/migration.py | 36 +++++++++++++++++++++++------------- common/st_unlock.py | 2 +- main.py | 10 +++++++--- 8 files changed, 71 insertions(+), 52 deletions(-) diff --git a/common/check.py b/common/check.py index f6053c3..7da56d1 100644 --- a/common/check.py +++ b/common/check.py @@ -1,26 +1,28 @@ -import os import time +import ujson as json +from aiohttp import ClientError from .log import log +from .stack_error import stack_error + async def check_github_api_rate_limit(headers, session): - url = 'https://api.github.com/rate_limit' + try: + url = 'https://api.github.com/rate_limit' - async with session.get(url, headers=headers, ssl=False) as r: - if not r == None: + async with session.get(url, headers=headers, ssl=False) as r: r_json = await r.json() - else: - log.error('孩子,你怎么做到的?') - os.system('pause') - if r.status == 200: - rate_limit = r_json['rate'] - remaining_requests = rate_limit['remaining'] - reset_time = rate_limit['reset'] - reset_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(reset_time)) - log.info(f' 🔄 剩余请求次数: {remaining_requests}') - else: - log.error('Github请求数检查失败') + if r.status == 200: + rate_limit = r_json['rate'] + remaining_requests = rate_limit['remaining'] + reset_time = rate_limit['reset'] + reset_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(reset_time)) + log.info(f' 🔄 剩余请求次数: {remaining_requests}') + else: + log.error('⚠ Github请求数检查失败,网络错误') - if remaining_requests == 0: - log.warning(f' ⚠ GitHub API 请求数已用尽,将在 {reset_time_formatted} 重置, 不想等生成一个填配置文件里') \ No newline at end of file + if remaining_requests == 0: + log.warning(f'⚠ GitHub API 请求数已用尽,将在 {reset_time_formatted} 重置, 不想等生成一个填配置文件里') + except ClientError as e: + log.error(f'⚠ 检查Github API 请求数失败,{stack_error(e)}') \ No newline at end of file diff --git a/common/get_manifest_info.py b/common/get_manifest_info.py index ed5b716..ce16698 100644 --- a/common/get_manifest_info.py +++ b/common/get_manifest_info.py @@ -6,7 +6,7 @@ from .log import log from .manifest_down import get from .stack_error import stack_error -# 获取清单信息 + async def get_manifest(sha, path, steam_path: Path, repo, session): collected_depots = [] try: diff --git a/common/init_text.py b/common/init_text.py index e9584f6..b2fd17e 100644 --- a/common/init_text.py +++ b/common/init_text.py @@ -13,7 +13,7 @@ def init(): print(f"{Fore.GREEN}{Back.BLACK}{Style.BRIGHT} \\_____/ |_| \\_| |_____| |_| \\_\\ |_____| /_/{Style.RESET_ALL}") log.info('作者ikun0014') log.info('本项目采用GNU General Public License v3开源许可证') - log.info('版本:1.2.1') + log.info('版本:1.2.2') log.info('项目仓库:https://github.com/ikunshare/Onekey') log.info('官网:ikunshare.com') log.warning('本项目完全开源免费,如果你在淘宝,QQ群内通过购买方式获得,赶紧回去骂商家死全家\n交流群组:\nhttps://qm.qq.com/q/d7sWovfAGI\nhttps://t.me/ikunshare_group') diff --git a/common/main_func.py b/common/main_func.py index 06edc87..82e3b55 100644 --- a/common/main_func.py +++ b/common/main_func.py @@ -18,16 +18,18 @@ isSteamTools = (steam_path / 'config' / 'stUI').is_dir() async def main(app_id, repos): app_id_list = list(filter(str.isdecimal, app_id.strip().split('-'))) - app_id = app_id_list[0] + if not app_id_list: + log.error(f'⚠ App ID无效') + return False + else: + app_id = app_id_list[0] async with ClientSession() as session: github_token = config["Github_Personal_Token"] headers = {'Authorization': f'Bearer {github_token}'} if github_token else None latest_date = None selected_repo = None - await check_github_api_rate_limit(headers, session) - for repo in repos: url = f'https://api.github.com/repos/{repo}/branches/{app_id}' try: @@ -39,7 +41,8 @@ async def main(app_id, repos): latest_date = date selected_repo = repo except Exception as e: - log.error(f' ⚠ 获取分支信息失败: {stack_error(e)}') + log.error(f'⚠ 获取分支信息失败: {stack_error(e)}') + if selected_repo: log.info(f' 🔄 选择清单仓库:{selected_repo}') url = f'https://api.github.com/repos/{selected_repo}/branches/{app_id}' @@ -61,16 +64,17 @@ async def main(app_id, repos): await stool_add(collected_depots, app_id) log.info(' ✅ 找到SteamTools,已添加解锁文件') if isGreenLuma: - migrate(st_use=False) + await migrate(st_use=False, session=session) await greenluma_add([app_id]) depot_config = {'depots': {depot_id: {'DecryptionKey': depot_key} for depot_id, depot_key in collected_depots}} await depotkey_merge(steam_path / 'config' / 'config.vdf', depot_config) if await greenluma_add([int(i) for i in depot_config['depots'] if i.isdecimal()]): - log.info(' ✅ 找到GreenLuma,已添加解锁文件') - log.info(f' ✅ 清单最后更新时间:{date}') - log.info(f' ✅ 入库成功: {app_id}') + log.info('✅ 找到GreenLuma,已添加解锁文件') + log.info(f'✅ 清单最后更新时间:{date}') + log.info(f'✅ 入库成功: {app_id}') os.system('pause') return True - log.error(f' ⚠ 清单下载或生成失败: {app_id}') + + log.error(f'⚠ 清单下载或生成失败: {app_id}') os.system('pause') return False \ No newline at end of file diff --git a/common/manifest_down.py b/common/manifest_down.py index 32acbfa..a374298 100644 --- a/common/manifest_down.py +++ b/common/manifest_down.py @@ -8,7 +8,7 @@ async def get(sha, path, repo, session): url_list = [ f'https://cdn.jsdmirror.com/gh/{repo}@{sha}/{path}', f'https://jsd.onmicrosoft.cn/gh/{repo}@{sha}/{path}', - # f'https://mirror.ghproxy.com/https://raw.githubusercontent.com/{repo}/{sha}/{path}', + f'https://raw.dgithub.xyz/{repo}/{sha}/{path}', f'https://raw.githubusercontent.com/{repo}/{sha}/{path}', ] retry = 3 @@ -25,13 +25,12 @@ async def get(sha, path, repo, session): async for chunk in r.content.iter_chunked(chunk_size): content.extend(chunk) pbar.update(len(chunk)) - return content else: - log.error(f' 🔄 获取失败: {path} - 状态码: {r.status}') + log.error(f'🔄 获取失败: {path} - 状态码: {r.status}') except ClientError: - log.error(f' 🔄 获取失败: {path} - 连接错误') + log.error(f'🔄 获取失败: {path} - 连接错误') retry -= 1 - log.warning(f' 🔄 重试剩余次数: {retry} - {path}') - log.error(f' 🔄 超过最大重试次数: {path}') - raise Exception(f' 🔄 无法下载: {path}') + log.warning(f'🔄 重试剩余次数: {retry} - {path}') + log.error(f'🔄 超过最大重试次数: {path}') + raise Exception(f'🔄 无法下载: {path}') diff --git a/common/migration.py b/common/migration.py index 9475863..b37999c 100644 --- a/common/migration.py +++ b/common/migration.py @@ -1,21 +1,22 @@ import os import subprocess -import requests - +import aiofiles from pathlib import Path +from tqdm.asyncio import tqdm + from .log import log from .get_steam_path import steam_path directory = Path(steam_path / "config" / "stplug-in") -def migrate(st_use): +async def migrate(st_use, session): if st_use == True: - log.info('检测到你正在使用SteamTools,尝试迁移旧文件') + log.info('🔄 检测到你正在使用SteamTools,尝试迁移旧文件') if os.path.exists(directory): for filename in os.listdir(directory): if filename.startswith("Onekey_unlock_"): new_filename = filename[len("Onekey_unlock_"):] - + old_file = os.path.join(directory, filename) new_file = os.path.join(directory, new_filename) @@ -25,20 +26,29 @@ def migrate(st_use): except Exception as e: log.error(f'Failed to rename {filename} -> {new_filename}: {e}') else: - log.error('故障,正在重新安装SteamTools') + log.error('⚠ 故障,正在重新安装SteamTools') temp_path = './temp' if not os.path.exists(temp_path): os.mkdir(temp_path) down_url = 'https://steamtools.net/res/SteamtoolsSetup.exe' out_path = './temp/SteamtoolsSetup.exe' - with requests.get(down_url, stream=True) as r: - if r.status_code == 200: - with open(out_path, 'wb') as f: - for chunk in r.iter_content(chunk_size=8192): - f.write(chunk) + + async with session.get(down_url, stream=True) as r: + if r.status == 200: + total_size = int(r.headers.get('Content-Length', 0)) + chunk_size = 8192 + progress = tqdm(total=total_size, unit='B', unit_scale=True) + + async with aiofiles.open(out_path, mode='wb') as f: + async for chunk in r.content.iter_chunked(chunk_size=chunk_size): + await f.write(chunk) + progress.update(len(chunk)) + + progress.close() else: - log.error('网络错误') + log.error('⚠ 网络错误') + subprocess.run(str(out_path)) os.rmdir(temp_path) else: - log.info('未使用SteamTools,停止迁移') \ No newline at end of file + log.info('✅ 未使用SteamTools,停止迁移') diff --git a/common/st_unlock.py b/common/st_unlock.py index a92f9a2..def4464 100644 --- a/common/st_unlock.py +++ b/common/st_unlock.py @@ -13,7 +13,7 @@ async def stool_add(depot_data, app_id): lua_filepath = steam_path / "config" / "stplug-in" / lua_filename async with lock: - log.info(f' ✅ SteamTools解锁文件生成: {lua_filepath}') + log.info(f'✅ SteamTools解锁文件生成: {lua_filepath}') async with aiofiles.open(lua_filepath, mode="w", encoding="utf-8") as lua_file: await lua_file.write(f'addappid({app_id}, 1, "None")\n') for depot_id, depot_key in depot_data: diff --git a/main.py b/main.py index 54d031b..71743c1 100644 --- a/main.py +++ b/main.py @@ -2,6 +2,8 @@ import os import time import asyncio +from colorama import Fore, Back, Style +from colorama import init as cinit from common.log import log from common.stack_error import stack_error from common.init_text import init @@ -10,17 +12,19 @@ from common.main_func import main lock = asyncio.Lock() init() +cinit() repos = [ 'ikun0014/ManifestHub', 'Auiowu/ManifestAutoUpdate', - 'tymolu233/ManifestAutoUpdate' + 'tymolu233/ManifestAutoUpdate', ] + if __name__ == '__main__': try: + log.info('❗ App ID可以在SteamDB或Steam商店链接页面查看') while True: - log.info('App ID可以在SteamDB或Steam商店链接页面查看') - app_id = input("请输入游戏AppID:").strip() + app_id = input(f"{Fore.CYAN}{Back.BLACK}{Style.BRIGHT}🤔 请输入游戏AppID:{Style.RESET_ALL}").strip() asyncio.run(main(app_id, repos)) except KeyboardInterrupt: exit()