ustc-tools 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ustc_tools/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Reusable workflows; protocol/UI adapters belong in their own applications."""
2
+ from .activities import ActivityService, EnrollmentResult, StatePersistenceError, filter_activities
3
+ from .models import (
4
+ ActivityChange,
5
+ ActivityPreferences,
6
+ FilterDecision,
7
+ FilterResult,
8
+ ScanResult,
9
+ TimeRange,
10
+ WeeklyBusy,
11
+ )
12
+ from .storage import ActivityStore, MemoryStore, SQLiteStore
13
+
14
+ __all__ = [
15
+ "ActivityService", "EnrollmentResult", "StatePersistenceError", "filter_activities",
16
+ "ActivityChange", "ActivityPreferences", "FilterDecision", "FilterResult", "ScanResult",
17
+ "TimeRange", "WeeklyBusy", "ActivityStore", "MemoryStore", "SQLiteStore",
18
+ ]
@@ -0,0 +1,176 @@
1
+ """Second-class workflows without bot, web or agent-protocol dependencies."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from collections.abc import Awaitable, Callable, Sequence
6
+ from datetime import datetime, timedelta, timezone
7
+
8
+ from pydantic import BaseModel, ConfigDict
9
+ from ustc_sdk.errors import ServiceError, USTCError
10
+ from ustc_sdk.young import Activity, MutationResult, SignInfo, YoungClient
11
+
12
+ from .models import ActivityPreferences, FilterDecision, FilterResult, ScanResult
13
+ from .storage import ActivityStore
14
+
15
+ CAMPUS_TZ = timezone(timedelta(hours=8))
16
+ ActivityPredicate = Callable[[Activity], Awaitable[bool]]
17
+
18
+
19
+ class EnrollmentResult(BaseModel):
20
+ model_config = ConfigDict(frozen=True)
21
+ result: MutationResult
22
+ activity: Activity
23
+ already_enrolled: bool = False
24
+
25
+
26
+ class StatePersistenceError(USTCError):
27
+ """The server mutation succeeded but the local snapshot could not be updated.
28
+
29
+ Query server state; do NOT resubmit the mutation. result contains the server outcome.
30
+ """
31
+ def __init__(self, result: MutationResult):
32
+ super().__init__("server mutation succeeded; local snapshot update failed")
33
+ self.result = result
34
+
35
+
36
+ def _conflicts(activity: Activity, preferences: ActivityPreferences,
37
+ enrolled: Sequence[Activity]) -> bool:
38
+ # Series can describe a multi-day envelope rather than a concrete meeting.
39
+ if activity.is_series or activity.starts_at is None:
40
+ return False
41
+ start = activity.starts_at.astimezone(CAMPUS_TZ)
42
+ end = (activity.ends_at or start + timedelta(hours=2)).astimezone(CAMPUS_TZ)
43
+ if end <= start:
44
+ return False
45
+ if any(p.overlaps(start, end) for p in preferences.busy_periods):
46
+ return True
47
+ day, last_day = start.date() - timedelta(days=1), end.date()
48
+ while day <= last_day:
49
+ if any(p.weekday == day.weekday() and p.on(day, CAMPUS_TZ).overlaps(start, end)
50
+ for p in preferences.weekly_busy):
51
+ return True
52
+ day += timedelta(days=1)
53
+ for other in enrolled:
54
+ if other.id == activity.id or other.is_series or other.starts_at is None:
55
+ continue
56
+ other_end = other.ends_at or other.starts_at + timedelta(hours=2)
57
+ if start < other_end and other.starts_at < end:
58
+ return True
59
+ return False
60
+
61
+
62
+ def filter_activities(activities: Sequence[Activity], preferences: ActivityPreferences,
63
+ *, enrolled: Sequence[Activity] = ()) -> FilterResult:
64
+ passed, excluded = [], []
65
+ for activity in activities:
66
+ reasons = []
67
+ if activity.id in preferences.ignored_ids:
68
+ reasons.append("ignored")
69
+ if preferences.exclude_enrolled and activity.applied:
70
+ reasons.append("already_enrolled")
71
+ if preferences.only_applyable and (
72
+ activity.status != 26 or activity.applied or
73
+ (activity.apply_count is not None and activity.apply_limit is not None
74
+ and activity.apply_count >= activity.apply_limit)
75
+ ):
76
+ reasons.append("not_applyable")
77
+ if preferences.exclude_conflicts and _conflicts(activity, preferences, enrolled):
78
+ reasons.append("time_conflict")
79
+ if reasons:
80
+ excluded.append(FilterDecision(activity=activity, reasons=tuple(reasons)))
81
+ else:
82
+ passed.append(activity)
83
+ return FilterResult(passed=tuple(passed), excluded=tuple(excluded),
84
+ interested_ids=frozenset(a.id for a in passed if a.id in preferences.interested_ids))
85
+
86
+
87
+ class ActivityService:
88
+ def __init__(self, client: YoungClient, store: ActivityStore, *, user_id: str,
89
+ clock: Callable[[], datetime] | None = None):
90
+ if not user_id.strip():
91
+ raise ValueError("user_id must not be empty")
92
+ self.client = client
93
+ self.store = store
94
+ self.user_id = user_id
95
+ self._clock = clock or (lambda: datetime.now(CAMPUS_TZ))
96
+ self._operations = asyncio.Lock()
97
+
98
+ async def scan(self, *, deep: bool = False) -> ScanResult:
99
+ """Fetch the complete active, ended and participated lists before committing.
100
+
101
+ Any network/protocol failure leaves the old snapshot intact. A deep scan fetches
102
+ each detail; a shallow scan compares list fields only and costs fewer requests.
103
+ """
104
+ async with self._operations:
105
+ active = await self.client.list_activities(expand_series=True)
106
+ ended = await self.client.list_activities(ended=True, expand_series=True)
107
+ enrolled = await self.client.enrolled()
108
+ by_id = {a.id: a for a in [*ended, *active]}
109
+ for activity in enrolled:
110
+ previous = by_id.get(activity.id, activity)
111
+ by_id[activity.id] = previous.model_copy(update={
112
+ "applied": True, "raw": previous.raw | {"booleanRegistration": 1},
113
+ })
114
+ if deep:
115
+ by_id = {aid: await self.client.get_activity(aid) for aid in by_id}
116
+ return await self.store.save_scan(self.user_id, list(by_id.values()), self._clock())
117
+
118
+ async def search(self, keyword: str = "") -> list[Activity]:
119
+ """Literal case-insensitive substring search over this user's last complete scan."""
120
+ needle = keyword.casefold()
121
+ return [a for a in await self.store.snapshot(self.user_id) or []
122
+ if needle in a.name.casefold() or needle in a.description.casefold()]
123
+
124
+ async def select(self, *, preferences: ActivityPreferences | None = None,
125
+ predicate: ActivityPredicate | None = None) -> FilterResult:
126
+ """Optional caller-supplied AI/content predicate; errors propagate, never silently pass."""
127
+ preferences = preferences or await self.store.get_preferences(self.user_id)
128
+ activities = await self.store.snapshot(self.user_id) or []
129
+ result = filter_activities(activities, preferences,
130
+ enrolled=[a for a in activities if a.applied])
131
+ if predicate is None:
132
+ return result
133
+ passed, excluded = [], list(result.excluded)
134
+ for activity in result.passed:
135
+ if await predicate(activity):
136
+ passed.append(activity)
137
+ else:
138
+ excluded.append(FilterDecision(activity=activity, reasons=("content_predicate",)))
139
+ return FilterResult(passed=tuple(passed), excluded=tuple(excluded),
140
+ interested_ids=result.interested_ids & {a.id for a in passed})
141
+
142
+ async def enroll(self, activity_id: str, *, sign_info: SignInfo | None = None) -> EnrollmentResult:
143
+ async with self._operations:
144
+ activity = await self.client.get_activity(activity_id)
145
+ if activity.applied:
146
+ return EnrollmentResult(result=MutationResult(activity_id=activity_id, success=True,
147
+ message="already enrolled"), activity=activity, already_enrolled=True)
148
+ if activity.status != 26:
149
+ raise ServiceError("activity is not accepting enrollment")
150
+ if (activity.apply_count is not None and activity.apply_limit is not None
151
+ and activity.apply_count >= activity.apply_limit):
152
+ raise ServiceError("activity is full")
153
+ now = self._clock()
154
+ if ((activity.apply_starts_at and now < activity.apply_starts_at)
155
+ or (activity.apply_ends_at and now >= activity.apply_ends_at)):
156
+ raise ServiceError("outside the enrollment period")
157
+ result = await self.client.enroll(activity_id, sign_info=sign_info)
158
+ if result.success:
159
+ activity = activity.model_copy(update={"applied": True})
160
+ try:
161
+ await self.store.set_enrolled(self.user_id, activity, True)
162
+ except Exception as exc:
163
+ raise StatePersistenceError(result) from exc
164
+ return EnrollmentResult(result=result, activity=activity)
165
+
166
+ async def cancel(self, activity_id: str) -> EnrollmentResult:
167
+ async with self._operations:
168
+ activity = await self.client.get_activity(activity_id)
169
+ result = await self.client.cancel(activity_id)
170
+ if result.success:
171
+ activity = activity.model_copy(update={"applied": False})
172
+ try:
173
+ await self.store.set_enrolled(self.user_id, activity, False)
174
+ except Exception as exc:
175
+ raise StatePersistenceError(result) from exc
176
+ return EnrollmentResult(result=result, activity=activity)
ustc_tools/models.py ADDED
@@ -0,0 +1,113 @@
1
+ """Transport-independent preferences, filtering decisions and scan events."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import date, datetime, time, timedelta
5
+ from typing import Literal
6
+
7
+ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
8
+ from ustc_sdk.young import Activity
9
+
10
+
11
+ class TimeRange(BaseModel):
12
+ model_config = ConfigDict(frozen=True, extra="forbid")
13
+ start: AwareDatetime
14
+ end: AwareDatetime
15
+
16
+ @model_validator(mode="after")
17
+ def ordered(self) -> TimeRange:
18
+ if self.end <= self.start:
19
+ raise ValueError("end must be later than start")
20
+ return self
21
+
22
+ def overlaps(self, start: datetime, end: datetime) -> bool:
23
+ return self.start < end and start < self.end
24
+
25
+
26
+ class WeeklyBusy(BaseModel):
27
+ """Campus-local weekly interval; an earlier end belongs to the following day."""
28
+ model_config = ConfigDict(frozen=True, extra="forbid")
29
+ weekday: int = Field(ge=0, le=6)
30
+ start: time
31
+ end: time
32
+
33
+ @model_validator(mode="after")
34
+ def nonempty_local(self) -> WeeklyBusy:
35
+ if self.start == self.end or self.start.tzinfo or self.end.tzinfo:
36
+ raise ValueError("weekly intervals need distinct local times without timezone")
37
+ return self
38
+
39
+ def on(self, day: date, tz) -> TimeRange:
40
+ start = datetime.combine(day, self.start, tzinfo=tz)
41
+ end = datetime.combine(day, self.end, tzinfo=tz)
42
+ if end < start:
43
+ end += timedelta(days=1)
44
+ return TimeRange(start=start, end=end)
45
+
46
+
47
+ class ActivityPreferences(BaseModel):
48
+ model_config = ConfigDict(frozen=True, extra="forbid")
49
+ ignored_ids: frozenset[str] = frozenset()
50
+ interested_ids: frozenset[str] = frozenset()
51
+ exclude_enrolled: bool = True
52
+ exclude_conflicts: bool = True
53
+ only_applyable: bool = False
54
+ busy_periods: tuple[TimeRange, ...] = ()
55
+ weekly_busy: tuple[WeeklyBusy, ...] = ()
56
+
57
+
58
+ class FilterDecision(BaseModel):
59
+ model_config = ConfigDict(frozen=True)
60
+ activity: Activity
61
+ reasons: tuple[str, ...]
62
+
63
+
64
+ class FilterResult(BaseModel):
65
+ model_config = ConfigDict(frozen=True)
66
+ passed: tuple[Activity, ...]
67
+ excluded: tuple[FilterDecision, ...]
68
+ interested_ids: frozenset[str]
69
+
70
+
71
+ class ActivityChange(BaseModel):
72
+ model_config = ConfigDict(frozen=True)
73
+ kind: Literal["added", "removed", "modified"]
74
+ activity_id: str
75
+ before: Activity | None = None
76
+ after: Activity | None = None
77
+ fields: tuple[str, ...] = ()
78
+
79
+
80
+ class ScanResult(BaseModel):
81
+ model_config = ConfigDict(frozen=True)
82
+ user_id: str
83
+ scanned_at: AwareDatetime
84
+ baseline: bool
85
+ activities: tuple[Activity, ...]
86
+ changes: tuple[ActivityChange, ...]
87
+
88
+
89
+ def compare_snapshots(
90
+ old: list[Activity] | None, new: list[Activity], *, user_id: str, scanned_at: datetime
91
+ ) -> ScanResult:
92
+ """First scan establishes a baseline; subsequent complete scans produce ordered deltas."""
93
+ current = {a.id: a for a in new}
94
+ if len(current) != len(new):
95
+ raise ValueError("snapshot contains duplicate activity IDs")
96
+ changes: list[ActivityChange] = []
97
+ if old is not None:
98
+ previous = {a.id: a for a in old}
99
+ for activity_id in sorted(previous.keys() | current.keys()):
100
+ before, after = previous.get(activity_id), current.get(activity_id)
101
+ if before is None:
102
+ changes.append(ActivityChange(kind="added", activity_id=activity_id, after=after))
103
+ elif after is None:
104
+ changes.append(ActivityChange(kind="removed", activity_id=activity_id, before=before))
105
+ else:
106
+ before_data = before.model_dump(mode="json")
107
+ after_data = after.model_dump(mode="json")
108
+ fields = tuple(k for k in before_data if before_data[k] != after_data[k])
109
+ if fields:
110
+ changes.append(ActivityChange(kind="modified", activity_id=activity_id,
111
+ before=before, after=after, fields=fields))
112
+ return ScanResult(user_id=user_id, scanned_at=scanned_at, baseline=old is None,
113
+ activities=tuple(current[k] for k in sorted(current)), changes=tuple(changes))
ustc_tools/monitor.py ADDED
@@ -0,0 +1,78 @@
1
+ """Optional APScheduler runtime; importing ustc_tools does not import APScheduler."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from collections.abc import Awaitable, Callable
6
+
7
+ from apscheduler.events import EVENT_SCHEDULER_SHUTDOWN
8
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
9
+ from pydantic import BaseModel, ConfigDict, Field
10
+
11
+ from .activities import CAMPUS_TZ, ActivityService
12
+ from .models import ScanResult
13
+
14
+
15
+ class MonitorSettings(BaseModel):
16
+ model_config = ConfigDict(frozen=True, extra="forbid")
17
+ interval_seconds: float = Field(default=900, gt=0, allow_inf_nan=False)
18
+ deep_scan: bool = False
19
+
20
+
21
+ class Monitor:
22
+ """One in-process job per instance; caller owns service/client/store lifetimes.
23
+
24
+ on_scan runs after every successful persisted scan, including baseline scans.
25
+ Callback failures propagate to run_once/standard APScheduler job error reporting.
26
+ Stop from the owner task, not from on_scan. Stop waits for the current callback.
27
+ """
28
+
29
+ def __init__(self, service: ActivityService, *, settings: MonitorSettings | None = None,
30
+ on_scan: Callable[[ScanResult], Awaitable[None]] | None = None):
31
+ self.service = service
32
+ self.settings = settings or MonitorSettings()
33
+ self.on_scan = on_scan
34
+ self._scheduler: AsyncIOScheduler | None = None
35
+ self._lock = asyncio.Lock()
36
+ self._running_task: asyncio.Task | None = None
37
+
38
+ async def run_once(self) -> ScanResult:
39
+ async with self._lock:
40
+ self._running_task = asyncio.current_task()
41
+ try:
42
+ result = await self.service.scan(deep=self.settings.deep_scan)
43
+ if self.on_scan is not None:
44
+ await self.on_scan(result)
45
+ return result
46
+ finally:
47
+ self._running_task = None
48
+
49
+ async def start(self) -> None:
50
+ if self._scheduler is not None:
51
+ raise RuntimeError("monitor is already running")
52
+ scheduler = AsyncIOScheduler(event_loop=asyncio.get_running_loop(), timezone=CAMPUS_TZ)
53
+ scheduler.add_job(self.run_once, "interval", seconds=self.settings.interval_seconds,
54
+ id="scan", max_instances=1, coalesce=True)
55
+ scheduler.start()
56
+ self._scheduler = scheduler
57
+
58
+ async def stop(self) -> None:
59
+ scheduler = self._scheduler
60
+ if scheduler is None:
61
+ return
62
+ if self._running_task is asyncio.current_task():
63
+ raise RuntimeError("stop monitor from its owner, not its scan callback")
64
+ scheduler.pause()
65
+ scheduler.remove_all_jobs()
66
+ async with self._lock:
67
+ stopped = asyncio.Event()
68
+ scheduler.add_listener(lambda event: stopped.set(), EVENT_SCHEDULER_SHUTDOWN)
69
+ scheduler.shutdown(wait=True)
70
+ await stopped.wait()
71
+ self._scheduler = None
72
+
73
+ async def __aenter__(self) -> Monitor:
74
+ await self.start()
75
+ return self
76
+
77
+ async def __aexit__(self, *args) -> None:
78
+ await self.stop()
ustc_tools/py.typed ADDED
File without changes