Skip to content

Commit

Permalink
v1.7.0 基本的多语言支持
Browse files Browse the repository at this point in the history
Author: Hikari16665
Co-authored-by: awaTsuki
  • Loading branch information
Hikari committed Oct 18, 2024
1 parent 50f0754 commit c5acdc6
Show file tree
Hide file tree
Showing 14 changed files with 525 additions and 183 deletions.
80 changes: 64 additions & 16 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,24 @@ on:
branches:
- main
jobs:
tag_version:
runs-on: ubuntu-20.04
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Bump version and push tag
id: tag
uses: anothrNick/github-tag-action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CUSTOM_TAG: "v${{ vars.VERSION }}"
outputs:
new_tag: ${{ steps.tag.outputs.new_tag }}
build:
strategy:
matrix:
os: [ubuntu-20.04, windows-latest]

needs: tag_version
runs-on: ${{ matrix.os }}

steps:
Expand Down Expand Up @@ -46,6 +59,7 @@ jobs:
- name: Build executable(Linux)
if: ${{ matrix.os == 'ubuntu-20.04' }}
uses: Nuitka/Nuitka-Action@main

with:
nuitka-version: main
script-name: main.py
Expand All @@ -59,30 +73,64 @@ jobs:
product-version: ${{ vars.VERSION }}
file-description: HikariServerLauncher
copyright: "Copyright 2024 Hikari"
include-data-files: lang/*.json=lang/
- name: Upload executable
uses: actions/upload-artifact@v3
with:
name: ${{ runner.os}} Build
path: |
build/*.exe
build/*.bin
build/*.app/**/*
- name: Bump version and push tag
id: tag_version
if: ${{ matrix.os == 'ubuntu-20.04' }}
uses: anothrNick/github-tag-action@v1
create_release:
needs: ['build', 'tag_version']
runs-on: ubuntu-20.04
steps:
- name: Download executable
uses: actions/download-artifact@v3
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CUSTOM_TAG: "v${{ vars.VERSION }}"
- name: Create Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.tag_version.outputs.new_tag }}
files: |
build/*.exe
build/*.bin
build/*.app/**/*
tag_name: ${{ needs.tag_version.outputs.new_tag }}
release_name: Release ${{ needs.tag_version.outputs.new_tag }}
body: |
Release ${{ vars.VERSION }}
Automatically generated release from tag ${{ steps.tag_version.outputs.new_tag }}
HikariServerLauncher Release ${{ needs.tag_version.outputs.new_tag }}
Release automatically by Github Actions
draft: false
prerelease: false
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
upload_release_asset:
needs: ['tag_version', 'create_release']
strategy:
matrix:
os: [ubuntu-20.04, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Download executable
uses: actions/download-artifact@v3
- name: Upload Release Asset(Linux)
if: ${{ matrix.os == 'ubuntu-20.04' }}
id: upload_release_asset_linux
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_content_type: application/octet-stream
upload_url: ${{ needs.create_release.outputs.upload_url }}
asset_path: build/HikariServerLauncher-${{ needs.tag_version.outputs.new_tag }}.bin
asset_name: HikariServerLauncher-${{ needs.tag_version.outputs.new_tag }}.bin
- name: Upload Release Asset(Windows)
if: ${{ matrix.os == 'windows-latest' }}
id: upload_release_asset_win
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_content_type: application/octet-stream
upload_url: ${{ needs.create_release.outputs.upload_url }}
asset_path: build/HikariServerLauncher-${{ needs.tag_version.outputs.new_tag }}.exe
asset_name: HikariServerLauncher-${{ needs.tag_version.outputs.new_tag }}.exe

4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ hsl-config.json
*.build/
*.dist/
nuitka-crash-report.xml
*.bin
*.bin
TODO
Dockerfile
4 changes: 2 additions & 2 deletions hsl.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"version": 16,
"minor": 5
"version": 17,
"minor": 0
}
4 changes: 3 additions & 1 deletion hsl/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
from . import main
from . import server
from . import workspace
from . import sponsor
from . import sponsor
from . import exceptions
from . import locale
35 changes: 16 additions & 19 deletions hsl/core/checks.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,33 @@
from functools import cache
import logging
import requests
import os
import httpx
from rich.console import Console
logger = logging.getLogger(__name__)
DOWNLOAD_SOURCE = r'https://hsl.hikari.bond/source.json'
SPCONFIGS_SOURCE = r'https://hsl.hikari.bond/spconfigs.json'
# DOWNLOAD_SOURCE = r'https://hsl.hikari.bond/source.json'
# SPCONFIGS_SOURCE = r'https://hsl.hikari.bond/spconfigs.json'
VERSION_SOURCE = r'https://hsl.hikari.bond/hsl.json'
HSL_VERSION = 16
HSL_VERSION_MINOR = 5
HSL_VERSION = 17
HSL_VERSION_MINOR = 0

console = Console()
async def make_request(url: str, error_message: str) -> dict:
console.print(f'Requesting: {url}')
#console.print(f'Requesting: {url}')
try:
response = requests.get(url,timeout=3)
if response.status_code == 200:
return response.json()
console.log(f'{error_message},状态码:{response.status_code}')
return {}
except Exception as e:
console.log(f'{error_message},错误信息:{e}')
async with httpx.AsyncClient() as client:
response = await client.get(url)
if response.status_code == 200:
return response.json()
console.print(f'[bold red]{error_message}[/bold red]')
return {}
except httpx.ConnectError:
console.print(f'[bold red]{error_message}[/bold red]')
return {}
async def check_update():
data = await make_request(VERSION_SOURCE, error_message='检查更新失败')
latest: int = data.get('version', 0)
minor: int = data.get('minor', 0)
console.log(f'Version data fetched: {latest}-{minor}')
#console.log(f'Version data fetched: {latest}-{minor}')
if (HSL_VERSION < latest):
console.print(f'[bold magenta]发现主要版本更新,版本号:[u]{latest/10}[/u],建议及时更新')
return
if (HSL_VERSION_MINOR < minor):
if (HSL_VERSION_MINOR < minor and HSL_VERSION == latest):
console.print(f'[bold magenta]发现次要版本更新,版本号:[u]{minor/10}[/u],建议及时更新')
return
def get_version() -> tuple:
Expand Down
9 changes: 6 additions & 3 deletions hsl/core/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import json
import logging
import os
from rich.console import Console
logger = logging.getLogger('hsl')
CONFIG_FILE = 'hsl-config.json'
console = Console()
class Config():
def __init__(self):
self.first_run: bool = True
Expand All @@ -12,6 +14,7 @@ def __init__(self):
self.backup_dir: str = 'backup'
self.autorun: str = ''
self.debug: bool = False
self.language: str = 'en'
def load(self):
try:
with open(CONFIG_FILE, 'r') as f:
Expand All @@ -21,12 +24,12 @@ def load(self):
pass
except KeyError:
os.remove(CONFIG_FILE)
logger.error('Invalid config file, removed and created a new one')
console.log('Invalid config file, removed and created a new one')
self.save()
except json.JSONDecodeError:
logger.error('Invalid config file')
console.log('Invalid config file')
return self
def save(self):
with open(CONFIG_FILE, 'w') as f:
json.dump(self.__dict__, f, indent=4)
logger.info(f'Config saved to {CONFIG_FILE} with data {self.__dict__}')
console.log(f'Config saved to {CONFIG_FILE} with data {self.__dict__}')
2 changes: 2 additions & 0 deletions hsl/core/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
class NoSuchServerException(Exception):
pass
class LanguageNotSupportedException(Exception):
pass
45 changes: 45 additions & 0 deletions hsl/core/locale.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# HSL Locale Module
from typing import Any, Union
from hsl.core.exceptions import LanguageNotSupportedException
import os
import sys
import json
from rich.console import Console
from hsl.core.config import Config
console = Console()
class Locale():
def __init__(self):
self.config = Config().load()
self.language = self.config.language
self.debug = self.config.debug
self.language_key = {}
self.set_language(self.language)
def set_language(self, language: str) -> None:
self.language = language
self.packaged = bool(getattr(sys, '_MEIPASS', False))
base_path = sys._MEIPASS if self.packaged else os.path.abspath(".") # type: ignore
file_path = os.path.join(base_path, 'lang', f'{self.language}.json')
if self.debug:
console.log(f'Loading language file {file_path}')
try:
with open(file_path, 'r', encoding='utf-8') as f:
self.language_key = json.load(f)
except FileNotFoundError as e:
raise LanguageNotSupportedException(
f'Language {self.language} is not supported.'
) from e
def replace(self, text: str, replaces: dict[str, str] = {}) -> str:
for k, v in replaces.items():
text = text.replace(f'{{{k}}}', v)
return text
def trans_key(self, key: Union[str, list[str]], /, **replaces: str) -> Any: # type: ignore
if isinstance(key, str):
#console.log(f'Translating key {key} in {self.language} replaces: {replaces}')
return self.replace(self.language_key.get(key, key), replaces)
if isinstance(key, list):
_texts = []
for k in key:
#console.log(f'Translating key {k} in {self.language} replaces: {replaces}')
_texts.append(self.language_key.get(k, k))
return [self.replace(text, replaces) for text in _texts]
return None
3 changes: 2 additions & 1 deletion hsl/core/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from hsl.core.config import Config
from hsl.core.locale import Locale
from hsl.core.checks import get_version
from hsl.source.source import get_source
from hsl.spconfigs.spconfigs import get_spconfigs
from rich.console import Console
import sys
import platform
console = Console()

locale = Locale()
OS_ARCH = platform.machine()
console.log(f'OS_ARCH: {OS_ARCH}')
if OS_ARCH not in ['AMD64', 'x86_64']:
Expand Down
3 changes: 2 additions & 1 deletion hsl/core/sponsor.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
SPONSOR = [
"Hikari<[email protected]>",
"awatsuki",
"BenXong"
"BenXong",
"Graphite_sm"
]
def get_sponsor_list() -> list:
return SPONSOR
12 changes: 7 additions & 5 deletions hsl/utils/prompt.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
from noneprompt import ListPrompt, InputPrompt, Choice
from hsl.core.locale import Locale
import asyncio
OPTIONS_YN = ['是', '否']
locale = Locale()
OPTIONS_YN = locale.trans_key(['yes','no'])
async def promptSelect(options: list,prompt: str) -> int:
choices = [Choice(options[i],data=i) for i in range(len(options))]
prompt_task = asyncio.create_task(ListPrompt(prompt, choices=choices).prompt_async())
prompt_task = asyncio.create_task(ListPrompt(prompt, choices=choices,annotation=locale.trans_key('choice-prompt-annotation')).prompt_async())
select = await asyncio.gather(prompt_task)
return select[0].data
async def promptInput(prompt: str) -> str:
prompt_task = asyncio.create_task(InputPrompt(prompt, validator=lambda string: True).prompt_async())
input = await asyncio.gather(prompt_task)
return input[0]
_input = await asyncio.gather(prompt_task)
return _input[0]
async def promptConfirm(prompt: str) -> bool:
# prompt_task = asyncio.create_task(ConfirmPrompt(prompt,default_choice=False).prompt_async())
# confirm = await asyncio.gather(prompt_task)
# return confirm[0]
return True if await promptSelect(OPTIONS_YN,prompt) == 0 else False
return bool(await promptSelect(OPTIONS_YN,prompt) == 0)
Loading

0 comments on commit c5acdc6

Please sign in to comment.