feat: Actions自动编译&&代码工整性

This commit is contained in:
ikun
2024-09-15 16:10:41 +08:00
parent 7c75628966
commit 98ce0c091a
15 changed files with 232 additions and 179 deletions

54
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: Build
on:
push:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
# Push tag to GitHub if package.json version's tag is not tagged
- name: Get package version
run: node -p -e '`PACKAGE_VERSION=${require("./package.json").version}`' >> $GITHUB_ENV
- name: Set up Python 3.11
uses: actions/setup-python@v3
with:
python-version: 3.11.9
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Build
uses: Nuitka/Nuitka-Action@main
with:
nuitka-version: main
script-name: main.py
standalone: true
onefile: true
show-memory: true
windows-uac-admin: true
windows-icon-from-ico: icon.jpg
windows-company-name: ikunshare
windows-product-name: Onekey
windows-file-version: ${{ env.PACKAGE_VERSION }}
windows-product-version: ${{ env.PACKAGE_VERSION }}
windows-file-description: 一个Steam仓库清单下载器
output-file: Onekey---v${{ env.PACKAGE_VERSION }}.exe
- name: Release
uses: softprops/action-gh-release@v2
with:
prerelease: false
draft: false
tag_name: v${{ env.PACKAGE_VERSION }}
files: |
Onekey---v${{ env.PACKAGE_VERSION }}.exe
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

26
common/check.py Normal file
View File

@@ -0,0 +1,26 @@
from .log import log
import os
import time
async def check_github_api_rate_limit(headers, session):
url = 'https://api.github.com/rate_limit'
async with session.get(url, headers=headers, ssl=False) as r:
if not r == None:
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 remaining_requests == 0:
log.warning(f' ⚠ GitHub API 请求数已用尽,将在 {reset_time_formatted} 重置, 不想等生成一个填配置文件里')

View File

