pywebtop 0.0.1__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.
@@ -0,0 +1,532 @@
1
+ Metadata-Version: 2.4
2
+ Name: pywebtop
3
+ Version: 0.0.1
4
+ Summary: Unofficial async Python API wrapper for Webtop (SmartSchool)
5
+ Home-page: https://github.com/t0mer/pywebtop
6
+ Download-URL: https://pypi.org/project/pywebtop/
7
+ Author: Tomer Klein
8
+ Author-email: tomer.klein@gmail.com
9
+ License: MIT
10
+ Keywords: webtop,smartschool,education,api,async
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Education
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Operating System :: OS Independent
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: httpx<1.0,>=0.25
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: description
31
+ Dynamic: description-content-type
32
+ Dynamic: download-url
33
+ Dynamic: home-page
34
+ Dynamic: keywords
35
+ Dynamic: license
36
+ Dynamic: license-file
37
+ Dynamic: requires-dist
38
+ Dynamic: requires-python
39
+ Dynamic: summary
40
+
41
+ # pywebtop
42
+
43
+ An unofficial async Python API wrapper for **Webtop** (SmartSchool educational platform). This library provides easy access to Webtop's student portal API endpoints for retrieving grades, homework, schedules, messages, notifications, and more.
44
+
45
+ ## Features
46
+
47
+ - 🔐 **Async/Await Support** - Built on `httpx` for modern async Python
48
+ - 📚 **Student Portal Access** - Login and retrieve student information
49
+ - 📖 **Homework & Assignments** - Get homework details by class
50
+ - 📅 **Schedule/Timetable** - Retrieve pupil schedules for any week
51
+ - 💬 **Messaging System** - Access message inbox with filtering
52
+ - 🔔 **Notifications** - Get unread notifications and notification settings
53
+ - 📊 **Discipline Events** - Retrieve behavior/discipline records
54
+ - ⚙️ **Configurable** - Custom base URL, timeout, and auto-login support
55
+
56
+ ## Installation
57
+
58
+ Install via pip:
59
+
60
+ ```bash
61
+ pip install pywebtop
62
+ ```
63
+
64
+ Or from source:
65
+
66
+ ```bash
67
+ git clone https://github.com/t0mer/pywebtop.git
68
+ cd pywebtop
69
+ pip install -e .
70
+ ```
71
+
72
+ ### Requirements
73
+
74
+ - Python 3.8+
75
+ - `httpx>=0.25,<1.0`
76
+
77
+ ## Quick Start
78
+
79
+ ### Basic Usage
80
+
81
+ ```python
82
+ import asyncio
83
+ from webtop import WebtopClient
84
+
85
+ async def main():
86
+ # Create client and login
87
+ async with WebtopClient(username="your_username", password="your_password") as client:
88
+ # Login automatically happens on first API call
89
+ session = await client.login()
90
+ print(f"Logged in as: {session.first_name} {session.last_name}")
91
+
92
+ # Get students dashboard
93
+ dashboard = await client.get_students()
94
+ print(dashboard)
95
+
96
+ asyncio.run(main())
97
+ ```
98
+
99
+ ### Without Auto-Login
100
+
101
+ If you prefer to control login manually:
102
+
103
+ ```python
104
+ async with WebtopClient(
105
+ username="your_username",
106
+ password="your_password",
107
+ auto_login=False
108
+ ) as client:
109
+ # Manually call login
110
+ session = await client.login()
111
+
112
+ # Now make requests
113
+ dashboard = await client.get_students()
114
+ ```
115
+
116
+ ## API Reference
117
+
118
+ ### Client Initialization
119
+
120
+ ```python
121
+ WebtopClient(
122
+ username: str,
123
+ password: str,
124
+ *,
125
+ data: str = "+Aabe7FAdVluG6Lu+0ibrA==",
126
+ remember_me: bool = False,
127
+ biometric_login: str = "",
128
+ base_url: str = "https://webtopserver.smartschool.co.il",
129
+ timeout: float = 20.0,
130
+ auto_login: bool = True,
131
+ )
132
+ ```
133
+
134
+ **Parameters:**
135
+ - `username` - Webtop username
136
+ - `password` - Webtop password
137
+ - `data` - Encryption data (default value works for SmartSchool)
138
+ - `remember_me` - Whether to remember login (boolean)
139
+ - `biometric_login` - Biometric login token (if available)
140
+ - `base_url` - Webtop server URL (defaults to SmartSchool Israel)
141
+ - `timeout` - Request timeout in seconds
142
+ - `auto_login` - Automatically login before requests (default: True)
143
+
144
+ ### Methods
145
+
146
+ #### Authentication
147
+
148
+ ##### `login()`
149
+ Perform login and establish session.
150
+
151
+ ```python
152
+ session = await client.login()
153
+ # session.token - auth token
154
+ # session.user_id - user ID
155
+ # session.student_id - student ID
156
+ # session.school_name - school name
157
+ # session.first_name, session.last_name - user names
158
+ ```
159
+
160
+ #### Dashboard & Students
161
+
162
+ ##### `get_students()`
163
+ Get student dashboard data with list of students.
164
+
165
+ ```python
166
+ dashboard = await client.get_students()
167
+ ```
168
+
169
+ #### Homework & Assignments
170
+
171
+ ##### `get_homework()`
172
+ Get homework for a specific class.
173
+
174
+ ```python
175
+ homework = await client.get_homework(
176
+ encrypted_student_id="rgIuvaSjTq1Iizmx8TyS/kVbqExiqaKN+HMmES/FcEoTjO1W4c5lY96Ca0/fef3I+++qdhjhoN7aLAqTStKx9AX8C2pLhUJBAZzXH3rEC+w=",
177
+ class_code=3,
178
+ class_number=3,
179
+ )
180
+ ```
181
+
182
+ **Parameters:**
183
+ - `encrypted_student_id` - Student ID from login response
184
+ - `class_code` - Class code
185
+ - `class_number` - Class number
186
+
187
+ #### Schedule & Timetable
188
+
189
+ ##### `get_pupil_schedule()`
190
+ Get student schedule/timetable for a specific week.
191
+
192
+ ```python
193
+ schedule = await client.get_pupil_schedule(
194
+ week_index=0, # 0 = current week
195
+ view_type=0, # schedule view type
196
+ study_year=2026, # school year
197
+ encrypted_student_id="...",
198
+ class_code=3,
199
+ module_id=10,
200
+ )
201
+ ```
202
+
203
+ **Parameters:**
204
+ - `week_index` - Week offset (0 = current week, 1 = next week, etc.)
205
+ - `view_type` - Schedule view type (usually 0)
206
+ - `study_year` - School year (e.g., 2026)
207
+ - `encrypted_student_id` - Student ID from login response
208
+ - `class_code` - Class code
209
+ - `module_id` - Module ID (default: 10)
210
+
211
+ #### Messaging
212
+
213
+ ##### `get_messages_inbox()`
214
+ Get messages from inbox with pagination and filtering.
215
+
216
+ ```python
217
+ messages = await client.get_messages_inbox(
218
+ page_id=1,
219
+ label_id=0,
220
+ has_read=None, # None, True, or False to filter
221
+ search_query="",
222
+ )
223
+ ```
224
+
225
+ **Parameters:**
226
+ - `page_id` - Page number (1-based, default: 1)
227
+ - `label_id` - Message label/category (default: 0)
228
+ - `has_read` - Filter by read status (None for all, default: None)
229
+ - `search_query` - Free-text search (default: "")
230
+
231
+ #### Notifications
232
+
233
+ ##### `get_preview_unread_notifications()`
234
+ Get preview of unread notifications.
235
+
236
+ ```python
237
+ notifications = await client.get_preview_unread_notifications()
238
+ ```
239
+
240
+ ##### `get_notification_settings()`
241
+ Get notification settings for the user.
242
+
243
+ ```python
244
+ settings = await client.get_notification_settings(
245
+ encrypted_student_id="...",
246
+ )
247
+ ```
248
+
249
+ **Parameters:**
250
+ - `encrypted_student_id` - Student ID from login response
251
+
252
+ #### Discipline & Behavior
253
+
254
+ ##### `get_discipline_events()`
255
+ Get student behavior/discipline events.
256
+
257
+ ```python
258
+ discipline = await client.get_discipline_events(
259
+ encrypted_student_id="...",
260
+ class_code=3,
261
+ )
262
+ ```
263
+
264
+ **Parameters:**
265
+ - `encrypted_student_id` - Student ID from login response
266
+ - `class_code` - Class code
267
+
268
+ ### Session Properties
269
+
270
+ After login, access session information via `client.session`:
271
+
272
+ ```python
273
+ session = client.session
274
+ print(session.token) # Auth token
275
+ print(session.user_id) # User ID
276
+ print(session.student_id) # Student ID
277
+ print(session.school_id) # School ID
278
+ print(session.school_name) # School name
279
+ print(session.first_name) # First name
280
+ print(session.last_name) # Last name
281
+ print(session.raw_login_data) # Raw login response data
282
+ ```
283
+
284
+ ### Connection Management
285
+
286
+ #### Check Login Status
287
+
288
+ ```python
289
+ if client.is_logged_in:
290
+ print("Already logged in")
291
+ ```
292
+
293
+ #### Manual Close
294
+
295
+ ```python
296
+ await client.close() # or use 'async with' for auto-close
297
+ ```
298
+
299
+ ## Examples
300
+
301
+ ### Complete Example: Get Homework
302
+
303
+ ```python
304
+ import asyncio
305
+ from webtop import WebtopClient
306
+
307
+ async def get_homework_example():
308
+ async with WebtopClient(
309
+ username="",
310
+ password=""
311
+ ) as client:
312
+ # Get students to find IDs
313
+ dashboard = await client.get_students()
314
+ student = dashboard['data'][0] # Get first student
315
+ encrypted_id = student['id']
316
+
317
+ # Get homework
318
+ homework = await client.get_homework(
319
+ encrypted_student_id=encrypted_id,
320
+ class_code=3,
321
+ class_number=3,
322
+ )
323
+ print(homework)
324
+
325
+ asyncio.run(get_homework_example())
326
+ ```
327
+
328
+ ### Complete Example: Check Schedule
329
+
330
+ ```python
331
+ import asyncio
332
+ from webtop import WebtopClient
333
+ from datetime import datetime
334
+
335
+ async def check_schedule():
336
+ async with WebtopClient(
337
+ username="",
338
+ password=""
339
+ ) as client:
340
+ dashboard = await client.get_students()
341
+ student = dashboard['data'][0]
342
+
343
+ # Get this week's schedule
344
+ schedule = await client.get_pupil_schedule(
345
+ week_index=0,
346
+ study_year=2026,
347
+ encrypted_student_id=student['id'],
348
+ class_code=student['classCode'],
349
+ )
350
+
351
+ print(f"Schedule for week {datetime.now().isocalendar()[1]}:")
352
+ print(schedule)
353
+
354
+ asyncio.run(check_schedule())
355
+ ```
356
+
357
+ ### Complete Example: Get Messages
358
+
359
+ ```python
360
+ import asyncio
361
+ from webtop import WebtopClient
362
+
363
+ async def check_messages():
364
+ async with WebtopClient(
365
+ username="",
366
+ password=""
367
+ ) as client:
368
+ # Get unread messages
369
+ messages = await client.get_messages_inbox(
370
+ page_id=1,
371
+ has_read=False, # Only unread
372
+ )
373
+
374
+ print(f"Found {len(messages.get('data', []))} unread messages")
375
+ for msg in messages.get('data', []):
376
+ print(f" - {msg['sender']}: {msg['subject']}")
377
+
378
+ asyncio.run(check_messages())
379
+ ```
380
+
381
+ ## Error Handling
382
+
383
+ The library provides specific exceptions for error handling:
384
+
385
+ ```python
386
+ from webtop import WebtopClient, WebtopLoginError, WebtopRequestError
387
+
388
+ try:
389
+ async with WebtopClient(username="user", password="pass") as client:
390
+ dashboard = await client.get_students()
391
+ except WebtopLoginError as e:
392
+ print(f"Login failed: {e}")
393
+ except WebtopRequestError as e:
394
+ print(f"API request failed: {e}")
395
+ except Exception as e:
396
+ print(f"Unexpected error: {e}")
397
+ ```
398
+
399
+ **Exception Types:**
400
+ - `WebtopError` - Base exception class
401
+ - `WebtopLoginError` - Raised when login fails or not logged in
402
+ - `WebtopRequestError` - Raised when API request fails
403
+
404
+ ## Authentication Details
405
+
406
+ ### How Authentication Works
407
+
408
+ 1. **Login Request** - Send username/password to `/server/api/user/LoginByUserNameAndPassword`
409
+ 2. **Token Response** - Server returns `data.token` in the response
410
+ 3. **Cookie-Based Auth** - Token is set as cookie: `webToken=<token>`
411
+ 4. **Subsequent Requests** - All API calls automatically include the `webToken` cookie
412
+
413
+ ### Cookie Management
414
+
415
+ Authentication is handled automatically via httpx's cookie jar. The token is stored as a cookie and included in all subsequent requests.
416
+
417
+ ## Configuration
418
+
419
+ ### Custom Base URL
420
+
421
+ If you use a custom Webtop server:
422
+
423
+ ```python
424
+ async with WebtopClient(
425
+ username="user",
426
+ password="pass",
427
+ base_url="https://custom-webtop-server.example.com"
428
+ ) as client:
429
+ # Use custom server
430
+ dashboard = await client.get_students()
431
+ ```
432
+
433
+ ### Timeout Configuration
434
+
435
+ Adjust request timeout:
436
+
437
+ ```python
438
+ async with WebtopClient(
439
+ username="user",
440
+ password="pass",
441
+ timeout=30.0 # 30 seconds
442
+ ) as client:
443
+ dashboard = await client.get_students()
444
+ ```
445
+
446
+ ### Remember Me
447
+
448
+ Enable remember-me login:
449
+
450
+ ```python
451
+ async with WebtopClient(
452
+ username="user",
453
+ password="pass",
454
+ remember_me=True
455
+ ) as client:
456
+ await client.login()
457
+ ```
458
+
459
+ ## Project Structure
460
+
461
+ ```
462
+ pywebtop/
463
+ ├── webtop/
464
+ │ ├── __init__.py # Package exports
465
+ │ ├── client.py # Main WebtopClient class
466
+ │ ├── models.py # Data models (WebtopSession)
467
+ │ └── exceptions.py # Custom exceptions
468
+ ├── test.py # Test script
469
+ ├── setup.py # Package setup
470
+ └── README.md # This file
471
+ ```
472
+
473
+ ## Development
474
+
475
+ ### Setting Up Development Environment
476
+
477
+ ```bash
478
+ # Clone repository
479
+ git clone https://github.com/t0mer/pywebtop.git
480
+ cd pywebtop
481
+
482
+ # Install in development mode with dependencies
483
+ pip install -e ".[dev]"
484
+ ```
485
+
486
+ ### Running Tests
487
+
488
+ ```bash
489
+ python test.py
490
+ ```
491
+
492
+ ## License
493
+
494
+ MIT License - see [LICENSE](LICENSE) file for details
495
+
496
+ ## Author
497
+
498
+ **Tomer Klein** - [GitHub](https://github.com/t0mer) - tomer.klein@gmail.com
499
+
500
+ ## Disclaimer
501
+
502
+ This is an **unofficial** wrapper for the Webtop API. It is not affiliated with or endorsed by SmartSchool. Use at your own risk and ensure compliance with Webtop's Terms of Service.
503
+
504
+ ## Contributing
505
+
506
+ Contributions are welcome! Please feel free to submit a Pull Request.
507
+
508
+ ## Support
509
+
510
+ For issues, feature requests, or questions:
511
+ - Open an issue on [GitHub Issues](https://github.com/t0mer/pywebtop/issues)
512
+ - Contact the author
513
+
514
+ ## Changelog
515
+
516
+ ### Version 0.0.1
517
+ - Initial release
518
+ - Login functionality
519
+ - Dashboard access
520
+ - Homework retrieval
521
+ - Schedule/timetable access
522
+ - Messaging system
523
+ - Notifications
524
+ - Discipline events tracking
525
+
526
+ ## Related Projects
527
+
528
+ - [pymashov](https://github.com/t0mer/pymashov) - Another Mashov wrapper
529
+
530
+ ---
531
+
532
+ **Last Updated:** January 2026
@@ -0,0 +1,9 @@
1
+ pywebtop-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
2
+ webtop/__init__.py,sha256=7ZxOqQrUn_zGb2ssl6wHwEq5-bC0z7UPzQrODTbHzCs,265
3
+ webtop/client.py,sha256=sNa4EJCa8PHmJLyRal0dV5pEKC58RuyS9faJ325HEqQ,14897
4
+ webtop/exceptions.py,sha256=MXCrWO3oCPYvjOi3FRw0hHA5wrt_GECtu4LH1gHrVsU,248
5
+ webtop/models.py,sha256=eeLE6KIWtfirQv2kOpkwY3-XAijjxaLiSPc2MRxC_hU,557
6
+ pywebtop-0.0.1.dist-info/METADATA,sha256=YS0czfrTfgbBpj7QtcclUg5Ma7PNRRH1Btt0oJYri8s,13106
7
+ pywebtop-0.0.1.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92
8
+ pywebtop-0.0.1.dist-info/top_level.txt,sha256=_bDSmWeeECbJ-EVE_vSOQjwJIC-EJkFxNOBDpiBLP1c,7
9
+ pywebtop-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ webtop
webtop/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ from .client import WebtopClient
2
+ from .exceptions import WebtopError, WebtopLoginError, WebtopRequestError
3
+ from .models import WebtopSession
4
+
5
+ __all__ = [
6
+ "WebtopClient",
7
+ "WebtopSession",
8
+ "WebtopError",
9
+ "WebtopLoginError",
10
+ "WebtopRequestError",
11
+ ]
webtop/client.py ADDED
@@ -0,0 +1,442 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any, Dict, Optional
5
+
6
+ import httpx
7
+
8
+ from .exceptions import WebtopLoginError, WebtopRequestError
9
+ from .models import WebtopSession
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ DEFAULT_BASE_URL = "https://webtopserver.smartschool.co.il"
14
+
15
+
16
+ class WebtopClient:
17
+ """
18
+ Async client for Webtop (SmartSchool).
19
+
20
+ Auth model:
21
+ - Login returns JSON with data.token
22
+ - Token must be sent as cookie: webToken=<token>
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ username: str,
28
+ password: str,
29
+ *,
30
+ data: str = "+Aabe7FAdVluG6Lu+0ibrA==",
31
+ remember_me: bool = False,
32
+ biometric_login: str = "",
33
+ base_url: str = DEFAULT_BASE_URL,
34
+ timeout: float = 20.0,
35
+ auto_login: bool = True,
36
+ ):
37
+ logger.info(f"Initializing WebtopClient for user: {username}, base_url: {base_url}")
38
+ self._username = username
39
+ self._password = password
40
+ self._data = data
41
+ self._remember_me = remember_me
42
+ self._biometric_login = biometric_login
43
+
44
+ self._base_url = base_url.rstrip("/")
45
+ self._auto_login = auto_login
46
+
47
+ try:
48
+ self._http = httpx.AsyncClient(
49
+ base_url=self._base_url,
50
+ timeout=timeout,
51
+ headers={"Content-Type": "application/json; charset=utf-8"},
52
+ follow_redirects=True,
53
+ )
54
+ logger.debug(f"HTTP client created with timeout={timeout}s")
55
+ except Exception as e:
56
+ logger.error(f"Failed to create HTTP client: {e}")
57
+ raise
58
+
59
+ self._session: Optional[WebtopSession] = None
60
+
61
+ async def __aenter__(self) -> "WebtopClient":
62
+ return self
63
+
64
+ async def __aexit__(self, exc_type, exc, tb) -> None:
65
+ await self.close()
66
+
67
+ async def close(self) -> None:
68
+ """Close the HTTP client connection."""
69
+ try:
70
+ logger.debug("Closing HTTP client connection")
71
+ await self._http.aclose()
72
+ logger.info("HTTP client connection closed successfully")
73
+ except Exception as e:
74
+ logger.error(f"Error closing HTTP client: {e}")
75
+ raise
76
+
77
+ @property
78
+ def is_logged_in(self) -> bool:
79
+ return self._session is not None
80
+
81
+ @property
82
+ def session(self) -> WebtopSession:
83
+ if not self._session:
84
+ raise WebtopLoginError("Not logged in. Call await client.login() first.")
85
+ return self._session
86
+
87
+ async def login(self) -> WebtopSession:
88
+ """
89
+ Perform ONLY the login call.
90
+ """
91
+ logger.info(f"Attempting to login as user: {self._username}")
92
+
93
+ try:
94
+ resp = await self._http.post(
95
+ "/server/api/user/LoginByUserNameAndPassword",
96
+ json={
97
+ "UserName": self._username,
98
+ "Password": self._password,
99
+ "Data": self._data,
100
+ "RememberMe": self._remember_me,
101
+ "BiometricLogin": self._biometric_login,
102
+ },
103
+ )
104
+ logger.debug(f"Login request completed with status code: {resp.status_code}")
105
+ except httpx.TimeoutException as e:
106
+ logger.error(f"Login request timed out: {e}")
107
+ raise WebtopLoginError(f"Login request timed out: {e}") from e
108
+ except httpx.RequestError as e:
109
+ logger.error(f"Login request failed: {e}")
110
+ raise WebtopLoginError(f"Login request failed: {e}") from e
111
+
112
+ if resp.status_code >= 400:
113
+ logger.error(f"Login failed with status {resp.status_code}: {resp.text}")
114
+ raise WebtopLoginError(f"Login failed ({resp.status_code}): {resp.text}")
115
+
116
+ try:
117
+ body = resp.json()
118
+ except Exception as e:
119
+ logger.error(f"Failed to parse login response as JSON: {e}")
120
+ raise WebtopLoginError(f"Login response is not JSON: {e}") from e
121
+
122
+ if body.get("status") is not True:
123
+ error_desc = body.get('errorDescription')
124
+ error_id = body.get('errorId')
125
+ logger.error(f"Login status is false. errorDescription={error_desc}, errorId={error_id}")
126
+ raise WebtopLoginError(
127
+ f"Login returned status=false. "
128
+ f"errorDescription={error_desc!r}, errorId={error_id!r}"
129
+ )
130
+
131
+ data = body.get("data") or {}
132
+ token = data.get("token")
133
+ if not token:
134
+ logger.error("Login response missing token in data")
135
+ raise WebtopLoginError("Login succeeded but data.token is missing")
136
+
137
+ # ✅ Webtop requires token as cookie: webToken=<token>
138
+ self._http.cookies.set("webToken", token)
139
+ logger.debug("Authentication token set as cookie")
140
+
141
+ self._session = WebtopSession(
142
+ token=token,
143
+ user_id=data.get("userId"),
144
+ student_id=data.get("studentId"),
145
+ school_id=data.get("schoolId"),
146
+ school_name=data.get("schoolName"),
147
+ first_name=data.get("firstName"),
148
+ last_name=data.get("lastName"),
149
+ raw_login_data=data,
150
+ )
151
+ logger.info(f"Login successful for user: {self._session.first_name} {self._session.last_name} (school: {self._session.school_name})")
152
+ return self._session
153
+
154
+ async def ensure_logged_in(self) -> None:
155
+ """Ensure user is logged in, auto-login if enabled."""
156
+ if self._session:
157
+ logger.debug("Already logged in, session exists")
158
+ return
159
+ if not self._auto_login:
160
+ logger.warning("Not logged in and auto_login is disabled")
161
+ raise WebtopLoginError("Not logged in and auto_login=False. Call await client.login().")
162
+ logger.info("Auto-login triggered")
163
+ await self.login()
164
+
165
+ async def request(
166
+ self,
167
+ method: str,
168
+ path: str,
169
+ *,
170
+ headers: Optional[Dict[str, str]] = None,
171
+ **kwargs,
172
+ ) -> httpx.Response:
173
+ """
174
+ Authenticated request helper.
175
+ Since auth is cookie-based (webToken), we only ensure login here.
176
+ """
177
+ logger.debug(f"Making {method} request to {path}")
178
+
179
+ try:
180
+ await self.ensure_logged_in()
181
+ except WebtopLoginError as e:
182
+ logger.error(f"Failed to ensure login before request: {e}")
183
+ raise
184
+
185
+ final_headers: Dict[str, str] = {}
186
+ if headers:
187
+ final_headers.update(headers)
188
+
189
+ try:
190
+ resp = await self._http.request(method, path, headers=final_headers, **kwargs)
191
+ logger.debug(f"{method} {path} completed with status {resp.status_code}")
192
+ except httpx.TimeoutException as e:
193
+ logger.error(f"{method} {path} timed out: {e}")
194
+ raise WebtopRequestError(f"{method} {path} timed out: {e}") from e
195
+ except httpx.RequestError as e:
196
+ logger.error(f"{method} {path} request error: {e}")
197
+ raise WebtopRequestError(f"{method} {path} request error: {e}") from e
198
+
199
+ if resp.status_code >= 400:
200
+ logger.error(f"{method} {path} failed with status {resp.status_code}: {resp.text}")
201
+ raise WebtopRequestError(f"{method} {path} failed ({resp.status_code}): {resp.text}")
202
+
203
+ return resp
204
+
205
+ # -----------------------------
206
+ # Endpoints
207
+ # -----------------------------
208
+ async def get_students(self) -> Any:
209
+ """
210
+ POST /server/api/dashboard/InitDashboard
211
+ Body: {}
212
+ Auth: cookie webToken
213
+ """
214
+ logger.info("Fetching students dashboard")
215
+ try:
216
+ resp = await self.request(
217
+ "POST",
218
+ "/server/api/dashboard/InitDashboard",
219
+ json={},
220
+ )
221
+ data = resp.json()
222
+ logger.info("Students dashboard fetched successfully")
223
+ return data
224
+ except Exception as e:
225
+ logger.error(f"Failed to get students: {e}")
226
+ raise
227
+
228
+ async def get_homework(
229
+ self,
230
+ *,
231
+ encrypted_student_id: str,
232
+ class_code: int,
233
+ class_number: int,
234
+ ) -> Any:
235
+ """
236
+ Get homework from Webtop.
237
+
238
+ POST /server/api/dashboard/GetHomeWork
239
+
240
+ Auth:
241
+ - Cookie: webToken=<token>
242
+
243
+ Params:
244
+ encrypted_student_id: value from login data['id']
245
+ class_code: ClassCode
246
+ class_number: ClassNumber
247
+ """
248
+ logger.info(f"Fetching homework for class {class_code}-{class_number}")
249
+ try:
250
+ resp = await self.request(
251
+ "POST",
252
+ "/server/api/dashboard/GetHomeWork",
253
+ json={
254
+ "id": encrypted_student_id,
255
+ "ClassCode": class_code,
256
+ "ClassNumber": class_number,
257
+ },
258
+ )
259
+ data = resp.json()
260
+ logger.info(f"Homework fetched successfully for class {class_code}-{class_number}")
261
+ return data
262
+ except Exception as e:
263
+ logger.error(f"Failed to get homework for class {class_code}-{class_number}: {e}")
264
+ raise
265
+
266
+ async def get_discipline_events(
267
+ self,
268
+ *,
269
+ encrypted_student_id: str,
270
+ class_code: int,
271
+ ) -> Any:
272
+ """
273
+ Get pupil discipline (behavior) events.
274
+
275
+ POST /server/api/dashboard/GetPupilDiciplineEvents
276
+
277
+ Auth:
278
+ - Cookie: webToken=<token>
279
+
280
+ Params:
281
+ encrypted_student_id: value from login data['id']
282
+ class_code: ClassCode
283
+ """
284
+ logger.info(f"Fetching discipline events for class {class_code}")
285
+ try:
286
+ resp = await self.request(
287
+ "POST",
288
+ "/server/api/dashboard/GetPupilDiciplineEvents",
289
+ json={
290
+ "id": encrypted_student_id,
291
+ "ClassCode": class_code,
292
+ },
293
+ )
294
+ data = resp.json()
295
+ logger.info(f"Discipline events fetched successfully for class {class_code}")
296
+ return data
297
+ except Exception as e:
298
+ logger.error(f"Failed to get discipline events for class {class_code}: {e}")
299
+ raise
300
+
301
+ async def get_preview_unread_notifications(self) -> Any:
302
+ """
303
+ Get preview of unread notifications.
304
+
305
+ POST /server/api/Menu/GetPreviewUnreadNotifications
306
+
307
+ Auth:
308
+ - Cookie: webToken=<token>
309
+ """
310
+ logger.info("Fetching preview of unread notifications")
311
+ try:
312
+ resp = await self.request(
313
+ "POST",
314
+ "/server/api/Menu/GetPreviewUnreadNotifications",
315
+ json={}, # empty body
316
+ )
317
+ data = resp.json()
318
+ logger.info("Unread notifications preview fetched successfully")
319
+ return data
320
+ except Exception as e:
321
+ logger.error(f"Failed to get unread notifications preview: {e}")
322
+ raise
323
+
324
+ async def get_notification_settings(
325
+ self,
326
+ *,
327
+ encrypted_student_id: str,
328
+ ) -> Any:
329
+ """
330
+ Get notification settings for the user.
331
+
332
+ POST /server/api/Notification/GetNotificationsSettings
333
+
334
+ Auth:
335
+ - Cookie: webToken=<token>
336
+
337
+ Params:
338
+ encrypted_student_id: value from login data['id']
339
+ """
340
+ logger.info("Fetching notification settings")
341
+ try:
342
+ resp = await self.request(
343
+ "POST",
344
+ "/server/api/Notification/GetNotificationsSettings",
345
+ json={
346
+ "id": encrypted_student_id,
347
+ },
348
+ )
349
+ data = resp.json()
350
+ logger.info("Notification settings fetched successfully")
351
+ return data
352
+ except Exception as e:
353
+ logger.error(f"Failed to get notification settings: {e}")
354
+ raise
355
+
356
+ async def get_messages_inbox(
357
+ self,
358
+ *,
359
+ page_id: int = 1,
360
+ label_id: int = 0,
361
+ has_read: Optional[bool] = None,
362
+ search_query: str = "",
363
+ ) -> Any:
364
+ """
365
+ Get messages inbox.
366
+
367
+ POST /server/api/messageBox/GetMessagesInbox
368
+
369
+ Auth:
370
+ - Cookie: webToken=<token>
371
+
372
+ Params:
373
+ page_id: page number (1-based)
374
+ label_id: message label/category
375
+ has_read: filter by read status (True / False / None)
376
+ search_query: free-text search
377
+ """
378
+ logger.info(f"Fetching messages inbox (page={page_id}, label={label_id}, has_read={has_read}, query='{search_query}')")
379
+ try:
380
+ resp = await self.request(
381
+ "POST",
382
+ "/server/api/messageBox/GetMessagesInbox",
383
+ json={
384
+ "PageId": page_id,
385
+ "LabelId": label_id,
386
+ "HasRead": has_read,
387
+ "SearchQuery": search_query,
388
+ },
389
+ )
390
+ data = resp.json()
391
+ logger.info(f"Messages inbox fetched successfully (page={page_id})")
392
+ return data
393
+ except Exception as e:
394
+ logger.error(f"Failed to get messages inbox (page={page_id}): {e}")
395
+ raise
396
+
397
+ async def get_pupil_schedule(
398
+ self,
399
+ *,
400
+ week_index: int = 0,
401
+ view_type: int = 0,
402
+ study_year: int,
403
+ encrypted_student_id: str,
404
+ class_code: int,
405
+ module_id: int = 10,
406
+ ) -> Any:
407
+ """
408
+ Get pupil schedule (timetable).
409
+
410
+ POST /server/api/PupilCard/GetPupilScheduale
411
+
412
+ Auth:
413
+ - Cookie: webToken=<token>
414
+
415
+ Params:
416
+ week_index: week offset (0 = current week)
417
+ view_type: schedule view type (usually 0)
418
+ study_year: school year (e.g. 2026)
419
+ encrypted_student_id: value from login data['id']
420
+ class_code: ClassCode
421
+ module_id: module identifier (usually 10)
422
+ """
423
+ logger.info(f"Fetching pupil schedule (year={study_year}, week={week_index}, class={class_code})")
424
+ try:
425
+ resp = await self.request(
426
+ "POST",
427
+ "/server/api/PupilCard/GetPupilScheduale",
428
+ json={
429
+ "weekIndex": week_index,
430
+ "viewType": view_type,
431
+ "studyYear": study_year,
432
+ "studentID": encrypted_student_id,
433
+ "classCode": class_code,
434
+ "moduleID": module_id,
435
+ },
436
+ )
437
+ data = resp.json()
438
+ logger.info(f"Pupil schedule fetched successfully (year={study_year}, week={week_index})")
439
+ return data
440
+ except Exception as e:
441
+ logger.error(f"Failed to get pupil schedule (year={study_year}, week={week_index}): {e}")
442
+ raise
webtop/exceptions.py ADDED
@@ -0,0 +1,10 @@
1
+ class WebtopError(Exception):
2
+ """Base exception for pywebtop."""
3
+
4
+
5
+ class WebtopLoginError(WebtopError):
6
+ """Raised when login fails or token is missing."""
7
+
8
+
9
+ class WebtopRequestError(WebtopError):
10
+ """Raised when an API request fails."""
webtop/models.py ADDED
@@ -0,0 +1,21 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Dict, Optional
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class WebtopSession:
7
+ """
8
+ Auth session returned from login.
9
+
10
+ token:
11
+ - value from login response data.token
12
+ - used as cookie: webToken=<token>
13
+ """
14
+ token: str
15
+ user_id: Optional[str] = None
16
+ student_id: Optional[int] = None
17
+ school_id: Optional[int] = None
18
+ school_name: Optional[str] = None
19
+ first_name: Optional[str] = None
20
+ last_name: Optional[str] = None
21
+ raw_login_data: Optional[Dict[str, Any]] = None