schedz 0.1.0__tar.gz
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.
- schedz-0.1.0/LICENSE +202 -0
- schedz-0.1.0/PKG-INFO +107 -0
- schedz-0.1.0/README.md +90 -0
- schedz-0.1.0/pyproject.toml +97 -0
- schedz-0.1.0/pyproject.toml.orig +81 -0
- schedz-0.1.0/src/schedz/__init__.py +2 -0
- schedz-0.1.0/src/schedz/diagnostics.py +17 -0
- schedz-0.1.0/src/schedz/exceptions.py +2 -0
- schedz-0.1.0/src/schedz/google.py +149 -0
- schedz-0.1.0/src/schedz/grouping.py +151 -0
- schedz-0.1.0/src/schedz/loading.py +78 -0
- schedz-0.1.0/src/schedz/parsing.py +242 -0
- schedz-0.1.0/src/schedz/py.typed +0 -0
- schedz-0.1.0/src/schedz/settings.py +59 -0
schedz-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
schedz-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: schedz
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read training sessions from a Google Calendar.
|
|
5
|
+
Author: m09
|
|
6
|
+
Author-email: m09 <142691+m09@users.noreply.github.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: platformdirs>=4
|
|
10
|
+
Requires-Dist: pydantic>=2.13
|
|
11
|
+
Requires-Dist: pyyaml>=6
|
|
12
|
+
Requires-Dist: google-api-python-client>=2 ; extra == 'google'
|
|
13
|
+
Requires-Dist: google-auth-oauthlib>=1 ; extra == 'google'
|
|
14
|
+
Requires-Python: >=3.13
|
|
15
|
+
Provides-Extra: google
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# `schedz`
|
|
19
|
+
|
|
20
|
+
Read training sessions from a Google Calendar, read-only. Shared by
|
|
21
|
+
[invoicez](https://github.com/shuuchuu/invoicez), which bills them, and
|
|
22
|
+
[deckz](https://github.com/shuuchuu/deckz), which tells which deck is taught
|
|
23
|
+
next.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
pip install "schedz[google]"
|
|
28
|
+
|
|
29
|
+
Without the `google` extra, schedz still parses events read from a JSON file
|
|
30
|
+
(`read_events_file`), e.g. an anonymised test fixture.
|
|
31
|
+
|
|
32
|
+
## Setup
|
|
33
|
+
|
|
34
|
+
In Google Cloud, enable the Google Calendar API and create an OAuth client of
|
|
35
|
+
type *Desktop app*. Save its JSON as `client-secrets.json` in schedz's user
|
|
36
|
+
config directory (`~/.config/schedz/` on Linux). The first call opens a browser
|
|
37
|
+
for consent; the token is cached next to it (`token.json`), readable by you
|
|
38
|
+
only, and serves every tool using schedz.
|
|
39
|
+
|
|
40
|
+
## Settings
|
|
41
|
+
|
|
42
|
+
A tool reads its calendar settings into `CalendarSettings`, or a subclass
|
|
43
|
+
adding its own keys (invoicez's `gcal` section is one):
|
|
44
|
+
|
|
45
|
+
```yaml
|
|
46
|
+
calendar_id: someone@example.com
|
|
47
|
+
# Verbose regex: groups continuation, company, training, place, and optionally
|
|
48
|
+
# extra and tentative. Titles are matched whole.
|
|
49
|
+
title_pattern: |
|
|
50
|
+
\s*
|
|
51
|
+
(?P<tentative> \? \s+ )?
|
|
52
|
+
(?P<continuation> -> \s+ )?
|
|
53
|
+
(?P<company> .*? ) \s+ - \s+
|
|
54
|
+
(?P<training> .*? ) \s+ - \s+
|
|
55
|
+
(?P<place> .*? )
|
|
56
|
+
(?: \s+ - \s+ (?P<extra> .*? ) )?
|
|
57
|
+
\s*
|
|
58
|
+
# Optional: what a timed event counts as, in hours.
|
|
59
|
+
durations: {half_day_hours: [2.5, 4], day_hours: [6, 9]}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Calendar conventions
|
|
63
|
+
|
|
64
|
+
- A title such as `Orsys - BDA - CV - Intra Acme` is a session: company,
|
|
65
|
+
training, place and extra, kept in their case.
|
|
66
|
+
- `-> Orsys - BDA - CV - Intra Acme` continues the latest earlier session with
|
|
67
|
+
the same title (ignoring case): together they make one engagement.
|
|
68
|
+
- `? Orsys - BDA - CV` is an unconfirmed booking (`tentative`).
|
|
69
|
+
- All-day events count their days; timed events of 2.5 to 4 hours are
|
|
70
|
+
half-days, of 6 to 9 hours days; others are reported, not kept.
|
|
71
|
+
- The description may hold YAML: `ref` (the client's reference),
|
|
72
|
+
`preparation_days`, `trainees` (the number of people trained) and `invoice`
|
|
73
|
+
(a number billed by hand). HTML and free text are reported and ignored.
|
|
74
|
+
|
|
75
|
+
Problems are reported as `Diagnostic`s (`info`, `warning`, `error`), never
|
|
76
|
+
raised.
|
|
77
|
+
|
|
78
|
+
## Use
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from schedz.loading import fetch_calendar, read_engagements
|
|
82
|
+
from schedz.settings import CalendarSettings
|
|
83
|
+
|
|
84
|
+
settings = CalendarSettings.model_validate(mapping)
|
|
85
|
+
engagements, diagnostics = read_engagements(
|
|
86
|
+
fetch_calendar(settings.calendar_id), settings
|
|
87
|
+
)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`schedz.google` lists the calendars (`list_calendars`) and fetches events
|
|
91
|
+
(`fetch_events`); `schedz.parsing` and `schedz.grouping` turn them into
|
|
92
|
+
`Session`s and `Engagement`s.
|
|
93
|
+
|
|
94
|
+
## Development
|
|
95
|
+
|
|
96
|
+
- `uv sync`, then `uv run doit install_hooks`: every commit runs `doit check
|
|
97
|
+
test` (ruff, pyrefly, pytest) through prek. There is no CI.
|
|
98
|
+
- `tests/assets/events.json` is invoicez's anonymised fixture (its
|
|
99
|
+
`scripts/dump_gcal_fixture.py`).
|
|
100
|
+
|
|
101
|
+
## Releasing
|
|
102
|
+
|
|
103
|
+
1. `uv run bumpver update --minor` (or `--patch`): bumps, commits, tags and
|
|
104
|
+
pushes.
|
|
105
|
+
2. `uv run doit publish`: builds and uploads to PyPI with the token of
|
|
106
|
+
`creds.env`, a gitignored file at the repository's root holding one line,
|
|
107
|
+
`export UV_PUBLISH_TOKEN=pypi-...`, readable by you only (`chmod 400`).
|
schedz-0.1.0/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# `schedz`
|
|
2
|
+
|
|
3
|
+
Read training sessions from a Google Calendar, read-only. Shared by
|
|
4
|
+
[invoicez](https://github.com/shuuchuu/invoicez), which bills them, and
|
|
5
|
+
[deckz](https://github.com/shuuchuu/deckz), which tells which deck is taught
|
|
6
|
+
next.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
pip install "schedz[google]"
|
|
11
|
+
|
|
12
|
+
Without the `google` extra, schedz still parses events read from a JSON file
|
|
13
|
+
(`read_events_file`), e.g. an anonymised test fixture.
|
|
14
|
+
|
|
15
|
+
## Setup
|
|
16
|
+
|
|
17
|
+
In Google Cloud, enable the Google Calendar API and create an OAuth client of
|
|
18
|
+
type *Desktop app*. Save its JSON as `client-secrets.json` in schedz's user
|
|
19
|
+
config directory (`~/.config/schedz/` on Linux). The first call opens a browser
|
|
20
|
+
for consent; the token is cached next to it (`token.json`), readable by you
|
|
21
|
+
only, and serves every tool using schedz.
|
|
22
|
+
|
|
23
|
+
## Settings
|
|
24
|
+
|
|
25
|
+
A tool reads its calendar settings into `CalendarSettings`, or a subclass
|
|
26
|
+
adding its own keys (invoicez's `gcal` section is one):
|
|
27
|
+
|
|
28
|
+
```yaml
|
|
29
|
+
calendar_id: someone@example.com
|
|
30
|
+
# Verbose regex: groups continuation, company, training, place, and optionally
|
|
31
|
+
# extra and tentative. Titles are matched whole.
|
|
32
|
+
title_pattern: |
|
|
33
|
+
\s*
|
|
34
|
+
(?P<tentative> \? \s+ )?
|
|
35
|
+
(?P<continuation> -> \s+ )?
|
|
36
|
+
(?P<company> .*? ) \s+ - \s+
|
|
37
|
+
(?P<training> .*? ) \s+ - \s+
|
|
38
|
+
(?P<place> .*? )
|
|
39
|
+
(?: \s+ - \s+ (?P<extra> .*? ) )?
|
|
40
|
+
\s*
|
|
41
|
+
# Optional: what a timed event counts as, in hours.
|
|
42
|
+
durations: {half_day_hours: [2.5, 4], day_hours: [6, 9]}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Calendar conventions
|
|
46
|
+
|
|
47
|
+
- A title such as `Orsys - BDA - CV - Intra Acme` is a session: company,
|
|
48
|
+
training, place and extra, kept in their case.
|
|
49
|
+
- `-> Orsys - BDA - CV - Intra Acme` continues the latest earlier session with
|
|
50
|
+
the same title (ignoring case): together they make one engagement.
|
|
51
|
+
- `? Orsys - BDA - CV` is an unconfirmed booking (`tentative`).
|
|
52
|
+
- All-day events count their days; timed events of 2.5 to 4 hours are
|
|
53
|
+
half-days, of 6 to 9 hours days; others are reported, not kept.
|
|
54
|
+
- The description may hold YAML: `ref` (the client's reference),
|
|
55
|
+
`preparation_days`, `trainees` (the number of people trained) and `invoice`
|
|
56
|
+
(a number billed by hand). HTML and free text are reported and ignored.
|
|
57
|
+
|
|
58
|
+
Problems are reported as `Diagnostic`s (`info`, `warning`, `error`), never
|
|
59
|
+
raised.
|
|
60
|
+
|
|
61
|
+
## Use
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from schedz.loading import fetch_calendar, read_engagements
|
|
65
|
+
from schedz.settings import CalendarSettings
|
|
66
|
+
|
|
67
|
+
settings = CalendarSettings.model_validate(mapping)
|
|
68
|
+
engagements, diagnostics = read_engagements(
|
|
69
|
+
fetch_calendar(settings.calendar_id), settings
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`schedz.google` lists the calendars (`list_calendars`) and fetches events
|
|
74
|
+
(`fetch_events`); `schedz.parsing` and `schedz.grouping` turn them into
|
|
75
|
+
`Session`s and `Engagement`s.
|
|
76
|
+
|
|
77
|
+
## Development
|
|
78
|
+
|
|
79
|
+
- `uv sync`, then `uv run doit install_hooks`: every commit runs `doit check
|
|
80
|
+
test` (ruff, pyrefly, pytest) through prek. There is no CI.
|
|
81
|
+
- `tests/assets/events.json` is invoicez's anonymised fixture (its
|
|
82
|
+
`scripts/dump_gcal_fixture.py`).
|
|
83
|
+
|
|
84
|
+
## Releasing
|
|
85
|
+
|
|
86
|
+
1. `uv run bumpver update --minor` (or `--patch`): bumps, commits, tags and
|
|
87
|
+
pushes.
|
|
88
|
+
2. `uv run doit publish`: builds and uploads to PyPI with the token of
|
|
89
|
+
`creds.env`, a gitignored file at the repository's root holding one line,
|
|
90
|
+
`export UV_PUBLISH_TOKEN=pypi-...`, readable by you only (`chmod 400`).
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
dependencies = [
|
|
3
|
+
"platformdirs >= 4",
|
|
4
|
+
"pydantic >= 2.13",
|
|
5
|
+
"pyyaml >= 6",
|
|
6
|
+
]
|
|
7
|
+
description = "Read training sessions from a Google Calendar."
|
|
8
|
+
homepage = "https://github.com/shuuchuu/schedz"
|
|
9
|
+
license = "Apache-2.0"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
name = "schedz"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">= 3.13"
|
|
14
|
+
version = "0.1.0"
|
|
15
|
+
|
|
16
|
+
[[project.authors]]
|
|
17
|
+
name = "m09"
|
|
18
|
+
email = "142691+m09@users.noreply.github.com"
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
google = [
|
|
22
|
+
"google-api-python-client >= 2",
|
|
23
|
+
"google-auth-oauthlib >= 1",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
dev = [
|
|
28
|
+
"bumpver >= 2026.1132",
|
|
29
|
+
"doit >= 0.37",
|
|
30
|
+
"google-api-python-client >= 2",
|
|
31
|
+
"google-auth-oauthlib >= 1",
|
|
32
|
+
"prek >= 0.5.7",
|
|
33
|
+
"pyrefly >= 1.4",
|
|
34
|
+
"pytest >= 9",
|
|
35
|
+
"ruff >= 0.17",
|
|
36
|
+
"types-pyyaml >= 6",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[tool.ruff]
|
|
40
|
+
target-version = "py313"
|
|
41
|
+
|
|
42
|
+
[tool.ruff.lint]
|
|
43
|
+
ignore = [
|
|
44
|
+
"D1",
|
|
45
|
+
"incorrect-blank-line-before-class",
|
|
46
|
+
"multi-line-summary-second-line",
|
|
47
|
+
"non-empty-init-module",
|
|
48
|
+
]
|
|
49
|
+
preview = true
|
|
50
|
+
select = [
|
|
51
|
+
"A",
|
|
52
|
+
"B",
|
|
53
|
+
"C",
|
|
54
|
+
"D",
|
|
55
|
+
"DOC",
|
|
56
|
+
"E",
|
|
57
|
+
"EM",
|
|
58
|
+
"F",
|
|
59
|
+
"I",
|
|
60
|
+
"N",
|
|
61
|
+
"PIE",
|
|
62
|
+
"PTH",
|
|
63
|
+
"RET",
|
|
64
|
+
"RUF",
|
|
65
|
+
"SIM",
|
|
66
|
+
"SLF",
|
|
67
|
+
"TC",
|
|
68
|
+
"UP",
|
|
69
|
+
"W",
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
[tool.ruff.lint.pydocstyle]
|
|
73
|
+
convention = "google"
|
|
74
|
+
|
|
75
|
+
[tool.pyrefly]
|
|
76
|
+
search-path = ["."]
|
|
77
|
+
|
|
78
|
+
[bumpver]
|
|
79
|
+
commit = true
|
|
80
|
+
tag = true
|
|
81
|
+
push = true
|
|
82
|
+
commit_message = "Bump version to {new_version}"
|
|
83
|
+
current_version = "0.1.0"
|
|
84
|
+
pre_commit_hook = "scripts/bumpver_pre_commit.sh"
|
|
85
|
+
tag_message = "{new_version}"
|
|
86
|
+
version_pattern = "MAJOR.MINOR.PATCH"
|
|
87
|
+
|
|
88
|
+
[bumpver.file_patterns]
|
|
89
|
+
"pyproject.toml" = [
|
|
90
|
+
'^version = "{version}"$',
|
|
91
|
+
'^current_version = "{version}"$',
|
|
92
|
+
]
|
|
93
|
+
"src/schedz/__init__.py" = ['^__version__ = "{version}"$']
|
|
94
|
+
|
|
95
|
+
[build-system]
|
|
96
|
+
build-backend = "uv_build"
|
|
97
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
authors = [
|
|
3
|
+
{name = "m09", email = "142691+m09@users.noreply.github.com"},
|
|
4
|
+
]
|
|
5
|
+
dependencies = [
|
|
6
|
+
"platformdirs >= 4",
|
|
7
|
+
"pydantic >= 2.13",
|
|
8
|
+
"pyyaml >= 6",
|
|
9
|
+
]
|
|
10
|
+
description = "Read training sessions from a Google Calendar."
|
|
11
|
+
homepage = "https://github.com/shuuchuu/schedz"
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
name = "schedz"
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
requires-python = ">= 3.13"
|
|
17
|
+
version = "0.1.0"
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
google = [
|
|
21
|
+
"google-api-python-client >= 2",
|
|
22
|
+
"google-auth-oauthlib >= 1",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
dev = [
|
|
27
|
+
"bumpver >= 2026.1132",
|
|
28
|
+
"doit >= 0.37",
|
|
29
|
+
"google-api-python-client >= 2",
|
|
30
|
+
"google-auth-oauthlib >= 1",
|
|
31
|
+
"prek >= 0.5.7",
|
|
32
|
+
"pyrefly >= 1.4",
|
|
33
|
+
"pytest >= 9",
|
|
34
|
+
"ruff >= 0.17",
|
|
35
|
+
"types-pyyaml >= 6",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[tool.ruff]
|
|
39
|
+
target-version = "py313"
|
|
40
|
+
|
|
41
|
+
[tool.ruff.lint]
|
|
42
|
+
ignore = [
|
|
43
|
+
"D1",
|
|
44
|
+
"incorrect-blank-line-before-class",
|
|
45
|
+
"multi-line-summary-second-line",
|
|
46
|
+
"non-empty-init-module",
|
|
47
|
+
]
|
|
48
|
+
preview = true
|
|
49
|
+
select = ["A", "B", "C", "D", "DOC", "E", "EM", "F", "I", "N", "PIE", "PTH", "RET", "RUF", "SIM", "SLF", "TC", "UP", "W"]
|
|
50
|
+
|
|
51
|
+
[tool.ruff.lint.pydocstyle]
|
|
52
|
+
convention = "google"
|
|
53
|
+
|
|
54
|
+
# Without a config, pyrefly falls back to its lenient "basic" preset. With one,
|
|
55
|
+
# it stops treating the project root as an import root, so tests couldn't
|
|
56
|
+
# import tests.conftest without search-path.
|
|
57
|
+
[tool.pyrefly]
|
|
58
|
+
search-path = ["."]
|
|
59
|
+
|
|
60
|
+
[bumpver]
|
|
61
|
+
commit = true
|
|
62
|
+
tag = true
|
|
63
|
+
push = true
|
|
64
|
+
commit_message = "Bump version to {new_version}"
|
|
65
|
+
current_version = "0.1.0"
|
|
66
|
+
pre_commit_hook = "scripts/bumpver_pre_commit.sh"
|
|
67
|
+
tag_message = "{new_version}"
|
|
68
|
+
version_pattern = "MAJOR.MINOR.PATCH"
|
|
69
|
+
|
|
70
|
+
[bumpver.file_patterns]
|
|
71
|
+
"pyproject.toml" = [
|
|
72
|
+
'^version = "{version}"$',
|
|
73
|
+
'^current_version = "{version}"$',
|
|
74
|
+
]
|
|
75
|
+
"src/schedz/__init__.py" = [
|
|
76
|
+
'^__version__ = "{version}"$',
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
[build-system]
|
|
80
|
+
build-backend = "uv_build"
|
|
81
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
Level = Literal["info", "warning", "error"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Diagnostic(BaseModel, extra="forbid", frozen=True):
|
|
9
|
+
"""A problem found in calendar data, reported instead of raised.
|
|
10
|
+
|
|
11
|
+
Errors make what they concern unusable; warnings and infos do not.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
level: Level
|
|
15
|
+
# None when the problem is not about a single event.
|
|
16
|
+
event_id: str | None
|
|
17
|
+
message: str
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Read-only access to Google Calendar, the only module importing Google libraries.
|
|
2
|
+
|
|
3
|
+
Needs the google extra: pip install schedz[google].
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from google.auth.exceptions import RefreshError
|
|
11
|
+
from google.auth.transport.requests import Request
|
|
12
|
+
from google.oauth2.credentials import Credentials
|
|
13
|
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
|
14
|
+
from googleapiclient.discovery import build
|
|
15
|
+
from platformdirs import user_config_path
|
|
16
|
+
|
|
17
|
+
from schedz import app_name
|
|
18
|
+
from schedz.exceptions import SchedzError
|
|
19
|
+
|
|
20
|
+
CLIENT_SECRETS_FILENAME = "client-secrets.json"
|
|
21
|
+
TOKEN_FILENAME = "token.json"
|
|
22
|
+
|
|
23
|
+
SCOPES = [
|
|
24
|
+
"https://www.googleapis.com/auth/calendar.events.readonly",
|
|
25
|
+
"https://www.googleapis.com/auth/calendar.calendarlist.readonly",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def client_secrets_path() -> Path:
|
|
30
|
+
return user_config_path(app_name) / CLIENT_SECRETS_FILENAME
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def token_path() -> Path:
|
|
34
|
+
return user_config_path(app_name) / TOKEN_FILENAME
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _load_token() -> Credentials | None:
|
|
38
|
+
path = token_path()
|
|
39
|
+
if not path.is_file():
|
|
40
|
+
return None
|
|
41
|
+
try:
|
|
42
|
+
return Credentials.from_authorized_user_file(str(path), SCOPES)
|
|
43
|
+
except ValueError:
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _store_token(creds: Credentials) -> None:
|
|
48
|
+
path = token_path()
|
|
49
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
50
|
+
# Created 0600 rather than chmod-ed after the write, so the refresh token
|
|
51
|
+
# is never readable by others, even briefly.
|
|
52
|
+
path.touch(mode=0o600, exist_ok=True)
|
|
53
|
+
path.chmod(0o600)
|
|
54
|
+
path.write_text(creds.to_json(), encoding="utf8")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _login() -> Credentials:
|
|
58
|
+
secrets = client_secrets_path()
|
|
59
|
+
if not secrets.is_file():
|
|
60
|
+
msg = (
|
|
61
|
+
f"Google OAuth client secrets not found at {secrets}. Create an OAuth "
|
|
62
|
+
"client of type 'Desktop app' in Google Cloud and save its JSON there."
|
|
63
|
+
)
|
|
64
|
+
raise SchedzError(msg)
|
|
65
|
+
flow = InstalledAppFlow.from_client_secrets_file(str(secrets), SCOPES)
|
|
66
|
+
# Typed for any flow, but an installed app flow always gives user credentials.
|
|
67
|
+
return cast("Credentials", flow.run_local_server(port=0))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def credentials() -> Credentials:
|
|
71
|
+
"""Return valid Google credentials, refreshing or logging in as needed.
|
|
72
|
+
|
|
73
|
+
Logging in opens a browser for the OAuth consent screen.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
Credentials for the read-only calendar scopes, cached in the user
|
|
77
|
+
config directory.
|
|
78
|
+
"""
|
|
79
|
+
creds = _load_token()
|
|
80
|
+
if creds is not None and creds.valid:
|
|
81
|
+
return creds
|
|
82
|
+
if creds is not None and creds.expired and creds.refresh_token:
|
|
83
|
+
try:
|
|
84
|
+
creds.refresh(Request())
|
|
85
|
+
except RefreshError:
|
|
86
|
+
creds = _login()
|
|
87
|
+
else:
|
|
88
|
+
creds = _login()
|
|
89
|
+
_store_token(creds)
|
|
90
|
+
return creds
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def calendar_service(creds: Credentials) -> Any:
|
|
94
|
+
return build("calendar", "v3", credentials=creds, cache_discovery=False)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _all_pages(request_page: Any) -> list[dict[str, Any]]:
|
|
98
|
+
items: list[dict[str, Any]] = []
|
|
99
|
+
page_token = None
|
|
100
|
+
while True:
|
|
101
|
+
result = request_page(page_token).execute()
|
|
102
|
+
items.extend(result.get("items", []))
|
|
103
|
+
page_token = result.get("nextPageToken")
|
|
104
|
+
if page_token is None:
|
|
105
|
+
return items
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def list_calendars(service: Any) -> list[dict[str, Any]]:
|
|
109
|
+
"""List the calendars of the logged-in user.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
The raw calendar list entries (id, summary, primary, ...).
|
|
113
|
+
"""
|
|
114
|
+
return _all_pages(
|
|
115
|
+
lambda page_token: service.calendarList().list(pageToken=page_token)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def fetch_events(
|
|
120
|
+
service: Any, calendar_id: str, time_min: datetime | None = None
|
|
121
|
+
) -> list[dict[str, Any]]:
|
|
122
|
+
"""Fetch all events of a calendar, recurring ones expanded into instances.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
service: A calendar service, from calendar_service.
|
|
126
|
+
calendar_id: The calendar to read.
|
|
127
|
+
time_min: Only fetch events ending after this time. Must be aware.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
The raw API events, ordered by start time.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
ValueError: If time_min is a naive datetime.
|
|
134
|
+
"""
|
|
135
|
+
if time_min is not None and time_min.utcoffset() is None:
|
|
136
|
+
msg = "time_min must be timezone-aware"
|
|
137
|
+
raise ValueError(msg)
|
|
138
|
+
parameters: dict[str, Any] = {
|
|
139
|
+
"calendarId": calendar_id,
|
|
140
|
+
"singleEvents": True,
|
|
141
|
+
"orderBy": "startTime",
|
|
142
|
+
"showDeleted": False,
|
|
143
|
+
"maxResults": 2500,
|
|
144
|
+
}
|
|
145
|
+
if time_min is not None:
|
|
146
|
+
parameters["timeMin"] = time_min.isoformat()
|
|
147
|
+
return _all_pages(
|
|
148
|
+
lambda page_token: service.events().list(**parameters, pageToken=page_token)
|
|
149
|
+
)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Group training sessions into engagements: a session and its continuations."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from datetime import date, timedelta
|
|
6
|
+
from hashlib import sha256
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
from schedz.diagnostics import Diagnostic, Level
|
|
11
|
+
from schedz.parsing import Session, SessionDescription
|
|
12
|
+
|
|
13
|
+
# Longer gaps between two sessions of an engagement are likely a continuation
|
|
14
|
+
# meant for a later root event.
|
|
15
|
+
MAX_GAP = timedelta(days=31)
|
|
16
|
+
|
|
17
|
+
_Key = tuple[str, str, str, str | None]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Engagement(BaseModel, extra="forbid", frozen=True):
|
|
21
|
+
"""A root session and its continuations, in chronological order."""
|
|
22
|
+
|
|
23
|
+
sessions: tuple[Session, ...]
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def root(self) -> Session:
|
|
27
|
+
return self.sessions[0]
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def id(self) -> str:
|
|
31
|
+
return self.root.event_id
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def company(self) -> str:
|
|
35
|
+
return self.root.company
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def training(self) -> str:
|
|
39
|
+
return self.root.training
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def place(self) -> str:
|
|
43
|
+
return self.root.place
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def extra(self) -> str | None:
|
|
47
|
+
return self.root.extra
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def description(self) -> SessionDescription:
|
|
51
|
+
return self.root.description
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def tentative(self) -> bool:
|
|
55
|
+
# Unconfirmed as long as one of its sessions is.
|
|
56
|
+
return any(session.tentative for session in self.sessions)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def start(self) -> date:
|
|
60
|
+
return self.root.start
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def end(self) -> date:
|
|
64
|
+
return max(session.end for session in self.sessions)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def fingerprint(self) -> str:
|
|
68
|
+
"""Hash of what an engagement is made of, to detect calendar changes.
|
|
69
|
+
|
|
70
|
+
Case changes in titles do not change it.
|
|
71
|
+
"""
|
|
72
|
+
content = {
|
|
73
|
+
"company": self.company.casefold(),
|
|
74
|
+
"training": self.training.casefold(),
|
|
75
|
+
"preparation_days": self.description.preparation_days,
|
|
76
|
+
"sessions": sorted(
|
|
77
|
+
(s.event_id, str(s.start), str(s.end), s.kind, s.quantity)
|
|
78
|
+
for s in self.sessions
|
|
79
|
+
),
|
|
80
|
+
}
|
|
81
|
+
dumped = json.dumps(content, sort_keys=True, separators=(",", ":"))
|
|
82
|
+
return sha256(dumped.encode("utf8")).hexdigest()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _key(session: Session) -> _Key:
|
|
86
|
+
# origin/gcal lowercased titles, so continuations matched whatever the case.
|
|
87
|
+
return (
|
|
88
|
+
session.company.casefold(),
|
|
89
|
+
session.training.casefold(),
|
|
90
|
+
session.place.casefold(),
|
|
91
|
+
session.extra.casefold() if session.extra else None,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _diagnostic(level: Level, session: Session, message: str) -> Diagnostic:
|
|
96
|
+
return Diagnostic(
|
|
97
|
+
level=level, event_id=session.event_id, message=f"{session.title!r}: {message}"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def group_sessions(
|
|
102
|
+
sessions: Iterable[Session],
|
|
103
|
+
) -> tuple[list[Engagement], list[Diagnostic]]:
|
|
104
|
+
"""Attach each continuation to the latest earlier root with the same title.
|
|
105
|
+
|
|
106
|
+
Titles are compared on company, training, place and extra, ignoring case.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
The engagements, by start date, and the diagnostics: an error for each
|
|
110
|
+
continuation without a root (left out of every engagement), a warning
|
|
111
|
+
for each gap over MAX_GAP and for each continuation description that
|
|
112
|
+
would be ignored.
|
|
113
|
+
"""
|
|
114
|
+
groups: dict[_Key, list[Session]] = {}
|
|
115
|
+
closed: list[list[Session]] = []
|
|
116
|
+
diagnostics: list[Diagnostic] = []
|
|
117
|
+
for session in sorted(sessions, key=lambda s: s.start):
|
|
118
|
+
key = _key(session)
|
|
119
|
+
if not session.continuation:
|
|
120
|
+
if key in groups:
|
|
121
|
+
closed.append(groups[key])
|
|
122
|
+
groups[key] = [session]
|
|
123
|
+
continue
|
|
124
|
+
group = groups.get(key)
|
|
125
|
+
if group is None:
|
|
126
|
+
diagnostics.append(
|
|
127
|
+
_diagnostic("error", session, "continuation without a root event")
|
|
128
|
+
)
|
|
129
|
+
continue
|
|
130
|
+
previous_end = max(s.end for s in group)
|
|
131
|
+
if session.start - previous_end > MAX_GAP:
|
|
132
|
+
diagnostics.append(
|
|
133
|
+
_diagnostic(
|
|
134
|
+
"warning",
|
|
135
|
+
session,
|
|
136
|
+
f"starts {(session.start - previous_end).days} days after the "
|
|
137
|
+
f"previous session of its engagement ({previous_end})",
|
|
138
|
+
)
|
|
139
|
+
)
|
|
140
|
+
if session.description != SessionDescription():
|
|
141
|
+
diagnostics.append(
|
|
142
|
+
_diagnostic(
|
|
143
|
+
"warning",
|
|
144
|
+
session,
|
|
145
|
+
"description of a continuation, ignored: put it on the root event",
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
group.append(session)
|
|
149
|
+
closed.extend(groups.values())
|
|
150
|
+
engagements = [Engagement(sessions=tuple(group)) for group in closed]
|
|
151
|
+
return sorted(engagements, key=lambda e: e.start), diagnostics
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Get raw events, from a JSON file or Google Calendar, and read them as sessions."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterable, Mapping
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from types import ModuleType
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from schedz.diagnostics import Diagnostic
|
|
10
|
+
from schedz.exceptions import SchedzError
|
|
11
|
+
from schedz.grouping import Engagement, group_sessions
|
|
12
|
+
from schedz.parsing import parse_events
|
|
13
|
+
from schedz.settings import CalendarSettings
|
|
14
|
+
|
|
15
|
+
GOOGLE_EXTRA_HINT = "pip install schedz[google]"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def google_api(install_hint: str = GOOGLE_EXTRA_HINT) -> ModuleType:
|
|
19
|
+
"""Import the Google adapter, which needs the google extra.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
install_hint: The command that installs the extra, as the calling tool
|
|
23
|
+
names it (e.g. "pip install invoicez[gcal]").
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
The schedz.google module.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
SchedzError: If the extra is not installed.
|
|
30
|
+
"""
|
|
31
|
+
try:
|
|
32
|
+
from schedz import google
|
|
33
|
+
except ImportError as e:
|
|
34
|
+
msg = f"Google Calendar access needs the Google libraries: {install_hint}"
|
|
35
|
+
raise SchedzError(msg) from e
|
|
36
|
+
return google
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read_events_file(path: Path) -> list[dict[str, Any]]:
|
|
40
|
+
"""Read raw events from a JSON file, e.g. an anonymised test fixture.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
The raw events, as the API returns them.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
SchedzError: If the file does not hold a JSON list.
|
|
47
|
+
"""
|
|
48
|
+
events = json.loads(path.read_text(encoding="utf8"))
|
|
49
|
+
if not isinstance(events, list):
|
|
50
|
+
msg = f"{path} must hold a JSON list of events"
|
|
51
|
+
raise SchedzError(msg)
|
|
52
|
+
return events
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def fetch_calendar(
|
|
56
|
+
calendar_id: str, install_hint: str = GOOGLE_EXTRA_HINT
|
|
57
|
+
) -> list[dict[str, Any]]:
|
|
58
|
+
"""Fetch every event of a calendar, logging in if needed.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
The raw API events, ordered by start time.
|
|
62
|
+
"""
|
|
63
|
+
google = google_api(install_hint)
|
|
64
|
+
service = google.calendar_service(google.credentials())
|
|
65
|
+
return google.fetch_events(service, calendar_id)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def read_engagements(
|
|
69
|
+
raw_events: Iterable[Mapping[str, Any]], settings: CalendarSettings
|
|
70
|
+
) -> tuple[list[Engagement], list[Diagnostic]]:
|
|
71
|
+
"""Parse the events and group them into engagements.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
The engagements, by start date, and the diagnostics of both steps.
|
|
75
|
+
"""
|
|
76
|
+
sessions, parsing_diagnostics = parse_events(raw_events, settings)
|
|
77
|
+
engagements, grouping_diagnostics = group_sessions(sessions)
|
|
78
|
+
return engagements, [*parsing_diagnostics, *grouping_diagnostics]
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Turn raw Google Calendar events into training sessions."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections.abc import Iterable, Mapping
|
|
5
|
+
from datetime import date, datetime, timedelta
|
|
6
|
+
from typing import Annotated, Any, Literal, NamedTuple
|
|
7
|
+
|
|
8
|
+
from pydantic import (
|
|
9
|
+
BaseModel,
|
|
10
|
+
BeforeValidator,
|
|
11
|
+
Field,
|
|
12
|
+
NonNegativeFloat,
|
|
13
|
+
NonNegativeInt,
|
|
14
|
+
ValidationError,
|
|
15
|
+
)
|
|
16
|
+
from yaml import YAMLError, safe_load
|
|
17
|
+
|
|
18
|
+
from schedz.diagnostics import Diagnostic, Level
|
|
19
|
+
from schedz.settings import CalendarSettings, DurationRules, compile_title_pattern
|
|
20
|
+
|
|
21
|
+
_HTML_RE = re.compile(r"<[a-zA-Z/][^>]*>")
|
|
22
|
+
_SATURDAY = 5
|
|
23
|
+
|
|
24
|
+
Kind = Literal["day", "half_day"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _to_str(value: Any) -> Any:
|
|
28
|
+
# YAML reads "ref: 12345" as an int and "invoice: 2020-11-02" as a date.
|
|
29
|
+
return value if value is None else str(value)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_Str = Annotated[str | None, BeforeValidator(_to_str)]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SessionDescription(BaseModel, extra="ignore", frozen=True):
|
|
36
|
+
"""The YAML mapping an event description may hold."""
|
|
37
|
+
|
|
38
|
+
ref: _Str = None
|
|
39
|
+
preparation_days: NonNegativeFloat = 0
|
|
40
|
+
# Number of people trained, copied to the invoice for the activity report.
|
|
41
|
+
trainees: NonNegativeInt | None = None
|
|
42
|
+
# Invoice number written by hand before invoicez tracked documents (invoicez).
|
|
43
|
+
legacy_invoice: _Str = Field(default=None, alias="invoice")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_KNOWN_KEYS = frozenset(
|
|
47
|
+
field.alias or name for name, field in SessionDescription.model_fields.items()
|
|
48
|
+
)
|
|
49
|
+
# Payment tracking written by hand, read by no tool.
|
|
50
|
+
_UNTRACKED_KEYS = frozenset(("sent", "paid"))
|
|
51
|
+
_KEY_RE = re.compile(rf"\b({'|'.join(sorted(_KNOWN_KEYS))})\s*:")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Session(BaseModel, extra="forbid", frozen=True):
|
|
55
|
+
"""One calendar event of a training: a block of days or a single half-day."""
|
|
56
|
+
|
|
57
|
+
event_id: str
|
|
58
|
+
html_link: str
|
|
59
|
+
title: str
|
|
60
|
+
continuation: bool
|
|
61
|
+
# An unconfirmed booking (the title pattern's tentative group): never billed.
|
|
62
|
+
tentative: bool = False
|
|
63
|
+
# Values keep the case of the title; settings lookups ignore case.
|
|
64
|
+
company: str
|
|
65
|
+
training: str
|
|
66
|
+
place: str
|
|
67
|
+
extra: str | None
|
|
68
|
+
start: date
|
|
69
|
+
# Inclusive.
|
|
70
|
+
end: date
|
|
71
|
+
kind: Kind
|
|
72
|
+
# Number of days or half-days, according to kind.
|
|
73
|
+
quantity: int
|
|
74
|
+
description: SessionDescription
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _Problem(NamedTuple):
|
|
78
|
+
"""A diagnostic about an event, before its id and title are attached."""
|
|
79
|
+
|
|
80
|
+
level: Level
|
|
81
|
+
message: str
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _Span(NamedTuple):
|
|
85
|
+
start: date
|
|
86
|
+
end: date
|
|
87
|
+
kind: Kind
|
|
88
|
+
quantity: int
|
|
89
|
+
warnings: list[str]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _all_day_span(first: date, after: date) -> _Span | _Problem:
|
|
93
|
+
days = (after - first).days
|
|
94
|
+
if days < 1:
|
|
95
|
+
return _Problem("error", f"all-day event ends before it starts ({after})")
|
|
96
|
+
weekend = [
|
|
97
|
+
str(day)
|
|
98
|
+
for day in (first + timedelta(days=i) for i in range(days))
|
|
99
|
+
if day.weekday() >= _SATURDAY
|
|
100
|
+
]
|
|
101
|
+
warnings = (
|
|
102
|
+
[f"spans weekend days, billed as worked: {', '.join(weekend)}"]
|
|
103
|
+
if weekend
|
|
104
|
+
else []
|
|
105
|
+
)
|
|
106
|
+
return _Span(first, after - timedelta(days=1), "day", days, warnings)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _timed_span(
|
|
110
|
+
start: datetime, end: datetime, rules: DurationRules
|
|
111
|
+
) -> _Span | _Problem:
|
|
112
|
+
if start.date() != end.date():
|
|
113
|
+
return _Problem("warning", "timed event over several days, not billed")
|
|
114
|
+
hours = (end - start).total_seconds() / 3600
|
|
115
|
+
for kind, (low, high) in (
|
|
116
|
+
("half_day", rules.half_day_hours),
|
|
117
|
+
("day", rules.day_hours),
|
|
118
|
+
):
|
|
119
|
+
if low <= hours <= high:
|
|
120
|
+
return _Span(start.date(), start.date(), kind, 1, [])
|
|
121
|
+
return _Problem(
|
|
122
|
+
"warning",
|
|
123
|
+
f"lasts {hours:g} h, neither a half-day {rules.half_day_hours} nor a "
|
|
124
|
+
f"day {rules.day_hours}, not billed",
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _span(raw: Mapping[str, Any], rules: DurationRules) -> _Span | _Problem:
|
|
129
|
+
try:
|
|
130
|
+
start, end = raw["start"], raw["end"]
|
|
131
|
+
if "date" in start:
|
|
132
|
+
return _all_day_span(
|
|
133
|
+
date.fromisoformat(start["date"]), date.fromisoformat(end["date"])
|
|
134
|
+
)
|
|
135
|
+
return _timed_span(
|
|
136
|
+
datetime.fromisoformat(start["dateTime"]),
|
|
137
|
+
datetime.fromisoformat(end["dateTime"]),
|
|
138
|
+
rules,
|
|
139
|
+
)
|
|
140
|
+
except (KeyError, TypeError, ValueError) as e:
|
|
141
|
+
return _Problem("error", f"unreadable start or end ({e!r})")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _description(
|
|
145
|
+
raw: Mapping[str, Any],
|
|
146
|
+
) -> tuple[SessionDescription, list[_Problem]] | _Problem:
|
|
147
|
+
# The parsed description, with notes about what was ignored.
|
|
148
|
+
text = raw.get("description") or ""
|
|
149
|
+
if not text.strip():
|
|
150
|
+
return SessionDescription(), []
|
|
151
|
+
if _HTML_RE.search(text):
|
|
152
|
+
# Checked before YAML: "<p>ref: X</p>" is a YAML mapping too.
|
|
153
|
+
if keys := sorted(set(_KEY_RE.findall(text))):
|
|
154
|
+
return SessionDescription(), [
|
|
155
|
+
_Problem(
|
|
156
|
+
"warning",
|
|
157
|
+
f"description is HTML, ignored, but mentions {', '.join(keys)}: "
|
|
158
|
+
"rewrite it as plain YAML",
|
|
159
|
+
)
|
|
160
|
+
]
|
|
161
|
+
return SessionDescription(), [_Problem("info", "description is HTML, ignored")]
|
|
162
|
+
try:
|
|
163
|
+
data = safe_load(text)
|
|
164
|
+
except YAMLError:
|
|
165
|
+
data = None
|
|
166
|
+
if not isinstance(data, dict):
|
|
167
|
+
return SessionDescription(), [
|
|
168
|
+
_Problem("info", "description is free text, ignored")
|
|
169
|
+
]
|
|
170
|
+
try:
|
|
171
|
+
description = SessionDescription.model_validate(data)
|
|
172
|
+
except ValidationError as e:
|
|
173
|
+
errors = "; ".join(
|
|
174
|
+
f"{'.'.join(map(str, error['loc']))}: {error['msg']}"
|
|
175
|
+
for error in e.errors()
|
|
176
|
+
)
|
|
177
|
+
return _Problem("error", f"invalid description ({errors})")
|
|
178
|
+
unknown = sorted(map(str, data.keys() - _KNOWN_KEYS - _UNTRACKED_KEYS))
|
|
179
|
+
notes = (
|
|
180
|
+
[_Problem("warning", f"unknown description keys ignored: {', '.join(unknown)}")]
|
|
181
|
+
if unknown
|
|
182
|
+
else []
|
|
183
|
+
)
|
|
184
|
+
return description, notes
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _diagnostic(level: Level, raw: Mapping[str, Any], message: str) -> Diagnostic:
|
|
188
|
+
return Diagnostic(
|
|
189
|
+
level=level,
|
|
190
|
+
event_id=raw.get("id"),
|
|
191
|
+
message=f"{raw.get('summary', '')!r}: {message}",
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def parse_events(
|
|
196
|
+
raw_events: Iterable[Mapping[str, Any]], settings: CalendarSettings
|
|
197
|
+
) -> tuple[list[Session], list[Diagnostic]]:
|
|
198
|
+
"""Parse the events whose titles match the settings' title pattern.
|
|
199
|
+
|
|
200
|
+
Events with other titles and cancelled events are skipped silently. Events
|
|
201
|
+
that match but cannot be billed as they are yield a diagnostic instead of a
|
|
202
|
+
session.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
The sessions, in event order, and the diagnostics.
|
|
206
|
+
"""
|
|
207
|
+
pattern = compile_title_pattern(settings.title_pattern)
|
|
208
|
+
sessions: list[Session] = []
|
|
209
|
+
diagnostics: list[Diagnostic] = []
|
|
210
|
+
for raw in raw_events:
|
|
211
|
+
match = pattern.fullmatch(raw.get("summary") or "")
|
|
212
|
+
if match is None or raw.get("status") == "cancelled":
|
|
213
|
+
continue
|
|
214
|
+
span = _span(raw, settings.durations)
|
|
215
|
+
described = _description(raw)
|
|
216
|
+
problems = [p for p in (span, described) if isinstance(p, _Problem)]
|
|
217
|
+
diagnostics.extend(_diagnostic(p.level, raw, p.message) for p in problems)
|
|
218
|
+
if isinstance(span, _Problem) or isinstance(described, _Problem):
|
|
219
|
+
continue
|
|
220
|
+
description, notes = described
|
|
221
|
+
diagnostics.extend(_diagnostic("warning", raw, w) for w in span.warnings)
|
|
222
|
+
diagnostics.extend(_diagnostic(n.level, raw, n.message) for n in notes)
|
|
223
|
+
extra = match.groupdict().get("extra")
|
|
224
|
+
sessions.append(
|
|
225
|
+
Session(
|
|
226
|
+
event_id=raw["id"],
|
|
227
|
+
html_link=raw.get("htmlLink", ""),
|
|
228
|
+
title=raw["summary"],
|
|
229
|
+
continuation=match.group("continuation") is not None,
|
|
230
|
+
tentative=match.groupdict().get("tentative") is not None,
|
|
231
|
+
company=match.group("company").strip(),
|
|
232
|
+
training=match.group("training").strip(),
|
|
233
|
+
place=match.group("place").strip(),
|
|
234
|
+
extra=extra.strip() if extra else None,
|
|
235
|
+
start=span.start,
|
|
236
|
+
end=span.end,
|
|
237
|
+
kind=span.kind,
|
|
238
|
+
quantity=span.quantity,
|
|
239
|
+
description=description,
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
return sessions, diagnostics
|
|
File without changes
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Self
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, model_validator
|
|
5
|
+
|
|
6
|
+
TITLE_PATTERN_REQUIRED_GROUPS = frozenset(
|
|
7
|
+
("continuation", "company", "training", "place")
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def compile_title_pattern(title_pattern: str) -> re.Pattern[str]:
|
|
12
|
+
# Titles must be matched with fullmatch: the pattern may lack ^ and $.
|
|
13
|
+
return re.compile(title_pattern, re.VERBOSE)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DurationRules(BaseModel, extra="forbid", frozen=True):
|
|
17
|
+
# Inclusive bounds, in hours, for a timed event to count as such.
|
|
18
|
+
half_day_hours: tuple[float, float] = (2.5, 4.0)
|
|
19
|
+
day_hours: tuple[float, float] = (6.0, 9.0)
|
|
20
|
+
|
|
21
|
+
@model_validator(mode="after")
|
|
22
|
+
def _check_ranges(self) -> Self:
|
|
23
|
+
for name, (low, high) in (
|
|
24
|
+
("half_day_hours", self.half_day_hours),
|
|
25
|
+
("day_hours", self.day_hours),
|
|
26
|
+
):
|
|
27
|
+
if not 0 < low <= high:
|
|
28
|
+
msg = f"{name} must be (low, high) with 0 < low <= high"
|
|
29
|
+
raise ValueError(msg)
|
|
30
|
+
if self.half_day_hours[1] >= self.day_hours[0]:
|
|
31
|
+
msg = "half_day_hours must end before day_hours starts"
|
|
32
|
+
raise ValueError(msg)
|
|
33
|
+
return self
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CalendarSettings(BaseModel, extra="forbid", frozen=True):
|
|
37
|
+
"""Which calendar to read, and how its titles and durations read as sessions.
|
|
38
|
+
|
|
39
|
+
A tool adds its own settings by subclassing it, e.g. invoicez's billing ones.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
calendar_id: str | None = None
|
|
43
|
+
# Verbose regex with groups continuation, company, training, place and
|
|
44
|
+
# optionally extra and tentative (unconfirmed bookings, e.g. "? Orsys - …").
|
|
45
|
+
title_pattern: str
|
|
46
|
+
durations: DurationRules = DurationRules()
|
|
47
|
+
|
|
48
|
+
@model_validator(mode="after")
|
|
49
|
+
def _check_title_pattern(self) -> Self:
|
|
50
|
+
try:
|
|
51
|
+
pattern = compile_title_pattern(self.title_pattern)
|
|
52
|
+
except re.error as e:
|
|
53
|
+
msg = f"title_pattern does not compile: {e}"
|
|
54
|
+
raise ValueError(msg) from e
|
|
55
|
+
missing = TITLE_PATTERN_REQUIRED_GROUPS - pattern.groupindex.keys()
|
|
56
|
+
if missing:
|
|
57
|
+
msg = f"title_pattern lacks the groups {', '.join(sorted(missing))}"
|
|
58
|
+
raise ValueError(msg)
|
|
59
|
+
return self
|