@@ -1,12 +1,12 @@
import ujson as json
import aiofiles
from .stack_error import stack_error
from .log import log
import ujson as json
import aiofiles
import os
import sys
import asyncio
# 生成配置文件
async def gen_config_file():
default_config ={
"Github_Personal_Token": "",
@@ -21,7 +21,6 @@ async def gen_config_file():
log.info(' 🖱️ 程序可能为第一次启动,请填写配置文件后重新启动程序')
# 加载配置文件
async def load_config():
if not os.path.exists('./config.json'):
await gen_config_file()

View File

@@ -1,7 +1,8 @@
from .log import log
import asyncio
import aiofiles
import vdf
from .log import log
lock = asyncio.Lock()

View File

@@ -0,0 +1,35 @@
from .log import log
from .manifest_down import get
from .stack_error import stack_error
import aiofiles
import vdf
from pathlib import Path
# 获取清单信息
async def get_manifest(sha, path, steam_path: Path, repo, session):
collected_depots = []
try:
if path.endswith('.manifest'):
depot_cache_path = steam_path / 'depotcache'
if not depot_cache_path.exists():
depot_cache_path.mkdir(exist_ok=True)
save_path = depot_cache_path / path
if save_path.exists():
log.warning(f'👋已存在清单: {path}')
return collected_depots
content = await get(sha, path, repo, session)
log.info(f' 🔄 清单下载成功: {path}')
async with aiofiles.open(save_path, 'wb') as f:
await f.write(content)
elif path == 'Key.vdf':
content = await get(sha, path, repo, session)
log.info(f' 🔄 密钥下载成功: {path}')
depots_config = vdf.loads(content.decode(encoding='utf-8'))
for depot_id, depot_info in depots_config['depots'].items():
collected_depots.append((depot_id, depot_info['DecryptionKey']))
except Exception as e:
log.error(f'处理失败: {path} - {stack_error(e)}')
raise
return collected_depots

View File

@@ -1,11 +1,11 @@
import winreg
import os
from .log import log
from .config import config
from .stack_error import stack_error
from pathlib import Path
# 通过注册表获取Steam安装路径
import winreg
import os
def get_steam_path():
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Valve\Steam')

View File

@@ -1,6 +1,5 @@
from .getsteampath import steam_path
from .get_steam_path import steam_path
# 增加GreenLuma解锁相关文件
async def greenluma_add(depot_id_list):
app_list_path = steam_path / 'AppList'
if app_list_path.exists() and app_list_path.is_file():
@@ -26,6 +25,4 @@ async def greenluma_add(depot_id_list):
with (app_list_path / f'{index}.txt').open('w', encoding='utf-8') as f:
f.write(str(depot_id))
depot_dict[index] = int(depot_id)
return True
glunlock = greenluma_add
return True

15
common/init_text.py Normal file
View File

@@ -0,0 +1,15 @@
from .log import log
def init():
print('\033[1;32;40m _____ __ _ _____ _ _ _____ __ __ ' + '\033[0m')
print('\033[1;32;40m / _ \\ | \\ | | | ____| | | / / | ____| \\ \\ / /' + '\033[0m')
print('\033[1;32;40m | | | | | \\| | | |__ | |/ / | |__ \\ \\/ /' + '\033[0m')
print('\033[1;32;40m | | | | | |\\ | | __| | |\\ \\ | __| \\ / ' + '\033[0m')
print('\033[1;32;40m | |_| | | | \\ | | |___ | | \\ \\ | |___ / /' + '\033[0m')
print('\033[1;32;40m \\_____/ |_| \\_| |_____| |_| \\_\\ |_____| /_/' + '\033[0m')
log.info('作者ikun0014')
log.info('本项目基于wxy1343/ManifestAutoUpdate进行修改采用ACSL许可证')
log.info('版本1.1.9')
log.info('项目仓库https://github.com/ikunshare/Onekey')
log.info('官网ikunshare.com')
log.warning('本项目完全开源免费如果你在淘宝QQ群内通过购买方式获得赶紧回去骂商家死全家\n交流群组:\n点击链接加入群聊【𝗶𝗸𝘂𝗻分享】https://qm.qq.com/q/d7sWovfAGI\nhttps://t.me/ikunshare_group')

View File

@@ -1,8 +1,6 @@
import colorlog
import logging
# 初始化日志记录器
def init_log():
logger = logging.getLogger('Onekey')
logger.setLevel(logging.DEBUG)

76
common/main_func.py Normal file
View File

@@ -0,0 +1,76 @@
from common.config import config
from common.dkey_merge import depotkey_merge
from common.migration import migrate
from common.st_unlock import stool_add
from common.gl_unlock import greenluma_add
from common.get_manifest_info import get_manifest
from common.check import check_github_api_rate_limit
from common.log import log
from common.get_steam_path import steam_path
from common.stack_error import stack_error
from aiohttp import ClientSession
import os
isGreenLuma = any((steam_path / dll).exists() for dll in ['GreenLuma_2024_x86.dll', 'GreenLuma_2024_x64.dll', 'User32.dll'])
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]
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:
async with session.get(url, headers=headers, ssl=False) as r:
r_json = await r.json()
if 'commit' in r_json:
date = r_json['commit']['commit']['author']['date']
if latest_date is None or date > latest_date:
latest_date = date
selected_repo = repo
except Exception as 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}'
async with session.get(url, headers=headers, ssl=False) as r:
r_json = await r.json()
if 'commit' in r_json:
sha = r_json['commit']['sha']
url = r_json['commit']['commit']['tree']['url']
async with session.get(url, headers=headers, ssl=False) as r2:
r2_json = await r2.json()
if 'tree' in r2_json:
collected_depots = []
for i in r2_json['tree']:
result = await get_manifest(sha, i['path'], steam_path, selected_repo, session)
collected_depots.extend(result)
if collected_depots:
if isSteamTools:
migrate(st_use=True)
await stool_add(collected_depots, app_id)
log.info(' ✅ 找到SteamTools已添加解锁文件')
if isGreenLuma:
migrate(st_use=False)
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}')
os.system('pause')
return True
log.error(f' ⚠ 清单下载或生成失败: {app_id}')
os.system('pause')
return False

View File

