Skip to content

Commit

Permalink
Merge pull request #1013 from ywmoyue/dev
Browse files Browse the repository at this point in the history
4.7.14
  • Loading branch information
ywmoyue authored Jan 28, 2025
2 parents 259b976 + 2cb69f4 commit 3e1b285
Show file tree
Hide file tree
Showing 53 changed files with 1,772 additions and 1,119 deletions.
40 changes: 40 additions & 0 deletions .github/workflows/choco.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Pack and Push Chocolatey Package

on:
workflow_dispatch:
inputs:
version:
description: "The version of the package"
required: true
type: string

env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHOCO_TOKEN: ${{ secrets.CHOCO_TOKEN }}

jobs:
pack-and-push:
runs-on: windows-latest

steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.9"

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install requests
- name: Check choco
run: |
choco -v
- name: Run packChoco.py script
run: |
$env:PYTHONUNBUFFERED = "1"
python scripts/packChoco.py --version ${{ github.event.inputs.version }} --githubtoken ${{ env.GITHUB_TOKEN }} --chocotoken ${{ env.CHOCO_TOKEN }}
19 changes: 19 additions & 0 deletions scripts/chocolaty-templates/BiliLite-uwp.nuspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>BiliLite-uwp-{arch}</id>
<version>{version}-beta</version>
<title>BiliLite-uwp</title>
<authors>ruamuyan</authors>
<owners>ruamuyan</owners>
<projectUrl>https://github.com/ywmoyue/biliuwp-lite</projectUrl>
<mailingListUrl>https://github.com/ywmoyue/biliuwp-lite/discussions</mailingListUrl>
<bugTrackerUrl>https://github.com/ywmoyue/biliuwp-lite/discussions</bugTrackerUrl>
<docsUrl>https://github.com/ywmoyue/biliuwp-lite</docsUrl>
<projectSourceUrl>https://github.com/ywmoyue/biliuwp-lite</projectSourceUrl>
<description>Bilibili third-party UWP client third-party release version. Fork from https://github.com/xiaoyaocz/biliuwp-lite.</description>
<summary >Bilibili third-party UWP client third-party release version.</summary >
<iconUrl>https://raw.githubusercontent.com/ywmoyue/biliuwp-lite/refs/heads/master/src/BiliLite.Packages/Images/StoreLogo.scale-400.png</iconUrl>
<tags>UWP BiliBili</tags>
</metadata>
</package>
98 changes: 98 additions & 0 deletions scripts/chocolaty-templates/tools/chocolateyInstall.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Due to Powershell limitations, this script can only be opened with GBK encoding
$AppName = "BiliLite.Packages"
$Version = "{version}"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Output "scriptDir: $scriptDir"

# 获取系统架构
$arch = $env:PROCESSOR_ARCHITECTURE
# 判断架构并赋值
if ($arch -eq "AMD64") {
$systemArch = "x64"
} elseif ($arch -eq "x86") {
$systemArch = "x86"
} elseif ($arch -eq "ARM64") {
$systemArch = "ARM64"
} else {
$systemArch = "Unknown"
}

$Package = "{0}_{1}_{2}" -f $AppName, $Version, $systemArch
Write-Output "Package: $Package"

# 找到对应的安装包并解压到unpack路径
$PackageZipRelativePath = "..\resources\{0}.zip" -f $Package
$PackageZipPath = Join-Path $scriptDir $PackageZipRelativePath
$UnpackPath = Join-Path $scriptDir "..\unpack"

