1
1
mirror of https://github.com/KenanZhu/AutoLibrary.git synced 2026-06-18 23:43:02 +08:00

Compare commits

...

9 Commits

Author SHA1 Message Date
KenanZhu 7df6a9157d refactor(LibReserve, LibRenew): 提取时间选择公共逻辑到 LibTimeSelector 基类
将 LibReserve 和 LibRenew 中重复的时间转换和选择逻辑提取到
LibTimeSelector 基类,消除代码重复,提升可维护性。

主要变更:
- 新增 LibTimeSelector 基类,提供时间转换和最佳时间选择算法
- LibReserve 和 LibRenew 继承 LibTimeSelector,移除重复代码
- 拆分过长方法,提升代码可读性
- 修正方法命名 __selectNearstTime -> __selectNearestTime

同时修复续约功能业务逻辑漏洞:
- 新增续约时间上限校验,防止续约时间超过图书馆闭馆时间(23:30)
2026-03-14 14:48:35 +08:00
KenanZhu ebe3910df5 fix(AutoLib): 修复自动预约,签到和续约功能的顺序处理逻辑问题
边缘情况下,即用户当前的预约时间满足签到或者续约的时间范围要求时,预期的处理顺序是先进行预约,再进行签到或者续约。
该提交修复了对这种情况的处理逻辑,确保先进行预约,再进行签到或者续约。
2026-03-10 11:00:01 +08:00
KenanZhu 84367e4abe chore(*): 更新网站地址为 www.autolibrary.kenanzhu.com 2026-03-10 10:59:13 +08:00
KenanZhu 3a50991860 fix(ALMainWindow): 修复程序最小化到托盘图标后,退出菜单异常处理问题 2026-03-10 10:58:27 +08:00
KenanZhu e4482b01da fix(ALMainWindow): 修复托盘图标初始化问题
1. 修复托盘图标初始化上下文菜单的重复调用问题
2. 修复托盘图标初始化忘记更改消息方法的问题
2026-03-05 07:55:36 +08:00
KenanZhu c06e0e05da fix(ALMainWindow): 修复定时任务的消息通知图标与运行状态不一致的问题 2026-03-05 07:54:18 +08:00
KenanZhu ff083884b6 style(utils.ConfigManager): 添加一些注释,并为 getBaseConfigDir 添加文档字符串。 2026-03-04 23:53:31 +08:00
KenanZhu 9ae89b61a4 chore(utils.ConfigManager): 将 ConfigManager 类的 appDir 重命名为 configDir 2026-03-04 23:52:28 +08:00
KenanZhu 2152cc46a3 style(*): 修改 ConfigManager 模块的 import 方式,并移除未使用的 import 语句 2026-03-04 23:52:01 +08:00
12 changed files with 336 additions and 233 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
This folder is used to store the manuals.
Our manuals are available at https://www.autolibrary.top/manuals
Our manuals are available at https://www.autolibrary.kenanzhu.com/manuals
+4 -4
View File
@@ -10,7 +10,7 @@
[![Release](https://img.shields.io/github/v/release/KenanZhu/AutoLibrary?label=latest&logo=github&logoColor=white)](https://github.com/KenanZhu/AutoLibrary/releases/latest)
![Downloads](https://img.shields.io/github/downloads/KenanZhu/AutoLibrary/total?label=downloads)
了解更多请访问 [_AutoLibrary 网站_](http://www.autolibrary.top)
了解更多请访问 [_AutoLibrary 网站_](http://www.autolibrary.kenanzhu.com)
---
@@ -22,18 +22,18 @@
4. 批量操作 - 支持同时预约多个用户,可以指定当前需要跳过的用户,并将用户分成多个组
5. 定时任务 - 使用内置定时任务管理,添加定时任务,指定时间后按当前预约信息自动运行
*1,2,3 的具体操作方法和注意事项请访问我们的 [帮助手册](https://www.autolibrary.top/manuals)*
*1,2,3 的具体操作方法和注意事项请访问我们的 [帮助手册](https://www.autolibrary.kenanzhu.com/manuals)*
### 如何使用
1. 下载最新版本的 [AutoLibrary 压缩包](https://github.com/KenanZhu/AutoLibrary/releases/latest)。
2. 解压下载的文件到任意目录。
3. 下载对应浏览器类型和版本(具体操作请参考适用软件版本的 [帮助手册](https://www.autolibrary.top/manuals))的驱动文件,并在配置界面的运行配置选项卡对应位置选择你下载好的浏览器驱动。
3. 下载对应浏览器类型和版本(具体操作请参考适用软件版本的 [帮助手册](https://www.autolibrary.kenanzhu.com/manuals))的驱动文件,并在配置界面的运行配置选项卡对应位置选择你下载好的浏览器驱动。
4. 运行 `AutoLibrary-[主版本号].[次版本号].[修订版本号].Z.exe` 文件 (如 `AutoLibrary-1.0.0.exe`)。
5. 点击 [配置] 按钮,在配置界面填写好预约信息和运行配置后,点击 [确认] 按钮。
6. 点击 [启动脚本] 按钮,即可开始自动预约、续约、签到等操作。
*注意 1*: 关于浏览器驱动的下载和其它相关问题,请参考我们的 [帮助手册](https://www.autolibrary.top/manuals) 中对应软件版本的内容。
*注意 1*: 关于浏览器驱动的下载和其它相关问题,请参考我们的 [帮助手册](https://www.autolibrary.kenanzhu.com/manuals) 中对应软件版本的内容。
#### 平台支持 & 编译步骤
+135
View File
@@ -0,0 +1,135 @@
# -*- 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 queue
from base.LibOperator import LibOperator
class LibTimeSelector(LibOperator):
"""
Base class for time selection operations.
This class provides common time selection logic for reservation and renewal
operations, including time conversion utilities and best time option finding.
"""
def __init__(
self,
input_queue: queue.Queue,
output_queue: queue.Queue
):
super().__init__(input_queue, output_queue)
@staticmethod
def _timeToMins(
time_str: str
) -> int:
"""
Convert time string "HH:MM" to minutes since midnight.
"""
hour, minute = map(int, time_str.split(":"))
return hour*60 + minute
@staticmethod
def _minsToTime(
mins: int
) -> str:
"""
Convert minutes since midnight to time string "HH:MM".
"""
hour, minute = divmod(mins, 60)
return f"{hour:02d}:{minute:02d}"
def _formatTimeRelation(
self,
abs_diff: int,
actual_diff: int,
time_type: str
) -> str:
"""
Format time difference relation string.
"""
if actual_diff < 0:
return f"早了 {abs_diff} 分钟"
elif actual_diff > 0:
return f"晚了 {abs_diff} 分钟"
else:
return f"正好等于 {time_type}"
def _findBestTimeOption(
self,
time_options: list,
target_time: int,
max_time_diff: int,
prefer_earlier: bool,
is_reserve: bool = True
) -> tuple:
"""
Find the best time option from available times.
Args:
time_options: List of WebElement time options
target_time: Target time in minutes
max_time_diff: Maximum acceptable time difference in minutes
prefer_earlier: If True, prefer earlier times when diffs are equal
is_reserve: If True, parse 'time' attribute; if False, parse 'id' attribute
Returns:
Tuple of (best_time_element, best_time_text, actual_diff, free_times_list)
or (None, None, None, []) if no suitable option found
"""
free_times = []
best_time_diff = max_time_diff
best_actual_diff = None
best_time_opt = None
for time_opt in time_options:
# Parse time value based on context
if is_reserve:
time_attr = time_opt.get_attribute("time")
if time_attr == "now":
from datetime import datetime
now = datetime.now()
time_val = now.hour * 60 + now.minute
elif time_attr and time_attr.isdigit():
time_val = int(time_attr)
else:
continue
else:
# Renewal context: parse 'id' attribute
time_attr = time_opt.get_attribute("id")
if not (time_attr and time_attr.isdigit()):
continue
time_val = int(time_attr)
free_times.append(time_opt.text.strip() if not is_reserve else self._minsToTime(time_val))
actual_diff = time_val - target_time
abs_diff = abs(actual_diff)
# Update best option if current is better
if (abs_diff < best_time_diff or
(abs_diff == best_time_diff and
((prefer_earlier and actual_diff <= 0) or
(not prefer_earlier and actual_diff >= 0)))):
best_time_diff = abs_diff
best_actual_diff = actual_diff
best_time_opt = time_opt
if best_time_opt is not None:
return (best_time_opt, best_time_opt.text.strip(), best_actual_diff, free_times)
return (None, None, None, free_times)
+1 -1
View File
@@ -82,7 +82,7 @@ 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.top" style="text-decoration: none;">https://www.autolibrary.top</a><br>
Project website: <a href="https://www.autolibrary.kenanzhu.com" style="text-decoration: none;">https://www.autolibrary.kenanzhu.com</a><br>
<h4>Author Information:</h4>
Developer: KenanZhu<br>
+8 -8
View File
@@ -21,10 +21,10 @@ from PySide6.QtGui import (
QCloseEvent, QAction
)
import utils.ConfigManager as ConfigManager
from utils.JSONReader import JSONReader
from utils.JSONWriter import JSONWriter
from utils.ConfigManager import ConfigType, instance
from utils.ConfigManager import getValidateAutomationConfigPaths
from gui.resources.ui.Ui_ALConfigWidget import Ui_ALConfigWidget
from gui.ALSeatMapSelectDialog import ALSeatMapSelectDialog
@@ -42,8 +42,8 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
):
super().__init__(parent)
self.__cfg_mgr = instance()
self.__config_paths = getValidateAutomationConfigPaths()
self.__cfg_mgr = ConfigManager.instance()
self.__config_paths = ConfigManager.getValidateAutomationConfigPaths()
self.__config_data = {"run": {}, "user": {}}
self.setupUi(self)
@@ -968,13 +968,13 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
self.setRunConfigToWidget(data)
self.__config_paths["run"] = run_config_path
self.CurrentRunConfigEdit.setText(run_config_path)
paths = self.__cfg_mgr.get(ConfigType.GLOBAL, "automation.run_path.paths", [])
paths = self.__cfg_mgr.get(ConfigManager.ConfigType.GLOBAL, "automation.run_path.paths", [])
if run_config_path not in paths:
paths.append(run_config_path)
index = len(paths) - 1
else:
index = paths.index(run_config_path)
self.__cfg_mgr.set(ConfigType.GLOBAL, "automation.run_path", {"current": index, "paths": paths})
self.__cfg_mgr.set(ConfigManager.ConfigType.GLOBAL, "automation.run_path", {"current": index, "paths": paths})
else:
QMessageBox.warning(
self,
@@ -1003,13 +1003,13 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
self.setUsersToTreeWidget(data)
self.__config_paths["user"] = user_config_path
self.CurrentUserConfigEdit.setText(user_config_path)
paths = self.__cfg_mgr.get(ConfigType.GLOBAL, "automation.user_path.paths", [])
paths = self.__cfg_mgr.get(ConfigManager.ConfigType.GLOBAL, "automation.user_path.paths", [])
if user_config_path not in paths:
paths.append(user_config_path)
index = len(paths) - 1
else:
index = paths.index(user_config_path)
self.__cfg_mgr.set(ConfigType.GLOBAL, "automation.user_path", {"current": index, "paths": paths})
self.__cfg_mgr.set(ConfigManager.ConfigType.GLOBAL, "automation.user_path", {"current": index, "paths": paths})
else:
QMessageBox.warning(
self,
+13 -14
View File
@@ -7,11 +7,10 @@ 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 queue
from PySide6.QtCore import (
Qt, Signal, Slot, QTimer, QDir, QUrl,
Qt, Signal, Slot, QTimer, QUrl,
)
from PySide6.QtWidgets import (
QMainWindow, QMenu, QSystemTrayIcon, QMessageBox
@@ -20,10 +19,9 @@ from PySide6.QtGui import (
QTextCursor, QCloseEvent, QFont, QIcon, QDesktopServices
)
from base.MsgBase import MsgBase
import utils.ConfigManager as ConfigManager
from utils.ConfigManager import ConfigType, instance
from utils.ConfigManager import getValidateAutomationConfigPaths
from base.MsgBase import MsgBase
from gui.resources.ui.Ui_ALMainWindow import Ui_ALMainWindow
from gui.resources import ALResource
@@ -46,9 +44,9 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
MsgBase.__init__(self, queue.Queue(), queue.Queue())
QMainWindow.__init__(self)
self.__cfg_mgr = instance()
self.__cfg_mgr = ConfigManager.instance()
self.__timer_task_queue = queue.Queue()
self.__config_paths = getValidateAutomationConfigPaths()
self.__config_paths = ConfigManager.getValidateAutomationConfigPaths()
self.__alTimerTaskManageWidget = None
self.__alConfigWidget = None
self.__auto_lib_thread = None
@@ -106,7 +104,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
self
):
url = QUrl("https://www.autolibrary.top/manuals")
url = QUrl("https://www.autolibrary.kenanzhu.com/manuals")
QDesktopServices.openUrl(url)
@@ -115,9 +113,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
):
if not QSystemTrayIcon.isSystemTrayAvailable():
self.showTraceSignal.emit(
"系统不支持系统托盘功能, 无法创建系统托盘图标。"
)
self._showTrace("操作系统不支持系统托盘功能, 无法创建系统托盘图标")
return
self.TrayIcon = QSystemTrayIcon(self.icon, self)
self.TrayIcon.setToolTip("AutoLibrary")
@@ -130,7 +126,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
self.TrayMenu.addAction("退出", self.close)
self.TrayIcon.setContextMenu(self.TrayMenu)
self.TrayIcon.setContextMenu(self.TrayMenu)
self.TrayIcon.activated.connect(self.onTrayIconActivated)
self.TrayIcon.show()
@@ -174,6 +169,10 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
event: QCloseEvent
):
if not self.isVisible():
self.showNormal()
event.ignore()
return
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():
@@ -187,7 +186,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
if self.__alConfigWidget:
self.__alConfigWidget.close()
# the config widget is already deleted in the 'self.onConfigWidgetClosed'
super().closeEvent(event)
QMainWindow.closeEvent(self, event)
def appendToTextEdit(
@@ -327,7 +326,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
self.TrayIcon.showMessage(
"定时任务 - AutoLibrary",
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
QSystemTrayIcon.MessageIcon.Information,
QSystemTrayIcon.MessageIcon.Warning if is_error else QSystemTrayIcon.MessageIcon.Information,
1000
)
self._showTrace(
+5 -5
View File
@@ -15,7 +15,7 @@ from enum import Enum
from datetime import datetime, timedelta
from PySide6.QtCore import (
Qt, Signal, Slot, QTimer, QFileInfo, QDir
Qt, Signal, Slot, QTimer
)
from PySide6.QtWidgets import (
QDialog, QWidget, QListWidgetItem, QMessageBox,
@@ -25,7 +25,7 @@ from PySide6.QtGui import (
QCloseEvent
)
from utils.ConfigManager import ConfigType, instance
import utils.ConfigManager as ConfigManager
from gui.resources.ui.Ui_ALTimerTaskManageWidget import Ui_ALTimerTaskManageWidget
from gui.ALTimerTaskAddDialog import ALTimerTaskAddDialog, ALTimerTaskStatus
@@ -145,7 +145,7 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
):
super().__init__(parent)
self.__cfg_mgr = instance()
self.__cfg_mgr = ConfigManager.instance()
self.__timer_tasks = []
self.__check_timer = None
self.__sort_policy = self.SortPolicy.BY_EXECUTE_TIME
@@ -199,7 +199,7 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
) -> list:
try:
timer_tasks = self.__cfg_mgr.get(ConfigType.TIMERTASK)
timer_tasks = self.__cfg_mgr.get(ConfigManager.ConfigType.TIMERTASK)
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")
@@ -226,7 +226,7 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
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
self.__cfg_mgr.set(ConfigType.TIMERTASK, "", { "timer_tasks": timer_tasks })
self.__cfg_mgr.set(ConfigManager.ConfigType.TIMERTASK, "", { "timer_tasks": timer_tasks })
return True
except Exception as e:
QMessageBox.warning(
+1 -1
View File
@@ -1356,7 +1356,7 @@
</size>
</property>
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;详情请参阅 &lt;a href=&quot;https://www.autolibrary.top/manuals&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#69fcff;&quot;&gt;用户手册&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;详情请参阅 &lt;a href=&quot;https://www.autolibrary.kenanzhu.com/manuals&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#69fcff;&quot;&gt;用户手册&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="whatsThis">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+2 -2
View File
@@ -241,7 +241,7 @@ class AutoLib(MsgBase):
self._showTrace(f"用户 {username} 无法预约,已跳过")
result = 2
# checkin
if run_mode["auto_checkin"] and result == 2:
if run_mode["auto_checkin"] and result != 1:
if self.__lib_checker.canCheckin():
if self.__lib_checkin.checkin(username):
result = 0
@@ -251,7 +251,7 @@ class AutoLib(MsgBase):
self._showTrace(f"用户 {username} 无法签到,已跳过")
result = 2
# renewal
if run_mode["auto_renewal"] and result == 2:
if run_mode["auto_renewal"] and result != 1:
can_renew, record = self.__lib_checker.canRenew()
if can_renew:
if self.__lib_renew.renew(username, record, reserve_info):
+75 -84
View File
@@ -14,10 +14,10 @@ from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from base.LibOperator import LibOperator
from base.LibTimeSelector import LibTimeSelector
class LibRenew(LibOperator):
class LibRenew(LibTimeSelector):
def __init__(
self,
@@ -38,22 +38,6 @@ class LibRenew(LibOperator):
self.__driver.refresh()
return True
@staticmethod
def __timeToMins(
time_str: str
) -> int:
hour, minute = map(int, time_str.split(":"))
return hour*60 + minute
@staticmethod
def __minsToTime(
mins: int
) -> str:
hour, minute = divmod(mins, 60)
return f"{hour:02d}:{minute:02d}"
def __waitRenewDialog(
self
@@ -94,85 +78,92 @@ class LibRenew(LibOperator):
return True
def __selectNearstTime(
def __selectNearestTime(
self,
record: dict,
reserve_info: dict
) -> bool:
"""
TODO : this function is too long and too ugly
we need to refactor it to make it more readable.
but may be it is not a good idea to refactor it. :) who knows...
Select the nearest available renewal time.
"""
end_time = record["time"]["end"]
renew_info = reserve_info["renew_time"]
max_diff = renew_info["max_diff"]
prefer_earlier = renew_info["prefer_early"]
target_renew_mins = self.__timeToMins(end_time) + renew_info["expect_duration"]*60
renew_ok_btn = self.__driver.find_element(
By.CSS_SELECTOR, "#extendDiv .btnOK"
)
try:
renew_time_opts = self.__driver.find_elements(
By.CSS_SELECTOR, "#extendDiv .renewal_List li"
)
free_times = []
best_time_diff = max_diff
best_actual_diff = None
best_time_opt = None
target_renew_mins = self._timeToMins(end_time) + renew_info["expect_duration"]*60
if not renew_time_opts:
self._showTrace("当前未查询到可用续约时间 !")
return False
for time_opt in renew_time_opts:
time_attr = time_opt.get_attribute("id")
if time_attr and time_attr.isdigit():
time_val = int(time_attr)
free_times.append(time_opt.text.strip())
else:
continue
actual_diff = time_val - target_renew_mins
abs_diff = abs(actual_diff)
if abs_diff < best_time_diff or (
abs_diff == best_time_diff and (
(prefer_earlier and actual_diff <= 0) or
(not prefer_earlier and actual_diff >= 0)
)
):
best_time_diff = abs_diff
best_actual_diff = actual_diff
best_time_opt = time_opt
if best_time_opt is not None:
best_time_opt.click()
abs_time_diff = abs(best_actual_diff)
if best_actual_diff < 0:
time_relation = f"早了 {abs_time_diff} 分钟"
elif best_actual_diff > 0:
time_relation = f"晚了 {abs_time_diff} 分钟"
else:
time_relation = f"正好等于续约时间"
self._showTrace(
f"选择距离期望续约时间最近的 {best_time_opt.text}, "\
f"与期望续约时间相比 {time_relation}"
)
# update the actual renew end time
record["time"]["end"] = best_time_opt.text.strip()
renew_ok_btn.click()
return True
self._showTrace(
"无法选择最近的可用续约时间 !" \
f"所有可选时间与目标时间相差都超过了 {max_diff} 分钟 !"
)
self._showTrace(
f"当前可供续约的时间有: {free_times}"
)
# Validate and adjust target renew time to library closing time
if not self.__validateAndAdjustRenewTime(end_time, target_renew_mins):
return False
renew_ok_btn = self.__driver.find_element(By.CSS_SELECTOR, "#extendDiv .btnOK")
renew_time_opts = self.__driver.find_elements(By.CSS_SELECTOR, "#extendDiv .renewal_List li")
if not renew_time_opts:
self._showTrace("当前未查询到可用续约时间 !")
return False
# Find best renewal time option
best_opt, best_text, actual_diff, free_times = self._findBestTimeOption(
renew_time_opts, target_renew_mins, max_diff, prefer_earlier, is_reserve=False
)
if best_opt is not None:
return self.__confirmRenewal(best_opt, best_text, actual_diff, record, renew_ok_btn)
self._showTrace(
"无法选择最近的可用续约时间 ! "
f"所有可选时间与目标时间相差都超过了 {max_diff} 分钟 !"
)
self._showTrace(f"当前可供续约的时间有: {free_times}")
return False
def __validateAndAdjustRenewTime(
self,
end_time: str,
target_renew_mins: int
) -> bool:
"""
Validate and adjust renewal time to library closing time if needed.
"""
LIBRARY_CLOSE_TIME = 1410 # 23:30 in minutes
if target_renew_mins > LIBRARY_CLOSE_TIME:
actual_renew_duration = LIBRARY_CLOSE_TIME - self._timeToMins(end_time)
if actual_renew_duration <= 0:
self._showTrace(f"当前结束时间 {end_time} 已接近闭馆时间,无法续约 !")
return False
self._showTrace(
f"续约时间已调整至闭馆时间 {self._minsToTime(LIBRARY_CLOSE_TIME)}"
f"实际续约时长为 {actual_renew_duration//60} 小时 {actual_renew_duration%60} 分钟"
)
return True
return True
def __confirmRenewal(
self,
best_opt,
best_text: str,
actual_diff: int,
record: dict,
ok_btn
) -> bool:
"""
Confirm the selected renewal time.
"""
try:
best_opt.click()
abs_diff = abs(actual_diff)
time_relation = self._formatTimeRelation(abs_diff, actual_diff, "续约时间")
self._showTrace(
f"选择距离期望续约时间最近的 {best_text}, "
f"与期望续约时间相比 {time_relation}"
)
record["time"]["end"] = best_text.strip()
ok_btn.click()
return True
except:
self._showTrace("查询可用续约时间时发生未知错误 !")
self._showTrace("确认续约时发生错误 !")
return False
@@ -204,7 +195,7 @@ class LibRenew(LibOperator):
# so we need to refresh the page for subsequent operations.
self.__driver.refresh()
return False
if not self.__selectNearstTime(record, reserve_info):
if not self.__selectNearestTime(record, reserve_info):
self._showTrace(f"用户 {username} 续约失败 !")
self.__driver.refresh()
return False
+75 -108
View File
@@ -10,16 +10,15 @@ See the LICENSE file for details.
import time
import queue
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
from base.LibOperator import LibOperator
from base.LibTimeSelector import LibTimeSelector
class LibReserve(LibOperator):
class LibReserve(LibTimeSelector):
def __init__(
self,
@@ -100,22 +99,6 @@ class LibReserve(LibOperator):
self._showTrace(f"预约结果加载失败 !")
return False
@staticmethod
def __timeToMins(
time_str: str
) -> int:
hour, minute = map(int, time_str.split(":"))
return hour*60 + minute
@staticmethod
def __minsToTime(
mins: int
) -> str:
hour, minute = divmod(mins, 60)
return f"{hour:02d}:{minute:02d}"
def __containRequiredInfo(
self,
@@ -207,10 +190,10 @@ class LibReserve(LibOperator):
if reserve_info.get("end_time") is None:
reserve_info["end_time"] = {}
if "time" not in reserve_info["end_time"]:
end_mins = self.__timeToMins(reserve_info["begin_time"]["time"])
end_mins = self._timeToMins(reserve_info["begin_time"]["time"])
end_mins = end_mins + int(reserve_info["expect_duration"]*60)
reserve_info["end_time"] = {
"time": self.__minsToTime(end_mins),
"time": self._minsToTime(end_mins),
"max_diff": 30,
"prefer_early": False
}
@@ -232,8 +215,8 @@ class LibReserve(LibOperator):
):
begin_time, end_time = reserve_info["begin_time"], reserve_info["end_time"]
begin_mins = self.__timeToMins(begin_time["time"])
end_mins = self.__timeToMins(end_time["time"])
begin_mins = self._timeToMins(begin_time["time"])
end_mins = self._timeToMins(end_time["time"])
# if end time is earlier than begin_time, exchange them
if end_mins < begin_mins:
self._showTrace(
@@ -242,15 +225,15 @@ class LibReserve(LibOperator):
reserve_info["end_time"] = begin_time
reserve_info["begin_time"] = end_time
begin_time, end_time = reserve_info["begin_time"], reserve_info["end_time"]
begin_mins = self.__timeToMins(begin_time["time"])
end_mins = self.__timeToMins(end_time["time"])
begin_mins = self._timeToMins(begin_time["time"])
end_mins = self._timeToMins(end_time["time"])
# ensure the end time is not later than 23:30
if end_mins > self.__timeToMins("23:30"):
if end_mins > self._timeToMins("23:30"):
self._showTrace(
f"结束时间 {end_time['time']} 晚于 23:30, 自动设置为 23:30"
)
reserve_info["end_time"]["time"] = "23:30"
end_mins = self.__timeToMins("23:30")
end_mins = self._timeToMins("23:30")
# ensure the duration is not longer than 8 hours
if reserve_info["satisfy_duration"]:
if reserve_info["expect_duration"] > 8:
@@ -267,7 +250,7 @@ class LibReserve(LibOperator):
f"{float((end_mins - begin_mins)/60)} 小时 "
f"超出最大时长 8 小时, 自动设置为 8 小时"
)
reserve_info["end_time"]["time"] = self.__minsToTime(begin_mins + 8*60)
reserve_info["end_time"]["time"] = self._minsToTime(begin_mins + 8*60)
return True
@@ -496,6 +479,10 @@ class LibReserve(LibOperator):
prefer_earlier: bool = True
) -> int:
"""
Select the nearest available time option.
"""
# Wait for time options to load
try:
WebDriverWait(self.__driver, 2).until(
EC.presence_of_all_elements_located(
@@ -505,67 +492,34 @@ class LibReserve(LibOperator):
except:
self._showTrace(f"{time_type} 选择失败 ! : 当前未查询到可用时间")
return -1
try:
all_time_opts = self.__driver.find_elements(
By.CSS_SELECTOR,
f"#{time_id} ul li a"
)
free_times = []
best_time_diff = max_time_diff
best_actual_diff = None
best_time_opt = None
if not all_time_opts:
self._showTrace(f"{time_type} 选择失败 ! : 当前未查询到可用时间")
return -1
for time_opt in all_time_opts:
time_attr = time_opt.get_attribute("time")
if time_attr == "now":
now = datetime.now()
time_val = int(now.hour*60 + now.minute)
elif time_attr and time_attr.isdigit():
time_val = int(time_attr)
else:
continue
free_times.append(self.__minsToTime(time_val))
actual_diff = time_val - target_time
abs_diff = abs(actual_diff)
if abs_diff < best_time_diff or (
abs_diff == best_time_diff and (
# prefer earlier time
(prefer_earlier and actual_diff <= 0) or
# prefer later time
(not prefer_earlier and actual_diff >= 0)
)
):
best_time_diff = abs_diff
best_actual_diff = actual_diff
best_time_opt = time_opt
if best_time_opt is not None:
best_time_opt.click()
abs_time_diff = abs(best_actual_diff)
if best_actual_diff < 0:
time_relation = f"早了 {abs_time_diff} 分钟"
elif best_actual_diff > 0:
time_relation = f"晚了 {abs_time_diff} 分钟"
else:
time_relation = f"正好等于 {time_type}"
target_time += best_actual_diff
self._showTrace(
f"选择距离期望 {time_type} 最近的 {best_time_opt.text}, "\
f"与期望 {time_type} 相比 {time_relation}"
)
return target_time
# Find best time option
all_time_opts = self.__driver.find_elements(
By.CSS_SELECTOR,
f"#{time_id} ul li a"
)
if not all_time_opts:
self._showTrace(f"{time_type} 选择失败 ! : 当前未查询到可用时间")
return -1
best_opt, best_text, actual_diff, free_times = self._findBestTimeOption(
all_time_opts, target_time, max_time_diff, prefer_earlier, is_reserve=True
)
if best_opt is not None:
best_opt.click()
abs_diff = abs(actual_diff)
time_relation = self._formatTimeRelation(abs_diff, actual_diff, time_type)
target_time += actual_diff
self._showTrace(
f"无法选择最近的 {time_type} {self.__minsToTime(target_time)}, "\
f"所有可选时间与目标时间相差都超过 {max_time_diff} 分钟"
f"选择距离期望 {time_type} 最近的 {best_text}, "
f"与期望 {time_type} 相比 {time_relation}"
)
self._showTrace(f"当前可供预约的 {time_type} 有: {free_times}")
return -1
except:
self._showTrace(f"{time_type} {self.__minsToTime(target_time)} 选择失败 !")
return -1
return target_time
self._showTrace(
f"无法选择最近的 {time_type} {self._minsToTime(target_time)}, "
f"所有可选时间与目标时间相差都超过 {max_time_diff} 分钟"
)
self._showTrace(f"当前可供预约的 {time_type} 有: {free_times}")
return -1
def __selectSeatTime(
@@ -576,40 +530,35 @@ class LibReserve(LibOperator):
satisfy_duration: bool = True
) -> bool:
"""Select seat begin and end time."""
expect_begin_time = actual_begin_time = begin_time["time"]
expect_end_time = actual_end_time = end_time["time"]
expect_begin_mins = self.__timeToMins(expect_begin_time)
expect_begin_mins = self._timeToMins(expect_begin_time)
actual_begin_mins = expect_begin_mins
expect_end_mins = self.__timeToMins(expect_end_time)
expect_end_mins = self._timeToMins(expect_end_time)
# select the begin time
# Select begin time
if self.__selectNearestTime(
time_id="startTime", # dont change into begin, this is the element in the page
time_id="startTime",
time_type="开始时间",
target_time=expect_begin_mins,
max_time_diff=begin_time["max_diff"],
prefer_earlier=begin_time["prefer_early"]
) == -1:
return False
else:
actual_begin_time = self.__minsToTime(expect_begin_mins)
actual_begin_mins = self.__timeToMins(actual_begin_time)
# if 'satisfy_duration' is True.
# select the end time based on the begin time
# (because it may be changed under the 'max time diff' strategy) and expect duration.
actual_begin_time = self._minsToTime(expect_begin_mins)
actual_begin_mins = self._timeToMins(actual_begin_time)
# If 'satisfy_duration' is True, select end time based on actual begin time
if satisfy_duration:
expect_end_mins = int(actual_begin_mins + expct_duration*60)
if expect_end_mins > self.__timeToMins("23:30"):
expect_end_mins = self.__timeToMins("23:30")
self._showTrace(
f"预约持续时间 {expct_duration} 小时, 超过最大预约时间 23:30, 自动调整为 23:30"
)
expect_end_time = self.__minsToTime(expect_end_mins)
expect_end_mins = self.validateAndAdjustEndTime(actual_begin_mins, expct_duration)
expect_end_time = self._minsToTime(expect_end_mins)
self._showTrace(
f"需要满足期望预约持续时间: {expct_duration} 小时, "\
f"根据开始时间 {actual_begin_time} 计算结束时间: {self.__minsToTime(expect_end_mins)}"
f"需要满足期望预约持续时间: {expct_duration} 小时, "
f"根据开始时间 {actual_begin_time} 计算结束时间: {expect_end_time}"
)
# select the end time
# Select end time
if self.__selectNearestTime(
time_id="endTime",
time_type="结束时间",
@@ -618,8 +567,7 @@ class LibReserve(LibOperator):
prefer_earlier=end_time["prefer_early"]
) == -1:
return False
else:
actual_end_time = self.__minsToTime(expect_end_mins)
actual_end_time = self._minsToTime(expect_end_mins)
self._showTrace(
f"期望预约时间段: {expect_begin_time} - {expect_end_time}, "
f"实际预约时间段: {actual_begin_time} - {actual_end_time}"
@@ -627,6 +575,25 @@ class LibReserve(LibOperator):
return True
def validateAndAdjustEndTime(
self,
begin_mins: int,
duration: int
) -> int:
"""
Validate and adjust reserve end time to library closing time if needed.
"""
LIBRARY_CLOSE_TIME = self._timeToMins("23:30")
expect_end_mins = begin_mins + duration * 60
if expect_end_mins > LIBRARY_CLOSE_TIME:
expect_end_mins = LIBRARY_CLOSE_TIME
self._showTrace(
f"预约持续时间 {duration} 小时, 超过最大预约时间 23:30, 自动调整为 23:30"
)
return expect_end_mins
def reserve(
self,
username: str,
+16 -5
View File
@@ -168,16 +168,19 @@ class ConfigManager:
JSONWriter(config_path, self.__config_data[config_type.value])
def appDir(
def configDir(
self
) -> str:
return self.__config_dir
# ConfigManager singleton instance.
_config_manager_instance = None
# Utility function to get config data (thread-safe and validated) from ConfigManager instance.
# Utility functions.
#
# Utility function to get validated automation config paths.
def getValidateAutomationConfigPaths(
) -> dict:
"""
@@ -193,7 +196,7 @@ def getValidateAutomationConfigPaths(
paths = auto_config.get(f"{cfg_type}_path", {}).get("paths", [])
index = auto_config.get(f"{cfg_type}_path", {}).get("current", 0)
if paths == []:
paths.append(os.path.join(_config_manager_instance.appDir(), f"{cfg_type}.json"))
paths.append(os.path.join(_config_manager_instance.configDir(), f"{cfg_type}.json"))
if index < 0:
index = 0
if index >= len(paths):
@@ -204,10 +207,18 @@ def getValidateAutomationConfigPaths(
_config_manager_instance.set(ConfigType.GLOBAL, "automation", auto_config)
return config_paths
# Utility function to get base config directory.
def getBaseConfigDir(
) -> str:
"""
Get base config directory, on Windows, it is usually at :
'C:\\Users\\<username>\\AppData\\Local\\AutoLibrary\\config'.
return _config_manager_instance.appDir()
Returns:
str: Base config directory.
"""
return _config_manager_instance.configDir()
# Singleton instance of ConfigManager.
_instance_lock = threading.Lock()
@@ -227,7 +238,7 @@ def instance(
else:
if config_dir == "":
return _config_manager_instance
if _config_manager_instance.appDir() != config_dir:
if getBaseConfigDir() != config_dir:
raise ValueError(
"ConfigManager 的实例已初始化,不能使用不同的配置目录。")
return _config_manager_instance