51 lines
1.7 KiB
Python
51 lines
1.7 KiB
Python
"""当前使用 Android 设备的本地设置服务。"""
|
|
|
|
from .settings_repository import SettingsRepository
|
|
|
|
|
|
SELECTED_ANDROID_SERIAL_KEY = "android.selected_serial"
|
|
MAX_ANDROID_SERIAL_LENGTH = 255
|
|
|
|
|
|
class SelectedAndroidDeviceService:
|
|
"""只保存自动化应使用的设备号,不缓存 ADB 搜索结果。"""
|
|
|
|
def __init__(self, repository: SettingsRepository):
|
|
self._repository = repository
|
|
|
|
def load(self) -> str:
|
|
"""读取已保存设备号;缺失或损坏时返回空字符串。"""
|
|
|
|
value = self._repository.get(SELECTED_ANDROID_SERIAL_KEY, "")
|
|
if not isinstance(value, str):
|
|
return ""
|
|
return value.strip()
|
|
|
|
def save(self, serial: str) -> str:
|
|
"""校验并保存设备号,返回规范化后的值。"""
|
|
|
|
normalized = self._normalize_serial(serial)
|
|
self._repository.set(SELECTED_ANDROID_SERIAL_KEY, normalized)
|
|
return normalized
|
|
|
|
def delete(self) -> bool:
|
|
"""清除当前设备配置;配置不存在时也视为安全完成。"""
|
|
|
|
return self._repository.delete(SELECTED_ANDROID_SERIAL_KEY)
|
|
|
|
@staticmethod
|
|
def _normalize_serial(serial: object) -> str:
|
|
if not isinstance(serial, str):
|
|
raise ValueError("Android 设备号必须是文本")
|
|
|
|
normalized = serial.strip()
|
|
if not normalized:
|
|
raise ValueError("Android 设备号不能为空")
|
|
if len(normalized) > MAX_ANDROID_SERIAL_LENGTH:
|
|
raise ValueError(
|
|
f"Android 设备号最多 {MAX_ANDROID_SERIAL_LENGTH} 个字符"
|
|
)
|
|
if any(character.isspace() for character in normalized):
|
|
raise ValueError("Android 设备号不能包含空白字符")
|
|
return normalized
|