@@ -1,7 +1,6 @@
from aiohttp import ClientError
from .log import log
# 下载清单
async def get(sha, path, repo, session):
url_list = [
f'https://cdn.jsdmirror.com/gh/{repo}@{sha}/{path}',

View File

@@ -1,9 +1,10 @@
from .log import log
from .get_steam_path import steam_path
from pathlib import Path
import os
import requests
import subprocess
from .log import log
from .getsteampath import steam_path
from pathlib import Path
directory = Path(steam_path / "config" / "stplug-in")
@@ -19,7 +20,6 @@ def migrate(st_use):
new_file = os.path.join(directory, new_filename)
try:
# 使用 os.replace 进行强制替换
os.replace(old_file, new_file)
log.info(f'Renamed: {filename} -> {new_filename}')
except Exception as e:
@@ -41,7 +41,4 @@ def migrate(st_use):
subprocess.run(str(out_path))
os.rmdir(temp_path)
else:
log.info('未使用SteamTools停止迁移')
migrate = migrate
log.info('未使用SteamTools停止迁移')

View File

@@ -1,15 +1,12 @@
from common import log, getsteampath
from .log import log
from .get_steam_path import steam_path
import asyncio
import aiofiles
import os
import subprocess
lock = asyncio.Lock()
log = log.log
steam_path = getsteampath.steam_path
# 增加SteamTools解锁相关文件
async def stool_add(depot_data, app_id):
lua_filename = f"{app_id}.lua"
lua_filepath = steam_path / "config" / "stplug-in" / lua_filename
@@ -24,6 +21,4 @@ async def stool_add(depot_data, app_id):
luapacka_path = steam_path / "config" / "stplug-in" / "luapacka.exe"
subprocess.run([str(luapacka_path), str(lua_filepath)])
os.remove(lua_filepath)
return True
stunlock = stool_add
return True

View File

@@ -1,8 +1,5 @@
import traceback
# 错误堆栈处理
def stack_error(exception):
stack_trace = traceback.format_exception(type(exception), exception, exception.__traceback__)
return ''.join(stack_trace)
stack_error = stack_error
return ''.join(stack_trace)

150
main.py
View File

@@ -1,152 +1,16 @@
from common.log import log
from common.stack_error import stack_error
from common.init_text import init
from common.main_func import main
import os
import vdf
import aiofiles
import traceback
import time
import asyncio
import time
from common import log, config, getsteampath, stunlock, glunlock, stack_error, manifestdown, dkey_merge, migration
from aiohttp import ClientSession
from pathlib import Path
log = log.log
config = config.config
lock = asyncio.Lock()
steam_path = getsteampath.steam_path
isGreenLuma = any((steam_path / dll).exists() for dll in ['GreenLuma_2024_x86.dll', 'GreenLuma_2024_x64.dll', 'User32.dll'])
isSteamTools = (steam_path / 'config' / 'stUI').is_dir()
stunlock = stunlock.stunlock
glunlock = glunlock.glunlock
stack_error = stack_error.stack_error
get = manifestdown.get
depotkey_merge = dkey_merge.depotkey_merge
migration = migration.migrate
print('\033[1;32;40m _____ __ _ _____ _ _ _____ __ __ ' + '\033[0m')
print('\033[1;32;40m / _ \\ | \\ | | | ____| | | / / | ____| \\ \\ / /' + '\033[0m')
print('\033[1;32;40m | | | | | \\| | | |__ | |/ / | |__ \\ \\/ /' + '\033[0m')
print('\033[1;32;40m | | | | | |\\ | | __| | |\\ \\ | __| \\ / ' + '\033[0m')
print('\033[1;32;40m | |_| | | | \\ | | |___ | | \\ \\ | |___ / /' + '\033[0m')
print('\033[1;32;40m \\_____/ |_| \\_| |_____| |_| \\_\\ |_____| /_/' + '\033[0m')
log.info('作者ikun0014')
log.info('本项目基于wxy1343/ManifestAutoUpdate进行修改采用ACSL许可证')
log.info('版本1.1.9')
log.info('项目仓库https://github.com/ikunshare/Onekey')
log.info('官网ikunshare.com')
log.warning('本项目完全开源免费如果你在淘宝QQ群内通过购买方式获得赶紧回去骂商家死全家\n交流群组:\n点击链接加入群聊【𝗶𝗸𝘂𝗻分享】https://qm.qq.com/q/d7sWovfAGI\nhttps://t.me/ikunshare_group')
# 获取清单信息
async def get_manifest(sha, path, steam_path: Path, repo, session):
collected_depots = []
try:
if path.endswith('.manifest'):
depot_cache_path = steam_path / 'depotcache'
if not depot_cache_path.exists():
depot_cache_path.mkdir(exist_ok=True)
save_path = depot_cache_path / path
if save_path.exists():
log.warning(f'👋已存在清单: {path}')
return collected_depots
content = await get(sha, path, repo, session)
log.info(f' 🔄 清单下载成功: {path}')
async with aiofiles.open(save_path, 'wb') as f:
await f.write(content)
elif path == 'Key.vdf':
content = await get(sha, path, repo, session)
log.info(f' 🔄 密钥下载成功: {path}')
depots_config = vdf.loads(content.decode(encoding='utf-8'))
for depot_id, depot_info in depots_config['depots'].items():
collected_depots.append((depot_id, depot_info['DecryptionKey']))
except Exception as e:
log.error(f'处理失败: {path} - {stack_error(e)}')
traceback.print_exc()
raise
return collected_depots
async def check_github_api_rate_limit(headers, session):
url = 'https://api.github.com/rate_limit'
async with session.get(url, headers=headers, ssl=False) as r:
if not r == None:
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 remaining_requests == 0:
log.warning(f' ⚠ GitHub API 请求数已用尽,将在 {reset_time_formatted} 重置, 不想等生成一个填配置文件里')
# 主函数
async def main(app_id):
app_id_list = list(filter(str.isdecimal, app_id.strip().split('-')))
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
# 检查Github API限额
await check_github_api_rate_limit(headers, session)
for repo in repos:
url = f'https://api.github.com/repos/{repo}/branches/{app_id}'
try:
async with session.get(url, headers=headers, ssl=False) as r:
r_json = await r.json()
if 'commit' in r_json:
date = r_json['commit']['commit']['author']['date']
if latest_date is None or date > latest_date:
latest_date = date
selected_repo = repo
except Exception as e:
log.error(f' ⚠ 获取分支信息失败: {stack_error(e)}')
traceback.print_exc()
if selected_repo:
log.info(f' 🔄 选择清单仓库:{selected_repo}')
url = f'https://api.github.com/repos/{selected_repo}/branches/{app_id}'
async with session.get(url, headers=headers, ssl=False) as r:
r_json = await r.json()
if 'commit' in r_json:
sha = r_json['commit']['sha']
url = r_json['commit']['commit']['tree']['url']
async with session.get(url, headers=headers, ssl=False) as r2:
r2_json = await r2.json()
if 'tree' in r2_json:
collected_depots = []
for i in r2_json['tree']:
result = await get_manifest(sha, i['path'], steam_path, selected_repo, session)
collected_depots.extend(result)
if collected_depots:
if isSteamTools:
migration(st_use=True)
await stunlock(collected_depots, app_id)
log.info(' ✅ 找到SteamTools已添加解锁文件')
if isGreenLuma:
migration(st_use=False)
await glunlock([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 glunlock([int(i) for i in depot_config['depots'] if i.isdecimal()]):
log.info(' ✅ 找到GreenLuma已添加解锁文件')
log.info(f' ✅ 清单最后更新时间:{date}')
log.info(f' ✅ 入库成功: {app_id}')
os.system('pause')
return True
log.error(f' ⚠ 清单下载或生成失败: {app_id}')
os.system('pause')
return False
init()
repos = [
'ikun0014/ManifestHub',
@@ -158,7 +22,7 @@ if __name__ == '__main__':
while True:
log.info('App ID可以在SteamDB或Steam商店链接页面查看')
app_id = input("请输入游戏AppID").strip()
asyncio.run(main(app_id))
asyncio.run(main(app_id, repos))
except KeyboardInterrupt:
exit()
except Exception as e: