mirror of
https://github.com/KenanZhu/AutoLibrary.git
synced 2026-06-18 07:23:03 +08:00
Compare commits
48 Commits
v1.0.0-beta.1
...
v1.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
| db7a868598 | |||
| f1e0334ce3 | |||
| b9411261ea | |||
| fa737711d4 | |||
| 79e2128fca | |||
| 128c8e7a83 | |||
| 6474f6e3bb | |||
| ba60a5d884 | |||
| 4d8f8130dc | |||
| eba99cab9f | |||
| aa7a806ff7 | |||
| bb180f8c8e | |||
| 107ed41b58 | |||
| 43b87db4eb | |||
| ae23f65e5a | |||
| a7b9c340ae | |||
| 96d733d2ed | |||
| 65cb951ada | |||
| 94ce3433a3 | |||
| dd48c8a01c | |||
| 924db3bdcc | |||
| 1e5452d411 | |||
| 1b378e5aaa | |||
| e069efb2ea | |||
| 407d25570a | |||
| bfcb65f56a | |||
| cde1e966e7 | |||
| 8c4f463889 | |||
| 39867cc20c | |||
| 149910d628 | |||
| 2a7ed099bf | |||
| 473f32ca29 | |||
| 580052f1e3 | |||
| 6abf530307 | |||
| 577c651ef8 | |||
| 18ae949900 | |||
| ca9059d1db | |||
| ad4deae0c6 | |||
| 55ae4d0d96 | |||
| 7dcd72939b | |||
| bfce61f4b4 | |||
| 60a5699822 | |||
| aab9565012 | |||
| 9255eec9f1 | |||
| cff6fd8fc0 | |||
| b129f47b48 | |||
| 069429be71 | |||
| 7d064fc8e7 |
@@ -0,0 +1,225 @@
|
||||
name: Build
|
||||
|
||||
# This workflow compiles the application for Windows platform using PyInstaller, and
|
||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
||||
#
|
||||
# It is triggered when called by the release workflow.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Version number'
|
||||
required: true
|
||||
type: string
|
||||
tag_name:
|
||||
description: 'Tag name'
|
||||
required: true
|
||||
type: string
|
||||
outputs:
|
||||
version:
|
||||
description: 'The version number'
|
||||
value: ${{ jobs.build-windows.outputs.version }}
|
||||
tag_name:
|
||||
description: 'The tag name'
|
||||
value: ${{ jobs.build-windows.outputs.tag_name }}
|
||||
|
||||
#
|
||||
# Build Windows
|
||||
#
|
||||
|
||||
jobs:
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
outputs:
|
||||
version: ${{ steps.get_version.outputs.VERSION }}
|
||||
tag_name: ${{ steps.get_version.outputs.TAG_NAME }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
|
||||
# here we download the build version of ALVersionInfo.py from artifacts
|
||||
# and replace the committed version
|
||||
- name: Download build version of ALVersionInfo.py
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: updated-version-info-for-build
|
||||
path: src/gui/
|
||||
|
||||
- name: Get version info
|
||||
id: get_version
|
||||
run: |
|
||||
$version = "${{ inputs.version }}"
|
||||
$tagName = "${{ inputs.tag_name }}"
|
||||
|
||||
echo "TAG_NAME=$tagName" >> $env:GITHUB_OUTPUT
|
||||
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
|
||||
Write-Host "✓ Tag: $tagName"
|
||||
Write-Host "✓ Version: $version"
|
||||
shell: pwsh
|
||||
|
||||
- name: Verify 'ALVersionInfo.py' was updated
|
||||
run: |
|
||||
$versionInfoFile = "src/gui/ALVersionInfo.py"
|
||||
Write-Host "Verifying $versionInfoFile content:"
|
||||
Write-Host "=================================="
|
||||
Get-Content $versionInfoFile | Write-Host
|
||||
Write-Host "=================================="
|
||||
shell: pwsh
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.13'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirement.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
$ddddocrPath = python -c "import ddddocr, os; print(os.path.dirname(ddddocr.__file__))"
|
||||
Write-Host "ddddocr package location: $ddddocrPath"
|
||||
|
||||
$initFile = Join-Path $ddddocrPath "__init__.py"
|
||||
if (Test-Path $initFile) {
|
||||
Write-Host "Fixing ddddocr compatibility in: $initFile"
|
||||
(Get-Content $initFile) -replace 'Image\.ANTIALIAS', 'Image.Resampling.LANCZOS' | Set-Content $initFile
|
||||
Write-Host "✓ Fixed: Image.ANTIALIAS -> Image.Resampling.LANCZOS"
|
||||
} else {
|
||||
Write-Error "✗ ddddocr __init__.py not found"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-Path "model")) {
|
||||
New-Item -ItemType Directory -Path "model" | Out-Null
|
||||
Write-Host "✓ Created model directory"
|
||||
}
|
||||
|
||||
$onnxSource = Join-Path $ddddocrPath "common.onnx"
|
||||
$onnxDest = "model/common.onnx"
|
||||
if (Test-Path $onnxSource) {
|
||||
Copy-Item $onnxSource $onnxDest -Force
|
||||
Write-Host "✓ Copied ONNX model from: $onnxSource"
|
||||
Write-Host "✓ ONNX model copied to: $onnxDest"
|
||||
} else {
|
||||
Write-Error "✗ ONNX model not found in ddddocr package: $onnxSource"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (Test-Path $onnxDest) {
|
||||
$fileSize = (Get-Item $onnxDest).Length / 1MB
|
||||
Write-Host "✓ Model file verified: $onnxDest (Size: $([math]::Round($fileSize, 2)) MB)"
|
||||
} else {
|
||||
Write-Error "✗ Failed to copy model file"
|
||||
exit 1
|
||||
}
|
||||
shell: pwsh
|
||||
|
||||
- name: Compile Qt UI files
|
||||
run: |
|
||||
cd src/gui/batchs
|
||||
./compile_ui.bat
|
||||
shell: cmd
|
||||
|
||||
- name: Compile Qt Resource files
|
||||
run: |
|
||||
cd src/gui/batchs
|
||||
./compile_rc.bat
|
||||
shell: cmd
|
||||
|
||||
- name: Generate 'Main.spec'
|
||||
run: |
|
||||
$version = "${{ steps.get_version.outputs.VERSION }}"
|
||||
$exeName = "AutoLibrary-$version"
|
||||
|
||||
Write-Host "Generating Main.spec for version: $version"
|
||||
Write-Host "Executable name: $exeName"
|
||||
|
||||
$specLines = @(
|
||||
"# -*- mode: python ; coding: utf-8 -*-"
|
||||
""
|
||||
""
|
||||
"a = Analysis("
|
||||
" ['src\\Main.py'],"
|
||||
" pathex=[],"
|
||||
" binaries=[],"
|
||||
" datas=["
|
||||
" ('model\\common.onnx', 'ddddocr'),"
|
||||
" ('src\\gui\\icons\\AutoLibrary_32x32.ico', 'gui\\icons'),"
|
||||
" ],"
|
||||
" hiddenimports=[],"
|
||||
" hookspath=[],"
|
||||
" hooksconfig={},"
|
||||
" runtime_hooks=[],"
|
||||
" excludes=[],"
|
||||
" noarchive=False,"
|
||||
" optimize=0,"
|
||||
")"
|
||||
"pyz = PYZ(a.pure)"
|
||||
""
|
||||
"exe = EXE("
|
||||
" pyz,"
|
||||
" a.scripts,"
|
||||
" a.binaries,"
|
||||
" a.datas,"
|
||||
" [],"
|
||||
" name='$exeName',"
|
||||
" debug=False,"
|
||||
" bootloader_ignore_signals=False,"
|
||||
" strip=False,"
|
||||
" upx=True,"
|
||||
" upx_exclude=[],"
|
||||
" runtime_tmpdir=None,"
|
||||
" console=False,"
|
||||
" disable_windowed_traceback=False,"
|
||||
" argv_emulation=False,"
|
||||
" target_arch=None,"
|
||||
" codesign_identity=None,"
|
||||
" entitlements_file=None,"
|
||||
" icon=['src\\gui\\icons\\AutoLibrary_32x32.ico'],"
|
||||
")"
|
||||
)
|
||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||
|
||||
Write-Host "✓ Main.spec generated successfully"
|
||||
Write-Host "`nGenerated Main.spec ============"
|
||||
Get-Content "Main.spec" | Write-Host
|
||||
Write-Host "==================================`n"
|
||||
shell: pwsh
|
||||
|
||||
- name: Build with PyInstaller
|
||||
run: |
|
||||
pyinstaller Main.spec
|
||||
|
||||
- name: Zip windows release
|
||||
id: zip_release
|
||||
run: |
|
||||
$tagName = "${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
$version = "${{ steps.get_version.outputs.VERSION }}"
|
||||
$exeName = "AutoLibrary-$version.exe"
|
||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
||||
|
||||
echo "ZIP_PATH=$zipName" >> $env:GITHUB_OUTPUT
|
||||
|
||||
Write-Host "Looking for executable: dist/$exeName"
|
||||
if (Test-Path "dist/$exeName") {
|
||||
Compress-Archive -Path "dist/$exeName" -DestinationPath $zipName
|
||||
Write-Host "✓ Created release archive: $zipName"
|
||||
} else {
|
||||
Write-Error "✗ Executable not found: dist/$exeName"
|
||||
Write-Host "Files in dist directory:"
|
||||
Get-ChildItem "dist" | ForEach-Object { Write-Host " - $($_.Name)" }
|
||||
exit 1
|
||||
}
|
||||
shell: pwsh
|
||||
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-windows-x86_64
|
||||
path: |
|
||||
${{ steps.zip_release.outputs.ZIP_PATH }}
|
||||
@@ -0,0 +1,109 @@
|
||||
name: Commit Release
|
||||
|
||||
# This workflow commits version changes in 'ALVersionInfo.py' (get from artifacts) and
|
||||
# moves the release tag to this new release commit.
|
||||
#
|
||||
# It is triggered when called by the release workflow.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: 'Tag name to move (e.g., v1.0.0)'
|
||||
required: true
|
||||
type: string
|
||||
version:
|
||||
description: 'Version number for commit message'
|
||||
required: true
|
||||
type: string
|
||||
file_path:
|
||||
description: 'File path to commit'
|
||||
required: true
|
||||
type: string
|
||||
outputs:
|
||||
new_commit_sha:
|
||||
description: 'The new commit SHA after moving the tag'
|
||||
value: ${{ jobs.commit-release.outputs.new_commit_sha }}
|
||||
|
||||
jobs:
|
||||
commit-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
new_commit_sha: ${{ steps.commit_info.outputs.commit_sha }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
|
||||
# here we download the commit version of ALVersionInfo.py from artifacts
|
||||
# and replace the original file with it.
|
||||
- name: Download commit version of ALVersionInfo.py
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: updated-version-info-for-commit
|
||||
path: downloaded-file/
|
||||
|
||||
- name: Replace file with updated version
|
||||
run: |
|
||||
FILE_PATH="${{ inputs.file_path }}"
|
||||
FILE_NAME=$(basename "$FILE_PATH")
|
||||
TARGET_DIR=$(dirname "$FILE_PATH")
|
||||
|
||||
mkdir -p "$TARGET_DIR"
|
||||
cp "downloaded-file/$FILE_NAME" "$FILE_PATH"
|
||||
|
||||
echo "✓ File replaced: $FILE_PATH"
|
||||
echo ""
|
||||
echo "Updated file content ==================="
|
||||
cat "$FILE_PATH"
|
||||
echo "========================================"
|
||||
|
||||
- name: Commit changes
|
||||
id: commit_changes
|
||||
run: |
|
||||
git config --local user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git config --local user.name "github-actions[bot]"
|
||||
|
||||
FILE_PATH="${{ inputs.file_path }}"
|
||||
VERSION="${{ inputs.version }}"
|
||||
|
||||
if [ ! -f "$FILE_PATH" ]; then
|
||||
echo "✗ Error: File $FILE_PATH not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git add "$FILE_PATH"
|
||||
git commit -m "chore(release): v${VERSION} [auto release commit]"
|
||||
echo "✓ Changes committed"
|
||||
|
||||
- name: Push to main branch
|
||||
run: |
|
||||
MAIN_BRANCH=$(git remote show origin | grep 'HEAD branch' | cut -d' ' -f5)
|
||||
if [ -z "$MAIN_BRANCH" ]; then
|
||||
MAIN_BRANCH="main"
|
||||
fi
|
||||
|
||||
echo "Pushing to branch: ${MAIN_BRANCH}"
|
||||
git push origin HEAD:${MAIN_BRANCH}
|
||||
echo "✓ Changes pushed to ${MAIN_BRANCH}"
|
||||
|
||||
- name: Move tag to new release commit
|
||||
run: |
|
||||
TAG_NAME="${{ inputs.tag_name }}"
|
||||
|
||||
echo "Moving tag ${TAG_NAME} to the new commit..."
|
||||
git tag -f ${TAG_NAME}
|
||||
git push origin ${TAG_NAME} --force
|
||||
echo "✓ Tag ${TAG_NAME} moved to commit $(git rev-parse --short HEAD)"
|
||||
|
||||
- name: Output commit info
|
||||
id: commit_info
|
||||
run: |
|
||||
COMMIT_SHA=$(git rev-parse --short HEAD)
|
||||
echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
||||
echo "✓ New commit SHA: $COMMIT_SHA"
|
||||
@@ -0,0 +1,156 @@
|
||||
name: Release
|
||||
|
||||
# This workflow automates the complete release process for AutoLibrary application
|
||||
# It is triggered when a new version tag (vX.Y.Z) is pushed to the repository
|
||||
#
|
||||
# Workflow Steps:
|
||||
# START >
|
||||
|
||||
# 1. Update Version:
|
||||
# Updates version information in 'ALVersionInfo.py' with build metadata and archives
|
||||
# the updated version file as an artifact.
|
||||
#
|
||||
# for more information, please refer to the comment in the workflow 'update-version.yml'
|
||||
|
||||
# 2. Commit Release:
|
||||
# Commits version changes and moves the release tag to this new release commit.
|
||||
|
||||
# 3. Build:
|
||||
# Compiles the application for Windows platform using PyInstaller, and
|
||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
||||
|
||||
# 4. Release:
|
||||
# Creates GitHub release with generated artifacts and release notes
|
||||
|
||||
# < END
|
||||
#
|
||||
# The workflow ensures version consistency between source code, built artifacts, and GitHub releases
|
||||
# while maintaining proper commit history and tag management.
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v[0-9]+.[0-9]+.[0-9]+'
|
||||
|
||||
jobs:
|
||||
#
|
||||
# Start :
|
||||
# virtual job that indacates the start of the release process
|
||||
#
|
||||
|
||||
start:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Start release
|
||||
run: |
|
||||
echo "✓ Starting release"
|
||||
|
||||
#
|
||||
# Update version :
|
||||
# this job updates the version in the file 'ALVersionInfo.py'
|
||||
#
|
||||
|
||||
update-version:
|
||||
needs:
|
||||
- start
|
||||
uses: ./.github/workflows/update-version.yml
|
||||
permissions:
|
||||
contents: write
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
#
|
||||
# Commit release :
|
||||
# this job commits the updated version file and move the release
|
||||
# tag to this new commit
|
||||
#
|
||||
|
||||
commit-release:
|
||||
needs:
|
||||
- update-version
|
||||
if: ${{ needs.update-version.outputs.has_changes == 'true' }}
|
||||
uses: ./.github/workflows/commit-release.yml
|
||||
permissions:
|
||||
contents: write
|
||||
with:
|
||||
tag_name: ${{ needs.update-version.outputs.tag_name }}
|
||||
version: ${{ needs.update-version.outputs.version }}
|
||||
file_path: src/gui/ALVersionInfo.py
|
||||
|
||||
#
|
||||
# Build :
|
||||
# this job builds the application artifacts and archives them
|
||||
|
||||
build:
|
||||
needs:
|
||||
- update-version
|
||||
- commit-release
|
||||
if: always() && needs.update-version.result == 'success' && needs.commit-release.result == 'success'
|
||||
uses: ./.github/workflows/build.yml
|
||||
permissions:
|
||||
contents: write
|
||||
with:
|
||||
version: ${{ needs.update-version.outputs.version }}
|
||||
tag_name: ${{ needs.update-version.outputs.tag_name }}
|
||||
|
||||
#
|
||||
# Release :
|
||||
# this job creates a GitHub release and uploads the archive files
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build
|
||||
if: always() && needs.build.result == 'success'
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: AutoLibrary.${{ needs.build.outputs.tag_name }}-windows-x86_64
|
||||
path: artifacts/
|
||||
|
||||
- name: Create release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.build.outputs.tag_name }}
|
||||
name: AutoLibrary ${{ needs.build.outputs.tag_name }}
|
||||
files: |
|
||||
artifacts/AutoLibrary.${{ needs.build.outputs.tag_name }}-windows-x86_64.zip
|
||||
draft: false
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
body: |
|
||||
### 下载获取
|
||||
- **Windows x86_64**: `AutoLibrary.${{ needs.build.outputs.tag_name }}-windows-x86_64.zip`
|
||||
|
||||
### 如何使用
|
||||
1. 下载 `AutoLibrary.${{ needs.build.outputs.tag_name }}-windows-x86_64.zip` 文件
|
||||
2. 解压到任意目录
|
||||
3. 下载对应浏览器的驱动文件
|
||||
4. 运行 `AutoLibrary-${{ needs.build.outputs.version }}.exe` (首次运行会初始化配置文件)
|
||||
5. 按照提示操作即可
|
||||
|
||||
更多详情请访问 [AutoLibrary 网站](http://autolibrary.cv) 和查看 [帮助手册](https://autolibrary.cv/docs/manual_lists.html)
|
||||
|
||||
---
|
||||
**完整更新日志见下方自动生成的 Release Notes**
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# End :
|
||||
# virtual job that indacates the end of the release process
|
||||
#
|
||||
|
||||
end:
|
||||
needs:
|
||||
- release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: End release
|
||||
run: |
|
||||
echo "✓ Ending release"
|
||||
@@ -0,0 +1,163 @@
|
||||
name: Update Version
|
||||
|
||||
# This workflow updates version information in 'ALVersionInfo.py' with build metadata.
|
||||
# In progress, it will generate two version files, the first one is locate in 'src/gui/ALVersionInfo.py',
|
||||
# and the second one is locate in 'src/gui/temp/ALVersionInfo.py'. The first one is use
|
||||
# in the release process, it only update the version and tag name. The commit and build infomation
|
||||
# is 'local' or 'null'. All of them will finally archive as artifacts.
|
||||
#
|
||||
# It is triggered when called by the release workflow.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: 'Tag name'
|
||||
required: true
|
||||
type: string
|
||||
ref:
|
||||
description: 'Git ref to checkout'
|
||||
required: true
|
||||
type: string
|
||||
outputs:
|
||||
tag_name:
|
||||
description: 'The tag name'
|
||||
value: ${{ jobs.update-version.outputs.tag_name }}
|
||||
version:
|
||||
description: 'The version number'
|
||||
value: ${{ jobs.update-version.outputs.version }}
|
||||
has_changes:
|
||||
description: 'Whether ALVersionInfo.py was modified'
|
||||
value: ${{ jobs.update-version.outputs.has_changes }}
|
||||
|
||||
jobs:
|
||||
update-version:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
tag_name: ${{ steps.get_version.outputs.TAG_NAME }}
|
||||
version: ${{ steps.get_version.outputs.VERSION }}
|
||||
has_changes: ${{ steps.check_changes.outputs.has_changes }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get tag name and version
|
||||
id: get_version
|
||||
env:
|
||||
TZ: UTC
|
||||
run: |
|
||||
TAG_NAME="${{ inputs.tag_name }}"
|
||||
VERSION="${TAG_NAME#v}"
|
||||
COMMIT_SHA="${GITHUB_SHA:0:7}"
|
||||
COMMIT_DATE=$(TZ=UTC git log -1 --format=%cd --date=format-local:'%Y-%m-%d %H:%M:%S UTC')
|
||||
|
||||
echo "TAG_NAME=$TAG_NAME" >> $GITHUB_OUTPUT
|
||||
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "COMMIT_SHA=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
||||
echo "COMMIT_DATE=$COMMIT_DATE" >> $GITHUB_OUTPUT
|
||||
|
||||
echo "✓ Tag: $TAG_NAME"
|
||||
echo "✓ Version: $VERSION"
|
||||
echo "✓ Commit SHA: $COMMIT_SHA"
|
||||
echo "✓ Commit Date: $COMMIT_DATE"
|
||||
|
||||
- name: Create 'temp' directory
|
||||
run: |
|
||||
echo "Creating temp directory..."
|
||||
mkdir -p "src/gui/temp"
|
||||
echo "✓ temp directory created successfully"
|
||||
|
||||
- name: Update ALVersionInfo.py with version info
|
||||
run: |
|
||||
VERSION="${{ steps.get_version.outputs.VERSION }}"
|
||||
TAG_NAME="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
COMMIT_SHA="${{ steps.get_version.outputs.COMMIT_SHA }}"
|
||||
COMMIT_DATE="${{ steps.get_version.outputs.COMMIT_DATE }}"
|
||||
VER_INFO_BUILDFILE="src/gui/temp/ALVersionInfo.py"
|
||||
VER_INFO_COMMITFILE="src/gui/ALVersionInfo.py"
|
||||
BUILD_DATE=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
|
||||
|
||||
echo "Updating ALVersionInfo.py files with build information..."
|
||||
{
|
||||
echo '# -*- coding: utf-8 -*-'
|
||||
echo ''
|
||||
echo '"""'
|
||||
echo ' The contents of this file will automatically be updated by the'
|
||||
echo ' workflow process. Do not edit manually.'
|
||||
echo ''
|
||||
echo ' This file is auto-generated during the workflow process.'
|
||||
echo " Last updated: ${BUILD_DATE}"
|
||||
echo '"""'
|
||||
echo ''
|
||||
echo "AL_VERSION = \"${VERSION}\""
|
||||
echo "AL_TAG = \"${TAG_NAME}\""
|
||||
echo "AL_COMMIT_SHA = \"${COMMIT_SHA}\""
|
||||
echo "AL_COMMIT_DATE = \"${COMMIT_DATE}\" # time zone : UTC"
|
||||
echo "AL_BUILD_DATE = \"${BUILD_DATE}\" # time zone : UTC"
|
||||
echo 'AL_VERSION_FULL = f"{AL_VERSION} ({AL_COMMIT_SHA})"'
|
||||
} > "$VER_INFO_BUILDFILE"
|
||||
|
||||
echo "Updating ALVersionInfo.py for release commit..."
|
||||
{
|
||||
echo '# -*- coding: utf-8 -*-'
|
||||
echo ''
|
||||
echo '"""'
|
||||
echo ' The contents of this file will automatically be updated by the'
|
||||
echo ' workflow process. Do not edit manually.'
|
||||
echo ''
|
||||
echo ' This file is auto-generated during the workflow process.'
|
||||
echo " Last updated: ${BUILD_DATE}"
|
||||
echo '"""'
|
||||
echo ''
|
||||
echo "AL_VERSION = \"${VERSION}\""
|
||||
echo "AL_TAG = \"${TAG_NAME}\""
|
||||
echo "AL_COMMIT_SHA = \"local\""
|
||||
echo "AL_COMMIT_DATE = \"null\" # time zone : UTC"
|
||||
echo "AL_BUILD_DATE = \"null\" # time zone : UTC"
|
||||
echo 'AL_VERSION_FULL = f"{AL_VERSION} ({AL_COMMIT_SHA})"'
|
||||
} > "$VER_INFO_COMMITFILE"
|
||||
|
||||
echo "✓ ALVersionInfo.py files updated successfully"
|
||||
echo ""
|
||||
echo "Build version file location: $VER_INFO_BUILDFILE"
|
||||
echo "Commit version file location: $VER_INFO_COMMITFILE"
|
||||
echo ""
|
||||
echo "Build version ALVersionInfo.py content ="
|
||||
cat "$VER_INFO_BUILDFILE"
|
||||
echo ""
|
||||
echo "Commit version ALVersionInfo.py content "
|
||||
cat "$VER_INFO_COMMITFILE"
|
||||
echo "========================================"
|
||||
|
||||
- name: Check if ALVersionInfo.py was modified
|
||||
id: check_changes
|
||||
run: |
|
||||
if git diff --quiet src/gui/ALVersionInfo.py; then
|
||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||
echo "! No changes detected in ALVersionInfo.py"
|
||||
else
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
echo "✓ ALVersionInfo.py has been modified"
|
||||
fi
|
||||
|
||||
- name: Upload modified ALVersionInfo.py ready for build
|
||||
if: steps.check_changes.outputs.has_changes == 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: updated-version-info-for-build
|
||||
path: src/gui/temp/ALVersionInfo.py
|
||||
retention-days: 1
|
||||
|
||||
- name: Upload modified ALVersionInfo.py ready for commit
|
||||
if: steps.check_changes.outputs.has_changes == 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: updated-version-info-for-commit
|
||||
path: src/gui/ALVersionInfo.py
|
||||
retention-days: 1
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright 2025 KenanZhu
|
||||
Copyright 2025 - 2026 KenanZhu
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -1,5 +1,118 @@
|
||||
|
||||
# AutoLibrary
|
||||
---
|
||||
|
||||
请访问[AutoLibrary 网站](http://autolibrary.cv)\
|
||||
Please access the [AutoLibrary Website](http://autolibrary.cv)
|
||||

|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
了解更多请访问 [_AutoLibrary 网站_](http://autolibrary.cv)
|
||||
|
||||
---
|
||||
|
||||
### 功能
|
||||
|
||||
1. 自动预约 - 支持自动预约
|
||||
2. 自动续约 - 支持自动续约
|
||||
3. 自动签到 - 支持自动签到
|
||||
4. 批量操作 - 支持同时预约多个用户,可以指定当前需要跳过的用户,并将用户分成多个组
|
||||
5. 定时任务 - 使用内置定时任务管理,添加定时任务,指定时间后按当前预约信息自动运行
|
||||
|
||||
*1,2,3 的具体操作方法和注意事项请访问我们的 [帮助手册](https://autolibrary.cv/docs/manual_lists.html)*
|
||||
|
||||
### 特点
|
||||
|
||||
#### 关于预约等操作的注意事项
|
||||
|
||||
工具会自动处理登录过程的验证码识别过程,正常情况下单次识别准确率在 90% 以上,如遇验证码识别错误,大概率是校园网网络环境不佳导致的。
|
||||
|
||||
只要确保处于校园网网络环境内,工具都是可以正常运行的。操作处理速度基本上取决于校园网的网络环境,一般情况下在 3-4 秒(不考虑硬件差异)左右即可完成一个用户的操作,完全满足正常使用需求。
|
||||
|
||||
> [!NOTE]
|
||||
> 工具仅作为正常的预约,签到和续约的图书馆辅助工具,请勿干扰图书馆的正常运行(如故意预约多个座位,或同时预约大量的用户等,对此影响图书馆正常运行本工具概不负责,请在善用工具方便自己的情况下尽量不用影响其他同学的使用)。
|
||||
|
||||
#### 关于批量操作的注意事项
|
||||
|
||||
批量操作时,建议将需要操作的用户分成多个组,每个组的用户数量不要超过 4 人(即一整张桌子的数量),否则会影响操作效率,大量用户同时预约会一定程度上增加图书馆服务器的压力,影响正常使用。根据需要在用户管理界面中可以勾选本次操作是否跳过该用户,以提高运行效率。
|
||||
|
||||
#### 关于定时任务的注意事项
|
||||
|
||||
定时任务会在指定的时间自动运行,运行时会根据当前预约信息进行操作。一般情况下不建议设置两个运行开始时间比较接近的定时任务,否则后一个任务会等待前一个任务完成后才会运行,按照队列的顺序执行。
|
||||
|
||||
### 如何使用
|
||||
|
||||
1. 下载最新版本的 [AutoLibrary 压缩包](https://github.com/KenanZhu/AutoLibrary/releases)。
|
||||
2. 解压下载的文件到任意目录。
|
||||
3. 下载对应浏览器的驱动文件,并在配置界面的运行配置选项卡对应位置选择你下载好的浏览器驱动
|
||||
4. 运行 `AutoLibrary.exe` 文件。
|
||||
5. 按照提示操作即可。
|
||||
|
||||
*注意 1*: 关于浏览器驱动的下载和其它相关问题,请参考我们的 [帮助手册](https://autolibrary.cv/docs/manual_lists.html) 中对应软件版本的内容。
|
||||
|
||||
#### 平台支持 & 编译步骤
|
||||
|
||||
本工具目前仅支持 Windows 平台,由于使用 PySide6 库开发,理论上是可以自行编译并在 Linux 和 macOS 上运行,这里提供简单的编译步骤:
|
||||
|
||||
1. 确保系统安装了 Python 3.13 版本 (推荐,过低或高版本会导致兼容问题)。
|
||||
2. 安装 pyside6 selenium ddddocr 库,命令为 `pip install pyside6 selenium ddddocr`。
|
||||
3. 在 `src/gui/batchs` 目录下运行 `compile_ui.bat` (linux 和 macOS 系统使用 `compile_ui.sh`) 文件来编译 Qt 的 UI 文件。
|
||||
4. 在上一步相同目录内运行 `compile_rc.bat` (linux 和 macOS 系统使用 `compile_rc.sh`) 文件来编译 Qt 的资源文件。
|
||||
5. 待上述步骤完成后,运行 `src/Main.py` 文件即可。
|
||||
|
||||
*注意 1*:如果 python 使用的是虚拟环境,请在虚拟环境安装依赖后,在激活的虚拟环境终端中使用 `cd src/gui/batchs` 命令切换到 `batchs` 目录下,再运行编译脚本。否则会提示缺少必要的 Qt PySide 依赖库。
|
||||
|
||||
*注意 2*:由于 ddddocr 的代码版本问题,其中 `__init__.py` 文件中的函数 `def classification(self, img: bytes):` 中的 `image.resize` 方法传入了不符合当前 pillow 版本的 `resample` 参数 `Image.ANTIALIAS`,该重采样常量已经在 10.0.0 版中删除 [1](@ref)。请将 `image.resize` 方法中的参数替换为 `resample=Image.Resampling.LANCZOS`,具体函数如下:
|
||||
```python
|
||||
def classification(self, img: bytes):
|
||||
image = Image.open(io.BytesIO(img))
|
||||
image = image.resize((int(image.size[0]*(64/image.size[1])), 64), Image.ANTIALIAS).convert('L')
|
||||
^^^^^
|
||||
请将上述参数替换为 `Image.Resampling.LANCZOS`
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
[1](@ref):[pillow 中已经删除或已经弃用的常量](https://pillow.ac.cn/en/stable/deprecations.html#constants)
|
||||
|
||||
### Q&A
|
||||
|
||||
#### 为什么开发这个工具?
|
||||
|
||||
当前图书馆的座位预约系统在使用中确实会遇到一些不便。例如,系统登录界面较为陈旧,在输入验证码时,若出现错误常常需要全部重新填写,过程繁琐。尤其在网络环境不稳定的情况下,登录和加载速度缓慢,让人难以快速完成当天的签到或预约次日座位。
|
||||
此外,当朋友需要帮忙预约座位时,手动操作也会分散自己学习和工作的注意力。
|
||||
因此,很希望有一个便捷的工具能自动处理这些预约、续约和签到等操作,从而让自己从这些琐碎事务中解脱出来,更专注于手头的重要事项。
|
||||
|
||||
#### 工具后续会收费吗?
|
||||
|
||||
不会,本工具完全免费使用,也不会有任何额外收费项。如果你觉工具对你很有帮助,可以为我捐助一瓶饮料的价格,以用于 AutoLibrary 网站的维护和软件的稳定更新。
|
||||
|
||||
<a href="https://afdian.com/a/autolibrary" style="display:inline-block;padding:10px 30px;background:linear-gradient(135deg,#946CE6,#946CE6);color:white;text-decoration:none;border-radius:6px;font-weight:bold;">❤ 支持作者</a>
|
||||
|
||||
#### 会有手机端的版本吗?
|
||||
|
||||
暂时没有考虑,而且也没有足够的时间和能力开发多平台的版本并测试维护,所以暂时只提供 Windows 版本。
|
||||
|
||||
#### 后续会有哪些功能?
|
||||
|
||||
当前 v1.0.0 版本的功能对于正常使用已经足够,不过后续会着重考虑完善 2-4 人预约时的使用体验,暂时有以下构想:
|
||||
|
||||
1. 2-4 人一起预约时,往往会偏向于预约并排或对面的整个空座位,这时候工具会按照一定策略查询搜索符合条件的座位,并预约并排或对面的整个座位,而不是各自独立预约。
|
||||
2. 预约时会考虑到组内用户的预约时间是否冲突,若冲突则会提示用户是否继续预约,若用户选择继续预约,则会按需要调整预约时间,再进行预约。
|
||||
3. 对于比较固定的用户,会考虑在定时任务管理中添加如 ‘每日任务’ ‘每周任务’ 等选项,用户可以根据需要设置定时任务重复的日期范围,自动完成预约,签到,续约等操作。
|
||||
|
||||
不过由于本人的时间和能力有限,也需要考虑到图书馆的正常运行,所以后续功能会有所取舍,但也许会进行一些小的功能验证。
|
||||
|
||||
#### 其他功能建议?
|
||||
|
||||
如果你有其他功能建议,或者遇到了什么功能性,操作上的问题,欢迎提交 Issue 到本项目。
|
||||
如果你有足够的开发能力,欢迎为本项目提交 PR,也可以 Fork 本项目,根据自己的需求进行修改和完善。
|
||||
|
||||
### 联系我
|
||||
|
||||
- 项目维护:[KenanZhu (Nanoki)](https://github.com/KenanZhu)
|
||||
- 电子邮箱:<nanoki_zh@163.com>
|
||||
|
||||
_**Free to use** —— AutoLibrary 是一个基于 MIT 协议免费开源的工具_
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -13,6 +13,13 @@ from base.MsgBase import MsgBase
|
||||
|
||||
|
||||
class LibOperator(MsgBase):
|
||||
"""
|
||||
Base abstract class for library operation.
|
||||
|
||||
This class provides the foundation for library-related operations, inheriting
|
||||
message handling and tracing abilities from MsgBase. It serves as an abstract
|
||||
base class that must be subclassed to implement specific library functionality.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
+19
-3
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -12,6 +12,22 @@ import queue
|
||||
|
||||
|
||||
class MsgBase:
|
||||
"""
|
||||
Base class for message and trace abilities (thread-safe).
|
||||
|
||||
This class provides the foundation for message handling and tracing
|
||||
abilities based on the provided input and output queues. It enables
|
||||
thread-safe communication between components using queue-based messaging.
|
||||
|
||||
Args:
|
||||
input_queue (queue.Queue): The input queue for receiving messages.
|
||||
output_queue (queue.Queue): The output queue for sending messages.
|
||||
|
||||
Usage:
|
||||
This class must be initialized with input and output queues. The queue
|
||||
provider (the caller of this class or its subclasses) must explicitly
|
||||
implement queue polling to retrieve and process messages.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -29,7 +45,7 @@ class MsgBase:
|
||||
msg: str
|
||||
):
|
||||
|
||||
self._output_queue.put(f"[{self._class_name:<12}] >>> : {msg}")
|
||||
self._output_queue.put(f"[{self._class_name:<15}] >>> : {msg}")
|
||||
|
||||
|
||||
def _showTrace(
|
||||
@@ -38,7 +54,7 @@ class MsgBase:
|
||||
):
|
||||
|
||||
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||||
self._output_queue.put(f"{timestamp}-[{self._class_name:<12}] : {msg}")
|
||||
self._output_queue.put(f"{timestamp}-[{self._class_name:<15}] : {msg}")
|
||||
|
||||
|
||||
def _waitMsg(
|
||||
|
||||
+19
-14
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -20,7 +20,9 @@ from PySide6.QtCore import (
|
||||
QTimer, Qt
|
||||
)
|
||||
|
||||
from gui.AppInfo import AL_VERSION
|
||||
from gui.ALVersionInfo import (
|
||||
AL_VERSION, AL_COMMIT_SHA, AL_COMMIT_DATE, AL_BUILD_DATE
|
||||
)
|
||||
from gui.Ui_ALAboutDialog import Ui_ALAboutDialog
|
||||
|
||||
from gui import AutoLibraryResource
|
||||
@@ -30,7 +32,7 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
parent = None
|
||||
):
|
||||
super().__init__(parent)
|
||||
|
||||
@@ -43,7 +45,7 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
self
|
||||
):
|
||||
|
||||
self.LogoIconLabel.setPixmap(QIcon(":/res/icon/icons/AutoLibrary.ico").pixmap(48, 48))
|
||||
self.LogoIconLabel.setPixmap(QIcon(":/res/icon/icons/AutoLibrary_32x32.ico").pixmap(48, 48))
|
||||
info_text = self.generateAboutText()
|
||||
self.AboutInfoEdit.setHtml(info_text)
|
||||
self.AboutInfoEdit.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
@@ -64,24 +66,27 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
about_text = f"""
|
||||
<h4>Version Information:</h4>
|
||||
Version: {AL_VERSION}<br>
|
||||
Commit SHA: {AL_COMMIT_SHA}<br>
|
||||
Commit date: {AL_COMMIT_DATE}<br>
|
||||
Build date: {AL_BUILD_DATE}<br>
|
||||
Python version: {platform.python_version()}<br>
|
||||
Qt version: {self.getQtVersion()}<br>
|
||||
|
||||
<h4>Author Information:</h4>
|
||||
Developer: KenanZhu<br>
|
||||
Contact: nanoki_zh@163.com<br>
|
||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;">https://www.github.com/KenanZhu</a><br>
|
||||
|
||||
<h4>Project Information:</h4>
|
||||
License: MIT License<br>
|
||||
Project repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration: none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
||||
Project website: <a href="https://www.autolibrary.cv/" style="text-decoration: none;">https://www.autolibrary.cv/</a><br>
|
||||
|
||||
<h4>System Information:</h4>
|
||||
Processor: {platform.processor()}<br>
|
||||
Operating system: {os_info['system']}<br>
|
||||
System version: {os_info['version']}<br>
|
||||
System architecture: {os_info['architecture']}<br>
|
||||
|
||||
<h4>Project Information:</h4>
|
||||
License: MIT License<br>
|
||||
Project repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration: none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
||||
Project website: <a href="https://www.autolibrary.cv/" style="text-decoration: none;">https://www.autolibrary.cv/</a><br>
|
||||
|
||||
<h4>Author Information:</h4>
|
||||
Developer: KenanZhu<br>
|
||||
Contact: nanoki_zh@163.com<br>
|
||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;">https://www.github.com/KenanZhu</a><br>
|
||||
"""
|
||||
return about_text
|
||||
|
||||
|
||||
+56
-21
@@ -6,25 +6,28 @@
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>300</width>
|
||||
<height>300</height>
|
||||
<width>400</width>
|
||||
<height>400</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>300</width>
|
||||
<height>300</height>
|
||||
<width>400</width>
|
||||
<height>400</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>300</height>
|
||||
<height>400</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>关于 - AutoLibrary</string>
|
||||
</property>
|
||||
<property name="sizeGripEnabled">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="ALAboutDialogLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
@@ -96,23 +99,55 @@
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTextEdit" name="AboutInfoEdit">
|
||||
<property name="font">
|
||||
<font>
|
||||
<family>Courier New</family>
|
||||
<bold>false</bold>
|
||||
</font>
|
||||
<layout class="QHBoxLayout" name="AboutInfoLayout">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="lineWrapMode">
|
||||
<enum>QTextEdit::LineWrapMode::NoWrap</enum>
|
||||
</property>
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="textInteractionFlags">
|
||||
<set>Qt::TextInteractionFlag::TextBrowserInteraction</set>
|
||||
</property>
|
||||
</widget>
|
||||
<item>
|
||||
<widget class="QFrame" name="frame">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>56</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>56</width>
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTextEdit" name="AboutInfoEdit">
|
||||
<property name="font">
|
||||
<font>
|
||||
<family>Courier New</family>
|
||||
<bold>false</bold>
|
||||
</font>
|
||||
</property>
|
||||
<property name="lineWrapMode">
|
||||
<enum>QTextEdit::LineWrapMode::NoWrap</enum>
|
||||
</property>
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="textInteractionFlags">
|
||||
<set>Qt::TextInteractionFlag::TextBrowserInteraction</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="CopyButton">
|
||||
|
||||
@@ -1,40 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import queue
|
||||
|
||||
from enum import Enum
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, Signal, Slot, QDateTime
|
||||
Slot, QDateTime
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QLabel, QDialog, QWidget, QSpinBox, QVBoxLayout,
|
||||
QLabel, QDialog, QWidget, QSpinBox,
|
||||
QHBoxLayout, QGridLayout, QDateTimeEdit
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QCloseEvent
|
||||
)
|
||||
|
||||
from gui.Ui_ALAddTimerTaskDialog import Ui_ALAddTimerTaskDialog
|
||||
|
||||
|
||||
class TimerTaskStatus(Enum):
|
||||
|
||||
PENDING = "等待中"
|
||||
READY = "已就绪"
|
||||
RUNNING = "执行中"
|
||||
EXECUTED = "已执行"
|
||||
ERROR = "执行失败"
|
||||
OUTDATED = "已过期"
|
||||
|
||||
|
||||
|
||||
+525
-266
File diff suppressed because it is too large
Load Diff
+112
-41
@@ -63,7 +63,7 @@
|
||||
</property>
|
||||
<widget class="QWidget" name="UserConfigWidget">
|
||||
<attribute name="title">
|
||||
<string>用户设置</string>
|
||||
<string>用户配置</string>
|
||||
</attribute>
|
||||
<layout class="QHBoxLayout" name="UserConfigWidgetLayout">
|
||||
<property name="spacing">
|
||||
@@ -93,11 +93,26 @@
|
||||
<string>用户列表</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="UserListLayout">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QListWidget" name="UserListWidget">
|
||||
<widget class="QTreeWidget" name="UserTreeWidget">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>230</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -107,18 +122,58 @@
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="isWrapping" stdset="0">
|
||||
<bool>false</bool>
|
||||
<property name="sizeAdjustPolicy">
|
||||
<enum>QAbstractScrollArea::SizeAdjustPolicy::AdjustIgnored</enum>
|
||||
</property>
|
||||
<property name="viewMode">
|
||||
<enum>QListView::ViewMode::ListMode</enum>
|
||||
<property name="tabKeyNavigation">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="currentRow">
|
||||
<number>-1</number>
|
||||
<property name="dragEnabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="dragDropMode">
|
||||
<enum>QAbstractItemView::DragDropMode::DragDrop</enum>
|
||||
</property>
|
||||
<property name="defaultDropAction">
|
||||
<enum>Qt::DropAction::MoveAction</enum>
|
||||
</property>
|
||||
<property name="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="sortingEnabled">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="animated">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="allColumnsShowFocus">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="headerHidden">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="columnCount">
|
||||
<number>2</number>
|
||||
</property>
|
||||
<attribute name="headerCascadingSectionResizes">
|
||||
<bool>false</bool>
|
||||
</attribute>
|
||||
<attribute name="headerHighlightSections">
|
||||
<bool>false</bool>
|
||||
</attribute>
|
||||
<attribute name="headerShowSortIndicator" stdset="0">
|
||||
<bool>false</bool>
|
||||
</attribute>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string notr="true">分组/用户</string>
|
||||
</property>
|
||||
</column>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>状态</string>
|
||||
</property>
|
||||
</column>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
@@ -236,7 +291,7 @@
|
||||
<widget class="QLabel" name="PasswordLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -325,7 +380,7 @@
|
||||
<widget class="QLabel" name="UsernameKabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -416,7 +471,7 @@
|
||||
<widget class="QLabel" name="RoomLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -435,7 +490,7 @@
|
||||
<widget class="QLabel" name="FloorLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -454,7 +509,7 @@
|
||||
<widget class="QLabel" name="ExpectRenewDurationLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -473,7 +528,7 @@
|
||||
<widget class="QLabel" name="EndTimeLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>30</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -556,7 +611,7 @@
|
||||
<widget class="QLabel" name="SeatIDLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -575,7 +630,7 @@
|
||||
<widget class="QLabel" name="ExpectDurationLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -594,7 +649,7 @@
|
||||
<widget class="QLabel" name="DateLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -738,7 +793,7 @@
|
||||
</time>
|
||||
</property>
|
||||
<property name="displayFormat">
|
||||
<string>H:mm</string>
|
||||
<string>HH:mm</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
@@ -746,7 +801,7 @@
|
||||
<widget class="QLabel" name="PlaceLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -850,7 +905,7 @@
|
||||
<widget class="QSpinBox" name="MaxBeginTimeDiffSpinBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>65</width>
|
||||
<width>55</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -869,6 +924,9 @@
|
||||
<property name="stepType">
|
||||
<enum>QAbstractSpinBox::StepType::AdaptiveDecimalStepType</enum>
|
||||
</property>
|
||||
<property name="value">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
@@ -902,7 +960,7 @@
|
||||
<widget class="QLabel" name="MaxBeginTimeDiffLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -921,7 +979,7 @@
|
||||
<widget class="QLabel" name="MaxEndTimeDiffLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -965,7 +1023,7 @@
|
||||
</time>
|
||||
</property>
|
||||
<property name="displayFormat">
|
||||
<string>H:mm</string>
|
||||
<string>HH:mm</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
@@ -973,7 +1031,7 @@
|
||||
<widget class="QLabel" name="BeginTimeLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -994,7 +1052,20 @@
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QSpinBox" name="MaxRenewTimeDiffSpinBox"/>
|
||||
<widget class="QSpinBox" name="MaxRenewTimeDiffSpinBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>55</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>16777215</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QCheckBox" name="PreferLateRenewTimeCheckBox">
|
||||
@@ -1024,7 +1095,7 @@
|
||||
<widget class="QLabel" name="label">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
@@ -1047,9 +1118,9 @@
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QWidget" name="SystemConfigWidget">
|
||||
<widget class="QWidget" name="RunConfigWidget">
|
||||
<attribute name="title">
|
||||
<string>系统设置</string>
|
||||
<string>运行配置</string>
|
||||
</attribute>
|
||||
<layout class="QGridLayout" name="SystemConfigWidgetLayout">
|
||||
<property name="leftMargin">
|
||||
@@ -1579,7 +1650,7 @@
|
||||
</property>
|
||||
<layout class="QGridLayout" name="CurrentConfigLayout">
|
||||
<item row="1" column="0">
|
||||
<widget class="QLineEdit" name="CurrentSystemConfigEdit">
|
||||
<widget class="QLineEdit" name="CurrentRunConfigEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
@@ -1620,7 +1691,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="0">
|
||||
<widget class="QLabel" name="CurrentSystemConfigLabel">
|
||||
<widget class="QLabel" name="CurrentRunConfigLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
@@ -1634,7 +1705,7 @@
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>当前系统配置路径:</string>
|
||||
<string>当前运行配置路径:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
@@ -1658,7 +1729,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="QPushButton" name="BrowseCurrentSystemConfigButton">
|
||||
<widget class="QPushButton" name="BrowseCurrentRunConfigButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>35</width>
|
||||
@@ -1672,7 +1743,7 @@
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>;;;</string>
|
||||
<string>...</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
@@ -1721,7 +1792,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="0">
|
||||
<widget class="QLineEdit" name="ExportSystemConfigEdit">
|
||||
<widget class="QLineEdit" name="ExportRunConfigEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
@@ -1737,7 +1808,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="0">
|
||||
<widget class="QLabel" name="ExportSystemConfigLabel">
|
||||
<widget class="QLabel" name="ExportRunConfigLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
@@ -1751,7 +1822,7 @@
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>系统配置导出路径:</string>
|
||||
<string>运行配置导出路径:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
@@ -1794,7 +1865,7 @@
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="QPushButton" name="BrowseExportSystemConfigButton">
|
||||
<widget class="QPushButton" name="BrowseExportRunConfigButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>35</width>
|
||||
@@ -1836,12 +1907,12 @@
|
||||
</item>
|
||||
</layout>
|
||||
<zorder>ExportUserConfigEdit</zorder>
|
||||
<zorder>ExportSystemConfigLabel</zorder>
|
||||
<zorder>ExportRunConfigLabel</zorder>
|
||||
<zorder>BrowseExportUserConfigButton</zorder>
|
||||
<zorder>ExportUserConfigLabel</zorder>
|
||||
<zorder>BrowseExportSystemConfigButton</zorder>
|
||||
<zorder>BrowseExportRunConfigButton</zorder>
|
||||
<zorder>ExportConfigButton</zorder>
|
||||
<zorder>ExportSystemConfigEdit</zorder>
|
||||
<zorder>ExportRunConfigEdit</zorder>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
|
||||
+56
-171
@@ -1,19 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import queue
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, Signal, Slot, QDir, QFileInfo, QTimer, QThread, QUrl,
|
||||
Qt, Signal, Slot, QDir, QFileInfo, QTimer, QUrl,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QMainWindow, QMenu, QSystemTrayIcon
|
||||
@@ -26,130 +25,16 @@ from gui.Ui_ALMainWindow import Ui_ALMainWindow
|
||||
from gui.ALConfigWidget import ALConfigWidget
|
||||
from gui.ALTimerTaskWidget import ALTimerTaskWidget
|
||||
from gui.ALAboutDialog import ALAboutDialog
|
||||
from gui.ALMainWorkers import TimerTaskWorker, AutoLibWorker
|
||||
|
||||
from gui import AutoLibraryResource
|
||||
|
||||
from operators.AutoLib import AutoLib
|
||||
from utils.ConfigReader import ConfigReader
|
||||
|
||||
|
||||
class AutoLibWorker(QThread):
|
||||
|
||||
finishedSignal = Signal()
|
||||
showTraceSignal = Signal(str)
|
||||
showMsgSignal = Signal(str)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
config_paths: dict
|
||||
):
|
||||
|
||||
super().__init__()
|
||||
|
||||
self.__input_queue = input_queue
|
||||
self.__output_queue = output_queue
|
||||
self.__config_paths = config_paths
|
||||
|
||||
|
||||
def checkTimeAvailable(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
current_time = time.strftime("%H:%M", time.localtime())
|
||||
if current_time >= "23:30" or current_time <= "07:30":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def checkConfigPaths(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
if not all(
|
||||
os.path.exists(path) for path in self.__config_paths.values()
|
||||
):
|
||||
self.showTraceSignal.emit(
|
||||
"配置文件路径不存在, 请检查配置文件路径是否正确。"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def run(
|
||||
self
|
||||
):
|
||||
|
||||
auto_lib = None
|
||||
try:
|
||||
if not self.checkTimeAvailable():
|
||||
self.showTraceSignal.emit(
|
||||
"当前时间不在图书馆开放时间内。\n"\
|
||||
" 请在 07:30 - 23:30 之间尝试"
|
||||
)
|
||||
return
|
||||
if not self.checkConfigPaths():
|
||||
return
|
||||
self.showTraceSignal.emit("AutoLibrary 开始运行")
|
||||
auto_lib = AutoLib(
|
||||
self.__input_queue,
|
||||
self.__output_queue,
|
||||
)
|
||||
auto_lib.run(
|
||||
ConfigReader(self.__config_paths["system"]),
|
||||
ConfigReader(self.__config_paths["users"]),
|
||||
)
|
||||
except Exception as e:
|
||||
self.showTraceSignal.emit(
|
||||
f"AutoLibrary 运行时发生异常 : {e}"
|
||||
)
|
||||
finally:
|
||||
if auto_lib:
|
||||
auto_lib.close()
|
||||
self.showTraceSignal.emit("AutoLibrary 运行结束")
|
||||
self.finishedSignal.emit()
|
||||
|
||||
|
||||
class TimerTaskWorker(AutoLibWorker):
|
||||
|
||||
finishedSignal_TimerWorker = Signal(dict)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
timer_task: dict,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
config_paths: dict
|
||||
):
|
||||
|
||||
super().__init__(
|
||||
input_queue,
|
||||
output_queue,
|
||||
config_paths,
|
||||
)
|
||||
|
||||
self.__timer_task = timer_task
|
||||
self.__stopped = False
|
||||
|
||||
def run(
|
||||
self
|
||||
):
|
||||
|
||||
self.showTraceSignal.emit(
|
||||
f"定时任务 {self.__timer_task['name']} 开始运行"
|
||||
)
|
||||
super().run()
|
||||
self.showTraceSignal.emit(
|
||||
f"定时任务 {self.__timer_task['name']} 运行结束"
|
||||
)
|
||||
self.finishedSignal_TimerWorker.emit(self.__timer_task)
|
||||
|
||||
|
||||
class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
|
||||
timerTaskIsRunning = Signal(dict)
|
||||
timerTaskIsExecuted = Signal(dict)
|
||||
timerTaskIsError = Signal(dict)
|
||||
|
||||
def __init__(
|
||||
self
|
||||
@@ -157,24 +42,23 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
|
||||
super().__init__()
|
||||
self.__class_name = self.__class__.__name__
|
||||
|
||||
self.setupUi(self)
|
||||
self.__input_queue = queue.Queue()
|
||||
self.__output_queue = queue.Queue()
|
||||
self.__timer_task_queue = queue.Queue()
|
||||
script_path = sys.executable
|
||||
script_dir = QFileInfo(script_path).absoluteDir()
|
||||
self.__config_paths = {
|
||||
"system": QDir.toNativeSeparators(script_dir.absoluteFilePath("system.json")),
|
||||
"users": QDir.toNativeSeparators(script_dir.absoluteFilePath("users.json")),
|
||||
"run": QDir.toNativeSeparators(script_dir.absoluteFilePath("run.json")),
|
||||
"user": QDir.toNativeSeparators(script_dir.absoluteFilePath("user.json")),
|
||||
"timer_task": QDir.toNativeSeparators(script_dir.absoluteFilePath("timer_task.json")),
|
||||
}
|
||||
self.__alTimerTaskWidget = None
|
||||
self.__alConfigWidget = None
|
||||
self.__alAboutDialog = None
|
||||
self.__auto_lib_thread = None
|
||||
self.__current_timer_task_thread = None
|
||||
self.__is_running_timer_task = False
|
||||
|
||||
self.setupUi(self)
|
||||
self.modifyUi()
|
||||
self.setupTray()
|
||||
self.connectSignals()
|
||||
@@ -186,20 +70,28 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
self.icon = QIcon(":/res/icon/icons/AutoLibrary.ico")
|
||||
self.icon = QIcon(":/res/icon/icons/AutoLibrary_32x32.ico")
|
||||
self.setWindowIcon(self.icon)
|
||||
self.MessageIOTextEdit.setFont(QFont("Courier New", 10))
|
||||
self.ManualAction.triggered.connect(self.onManualActionTriggered)
|
||||
self.AboutAction.triggered.connect(self.onAboutActionTriggered)
|
||||
|
||||
# initialize timer task widget, but not show it
|
||||
self.__alTimerTaskWidget = ALTimerTaskWidget(self, self.__config_paths["timer_task"])
|
||||
self.timerTaskIsRunning.connect(self.__alTimerTaskWidget.onTimerTaskIsRunning)
|
||||
self.timerTaskIsExecuted.connect(self.__alTimerTaskWidget.onTimerTaskIsExecuted)
|
||||
self.timerTaskIsError.connect(self.__alTimerTaskWidget.onTimerTaskIsError)
|
||||
self.__alTimerTaskWidget.timerTaskIsReady.connect(self.onTimerTaskIsReady)
|
||||
self.__alTimerTaskWidget.timerTaskWidgetClosed.connect(self.onTimerTaskWidgetClosed)
|
||||
self.__alTimerTaskWidget.setWindowFlags(Qt.WindowType.Window|Qt.WindowType.WindowCloseButtonHint)
|
||||
|
||||
|
||||
def onAboutActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__alAboutDialog is None:
|
||||
self.__alAboutDialog = ALAboutDialog(self)
|
||||
self.__alAboutDialog.show()
|
||||
about_dialog = ALAboutDialog(self)
|
||||
about_dialog.exec()
|
||||
|
||||
|
||||
def onManualActionTriggered(
|
||||
@@ -274,8 +166,8 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
event: QCloseEvent
|
||||
):
|
||||
|
||||
if self.__timer and self.__timer.isActive():
|
||||
self.__timer.stop()
|
||||
if self.__msg_queue_timer and self.__msg_queue_timer.isActive():
|
||||
self.__msg_queue_timer.stop()
|
||||
if self.__timer_task_timer and self.__timer_task_timer.isActive():
|
||||
self.__timer_task_timer.stop()
|
||||
if self.__is_running_timer_task:
|
||||
@@ -286,7 +178,7 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.__alTimerTaskWidget.deleteLater()
|
||||
if self.__alConfigWidget:
|
||||
self.__alConfigWidget.close()
|
||||
self.__alConfigWidget.deleteLater()
|
||||
# the config widget is already deleted in the 'self.onConfigWidgetClosed'
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
@@ -308,9 +200,9 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
self.__timer = QTimer()
|
||||
self.__timer.timeout.connect(self.pollMsgQueue)
|
||||
self.__timer.start(100)
|
||||
self.__msg_queue_timer = QTimer()
|
||||
self.__msg_queue_timer.timeout.connect(self.pollMsgQueue)
|
||||
self.__msg_queue_timer.start(100)
|
||||
|
||||
|
||||
def startTimerTaskPolling(
|
||||
@@ -334,7 +226,7 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.timerTaskIsRunning.emit(timer_task)
|
||||
self.__timer_task_timer.stop()
|
||||
self.__is_running_timer_task = True
|
||||
self.setControlButtons(False, False, True)
|
||||
self.setControlButtons(True, True, False)
|
||||
if not timer_task["silent"]:
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
@@ -350,8 +242,6 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.__config_paths
|
||||
)
|
||||
self.__current_timer_task_thread.finishedSignal_TimerWorker.connect(self.onTimerTaskFinished)
|
||||
self.__current_timer_task_thread.showTraceSignal.connect(self.showTrace)
|
||||
self.__current_timer_task_thread.showMsgSignal.connect(self.showMsg)
|
||||
self.__current_timer_task_thread.start()
|
||||
except queue.Empty:
|
||||
self.__is_running_timer_task = False
|
||||
@@ -361,13 +251,17 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
def setControlButtons(
|
||||
self,
|
||||
config_button_enabled: bool,
|
||||
start_button_enabled: bool,
|
||||
stop_button_enabled: bool
|
||||
stop_button_enabled: bool,
|
||||
start_button_enabled: bool
|
||||
):
|
||||
|
||||
self.ConfigButton.setEnabled(config_button_enabled)
|
||||
self.StartButton.setEnabled(start_button_enabled)
|
||||
self.StopButton.setEnabled(stop_button_enabled)
|
||||
# if the enable is None, then keep the original state
|
||||
if config_button_enabled is not None:
|
||||
self.ConfigButton.setEnabled(config_button_enabled)
|
||||
if stop_button_enabled is not None:
|
||||
self.StopButton.setEnabled(stop_button_enabled)
|
||||
if start_button_enabled is not None:
|
||||
self.StartButton.setEnabled(start_button_enabled)
|
||||
|
||||
@Slot()
|
||||
def showMsg(
|
||||
@@ -375,7 +269,7 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
msg: str
|
||||
):
|
||||
|
||||
self.appendToTextEdit(f"[{self.__class_name:<12}] >>> : {msg}")
|
||||
self.__output_queue.put(f"[{self.__class_name:<15}] >>> : {msg}")
|
||||
|
||||
@Slot()
|
||||
def showTrace(
|
||||
@@ -384,7 +278,7 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
):
|
||||
|
||||
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||||
self.appendToTextEdit(f"{timestamp}-[{self.__class_name:<12}] : {msg}")
|
||||
self.__output_queue.put(f"{timestamp}-[{self.__class_name:<15}] : {msg}")
|
||||
|
||||
@Slot()
|
||||
def pollMsgQueue(
|
||||
@@ -398,7 +292,6 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
except queue.Empty:
|
||||
pass
|
||||
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskWidgetClosed(
|
||||
self
|
||||
@@ -406,7 +299,6 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
|
||||
self.TimerTaskWidgetButton.setEnabled(True)
|
||||
|
||||
|
||||
@Slot(dict)
|
||||
def onConfigWidgetClosed(
|
||||
self,
|
||||
@@ -417,13 +309,11 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.__alConfigWidget.configWidgetCloseSingal.disconnect(self.onConfigWidgetClosed)
|
||||
self.__alConfigWidget.deleteLater()
|
||||
self.__alConfigWidget = None
|
||||
self.ConfigButton.setEnabled(True)
|
||||
self.StartButton.setEnabled(True)
|
||||
self.StopButton.setEnabled(False)
|
||||
self.setControlButtons(True, None, None)
|
||||
self.__config_paths = config_paths
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskReady(
|
||||
def onTimerTaskIsReady(
|
||||
self,
|
||||
timer_task: dict
|
||||
):
|
||||
@@ -433,39 +323,37 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
@Slot(dict)
|
||||
def onTimerTaskFinished(
|
||||
self,
|
||||
is_error: bool,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
self.__current_timer_task_thread.wait(1000)
|
||||
self.__current_timer_task_thread.finishedSignal_TimerWorker.disconnect(self.onTimerTaskFinished)
|
||||
self.__current_timer_task_thread.showTraceSignal.disconnect(self.showTrace)
|
||||
self.__current_timer_task_thread.showMsgSignal.disconnect(self.showMsg)
|
||||
self.__current_timer_task_thread.deleteLater()
|
||||
self.__current_timer_task_thread = None
|
||||
self.setControlButtons(True, True, False)
|
||||
self.setControlButtons(None, False, True)
|
||||
self.__is_running_timer_task = False
|
||||
self.__timer_task_timer.start(500)
|
||||
timer_task["executed"] = True
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n定时任务 '{timer_task['name']}' 执行完成",
|
||||
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self.showTrace(f"定时任务 {timer_task['name']} 执行完成, uuid: {timer_task['task_uuid']}")
|
||||
self.timerTaskIsExecuted.emit(timer_task)
|
||||
self.showTrace(
|
||||
f"定时任务 {timer_task['name']} 执行{'失败' if is_error else '完成'}, uuid: {timer_task['task_uuid']}"
|
||||
)
|
||||
if not is_error:
|
||||
self.timerTaskIsExecuted.emit(timer_task)
|
||||
else:
|
||||
self.timerTaskIsError.emit(timer_task)
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskWidgetButtonClicked(
|
||||
self
|
||||
):
|
||||
if self.__alTimerTaskWidget is None:
|
||||
self.__alTimerTaskWidget = ALTimerTaskWidget(self)
|
||||
self.timerTaskIsRunning.connect(self.__alTimerTaskWidget.onTimerTaskIsRunning)
|
||||
self.timerTaskIsExecuted.connect(self.__alTimerTaskWidget.onTimerTaskIsExecuted)
|
||||
self.__alTimerTaskWidget.timerTaskReady.connect(self.onTimerTaskReady)
|
||||
self.__alTimerTaskWidget.timerTaskWidgetClosed.connect(self.onTimerTaskWidgetClosed)
|
||||
self.__alTimerTaskWidget.setWindowFlags(Qt.Window)
|
||||
|
||||
self.__alTimerTaskWidget.show()
|
||||
self.__alTimerTaskWidget.raise_()
|
||||
self.__alTimerTaskWidget.activateWindow()
|
||||
@@ -482,8 +370,6 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.__config_paths
|
||||
)
|
||||
self.__alConfigWidget.configWidgetCloseSingal.connect(self.onConfigWidgetClosed)
|
||||
self.__alConfigWidget.setWindowFlags(Qt.Window)
|
||||
self.__alConfigWidget.setWindowModality(Qt.ApplicationModal)
|
||||
self.__alConfigWidget.show()
|
||||
self.__alConfigWidget.raise_()
|
||||
self.__alConfigWidget.activateWindow()
|
||||
@@ -494,7 +380,7 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
self.setControlButtons(False, False, True)
|
||||
self.setControlButtons(None, True, False)
|
||||
if self.__auto_lib_thread is None:
|
||||
self.__auto_lib_thread = AutoLibWorker(
|
||||
self.__input_queue,
|
||||
@@ -502,8 +388,7 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.__config_paths
|
||||
)
|
||||
self.__auto_lib_thread.finishedSignal.connect(self.onStopButtonClicked)
|
||||
self.__auto_lib_thread.showMsgSignal.connect(self.showMsg)
|
||||
self.__auto_lib_thread.showTraceSignal.connect(self.showTrace)
|
||||
self.__auto_lib_thread.finishedWithErrorSignal.connect(self.onStopButtonClicked)
|
||||
self.__auto_lib_thread.start()
|
||||
|
||||
@Slot()
|
||||
@@ -515,12 +400,11 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
self.showTrace("正在停止操作......")
|
||||
self.__auto_lib_thread.wait(2000)
|
||||
self.showTrace("操作已停止")
|
||||
self.__auto_lib_thread.showMsgSignal.disconnect(self.showMsg)
|
||||
self.__auto_lib_thread.showTraceSignal.disconnect(self.showTrace)
|
||||
self.__auto_lib_thread.finishedSignal.disconnect(self.onStopButtonClicked)
|
||||
self.__auto_lib_thread.finishedWithErrorSignal.disconnect(self.onStopButtonClicked)
|
||||
self.__auto_lib_thread.deleteLater()
|
||||
self.__auto_lib_thread = None
|
||||
self.setControlButtons(True, True, False)
|
||||
self.setControlButtons(None, False, True)
|
||||
|
||||
@Slot()
|
||||
def onSendButtonClicked(
|
||||
@@ -531,4 +415,5 @@ class ALMainWindow(QMainWindow, Ui_ALMainWindow):
|
||||
if not msg:
|
||||
return
|
||||
self.showMsg(msg)
|
||||
self.__input_queue.put(msg) # put message to input queue
|
||||
self.MessageEdit.clear()
|
||||
@@ -0,0 +1,166 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import queue
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Slot, Signal, QThread
|
||||
)
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from operators.AutoLib import AutoLib
|
||||
from utils.ConfigReader import ConfigReader
|
||||
|
||||
|
||||
class AutoLibWorker(QThread, MsgBase):
|
||||
|
||||
finishedSignal = Signal()
|
||||
finishedWithErrorSignal = Signal()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
config_paths: dict
|
||||
):
|
||||
|
||||
super().__init__(input_queue=input_queue, output_queue=output_queue)
|
||||
|
||||
self.__config_paths = config_paths
|
||||
|
||||
|
||||
def checkTimeAvailable(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
current_time = time.strftime("%H:%M", time.localtime())
|
||||
if current_time >= "23:30" or current_time <= "07:30":
|
||||
self._showTrace(
|
||||
"当前时间不在图书馆开放时间内, 请在 07:30 - 23:30 之间尝试"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def checkConfigPaths(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
if not all(
|
||||
os.path.exists(path) for path in self.__config_paths.values()
|
||||
):
|
||||
self._showTrace("配置文件路径不存在, 请检查配置文件路径是否正确")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def loadConfigs(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
self._showTrace(
|
||||
f"正在加载配置文件, 运行配置文件路径: {self.__config_paths["run"]}"
|
||||
)
|
||||
self.__run_config = ConfigReader(self.__config_paths["run"]).getConfigs()
|
||||
self._showTrace(
|
||||
f"正在加载配置文件, 用户配置文件路径: {self.__config_paths["user"]}"
|
||||
)
|
||||
self.__user_config = ConfigReader(self.__config_paths["user"]).getConfigs()
|
||||
if self.__run_config is None or self.__user_config is None:
|
||||
self._showTrace("配置文件加载失败, 请检查配置文件是否正确")
|
||||
self._showTrace("配置文件加载失败, 请检查配置文件是否正确")
|
||||
return False
|
||||
if not self.__user_config.get("groups"):
|
||||
self._showTrace(
|
||||
"用户配置文件中无有效任务组, 请检查用户配置文件是否正确"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def run(
|
||||
self
|
||||
):
|
||||
|
||||
auto_lib = None
|
||||
self._showTrace("AutoLibrary 开始运行")
|
||||
if not self.checkTimeAvailable()\
|
||||
or not self.checkConfigPaths():
|
||||
# time or config existence check failed, skip and finish
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
if not self.loadConfigs():
|
||||
raise Exception("配置文件加载失败")
|
||||
auto_lib = AutoLib(
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self.__run_config
|
||||
)
|
||||
groups = self.__user_config.get("groups")
|
||||
for group in groups:
|
||||
if not group["enabled"]:
|
||||
self._showTrace(f"任务组 {group["name"]} 已跳过")
|
||||
continue
|
||||
self._showTrace(f"正在运行任务组 {group["name"]}")
|
||||
auto_lib.run(
|
||||
{ "users": group.get("users", []) }
|
||||
)
|
||||
except Exception as e:
|
||||
self._showTrace(f"AutoLibrary 运行时发生异常 : {e}")
|
||||
self.finishedWithErrorSignal.emit()
|
||||
return
|
||||
if auto_lib:
|
||||
auto_lib.close()
|
||||
self._showTrace("AutoLibrary 运行结束")
|
||||
self.finishedSignal.emit()
|
||||
|
||||
|
||||
class TimerTaskWorker(AutoLibWorker):
|
||||
|
||||
finishedSignal_TimerWorker = Signal(bool, dict)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
timer_task: dict,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
config_paths: dict
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue, config_paths)
|
||||
|
||||
self.__timer_task = timer_task
|
||||
self.finishedSignal.connect(self.onTimerTaskIsFinished)
|
||||
self.finishedWithErrorSignal.connect(self.onTimerTaskIsError)
|
||||
|
||||
def run(
|
||||
self
|
||||
):
|
||||
|
||||
self._showTrace(f"定时任务 {self.__timer_task['name']} 开始运行")
|
||||
super().run()
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskIsError(
|
||||
self
|
||||
):
|
||||
|
||||
self._showTrace(f"定时任务 {self.__timer_task['name']} 运行时发生异常")
|
||||
self.finishedSignal_TimerWorker.emit(True, self.__timer_task)
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskIsFinished(
|
||||
self
|
||||
):
|
||||
|
||||
self._showTrace(f"定时任务 {self.__timer_task['name']} 运行结束")
|
||||
self.finishedSignal_TimerWorker.emit(False, self.__timer_task)
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -15,7 +15,7 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
|
||||
class SeatFrame(QFrame):
|
||||
class ALSeatFrame(QFrame):
|
||||
|
||||
clicked = Signal(str)
|
||||
|
||||
@@ -28,6 +28,7 @@ class SeatFrame(QFrame):
|
||||
super().__init__(parent)
|
||||
self.__seat_number = seat_number
|
||||
self.__is_selected = False
|
||||
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -18,10 +18,10 @@ from PySide6.QtWidgets import (
|
||||
from PySide6.QtGui import (
|
||||
QPainter, QWheelEvent, QCloseEvent
|
||||
)
|
||||
from gui.SeatFrame import SeatFrame
|
||||
from gui.ALSeatFrame import ALSeatFrame
|
||||
|
||||
|
||||
class SeatMapWidget(QWidget):
|
||||
class ALSeatMapWidget(QWidget):
|
||||
|
||||
seatMapWidgetClosed = Signal(list)
|
||||
|
||||
@@ -34,12 +34,13 @@ class SeatMapWidget(QWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.__floor = floor
|
||||
self.__room = room
|
||||
self.__seats_data = seats_data
|
||||
self.__selected_seats = []
|
||||
self.__seat_frames = {}
|
||||
self.__confirmed = False
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
|
||||
@@ -115,11 +116,37 @@ class SeatMapWidget(QWidget):
|
||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
||||
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
):
|
||||
|
||||
if not self.__confirmed:
|
||||
self.clearSelections()
|
||||
self.seatMapWidgetClosed.emit(self.__selected_seats)
|
||||
super().closeEvent(event)
|
||||
|
||||
@@ -160,7 +187,7 @@ class SeatMapWidget(QWidget):
|
||||
seats_number = [seat.strip() for seat in row.split(",")]
|
||||
for seat_number in seats_number:
|
||||
if seat_number:
|
||||
seat_widget = SeatFrame(seat_number)
|
||||
seat_widget = ALSeatFrame(seat_number)
|
||||
seat_widget.clicked.connect(self.onSeatClicked)
|
||||
self.SeatsContainerLayout.addWidget(seat_widget, row_idx, col_idx)
|
||||
self.__seat_frames[seat_number] = seat_widget
|
||||
@@ -241,6 +268,7 @@ class SeatMapWidget(QWidget):
|
||||
self
|
||||
):
|
||||
|
||||
self.__confirmed = True
|
||||
self.close()
|
||||
|
||||
@Slot()
|
||||
@@ -248,5 +276,5 @@ class SeatMapWidget(QWidget):
|
||||
self
|
||||
):
|
||||
|
||||
self.clearSelections()
|
||||
self.__confirmed = False
|
||||
self.close()
|
||||
+218
-25
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -8,9 +8,7 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import queue
|
||||
import copy
|
||||
|
||||
from enum import Enum
|
||||
from datetime import datetime, timedelta
|
||||
@@ -29,6 +27,16 @@ from PySide6.QtGui import (
|
||||
from gui.Ui_ALTimerTaskWidget import Ui_ALTimerTaskWidget
|
||||
from gui.ALAddTimerTaskDialog import ALAddTimerTaskWidget, TimerTaskStatus
|
||||
|
||||
from utils.ConfigReader import ConfigReader
|
||||
from utils.ConfigWriter import ConfigWriter
|
||||
|
||||
|
||||
class SortPolicy(Enum):
|
||||
|
||||
BY_NAME = "按名称"
|
||||
BY_ADD_TIME = "按添加时间"
|
||||
BY_EXECUTE_TIME = "按执行时间"
|
||||
|
||||
|
||||
class TimerTaskItemWidget(QWidget):
|
||||
|
||||
@@ -39,8 +47,8 @@ class TimerTaskItemWidget(QWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.__timer_task = timer_task
|
||||
|
||||
self.modifyUi()
|
||||
|
||||
|
||||
@@ -83,6 +91,9 @@ class TimerTaskItemWidget(QWidget):
|
||||
case TimerTaskStatus.EXECUTED:
|
||||
TaskStatusText = "已执行"
|
||||
TaskStatusColor = "#4CAF50"
|
||||
case TimerTaskStatus.ERROR:
|
||||
TaskStatusText = "执行失败"
|
||||
TaskStatusColor = "#FF5722"
|
||||
case TimerTaskStatus.OUTDATED:
|
||||
TaskStatusText = "已过期"
|
||||
TaskStatusColor = "#FF5722"
|
||||
@@ -125,22 +136,40 @@ class TimerTaskItemWidget(QWidget):
|
||||
|
||||
class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
|
||||
timerTasksChanged = Signal(list)
|
||||
timerTaskReady = Signal(dict)
|
||||
timerTasksChanged = Signal()
|
||||
timerTaskIsReady = Signal(dict)
|
||||
timerTaskWidgetClosed = Signal()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
parent = None,
|
||||
timer_tasks_config_path: str = ""
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.__timer_tasks = []
|
||||
self.__check_timer = None
|
||||
self.__sort_policy = SortPolicy.BY_EXECUTE_TIME
|
||||
self.__sort_order = Qt.SortOrder.AscendingOrder
|
||||
self.__timer_tasks_config_path = timer_tasks_config_path
|
||||
|
||||
self.setupUi(self)
|
||||
self.connectSignals()
|
||||
self.setupTimer()
|
||||
if not self.initializeTimerTasks():
|
||||
return
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.AddTimerTaskButton.clicked.connect(self.addTask)
|
||||
self.ClearAllTimerTasksButton.clicked.connect(self.clearAllTasks)
|
||||
self.TimerTaskSortTypeComboBox.currentIndexChanged.connect(self.onSortPolicyComboBoxChanged)
|
||||
self.TimerTaskSortOrderToggleButton.clicked.connect(self.onSortOrderToggleButtonClicked)
|
||||
self.timerTasksChanged.connect(self.onTimerTasksChanged)
|
||||
|
||||
|
||||
def setupTimer(
|
||||
@@ -152,12 +181,104 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
self.__check_timer.start(500)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
def initializeTimerTasks(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
timer_tasks = self.loadTimerTasks(self.__timer_tasks_config_path)
|
||||
if timer_tasks is not None:
|
||||
self.__timer_tasks = timer_tasks
|
||||
self.timerTasksChanged.emit()
|
||||
return True
|
||||
timer_tasks = []
|
||||
if self.saveTimerTasks(self.__timer_tasks_config_path, copy.deepcopy(timer_tasks)):
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"信息 - AutoLibrary",
|
||||
f"定时任务配置文件初始化完成: \n{self.__timer_tasks_config_path}"
|
||||
)
|
||||
self.__timer_tasks = timer_tasks
|
||||
self.updateTimerTaskList()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def loadTimerTasks(
|
||||
self,
|
||||
timer_tasks_config_path: str
|
||||
) -> list:
|
||||
|
||||
try:
|
||||
if not timer_tasks_config_path or not os.path.exists(timer_tasks_config_path):
|
||||
raise Exception("定时任务配置文件不存在")
|
||||
timer_tasks = ConfigReader(timer_tasks_config_path).getConfigs()
|
||||
if timer_tasks and "timer_tasks" in timer_tasks:
|
||||
for task in timer_tasks["timer_tasks"]:
|
||||
task["add_time"] = datetime.strptime(task["add_time"], "%Y-%m-%d %H:%M:%S")
|
||||
task["execute_time"] = datetime.strptime(task["execute_time"], "%Y-%m-%d %H:%M:%S")
|
||||
task["status"] = TimerTaskStatus(task["status"])
|
||||
return timer_tasks["timer_tasks"]
|
||||
raise Exception("定时任务配置文件格式错误")
|
||||
except Exception as e:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"警告 - AutoLibrary",
|
||||
f"加载定时任务配置发生错误 ! : {e}\n"\
|
||||
f"文件路径: {timer_tasks_config_path}"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def saveTimerTasks(
|
||||
self,
|
||||
timer_tasks_config_path: str,
|
||||
timer_tasks: list
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
if not timer_tasks_config_path:
|
||||
raise Exception("配置文件路径为空")
|
||||
for task in timer_tasks:
|
||||
task["add_time"] = task["add_time"].strftime("%Y-%m-%d %H:%M:%S")
|
||||
task["execute_time"] = task["execute_time"].strftime("%Y-%m-%d %H:%M:%S")
|
||||
task["status"] = task["status"].value
|
||||
ConfigWriter(
|
||||
timer_tasks_config_path,
|
||||
{ "timer_tasks": timer_tasks }
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"警告 - AutoLibrary",
|
||||
f"保存定时任务配置发生错误 ! : {e}\n"\
|
||||
f"文件路径: {timer_tasks_config_path}"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
self.AddTimerTaskButton.clicked.connect(self.addTask)
|
||||
self.ClearAllTimerTasksButton.clicked.connect(self.clearAllTasks)
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def closeEvent(
|
||||
@@ -170,6 +291,29 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
event.ignore()
|
||||
|
||||
|
||||
def sortTimerTasks(
|
||||
self,
|
||||
policy: SortPolicy = SortPolicy.BY_EXECUTE_TIME,
|
||||
order: Qt.SortOrder = Qt.SortOrder.AscendingOrder
|
||||
):
|
||||
|
||||
if policy == SortPolicy.BY_NAME:
|
||||
self.__timer_tasks.sort(
|
||||
key = lambda x: x["name"],
|
||||
reverse = order is Qt.SortOrder.DescendingOrder
|
||||
)
|
||||
elif policy == SortPolicy.BY_ADD_TIME:
|
||||
self.__timer_tasks.sort(
|
||||
key = lambda x: x["add_time"],
|
||||
reverse = order is Qt.SortOrder.DescendingOrder
|
||||
)
|
||||
elif policy == SortPolicy.BY_EXECUTE_TIME:
|
||||
self.__timer_tasks.sort(
|
||||
key = lambda x: x["execute_time"],
|
||||
reverse = order is Qt.SortOrder.DescendingOrder
|
||||
)
|
||||
|
||||
|
||||
def updateStat(
|
||||
self
|
||||
):
|
||||
@@ -177,6 +321,7 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
pending = 0
|
||||
in_queue = 0
|
||||
executed = 0
|
||||
invalid = 0
|
||||
total = len(self.__timer_tasks)
|
||||
for timer_task in self.__timer_tasks:
|
||||
if timer_task["status"] == TimerTaskStatus.PENDING:
|
||||
@@ -186,10 +331,14 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
in_queue += 1
|
||||
elif timer_task["status"] == TimerTaskStatus.EXECUTED:
|
||||
executed += 1
|
||||
elif timer_task["status"] == TimerTaskStatus.ERROR\
|
||||
or timer_task["status"] == TimerTaskStatus.OUTDATED:
|
||||
invalid += 1
|
||||
self.TotalTaskLabel.setText(f"总任务:{total}")
|
||||
self.PendingTaskLabel.setText(f"待执行:{pending}")
|
||||
self.InQueueTaskLabel.setText(f"队列中:{in_queue}")
|
||||
self.ExecutedTaskLabel.setText(f"已执行:{executed}")
|
||||
self.InvalidTaskLabel.setText(f"无效的:{invalid}")
|
||||
|
||||
|
||||
def updateTimerTaskList(
|
||||
@@ -197,9 +346,7 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
):
|
||||
|
||||
self.TimerTasksListWidget.clear()
|
||||
self.__timer_tasks.sort(
|
||||
key = lambda x: x["execute_time"]
|
||||
)
|
||||
self.sortTimerTasks(self.__sort_policy, self.__sort_order)
|
||||
for timer_task in self.__timer_tasks:
|
||||
item = QListWidgetItem()
|
||||
item.setData(Qt.UserRole, timer_task)
|
||||
@@ -220,8 +367,7 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
timer_task = dialog.getTimerTask()
|
||||
self.__timer_tasks.append(timer_task)
|
||||
self.updateTimerTaskList()
|
||||
self.updateStat()
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def deleteTask(
|
||||
@@ -233,8 +379,7 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
x for x in self.__timer_tasks
|
||||
if x["task_uuid"] != task_uuid
|
||||
]
|
||||
self.updateTimerTaskList()
|
||||
self.updateStat()
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def clearAllTasks(
|
||||
@@ -264,14 +409,15 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
"存在正在执行或已就绪的队列任务,无法清除所有定时任务 !"
|
||||
)
|
||||
self.__timer_tasks = in_queue_tasks
|
||||
self.updateTimerTaskList()
|
||||
self.updateStat()
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def checkTasks(
|
||||
self
|
||||
):
|
||||
|
||||
need_update = False
|
||||
|
||||
now = datetime.now()
|
||||
for timer_task in self.__timer_tasks:
|
||||
if timer_task["execute_time"] > now:
|
||||
@@ -280,9 +426,47 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
continue
|
||||
if timer_task["execute_time"] <= now + timedelta(seconds = -5):
|
||||
timer_task["status"] = TimerTaskStatus.OUTDATED
|
||||
need_update = True
|
||||
else:
|
||||
timer_task["status"] = TimerTaskStatus.READY
|
||||
self.timerTaskReady.emit(timer_task)
|
||||
self.timerTaskIsReady.emit(timer_task)
|
||||
need_update = True
|
||||
if need_update:
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
@Slot(int)
|
||||
def onSortPolicyComboBoxChanged(
|
||||
self,
|
||||
policy: int
|
||||
):
|
||||
|
||||
mapping = {
|
||||
0: SortPolicy.BY_NAME,
|
||||
1: SortPolicy.BY_ADD_TIME,
|
||||
2: SortPolicy.BY_EXECUTE_TIME
|
||||
}
|
||||
self.__sort_policy = mapping[policy]
|
||||
self.updateTimerTaskList()
|
||||
|
||||
@Slot()
|
||||
def onSortOrderToggleButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
self.__sort_order = Qt.SortOrder.AscendingOrder\
|
||||
if self.__sort_order is Qt.SortOrder.DescendingOrder\
|
||||
else Qt.SortOrder.DescendingOrder
|
||||
self.TimerTaskSortOrderToggleButton.setText(
|
||||
"↑" if self.__sort_order is Qt.SortOrder.AscendingOrder else "↓"
|
||||
)
|
||||
self.updateTimerTaskList()
|
||||
|
||||
@Slot()
|
||||
def onTimerTasksChanged(
|
||||
self
|
||||
):
|
||||
|
||||
self.saveTimerTasks(self.__timer_tasks_config_path, copy.deepcopy(self.__timer_tasks))
|
||||
self.updateTimerTaskList()
|
||||
self.updateStat()
|
||||
|
||||
@@ -296,8 +480,7 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
for task in self.__timer_tasks:
|
||||
if task["task_uuid"] == timer_task["task_uuid"]:
|
||||
task["status"] = TimerTaskStatus.RUNNING
|
||||
self.updateTimerTaskList()
|
||||
self.updateStat()
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
@Slot(dict)
|
||||
@@ -309,5 +492,15 @@ class ALTimerTaskWidget(QWidget, Ui_ALTimerTaskWidget):
|
||||
for task in self.__timer_tasks:
|
||||
if task["task_uuid"] == timer_task["task_uuid"]:
|
||||
task["status"] = TimerTaskStatus.EXECUTED
|
||||
self.updateTimerTaskList()
|
||||
self.updateStat()
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskIsError(
|
||||
self,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
for task in self.__timer_tasks:
|
||||
if task["task_uuid"] == timer_task["task_uuid"]:
|
||||
task["status"] = TimerTaskStatus.ERROR
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
@@ -137,6 +137,30 @@
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="InvalidTaskLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>70</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>70</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="styleSheet">
|
||||
<string notr="true">QLabel {
|
||||
color: #FF5722
|
||||
}</string>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>无效的:0</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QFrame" name="TimerTaskSpaceFrame">
|
||||
<property name="minimumSize">
|
||||
@@ -161,6 +185,101 @@
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="TimerTaskSortLayout">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QFrame" name="TimerTaskSortSpaceFrame">
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>16777215</width>
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="TimerTaskSortLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>排序:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QComboBox" name="TimerTaskSortTypeComboBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>90</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>90</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>按名称</string>
|
||||
</property>
|
||||
</item>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>按添加时间</string>
|
||||
</property>
|
||||
</item>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>按执行时间</string>
|
||||
</property>
|
||||
</item>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="TimerTaskSortOrderToggleButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>↑</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QListWidget" name="TimerTasksListWidget">
|
||||
<property name="enabled">
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from enum import Enum
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, QSize, QCoreApplication, QRect, QPoint
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractScrollArea, QAbstractItemView,
|
||||
QTreeWidget, QTreeWidgetItem
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QDragEnterEvent, QDragMoveEvent, QDropEvent
|
||||
)
|
||||
|
||||
|
||||
class TreeItemType(Enum):
|
||||
|
||||
GROUP = 0
|
||||
USER = 1
|
||||
|
||||
|
||||
class ALUserTreeWidget(QTreeWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
self.translateUi()
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
__qtreewidgetitem = QTreeWidgetItem()
|
||||
__qtreewidgetitem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
||||
self.setHeaderItem(__qtreewidgetitem)
|
||||
self.setObjectName(u"UserTreeWidget")
|
||||
self.setMinimumSize(QSize(230, 0))
|
||||
self.setMaximumSize(QSize(250, 16777215))
|
||||
self.setSizeAdjustPolicy(QAbstractScrollArea.SizeAdjustPolicy.AdjustIgnored)
|
||||
self.setTabKeyNavigation(True)
|
||||
self.setDragEnabled(True)
|
||||
self.setAcceptDrops(True)
|
||||
self.setDropIndicatorShown(True)
|
||||
self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
|
||||
self.setDefaultDropAction(Qt.DropAction.IgnoreAction)
|
||||
self.setAlternatingRowColors(True)
|
||||
self.setSortingEnabled(True)
|
||||
self.sortByColumn(0, Qt.SortOrder.AscendingOrder)
|
||||
self.setAnimated(True)
|
||||
self.setAllColumnsShowFocus(False)
|
||||
self.setHeaderHidden(False)
|
||||
self.setColumnCount(2)
|
||||
self.setColumnWidth(0, 150)
|
||||
self.setColumnWidth(1, 20)
|
||||
self.header().setCascadingSectionResizes(False)
|
||||
self.header().setHighlightSections(False)
|
||||
self.header().setProperty(u"showSortIndicator", True)
|
||||
|
||||
|
||||
def translateUi(
|
||||
self
|
||||
):
|
||||
|
||||
___qtreewidgetitem = self.headerItem()
|
||||
___qtreewidgetitem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
||||
|
||||
|
||||
@staticmethod
|
||||
def isDragPositionValid(
|
||||
target_rect: QRect,
|
||||
drag_pos: QPoint,
|
||||
) -> bool:
|
||||
|
||||
y_offset = drag_pos.y() - target_rect.top()
|
||||
valid = (y_offset > target_rect.height()*0.2 and
|
||||
y_offset < target_rect.height()*0.8)
|
||||
return valid
|
||||
|
||||
|
||||
def dragEnterEvent(
|
||||
self,
|
||||
event: QDragEnterEvent
|
||||
):
|
||||
|
||||
super().dragEnterEvent(event)
|
||||
|
||||
|
||||
def dragMoveEvent(
|
||||
self,
|
||||
event: QDragMoveEvent
|
||||
):
|
||||
|
||||
super().dragMoveEvent(event)
|
||||
|
||||
source_item = self.currentItem()
|
||||
target_item = self.itemAt(event.position().toPoint())
|
||||
if source_item is None:
|
||||
event.ignore()
|
||||
return
|
||||
if source_item.type() == TreeItemType.GROUP.value:
|
||||
if target_item is not None:
|
||||
event.ignore()
|
||||
return
|
||||
elif source_item.type() == TreeItemType.USER.value:
|
||||
if target_item is None:
|
||||
event.ignore()
|
||||
return
|
||||
if target_item.type() != TreeItemType.GROUP.value:
|
||||
event.ignore()
|
||||
return
|
||||
if target_item.checkState(1) == Qt.CheckState.Unchecked:
|
||||
event.ignore()
|
||||
return
|
||||
if not self.isDragPositionValid(
|
||||
self.visualItemRect(target_item),
|
||||
event.position().toPoint()
|
||||
):
|
||||
event.ignore()
|
||||
return
|
||||
else:
|
||||
event.ignore()
|
||||
return
|
||||
event.acceptProposedAction()
|
||||
|
||||
|
||||
def dropEvent(
|
||||
self,
|
||||
event: QDropEvent
|
||||
):
|
||||
|
||||
super().dropEvent(event)
|
||||
|
||||
for item_index in range(self.topLevelItemCount()):
|
||||
self.topLevelItem(item_index).setExpanded(True)
|
||||
self.setCurrentItem(None)
|
||||
@@ -0,0 +1,16 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
The contents of this file will automatically be updated by the
|
||||
workflow process. Do not edit manually.
|
||||
|
||||
This file is auto-generated during the workflow process.
|
||||
Last updated: 2026-01-17 17:51:55 UTC
|
||||
"""
|
||||
|
||||
AL_VERSION = "1.0.3"
|
||||
AL_TAG = "v1.0.3"
|
||||
AL_COMMIT_SHA = "local"
|
||||
AL_COMMIT_DATE = "null" # time zone : UTC
|
||||
AL_BUILD_DATE = "null" # time zone : UTC
|
||||
AL_VERSION_FULL = f"{AL_VERSION} ({AL_COMMIT_SHA})"
|
||||
@@ -1 +0,0 @@
|
||||
AL_VERSION = "1.0.0-beta"
|
||||
@@ -1,6 +1,6 @@
|
||||
<RCC>
|
||||
<qresource prefix="/res/icon">
|
||||
<file>icons/AutoLibrary.ico</file>
|
||||
<file>icons/AutoLibrary_32x32.ico</file>
|
||||
</qresource>
|
||||
<qresource prefix="/res/trans">
|
||||
<file>translators/qtbase_zh_CN.qm</file>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
cd /d "%~dp0.."
|
||||
|
||||
echo [AutoLibrary compile] 检查翻译文件...
|
||||
if exist translators (
|
||||
cd translators
|
||||
set ts_count=0
|
||||
for %%f in (*.ts) do set /a ts_count+=1
|
||||
|
||||
if !ts_count! gtr 0 (
|
||||
echo [AutoLibrary compile] 找到 !ts_count! 个 .ts 文件,开始编译翻译文件...
|
||||
for %%f in (*.ts) do (
|
||||
set "qm_filename=%%~nf.qm"
|
||||
echo [AutoLibrary compile] 正在编译翻译文件: "%%f" -> "!qm_filename!"
|
||||
|
||||
pyside6-lrelease "%%f"
|
||||
if !errorlevel! equ 0 (
|
||||
echo [AutoLibrary compile] 翻译文件 "%%f" ✓ 编译成功,输出文件: "!qm_filename!"
|
||||
) else (
|
||||
echo [AutoLibrary compile] 翻译文件 "%%f" ✗ 编译失败
|
||||
)
|
||||
)
|
||||
echo.
|
||||
) else (
|
||||
echo [AutoLibrary compile] 未找到任何 .ts 翻译文件
|
||||
)
|
||||
cd ..
|
||||
) else (
|
||||
echo [AutoLibrary compile] 未找到 translators 目录
|
||||
)
|
||||
echo.
|
||||
|
||||
set count=0
|
||||
for %%f in (*.qrc) do set /a count+=1
|
||||
|
||||
if %count% equ 0 (
|
||||
echo [AutoLibrary compile] 错误: 未找到任何 .qrc 文件
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [AutoLibrary compile] 找到 %count% 个 .qrc 文件,开始编译...
|
||||
echo.
|
||||
|
||||
for %%f in (*.qrc) do (
|
||||
set "filename=%%~nf"
|
||||
set "output_file=!filename!.py"
|
||||
echo [AutoLibrary compile] 正在编译: "%%f" -> "!output_file!"
|
||||
|
||||
pyside6-rcc "%%f" -o "!output_file!"
|
||||
if !errorlevel! equ 0 (
|
||||
echo [AutoLibrary compile] 文件 "%%f" ✓ 编译成功,输出文件: "!output_file!"
|
||||
) else (
|
||||
echo [AutoLibrary compile] 文件 "%%f" ✗ 编译失败
|
||||
)
|
||||
echo.
|
||||
)
|
||||
|
||||
echo [AutoLibrary compile] 所有操作完成。
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PARENT_DIR="$(dirname "$SCRIPT_DIR")"
|
||||
cd "$PARENT_DIR"
|
||||
|
||||
echo "[AutoLibrary compile] 检查翻译文件..."
|
||||
if [ -d "translators" ]; then
|
||||
cd translators
|
||||
ts_files=(*.ts)
|
||||
ts_count=${#ts_files[@]}
|
||||
|
||||
# 如果第一个元素是"*.ts"(表示没有匹配),则数量为0
|
||||
if [ "$ts_count" -eq 1 ] && [ "${ts_files[0]}" = "*.ts" ]; then
|
||||
ts_count=0
|
||||
fi
|
||||
|
||||
if [ $ts_count -gt 0 ]; then
|
||||
echo "[AutoLibrary compile] 找到 $ts_count 个 .ts 文件,开始编译翻译文件..."
|
||||
for file in *.ts; do
|
||||
base_name=$(basename "$file" .ts)
|
||||
qm_file="${base_name}.qm"
|
||||
echo "[AutoLibrary compile] 正在编译翻译文件: \"$file\" -> \"$qm_file\""
|
||||
|
||||
if pyside6-lrelease "$file"; then
|
||||
echo "[AutoLibrary compile] 翻译文件 \"$file\" ✓ 编译成功,输出文件: \"$qm_file\""
|
||||
else
|
||||
echo "[AutoLibrary compile] 翻译文件 \"$file\" ✗ 编译失败"
|
||||
fi
|
||||
done
|
||||
echo
|
||||
else
|
||||
echo "[AutoLibrary compile] 未找到任何 .ts 翻译文件"
|
||||
fi
|
||||
cd ..
|
||||
else
|
||||
echo "[AutoLibrary compile] 未找到 translators 目录"
|
||||
fi
|
||||
echo
|
||||
|
||||
file_count=$(ls *.qrc 2>/dev/null | wc -l)
|
||||
|
||||
if [ $file_count -eq 0 ]; then
|
||||
echo "[AutoLibrary compile] 错误: 未找到任何 .qrc 文件"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[AutoLibrary compile] 找到 $file_count 个 .qrc 文件,开始编译..."
|
||||
echo
|
||||
|
||||
for file in *.qrc; do
|
||||
base_name=$(basename "$file" .qrc)
|
||||
output_file="${base_name}.py"
|
||||
echo "[AutoLibrary compile] 正在编译: \"$file\" -> \"$output_file\""
|
||||
|
||||
if pyside6-rcc "$file" -o "$output_file"; then
|
||||
echo "[AutoLibrary compile] 文件 \"$file\" ✓ 编译成功,输出文件: \"$output_file\""
|
||||
else
|
||||
echo "[AutoLibrary compile] 文件 \"$file\" ✗ 编译失败"
|
||||
fi
|
||||
echo
|
||||
done
|
||||
|
||||
echo "[AutoLibrary compile] 所有操作完成。"
|
||||
@@ -0,0 +1,33 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
cd /d "%~dp0.."
|
||||
|
||||
set count=0
|
||||
for %%f in (*.ui) do set /a count+=1
|
||||
|
||||
if %count% equ 0 (
|
||||
echo [AutoLibrary compile] 错误: 未找到任何 .ui 文件
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [AutoLibrary compile] 找到 %count% 个 .ui 文件,开始编译...
|
||||
echo.
|
||||
|
||||
for %%f in (*.ui) do (
|
||||
set "filename=%%~nf"
|
||||
set "output_file=Ui_!filename!.py"
|
||||
echo [AutoLibrary compile] 正在编译: "%%f" -> "!output_file!"
|
||||
|
||||
pyside6-uic "%%f" -o "!output_file!"
|
||||
if !errorlevel! equ 0 (
|
||||
echo [AutoLibrary compile] 文件 "%%f" ✓ 编译成功,输出文件: "!output_file!"
|
||||
) else (
|
||||
echo [AutoLibrary compile] 文件 "%%f" ✗ 编译失败
|
||||
)
|
||||
echo.
|
||||
)
|
||||
|
||||
echo [AutoLibrary compile] 所有操作完成。
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/bin/bash
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PARENT_DIR="$(dirname "$SCRIPT_DIR")"
|
||||
cd "$PARENT_DIR"
|
||||
|
||||
file_count=$(ls *.ui 2>/dev/null | wc -l)
|
||||
|
||||
if [ $file_count -eq 0 ]; then
|
||||
echo "[AutoLibrary compile] 错误: 未找到任何 .ui 文件"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[AutoLibrary compile] 找到 $file_count 个 .ui 文件,开始编译..."
|
||||
echo
|
||||
|
||||
for file in *.ui; do
|
||||
base_name=$(basename "$file" .ui)
|
||||
output_file="Ui_${base_name}.py"
|
||||
echo "[AutoLibrary compile] 正在编译: \"$file\" -> \"$output_file\""
|
||||
|
||||
if pyside6-uic "$file" -o "$output_file"; then
|
||||
echo "[AutoLibrary compile] 文件 \"$file\" ✓ 编译成功,输出文件: \"$output_file\""
|
||||
else
|
||||
echo "[AutoLibrary compile] 文件 \"$file\" ✗ 编译失败"
|
||||
fi
|
||||
echo
|
||||
done
|
||||
|
||||
echo "[AutoLibrary compile] 所有操作完成。"
|
||||
@@ -0,0 +1 @@
|
||||
this folder is used to store the batch scripts.
|
||||
|
Before Width: | Height: | Size: 785 KiB After Width: | Height: | Size: 785 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
+101
-64
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -14,7 +14,9 @@ from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.edge.service import Service
|
||||
from selenium.webdriver.edge.service import Service as EdgeService
|
||||
from selenium.webdriver.chrome.service import Service as ChromeService
|
||||
from selenium.webdriver.firefox.service import Service as FirefoxService
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from operators.LibChecker import LibChecker
|
||||
@@ -24,21 +26,26 @@ from operators.LibReserve import LibReserve
|
||||
from operators.LibCheckin import LibCheckin
|
||||
from operators.LibRenew import LibRenew
|
||||
|
||||
from utils.ConfigReader import ConfigReader
|
||||
|
||||
|
||||
class AutoLib(MsgBase):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue
|
||||
output_queue: queue.Queue,
|
||||
run_config: dict
|
||||
):
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__system_config_reader = None
|
||||
self.__users_config_reader = None
|
||||
self.__run_config = run_config
|
||||
self.__user_config = None
|
||||
self.__driver = None
|
||||
if not self.__initBrowserDriver():
|
||||
raise Exception("浏览器驱动初始化失败")
|
||||
else:
|
||||
if not self.__initDriverUrl():
|
||||
raise Exception("浏览器驱动URL初始化失败")
|
||||
self.__initLibOperators()
|
||||
|
||||
|
||||
def __initBrowserDriver(
|
||||
@@ -46,50 +53,75 @@ class AutoLib(MsgBase):
|
||||
) -> bool:
|
||||
|
||||
self._showTrace("正在初始化浏览器驱动......")
|
||||
edge_options = webdriver.EdgeOptions()
|
||||
|
||||
if self.__system_config_reader.get("web_driver/headless"):
|
||||
edge_options.add_argument("--headless")
|
||||
edge_options.add_argument("--disable-gpu")
|
||||
edge_options.add_argument("--no-sandbox")
|
||||
edge_options.add_argument("--disable-dev-shm-usage")
|
||||
web_driver_config = self.__run_config.get("web_driver", None)
|
||||
self.__driver_type = web_driver_config.get("driver_type")
|
||||
match self.__driver_type.lower():
|
||||
case "edge":
|
||||
driver_options = webdriver.EdgeOptions()
|
||||
case "chrome":
|
||||
driver_options = webdriver.ChromeOptions()
|
||||
case "firefox":
|
||||
driver_options = webdriver.FirefoxOptions()
|
||||
case _:
|
||||
raise Exception(f"不支持的浏览器驱动类型: {self.__driver_type} !")
|
||||
|
||||
if not web_driver_config:
|
||||
self._showTrace("未配置浏览器驱动参数 !")
|
||||
return False
|
||||
if web_driver_config.get("headless"):
|
||||
driver_options.add_argument("--headless")
|
||||
driver_options.add_argument("--disable-gpu")
|
||||
driver_options.add_argument("--no-sandbox")
|
||||
driver_options.add_argument("--disable-dev-shm-usage")
|
||||
|
||||
# must be 1920x1080, otherwise the page will cause some elements not accessible
|
||||
edge_options.add_argument("--window-size=1920,1080")
|
||||
edge_options.add_argument("--remote-allow-origins=*")
|
||||
driver_options.add_argument("--window-size=1920,1080")
|
||||
|
||||
# omit ssl errors and verbose log level
|
||||
edge_options.add_argument("--ignore-certificate-errors")
|
||||
edge_options.add_argument("--ignore-ssl-errors")
|
||||
edge_options.add_argument("--log-level=OFF")
|
||||
edge_options.add_argument("--silent")
|
||||
driver_options.add_argument("--ignore-certificate-errors")
|
||||
driver_options.add_argument("--ignore-ssl-errors")
|
||||
driver_options.add_argument("--log-level=OFF")
|
||||
driver_options.add_argument("--silent")
|
||||
|
||||
edge_options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
||||
edge_options.add_experimental_option("useAutomationExtension", False)
|
||||
edge_options.add_argument("--disable-blink-features=AutomationControlled")
|
||||
edge_options.add_argument(
|
||||
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) "\
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "\
|
||||
"Chrome/120.0.0.0 "\
|
||||
"Safari/537.36 "\
|
||||
"Edg/120.0.0.0"
|
||||
)
|
||||
# set options for chrome and edge
|
||||
if self.__driver_type.lower() in ["edge", "chrome"]:
|
||||
driver_options.add_argument("--remote-allow-origins=*")
|
||||
driver_options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
||||
driver_options.add_experimental_option("useAutomationExtension", False)
|
||||
driver_options.add_argument("--disable-blink-features=AutomationControlled")
|
||||
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "\
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "\
|
||||
"Chrome/120.0.0.0 "\
|
||||
"Safari/537.36"
|
||||
if self.__driver_type.lower() == "edge":
|
||||
user_agent += " Edg/120.0.0.0"
|
||||
# set options for firefox
|
||||
elif self.__driver_type.lower() == "firefox":
|
||||
driver_options.set_preference("dom.webdriver.enabled", False)
|
||||
driver_options.set_preference("useAutomationExtension", False)
|
||||
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) "\
|
||||
"Gecko/20100101 Firefox/120.0"
|
||||
driver_options.add_argument(f"user-agent={user_agent}")
|
||||
|
||||
# init browser driver
|
||||
self.__driver_path = self.__system_config_reader.get("web_driver/driver_path")
|
||||
self.__driver_type = self.__system_config_reader.get("web_driver/driver_type")
|
||||
self.__driver_path = web_driver_config.get("driver_path")
|
||||
if not self.__driver_path:
|
||||
raise Exception(f"未配置浏览器驱动路径 !")
|
||||
self.__driver_path = os.path.abspath(self.__driver_path)
|
||||
try:
|
||||
service = None
|
||||
if self.__driver_path:
|
||||
service = Service(executable_path=self.__driver_path)
|
||||
match self.__driver_type.lower():
|
||||
case "edge":
|
||||
self.__driver = webdriver.Edge(service=service, options=edge_options)
|
||||
service = EdgeService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Edge(service=service, options=driver_options)
|
||||
case "chrome":
|
||||
self.__driver = webdriver.Chrome(service=service, options=edge_options)
|
||||
service = ChromeService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Chrome(service=service, options=driver_options)
|
||||
case "firefox":
|
||||
self.__driver = webdriver.Firefox(service=service, options=edge_options)
|
||||
self._showTrace(f"Firefox 浏览器驱动初始化略慢, 请耐心等待...")
|
||||
service = FirefoxService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Firefox(service=service, options=driver_options)
|
||||
case _:
|
||||
raise Exception(f"不支持的浏览器驱动类型: {self.__driver_type}")
|
||||
self.__driver.implicitly_wait(1)
|
||||
@@ -149,8 +181,11 @@ class AutoLib(MsgBase):
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
url = self.__system_config_reader.get("library/host_url")
|
||||
url += self.__system_config_reader.get("library/login_url")
|
||||
lib_config = self.__run_config.get("library", None)
|
||||
if not lib_config:
|
||||
self._showError("未配置图书馆参数 !")
|
||||
return False
|
||||
url = lib_config.get("host_url") + lib_config.get("login_url")
|
||||
self.__driver.get(url)
|
||||
if not self.__waitResponseLoad():
|
||||
return False
|
||||
@@ -161,24 +196,24 @@ class AutoLib(MsgBase):
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
login_config: dict,
|
||||
run_mode_config: dict,
|
||||
reserve_info: dict
|
||||
) -> int:
|
||||
|
||||
# result : 0 - success, 1 - failed, 2 - passed
|
||||
# result : -1 - terminate, 0 - success, 1 - failed, 2 - passed
|
||||
result = 2
|
||||
|
||||
# login
|
||||
if not self.__lib_login.login(
|
||||
username,
|
||||
password,
|
||||
self.__system_config_reader.get("login/max_attempt", 5),
|
||||
self.__system_config_reader.get("login/auto_captcha", True),
|
||||
login_config.get("max_attempt", 3),
|
||||
login_config.get("auto_captcha", True),
|
||||
):
|
||||
return 1
|
||||
"""
|
||||
Here, we collect the run mode from the config file.
|
||||
"""
|
||||
run_mode = self.__system_config_reader.get("mode/run_mode", 0)
|
||||
# Here, we collect the run mode from the run config.
|
||||
run_mode = run_mode_config.get("run_mode", 0)
|
||||
run_mode = {
|
||||
"auto_reserve": run_mode&0x1,
|
||||
"auto_checkin": run_mode&0x2,
|
||||
@@ -223,43 +258,43 @@ class AutoLib(MsgBase):
|
||||
):
|
||||
# if logout is failed, we must make sure the host to be reloaded
|
||||
# otherwise, the next login may fail
|
||||
self.__driver.get(self.__system_config_reader.get("library/host_url"))
|
||||
return 1
|
||||
if not self.__initDriverUrl():
|
||||
return -1
|
||||
return result
|
||||
|
||||
|
||||
def run(
|
||||
self,
|
||||
system_config_reader: ConfigReader,
|
||||
users_config_reader: ConfigReader
|
||||
user_config: dict
|
||||
):
|
||||
|
||||
self.__system_config_reader = system_config_reader
|
||||
self.__users_config_reader = users_config_reader
|
||||
if not self.__initBrowserDriver():
|
||||
return
|
||||
else:
|
||||
if not self.__initDriverUrl():
|
||||
return
|
||||
self.__initLibOperators()
|
||||
self.__user_config = user_config
|
||||
|
||||
user_counter = {"current": 0, "success": 0, "failed": 0, "passed": 0}
|
||||
users = self.__users_config_reader.get("users")
|
||||
self._showTrace(
|
||||
f"共发现 {len(users)} 个用户, "\
|
||||
f"用户配置文件路径: {self.__users_config_reader.configPath()}"
|
||||
)
|
||||
users = self.__user_config["users"]
|
||||
self._showTrace(f"共发现 {len(users)} 个用户")
|
||||
for user in users:
|
||||
user_counter["current"] += 1
|
||||
self._showTrace(
|
||||
f"正在处理第 {user_counter["current"]}/{len(users)} 个用户: {user['username']}......"
|
||||
f"正在处理第 {user_counter["current"]}/{len(users)} 个用户: {user["username"]}......"
|
||||
)
|
||||
if not user["enabled"]:
|
||||
self._showTrace(f"用户 {user["username"]} 已跳过")
|
||||
user_counter["passed"] += 1
|
||||
continue
|
||||
r = self.__run(
|
||||
username=user["username"],
|
||||
password=user["password"],
|
||||
login_config=self.__run_config["login"],
|
||||
run_mode_config=self.__run_config["mode"],
|
||||
reserve_info=user["reserve_info"],
|
||||
)
|
||||
if r == 0:
|
||||
if r == -1:
|
||||
self._showTrace(
|
||||
f"用户 {user["username"]} 处理过程中页面发生异常,无法继续操作, 任务已终止 !"
|
||||
)
|
||||
break
|
||||
elif r == 0:
|
||||
user_counter["success"] += 1
|
||||
elif r == 1:
|
||||
user_counter["failed"] += 1
|
||||
@@ -278,6 +313,8 @@ class AutoLib(MsgBase):
|
||||
) -> bool:
|
||||
|
||||
if self.__driver:
|
||||
if self.__driver_type.lower() == "firefox":
|
||||
self._showTrace(f"Firefox 浏览器驱动关闭略慢, 请耐心等待...")
|
||||
self.__driver.quit()
|
||||
self.__driver = None
|
||||
self._showTrace(f"浏览器驱动已关闭")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -13,6 +13,7 @@ import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
@@ -25,7 +26,7 @@ class LibChecker(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
@@ -336,15 +337,15 @@ class LibChecker(LibOperator):
|
||||
def postRenewCheck(
|
||||
self,
|
||||
record: dict
|
||||
):
|
||||
) -> bool:
|
||||
"""
|
||||
Check if the renew operation is successful
|
||||
Check if the renew operation is successful
|
||||
|
||||
Args:
|
||||
record (dict): The expected record after renewal
|
||||
Args:
|
||||
record (dict): The expected record after renewal
|
||||
|
||||
Returns:
|
||||
bool: True if the renew operation is successful, False otherwise
|
||||
Returns:
|
||||
bool: True if the renew operation is successful, False otherwise
|
||||
"""
|
||||
# because the special circumstance that the renew operation
|
||||
# do not show the success message or anything else,
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
@@ -25,7 +24,7 @@ class LibCheckin(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -13,6 +13,7 @@ import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
@@ -25,7 +26,7 @@ class LibCheckout(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
+13
-16
@@ -1,19 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import time
|
||||
import queue
|
||||
import base64
|
||||
|
||||
import ddddocr
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
@@ -26,7 +26,7 @@ class LibLogin(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
@@ -88,13 +88,12 @@ class LibLogin(LibOperator):
|
||||
captcha_img = base64.b64decode(base64_str)
|
||||
captcha_text = self.__ddddocr.classification(captcha_img)
|
||||
captcha_text = ''.join(filter(str.isalnum, captcha_text)).lower()
|
||||
self._showTrace(f"识别到验证码为 : '{captcha_text}'.")
|
||||
self._showTrace(f"识别到验证码为 : '{captcha_text}'")
|
||||
if len(captcha_text) != 4:
|
||||
raise Exception("识别到的验证码长度不等于 4 个字符 !")
|
||||
return captcha_text
|
||||
except Exception as e:
|
||||
self._showTrace(f"验证码识别失败 ! : {e}")
|
||||
self.__refreshCaptcha()
|
||||
return ""
|
||||
|
||||
|
||||
@@ -104,15 +103,14 @@ class LibLogin(LibOperator):
|
||||
|
||||
# manual recognize captcha
|
||||
try:
|
||||
self._show_msg("请输入验证码:")
|
||||
captcha_text = self._wait_msg(timeout=15)
|
||||
self._showTrace(f"输入的验证码为 : '{captcha_text}'.")
|
||||
self._showMsg("请输入验证码:")
|
||||
captcha_text = self._waitMsg(timeout=15)
|
||||
self._showTrace(f"输入的验证码为 : '{captcha_text}'")
|
||||
if len(captcha_text) != 4:
|
||||
raise Exception("输入的验证码长度不等于 4 个字符 !")
|
||||
return captcha_text
|
||||
except Exception as e:
|
||||
self._showTrace(f"输入验证码失败 ! : {e}")
|
||||
self.__refreshCaptcha()
|
||||
return ""
|
||||
|
||||
|
||||
@@ -126,11 +124,9 @@ class LibLogin(LibOperator):
|
||||
self.__driver.find_element(
|
||||
By.ID, "loadImgId"
|
||||
).click()
|
||||
time.sleep(1)
|
||||
return True
|
||||
except Exception as e:
|
||||
self._showTrace(f"刷新验证码失败 ! : {e}")
|
||||
self.__refreshCaptcha()
|
||||
return False
|
||||
|
||||
|
||||
@@ -139,8 +135,7 @@ class LibLogin(LibOperator):
|
||||
auto_captcha: bool = True
|
||||
) -> str:
|
||||
|
||||
max_attempts = 5
|
||||
|
||||
max_attempts = 3 # the possibility of 3 times failed is less than (10%^3)
|
||||
for _ in range(max_attempts):
|
||||
if auto_captcha:
|
||||
captcha_text = self.__autoRecognizeCaptcha()
|
||||
@@ -149,7 +144,10 @@ class LibLogin(LibOperator):
|
||||
captcha_text = self.__manualRecognizeCaptcha()
|
||||
if captcha_text:
|
||||
return captcha_text
|
||||
self._showTrace(f"验证码识别失败 {max_attempts} 次, 请检查验证码是否正确 !")
|
||||
else:
|
||||
if not self.__refreshCaptcha():
|
||||
return ""
|
||||
self._showTrace(f"验证码识别失败 {max_attempts} 次, 达到最大尝试次数 !")
|
||||
return ""
|
||||
|
||||
|
||||
@@ -165,7 +163,6 @@ class LibLogin(LibOperator):
|
||||
return True
|
||||
except Exception as e:
|
||||
self._showTrace(f"验证码填写失败 ! : {e}")
|
||||
self.__refreshCaptcha()
|
||||
return False
|
||||
|
||||
|
||||
@@ -200,7 +197,7 @@ class LibLogin(LibOperator):
|
||||
"//input[@type='button' and @value='登录']"
|
||||
).click()
|
||||
except Exception as e:
|
||||
self._showTrace(f"登录失败 ! : {e}")
|
||||
self._showTrace(f"尝试登录失败 ! : {e}")
|
||||
continue
|
||||
if self._waitResponseLoad():
|
||||
self._showTrace(f"用户 {username} 第 {attempt + 1} 次登录成功 !")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -10,8 +10,7 @@ See the LICENSE file for details.
|
||||
import queue
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
@@ -22,7 +21,7 @@ class LibLogout(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
@@ -25,7 +23,7 @@ class LibRenew(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
@@ -25,7 +25,7 @@ class LibReserve(LibOperator):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: any
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
@@ -40,12 +40,12 @@ class LibReserve(LibOperator):
|
||||
}
|
||||
self.__room_map = {
|
||||
"1": "二层内环",
|
||||
"2": "二层外环",
|
||||
"2": "二层西区",
|
||||
"3": "三层内环",
|
||||
"4": "三层外环",
|
||||
"5": "四层内环",
|
||||
"6": "四层外环",
|
||||
"7": "四层期刊区",
|
||||
"7": "四层期刊",
|
||||
"8": "五层考研"
|
||||
}
|
||||
|
||||
|
||||
@@ -8,5 +8,6 @@
|
||||
- LibReserve: Library operator for reserving seat.
|
||||
- LibCheckin: Library operator for checking in seat.
|
||||
- LibCheckout: Library operator for checking out seat.
|
||||
- LibChecker: Library operator for checking record status.
|
||||
- LibRenew: Library operator for renewing seat.
|
||||
"""
|
||||
+45
-19
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -8,63 +8,89 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import json
|
||||
import copy
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ConfigReader:
|
||||
"""
|
||||
Config reader class.
|
||||
|
||||
This class is used to read config file in JSON format.
|
||||
|
||||
Args:
|
||||
config_path (str): The path of config file.
|
||||
|
||||
Examples:
|
||||
>>> print(open("config.json", "r", encoding="utf-8").read())
|
||||
{
|
||||
"key1": {
|
||||
"key2": "value1"
|
||||
}
|
||||
}
|
||||
>>> config_reader = ConfigReader("config.json")
|
||||
>>> config_reader.get("key1/key2")
|
||||
"value1"
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_path: str
|
||||
):
|
||||
|
||||
self._config_path = config_path
|
||||
self._config_data = {}
|
||||
if not self.__readConfig():
|
||||
return None
|
||||
self.__config_path = config_path
|
||||
self.__config_data = None
|
||||
self.__readConfig()
|
||||
|
||||
|
||||
def __readConfig(
|
||||
self
|
||||
) -> bool:
|
||||
):
|
||||
|
||||
try:
|
||||
with open(self._config_path, 'r', encoding='utf-8') as file:
|
||||
self._config_data = json.load(file)
|
||||
return True
|
||||
with open(self.__config_path, 'r', encoding='utf-8') as file:
|
||||
self.__config_data = json.load(file)
|
||||
except FileNotFoundError as e:
|
||||
raise Exception(f"Config file not found: {self.__config_path}") from e
|
||||
except PermissionError as e:
|
||||
raise Exception(f"Without enough permission to read config file: {self.__config_path}") from e
|
||||
except json.JSONDecodeError as e:
|
||||
raise Exception(f"JSON decode error in config file: {self.__config_path}") from e
|
||||
except Exception as e:
|
||||
print(f"Error reading config file: {e}")
|
||||
return False
|
||||
raise Exception(f"Unknown error occurred while reading config file: {e}") from e
|
||||
|
||||
|
||||
def getConfigs(
|
||||
self
|
||||
) -> dict:
|
||||
|
||||
return self._config_data.copy()
|
||||
return self.__config_data.copy()
|
||||
|
||||
|
||||
def getConfig(
|
||||
self,
|
||||
key: str
|
||||
) -> dict:
|
||||
) -> Any:
|
||||
|
||||
return self._config_data.get(key, {})
|
||||
config = self.__config_data.get(key, {})
|
||||
return copy.deepcopy(config)
|
||||
|
||||
|
||||
def get(
|
||||
self,
|
||||
key: str,
|
||||
default: any = None
|
||||
) -> any:
|
||||
default: Any = None
|
||||
) -> Any:
|
||||
|
||||
keys = key.split('/')
|
||||
current = self._config_data
|
||||
current = self.__config_data
|
||||
for k in keys:
|
||||
if isinstance(current, dict) and k in current:
|
||||
current = current[k]
|
||||
else:
|
||||
return default
|
||||
return current
|
||||
return copy.deepcopy(current)
|
||||
|
||||
|
||||
def hasConfig(
|
||||
@@ -86,4 +112,4 @@ class ConfigReader:
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self._config_path
|
||||
return self.__config_path
|
||||
|
||||
+41
-12
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
Copyright (c) 2025 - 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
@@ -9,8 +9,35 @@ See the LICENSE file for details.
|
||||
"""
|
||||
import json
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ConfigWriter:
|
||||
"""
|
||||
Config writer class.
|
||||
|
||||
This class is used to write config file in JSON format.
|
||||
|
||||
Args:
|
||||
config_path (str): The path of config file.
|
||||
config_data (dict): The config data to be written.
|
||||
|
||||
Examples:
|
||||
>>> config_data = {
|
||||
... "key1": {
|
||||
... "key2": "value1"
|
||||
... }
|
||||
... }
|
||||
>>> config_writer = ConfigWriter("config.json", config_data)
|
||||
>>> config_writer.set("key1/key2", "value1")
|
||||
True
|
||||
>>> print(open("config.json", "r", encoding="utf-8").read())
|
||||
{
|
||||
"key1": {
|
||||
"key2": "value1"
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -19,23 +46,25 @@ class ConfigWriter:
|
||||
):
|
||||
|
||||
self.__config_path = config_path
|
||||
self.__config_data = config_data if config_data is not None else {}
|
||||
if config_data is None:
|
||||
return None
|
||||
if not self.__writeConfig():
|
||||
return None
|
||||
self.__config_data = config_data.copy() if config_data is not None else {}
|
||||
self.__writeConfig()
|
||||
|
||||
|
||||
def __writeConfig(
|
||||
self
|
||||
) -> bool:
|
||||
):
|
||||
|
||||
try:
|
||||
with open(self.__config_path, "w") as f:
|
||||
with open(self.__config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(self.__config_data, f, indent=4, sort_keys=False)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
except PermissionError as e:
|
||||
raise Exception(f"Without enough permission to write config file: {self.__config_path}") from e
|
||||
except IOError as e:
|
||||
raise Exception(f"IO error occurred while writing config file: {self.__config_path}") from e
|
||||
except TypeError as e:
|
||||
raise Exception(f"Config data contains invalid type that can not be JSON serialized: {e}") from e
|
||||
except Exception as e:
|
||||
raise Exception(f"Unknown error occurred while writing config file: {e}") from e
|
||||
|
||||
|
||||
def setConfigs(
|
||||
@@ -60,7 +89,7 @@ class ConfigWriter:
|
||||
def set(
|
||||
self,
|
||||
key: str,
|
||||
value: dict
|
||||
value: Any
|
||||
) -> bool:
|
||||
|
||||
keys = key.replace("\\", "/").split("/")
|
||||
|
||||
Reference in New Issue
Block a user