# 检查文件是否存在并解压
if (Test-Path $PackageZipPath) {
# 确保解压路径存在
if (-not (Test-Path $UnpackPath)) {
New-Item -ItemType Directory -Path $UnpackPath | Out-Null
}

# 解压文件
Expand-Archive -Path $PackageZipPath -DestinationPath $UnpackPath -Force
Write-Host "文件已解压到 $UnpackPath"
} else {
Write-Host "文件 $PackageZipPath 不存在,即将从 GitHub 下载当前平台适配的安装包"

# 从 GitHub 下载软件包并解压
$downloadUrl = "https://github.com/ywmoyue/biliuwp-lite/releases/download/v{0}/{1}.zip" -f $Version, $Package
Write-Host "下载地址: $downloadUrl"

try {
# 下载文件
Invoke-WebRequest -Uri $downloadUrl -OutFile $PackageZipPath
Write-Host "文件下载完成: $PackageZipPath"

# 确保解压路径存在
if (-not (Test-Path $UnpackPath)) {
New-Item -ItemType Directory -Path $UnpackPath | Out-Null
}

# 解压文件
Expand-Archive -Path $PackageZipPath -DestinationPath $UnpackPath -Force
Write-Host "文件已解压到 $UnpackPath"
} catch {
Write-Host "下载或解压失败: $_"
exit 1
}
}

# 设置开发者模式允许安装未知来源包
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -Name "AllowDevelopmentWithoutDevLicense" -Value 1
Write-Host "已允许安装未知来源包"

# 证书路径
$certRelativePath = "..\unpack\{0}_Test\{0}.cer" -f $Package
$certPath = Resolve-Path (Join-Path $scriptDir $certRelativePath)

# 安装脚本路径
$installScriptPath = "$scriptDir\..\unpack\{0}_Test\install.ps1" -f $Package
Write-Host "安装路径 $installScriptPath"

# 安装证书
try {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($certPath.Path)

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root", "LocalMachine")
$store.Open("ReadWrite")
$store.Add($cert)
$store.Close()
Write-Host "证书安装完成"
} catch {
Write-Host "证书安装失败: $_"
exit 1
}

# 执行安装脚本
try {
. "$installScriptPath"
Write-Host "安装脚本执行成功"
} catch {
Write-Host "安装脚本执行失败: $_"
exit 1
}
18 changes: 18 additions & 0 deletions scripts/chocolaty-templates/tools/chocolateyUninstall.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Due to Powershell limitations, this script can only be opened with GBK encoding
$PackageId = "5422.502643927C6AD"

$PackageNamePrefix = "{0}_" -f $PackageId
Write-Host "PackageNamePrefix: $PackageNamePrefix"

# 삿혤UWP관供憐츰냔
$PackageFullName = (Get-AppxPackage | Where-Object { $_.PackageFullName -like "$PackageNamePrefix*" }).PackageFullName
Write-Host "PackageFullName: $PackageFullName"

if ($PackageFullName) {
Write-Host "冷돕 UWP 관: $PackageFullName"
# 菌潼 UWP 관
Remove-AppxPackage -Package $PackageFullName
Write-Host "UWP 관綠菌潼"
} else {
Write-Host "灌冷돕튈토돨 UWP 관"
}
159 changes: 159 additions & 0 deletions scripts/packChoco.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import os
import requests
import shutil
import subprocess

# python choco_pack.py --version 4.7.13.1403 --githubtoken YOUR_GITHUB_TOKEN --chocotoken YOUR_CHOCO_TOKEN

def replace_string_in_file(file_path, target_string, replacement_string):
try:
# 根据文件扩展名选择编码
if file_path.endswith('.ps1'):
encoding = 'gbk' # 对于 .ps1 文件,使用 GBK 编码
else:
encoding = 'utf-8' # 对于其他文件,使用 UTF-8 编码

# 读取文件内容
with open(file_path, 'r', encoding=encoding) as file:
file_contents = file.read()

# 替换文件内容中的目标字符串
updated_contents = file_contents.replace(target_string, replacement_string)

# 将更新后的内容写回文件
with open(file_path, 'w', encoding=encoding) as file:
file.write(updated_contents)

print(f"Successfully replaced '{target_string}' with '{replacement_string}' in {file_path}")
except FileNotFoundError:
print(f"The file at {file_path} was not found.")
except IOError as e:
print(f"An IOError occurred: {e.strerror}.")
except UnicodeDecodeError:
print(f"Failed to decode the file {file_path} with {encoding} encoding.")
except UnicodeEncodeError:
print(f"Failed to encode the file {file_path} with {encoding} encoding.")

def download_github_release_asset(tag, github_token, arch, output_dir):
# 获取所有 releases
url = "https://api.github.com/repos/ywmoyue/biliuwp-lite/releases"
headers = {
"Authorization": f"token {github_token}",
"Accept": "application/vnd.github.v3+json"
}

response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to fetch releases. Status code: {response.status_code}")
return False

releases = response.json()

# 根据 tag 查找对应的 release
release_item = None
for release in releases:
if release["tag_name"] == tag:
release_item = release
break

if not release_item:
print(f"Release with tag {tag} not found.")
return False

# 查找匹配的 asset
zip_filename = f"BiliLite.Packages_{tag[1:]}_{arch}.zip"
asset_url = None

for asset in release_item["assets"]:
if asset["name"] == zip_filename:
asset_url = asset["url"]
break

if not asset_url:
print(f"Asset {zip_filename} not found in release {tag}.")
return False

# 下载 asset
headers["Accept"] = "application/octet-stream"
response = requests.get(asset_url, headers=headers, stream=True)
if response.status_code != 200:
print(f"Failed to download asset {zip_filename}. Status code: {response.status_code}")
return False

os.makedirs(output_dir, exist_ok=True)
zip_path = os.path.join(output_dir, zip_filename)
with open(zip_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)

print(f"Downloaded {zip_filename} to {output_dir}")
return True

def process_architecture(arch, version, github_token, chocotoken):
# 定义路径
template_dir = "scripts/chocolaty-templates"
pack_parent_dir = "C:/choco/pack"
pack_dir = f"{pack_parent_dir}/{arch}"
nuspec_file = f"{pack_dir}/BiliLite-uwp.nuspec"
install_script = f"{pack_dir}/tools/chocolateyInstall.ps1"
resources_dir = f"{pack_dir}/resources"

# 复制模板文件夹到目标目录
if not os.path.exists(template_dir):
print(f"Template directory {template_dir} not found.")
return

os.makedirs(pack_parent_dir, exist_ok=True)
shutil.copytree(template_dir, pack_dir, dirs_exist_ok=True)

# 替换 nuspec 文件中的 {version} 和 {arch}
replace_string_in_file(nuspec_file, "{version}", version)
replace_string_in_file(nuspec_file, "{arch}", arch)

# 替换 chocolateyInstall.ps1 文件中的 {version}
replace_string_in_file(install_script, "{version}", version)

# 创建 resources 文件夹
os.makedirs(resources_dir, exist_ok=True)

# 下载 GitHub Release 的 zip 包
tag = f"v{version}"
if not download_github_release_asset(tag, github_token, arch, resources_dir):
print(f"Skipping architecture {arch} due to missing asset.")
return

# 在目标目录下执行 choco pack 命令
try:
subprocess.run(["choco", "pack"], cwd=pack_dir, check=True)
except subprocess.CalledProcessError as e:
print(f"Failed to pack for architecture {arch}. Error: {e}")
return

# 拼接包名
package_name = f"BiliLite-uwp-{arch}.{version}-beta.nupkg"
package_path = os.path.join(pack_dir, package_name)

# 执行 choco push 命令
try:
subprocess.run(["choco", "push", package_path, "--source", "https://push.chocolatey.org/", "--api-key", chocotoken], check=True)
except subprocess.CalledProcessError as e:
print(f"Failed to push package for architecture {arch}. Error: {e}")

def main(version, github_token, chocotoken):
architectures = ["x64", "x86", "ARM64"]

for arch in architectures:
print(f"Processing architecture: {arch}")
process_architecture(arch, version, github_token, chocotoken)

if __name__ == "__main__":
import argparse

parser = argparse.ArgumentParser(description="Process Chocolatey packages for different architectures.")
parser.add_argument("--version", required=True, help="The version of the package.")
parser.add_argument("--githubtoken", required=True, help="GitHub token for accessing the release assets.")
parser.add_argument("--chocotoken", required=True, help="Chocolatey API key for pushing the package.")

args = parser.parse_args()

main(args.version, args.githubtoken, args.chocotoken)
Loading

0 comments on commit 3e1b285

Please sign in to comment.