From d3e3aa67752e75b33df436712da62ed4041143ae Mon Sep 17 00:00:00 2001 From: EpicGamerCodes <62027082+EpicGamerCodes@users.noreply.github.com> Date: Wed, 9 Aug 2023 15:40:20 +0100 Subject: [PATCH] Initial Code --- .gitignore | 1 + CHANGELOG.md | 4 +- CONTRIBUTING.md | 112 +--- LICENSE.txt | 695 ++++++++++++++++++++++- README.md | 93 ++- examples/calendar/demo.py | 36 ++ examples/complete_quiz/demo.py | 33 ++ examples/complete_task/demo.py | 22 + examples/debug/demo.py | 18 + examples/get_all_employees/demo.py | 33 ++ examples/get_behaviour/demo.py | 25 + examples/get_quiz_grade/demo.py | 26 + examples/get_todo/demo.py | 37 ++ examples/login/demo.py | 28 + examples/timetable/demo.py | 28 + setup.cfg | 23 +- src/smhw_api/__init__.py | 26 + src/smhw_api/api.py | 881 +++++++++++++++++++++++++++++ src/smhw_api/exceptions.py | 34 ++ src/smhw_api/objects.py | 774 +++++++++++++++++++++++++ src/smhw_api/requirements.txt | 17 + src/smhw_api/skeleton.py | 149 ----- tests/test_skeleton.py | 22 +- 23 files changed, 2789 insertions(+), 328 deletions(-) create mode 100644 examples/calendar/demo.py create mode 100644 examples/complete_quiz/demo.py create mode 100644 examples/complete_task/demo.py create mode 100644 examples/debug/demo.py create mode 100644 examples/get_all_employees/demo.py create mode 100644 examples/get_behaviour/demo.py create mode 100644 examples/get_quiz_grade/demo.py create mode 100644 examples/get_todo/demo.py create mode 100644 examples/login/demo.py create mode 100644 examples/timetable/demo.py create mode 100644 src/smhw_api/api.py create mode 100644 src/smhw_api/exceptions.py create mode 100644 src/smhw_api/objects.py create mode 100644 src/smhw_api/requirements.txt delete mode 100644 src/smhw_api/skeleton.py diff --git a/.gitignore b/.gitignore index e9e1e9b..3e62c97 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,4 @@ MANIFEST .venv*/ .conda*/ .python-version +env \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 205cc5e..1278524 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,4 @@ ## Version 0.1 (development) -- Feature A added -- FIX: nasty bug #1729 fixed -- add your changes here! +- Initial Code diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7c59731..5db5c7e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,30 +1,3 @@ -```{todo} THIS IS SUPPOSED TO BE AN EXAMPLE. MODIFY IT ACCORDING TO YOUR NEEDS! - - The document assumes you are using a source repository service that promotes a - contribution model similar to [GitHub's fork and pull request workflow]. - While this is true for the majority of services (like GitHub, GitLab, - BitBucket), it might not be the case for private repositories (e.g., when - using Gerrit). - - Also notice that the code examples might refer to GitHub URLs or the text - might use GitHub specific terminology (e.g., *Pull Request* instead of *Merge - Request*). - - Please make sure to check the document having these assumptions in mind - and update things accordingly. -``` - -```{todo} Provide the correct links/replacements at the bottom of the document. -``` - -```{todo} You might want to have a look on [PyScaffold's contributor's guide], - - especially if your project is open source. The text should be very similar to - this template, but there are a few extra contents that you might decide to - also include, like mentioning labels of your issue tracker or automated - releases. -``` - # Contributing Welcome to `smhw-api` contributor's guide. @@ -47,11 +20,9 @@ If you experience bugs or general issues with `smhw-api`, please have a look on the [issue tracker]. If you don't see anything useful there, please feel free to fire an issue report. -:::{tip} Please don't forget to include the closed issues in your search. Sometimes a solution was already reported, and the problem is considered **solved**. -::: New issue reports should include information about your programming environment (e.g., operating system, Python version) and steps to reproduce the problem. @@ -68,29 +39,6 @@ by adding missing information and correcting mistakes. This means that the docs are kept in the same repository as the project code, and that any documentation update is done in the same way was a code contribution. -```{todo} Don't forget to mention which markup language you are using. - - e.g., [reStructuredText] or [CommonMark] with [MyST] extensions. -``` - -```{todo} If your project is hosted on GitHub, you can also mention the following tip: - - :::{tip} - Please notice that the [GitHub web interface] provides a quick way of - propose changes in `smhw-api`'s files. While this mechanism can - be tricky for normal code contributions, it works perfectly fine for - contributing to the docs, and can be quite handy. - - If you are interested in trying this method out, please navigate to - the `docs` folder in the source [repository], find which file you - would like to propose changes and click in the little pencil icon at the - top, to open [GitHub's code editor]. Once you finish editing the file, - please write a message in the form at the bottom of the page describing - which changes have you made and what are the motivations behind them and - submit your proposal. - ::: -``` - When working on documentation changes in your local machine, you can compile them using [tox] : @@ -107,12 +55,7 @@ python3 -m http.server --directory 'docs/_build/html' ## Code Contributions -```{todo} Please include a reference or explanation about the internals of the project. - - An architecture description, design principles or at least a summary of the - main concepts will make it easy for potential contributors to get started - quickly. -``` +The code is all formatted using black so using the same formatting would be very helpful. ### Submit an issue @@ -160,19 +103,6 @@ conda activate smhw-api to be able to import the package under development in the Python REPL. - ```{todo} if you are not using pre-commit, please remove the following item: - ``` - -5. Install [pre-commit]: - - ``` - pip install pre-commit - pre-commit install - ``` - - `smhw-api` comes with a lot of hooks configured to automatically help the - developer to check the code being written. - ### Implement your changes 1. Create a branch to hold your changes: @@ -197,15 +127,7 @@ conda activate smhw-api to record your changes in [git]. - ```{todo} if you are not using pre-commit, please remove the following item: - ``` - - Please make sure to see the validation messages from [pre-commit] and fix - any eventual issues. - This should automatically use [flake8]/[black] to check/fix the code style - in a way that is compatible with the project. - - :::{important} + Don't forget to add unit tests and documentation in case your contribution adds an additional feature and is not just a bugfix. @@ -241,14 +163,10 @@ conda activate smhw-api 2. Go to the web page of your fork and click "Create pull request" to send your changes for review. - ```{todo} if you are using GitHub, you can uncomment the following paragraph - - Find more detailed information in [creating a PR]. You might also want to open + Find more detailed information in [creating a PR]. You might also want to open the PR as a draft first and mark it as ready for review after the feedbacks from the continuous integration (CI) system or any required fixes. - ``` - ### Troubleshooting The following tips can be used when facing problems to build or test the @@ -306,12 +224,6 @@ package: ### Releases -```{todo} This section assumes you are using PyPI to publicly release your package. - - If instead you are using a different/private package index, please update - the instructions accordingly. -``` - If you are part of the group of maintainers and have correct user permissions on [PyPI], the following steps can be used to release a new version for `smhw-api`: @@ -335,37 +247,23 @@ on [PyPI], the following steps can be used to release a new version for to collectively create software are general and can be applied to all sorts of environments, including private companies and proprietary code bases. - [black]: https://pypi.org/project/black/ -[commonmark]: https://commonmark.org/ [contribution-guide.org]: http://www.contribution-guide.org/ -[creating a pr]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request [descriptive commit message]: https://chris.beams.io/posts/git-commit [docstrings]: https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html -[first-contributions tutorial]: https://github.com/firstcontributions/first-contributions [flake8]: https://flake8.pycqa.org/en/stable/ [git]: https://git-scm.com -[github web interface]: https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-on-github/editing-files-in-your-repository -[github's code editor]: https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-on-github/editing-files-in-your-repository -[github's fork and pull request workflow]: https://guides.github.com/activities/forking/ [guide created by freecodecamp]: https://github.com/freecodecamp/how-to-contribute-to-open-source [miniconda]: https://docs.conda.io/en/latest/miniconda.html -[myst]: https://myst-parser.readthedocs.io/en/latest/syntax/syntax.html [other kinds of contributions]: https://opensource.guide/how-to-contribute [pre-commit]: https://pre-commit.com/ [pypi]: https://pypi.org/ -[pyscaffold's contributor's guide]: https://pyscaffold.org/en/stable/contributing.html [pytest can drop you]: https://docs.pytest.org/en/stable/usage.html#dropping-to-pdb-python-debugger-at-the-start-of-a-test [python software foundation's code of conduct]: https://www.python.org/psf/conduct/ -[restructuredtext]: https://www.sphinx-doc.org/en/master/usage/restructuredtext/ [sphinx]: https://www.sphinx-doc.org/en/master/ [tox]: https://tox.readthedocs.io/en/stable/ [virtual environment]: https://realpython.com/python-virtual-environments-a-primer/ [virtualenv]: https://virtualenv.pypa.io/en/stable/ - -```{todo} Please review and change the following definitions: -``` - -[repository]: https://github.com//smhw-api -[issue tracker]: https://github.com//smhw-api/issues +[repository]: https://github.com/EpicGamerCodes/smhw-api +[issue tracker]: https://github.com/EpicGamerCodes/smhw-api/issues diff --git a/LICENSE.txt b/LICENSE.txt index 4a50759..f288702 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,21 +1,674 @@ -The MIT License (MIT) - -Copyright (c) 2023 EpicGamerCodes - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 733b626..4c42f31 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,84 @@ - +# smhw-api [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) -# smhw-api +## Table of Contents + +1. [Introduction](#introduction) +2. [Features](#features) +3. [Installation](#installation) +4. [Dependencies](#dependencies) +5. [Disclaimer](#disclaimer) +6. [License](#license) + +## Introduction + +The `smhw-api` project allows users to connect to the Satchel: One API using their user credentials. The project is designed to run on Python 3.11. The responses are returned as objects which are fully type hinted (see `src/smhw_api/objects.py`). Please note that there is no rate limiting kept by the script yet, so make sure you send API requests appropriately. The script uses the Web client ids (to switch to the mobile app client, replace the `Server.client_id` and `Server.client_secret` variables). + +## Features + +As of now, the project can perform the following tasks (examples can be viewed in `/examples/`): + +- Fetching the user's todo list +- Fetching a specific task and its details +- Fetching quiz data (Questions and previous tries) +- Fetching the user's specific data +- Fetching the user's school data +- Fetching the user's parents data +- Fetching employee data from the school +- Fetching the user's calendar +- Fetching the entire school's calendar +- Fetching the user's behavior (praise points and behavior points) +- Sending Quiz answers +- Sending comments on tasks +- Marking tasks as complete +- Marking tasks as viewed +- Fetching the user's timetable +- Fetching public school data (used to login) + +## Installation + +### From Github Releases + +1. Download the latest wheel file from the [Releases](https://github.com/EpicGamerCodes/smhw-api/releases) page. +2. Install the wheel file using pip: + + ```bash + pip install /path/to/wheel/file + ``` + +### From Source + +1. Clone the repository: + + ```bash + git clone https://github.com/EpicGamerCodes/smhw-api.git + ``` + +2. Navigate into the cloned repository: + + ```bash + cd smhw-api + ``` + +3. Install the project: + + ```bash + pip install . + ``` + +## Dependencies -> Add a short description here! +The project requires 2 dependencies for running: -A longer description of your project goes here... +- `httpx[http2]` - For HTTP/2 requests +- `loguru` - For simple and better formatted logs +## Disclaimer - +Users are responsible for their own actions while using this API. Please ensure to comply with any guidelines provided by Satchel: One API. Any consequences resulting from the misuse of this API are solely the user's responsibility. -## Note +## License -This project has been set up using PyScaffold 4.4.1. For details and usage -information on PyScaffold see https://pyscaffold.org/. +The project is licensed under the GPL v3 license. diff --git a/examples/calendar/demo.py b/examples/calendar/demo.py new file mode 100644 index 0000000..56ce5de --- /dev/null +++ b/examples/calendar/demo.py @@ -0,0 +1,36 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + calender = server.get_calendar() # get the student's personal calender from today + for ( + ctask + ) in ( + calender + ): # Loop through each calender task in the list and print it's information + print( + f"{ctask.id} | Subject: {ctask.subject} | Teacher: {ctask.teacher_name} | Name: {ctask.class_task_title} | Due on: {ctask.due_on}" + ) + + +def public_calender(): + # The entire school's calender + # It's the same code as above but with a different server function + + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + calender = server.get_school_calendar() # < The different server function + for ctask in calender: + print( + f"{ctask.id} | Subject: {ctask.subject} | Teacher: {ctask.teacher_name} | Name: {ctask.title} | Due on: {ctask.due_on}" + ) + + +if __name__ == "__main__": + main() + public_calender() diff --git a/examples/complete_quiz/demo.py b/examples/complete_quiz/demo.py new file mode 100644 index 0000000..2812af3 --- /dev/null +++ b/examples/complete_quiz/demo.py @@ -0,0 +1,33 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + todo = ( + server.get_todo() + ) # get all the tasks from the todo (current date to 3 weeks ahead,) + quiz = server.get_auto_detailed_task( + todo.quiz[0] + ) # Get the first available quiz from the todo and get its detailed information (see the get_todo demo for more information) + print(quiz.description) # Print the quiz description + input("Proceed? ") + for question in quiz.questions: # Loop through each question from the quiz + print(f"Answering question: {question.description}") # Print the question + try: + print( + server.put_quiz_answer(quiz, question.id, question.correct_answer) + ) # Send the correct quiz answer with no delay, this may be a bit suspicious though + # so the delay= parameter can be used wait X seconds to "answer the question". + except ( + api.exceptions.QuestionAlreadyComplete + ) as e: # If the question already been completed before + print(e) + + +if __name__ == "__main__": + main() diff --git a/examples/complete_task/demo.py b/examples/complete_task/demo.py new file mode 100644 index 0000000..598f9e4 --- /dev/null +++ b/examples/complete_task/demo.py @@ -0,0 +1,22 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + # Mark a task as complete + + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + todo = server.get_todo() # get all current tasks + task = todo.tasks[0] # Get the first task + + # Complete the task with that id, second parameter is the state + # If second param is True, the task will be set as completed, if False it will not be completed. + server.complete_task(task.id, True) + + +if __name__ == "__main__": + main() diff --git a/examples/debug/demo.py b/examples/debug/demo.py new file mode 100644 index 0000000..a59e2cf --- /dev/null +++ b/examples/debug/demo.py @@ -0,0 +1,18 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + # Enable debug mode on the module + # This shows the requests sent to the API in the console + api.set_debug(True) + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + # Your code here + + +if __name__ == "__main__": + main() diff --git a/examples/get_all_employees/demo.py b/examples/get_all_employees/demo.py new file mode 100644 index 0000000..0ec44fc --- /dev/null +++ b/examples/get_all_employees/demo.py @@ -0,0 +1,33 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + school = server.get_current_school() # get the student's school + for ( + id + ) in school.employee_ids: # iterate through a list of the school's employee_ids + try: + employee = server.get_employee( + id + ) # get_user can also be used but it returns more data that is not needed for this function + + # Some employee's accounts that do not exist are also in this list + # When the employee data can not be found, the `InvalidUser` exception is raised + # The below code just skips accounts that do not exist. + except api.exceptions.InvalidUser: + continue + + # Print the employee id used to fetch the data + # The employee's full name (this is auto generated by the dataclass) + # When the employee's account was created + print(f"{id} | {employee.full_name}, {employee.created_at}") + + +if __name__ == "__main__": + main() diff --git a/examples/get_behaviour/demo.py b/examples/get_behaviour/demo.py new file mode 100644 index 0000000..072253c --- /dev/null +++ b/examples/get_behaviour/demo.py @@ -0,0 +1,25 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + behaviour = ( + server.get_behaviour() + ) # Get the last 20 (limit default) behaviour points (positive and negative) + for ( + praise + ) in ( + behaviour.student_praises + ): # loop through each behaviour point (positive and negative) + print( + f"Positive: {praise.positive} | Points: {praise.points} | Reason: {praise.description} | Comments: {praise.comments} | Teacher: {praise.full_name}" + ) + + +if __name__ == "__main__": + main() diff --git a/examples/get_quiz_grade/demo.py b/examples/get_quiz_grade/demo.py new file mode 100644 index 0000000..858a555 --- /dev/null +++ b/examples/get_quiz_grade/demo.py @@ -0,0 +1,26 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + todo = ( + server.get_todo() + ) # get all the tasks from the todo (current date to 3 weeks ahead,) + quiz = server.get_auto_detailed_task( + todo.quiz[0] + ) # Get the first available quiz from the todo and get its detailed information (see the get_todo demo for more information) + quiz_submission = server.get_quiz_submission( + quiz + ) # get the student's quiz submission data, passing the quiz as a param + print( + f"{quiz_submission.student_name} | Grade: {quiz_submission.grade} | Status: {quiz_submission.status}" + ) # Print the student's name, quiz grade and the status of the quiz. + + +if __name__ == "__main__": + main() diff --git a/examples/get_todo/demo.py b/examples/get_todo/demo.py new file mode 100644 index 0000000..19bbcbe --- /dev/null +++ b/examples/get_todo/demo.py @@ -0,0 +1,37 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + # Get the user's current task todo list + # If you wish to get tasks from earlier dates, use the datetime module like so: + # todo = server.get_todo(start=datetime.datetime.now() - datetime.timedelta(weeks=4)) + # this code ^ fetches tasks starting from 4 weeks ago to 3 weeks ahead (the end parameter's default) + todo = server.get_todo() + + # All tasks are stored in todo.tasks + # If you wish to access specific types of tasks, the todo is categorised into 5 different lists: + # homework, quiz, test, classwork and flexible_task + for task in todo.tasks: + print(f"{task.id} | {task.teacher_name}, {task.subject} | {task.completed}") + + # As you might have noticed, the information is very limited. To fetch more information you must use the + # `get_auto_detailed_task` function + # This function automatically detects the type of task, fetches the data and returns the appropriate dataclass. + detailed_task: api.objects.DetailedTask = server.get_auto_detailed_task( + todo.homework[0] + ) # Get detailed information about the first homework + print( + f"Submission type: {detailed_task.submission_type}\nWeb Links: {detailed_task.web_links}\nClass: {detailed_task.class_group_name}" + ) + + # Tasks like a quiz have much more detailed information such as the questions, etc... + + +if __name__ == "__main__": + main() diff --git a/examples/login/demo.py b/examples/login/demo.py new file mode 100644 index 0000000..3fc1209 --- /dev/null +++ b/examples/login/demo.py @@ -0,0 +1,28 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + email = input("Email: ") + password = input("Password: ") + school = input("School Name: ") + school_results = api.Server.get_public_schools( + school, limit=1 + ) # get the school with the most similar name as `school` + + # Attempt to login + # If the login is invalid the `InvalidCredentials` exception is thrown. + auth = api.Server.get_auth(email, password, school_results.schools[0]) + print(f"Logging into account with USER ID: {auth.user_id}") + + # Create the server instance + server = api.Server(f"Bearer {auth.access_token}", auth.user_id, auth.school_id) + # Your code + + +if __name__ == "__main__": + main() diff --git a/examples/timetable/demo.py b/examples/timetable/demo.py new file mode 100644 index 0000000..321922a --- /dev/null +++ b/examples/timetable/demo.py @@ -0,0 +1,28 @@ +import smhw_api as api + +# Enter your account credentials +AUTH: str = "" +USER_ID: int = 0 +SCHOOL_ID: int = 0 + + +def main(): + # Some notes: + # The TimetableInterface object is very confusing, even for me, hopefully I will have the time to redesign it + + server = api.Server(AUTH, USER_ID, SCHOOL_ID) + timetable = ( + server.get_timetable() + ) # Get the TimetableInterface object from the start of this week (Monday) + print( + timetable.weeks[0].days[0].lessons + ) # All the lessons for the first day (Monday) + print( + timetable.weeks[0].days[1].lessons + ) # All the lessons for the second day (Tuesday) + lesson = timetable.weeks[0].days[1].lessons[0] # The first lesson of the second day + print(lesson.room, lesson.period, lesson.teacher) + + +if __name__ == "__main__": + main() diff --git a/setup.cfg b/setup.cfg index fa9116e..0f8dee5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,23 +5,17 @@ [metadata] name = smhw-api -description = Add a short description here! +description = A Python interface for the Satchel One (previously called Show my Homework) student API endpoints. author = EpicGamerCodes author_email = 62027082+EpicGamerCodes@users.noreply.github.com -license = MIT +license = GPL-3.0-or-later license_files = LICENSE.txt long_description = file: README.md long_description_content_type = text/markdown; charset=UTF-8; variant=GFM -url = https://github.com/pyscaffold/pyscaffold/ -# Add here related links, for example: -project_urls = - Documentation = https://pyscaffold.org/ -# Source = https://github.com/pyscaffold/pyscaffold/ -# Changelog = https://pyscaffold.org/en/latest/changelog.html -# Tracker = https://github.com/pyscaffold/pyscaffold/issues -# Conda-Forge = https://anaconda.org/conda-forge/pyscaffold -# Download = https://pypi.org/project/PyScaffold/#files -# Twitter = https://twitter.com/PyScaffold +url = https://github.com/EpicGamerCodes/smhw-api/ +Source = https://github.com/EpicGamerCodes/smhw-api/ +Tracker = https://github.com/EpicGamerCodes/smhw-api/issues +Download = https://github.com/EpicGamerCodes/smhw-api/releases # Change if running only on Windows, Mac or Linux (comma-separated) platforms = any @@ -29,7 +23,7 @@ platforms = any # Add here all kinds of additional classifiers as defined under # https://pypi.org/classifiers/ classifiers = - Development Status :: 4 - Beta + Development Status :: 2 - Pre-Alpha Programming Language :: Python @@ -48,6 +42,9 @@ package_dir = # new major versions. This works if the required packages follow Semantic Versioning. # For more information, check out https://semver.org/. install_requires = + loguru + httpx + h2 importlib-metadata; python_version<"3.8" diff --git a/src/smhw_api/__init__.py b/src/smhw_api/__init__.py index 771ca8e..d4b91ce 100644 --- a/src/smhw_api/__init__.py +++ b/src/smhw_api/__init__.py @@ -14,3 +14,29 @@ __version__ = "unknown" finally: del version, PackageNotFoundError + +from loguru import logger + +logger.remove(0) +__logid = logger.add(sys.stderr, level="INFO") + +from .api import * +from . import exceptions +from . import objects + + +def set_debug(state: bool): + """ + The function sets the debug state and updates the logger accordingly. + + Args: + state (bool): state is a boolean parameter that determines whether debug log is turned on or off. + If state is True, debug log is turned on and if it is False, debug log is turned off. + """ + global __logid + logger.remove(__logid) + if state: + __logid = logger.add(sys.stderr, level="DEBUG") + else: + __logid = logger.add(sys.stderr, level="INFO") + logger.debug(f"Debug set to: {state=}") diff --git a/src/smhw_api/api.py b/src/smhw_api/api.py new file mode 100644 index 0000000..3e28248 --- /dev/null +++ b/src/smhw_api/api.py @@ -0,0 +1,881 @@ +import datetime +import time +from dataclasses import asdict + +import httpx +from loguru import logger + +from smhw_api import exceptions, objects + + +class Server: + session = httpx.Client(http2=True) + base_headers = { + "Accept": "application/smhw.v2021.5+json", + "Connection": "keep-alive", + } + + client_id = "55283c8c45d97ffd88eb9f87e13f390675c75d22b4f2085f43b0d7355c1f" + client_secret = "c8f7d8fcd0746adc50278bc89ed6f004402acbbf4335d3cb12d6ac6497d3" + """The Server class provides methods for interacting with the SatchelOne API to retrieve information about a student's tasks, classes, school, and more.""" + + def __init__(self, auth: str, user_id: int, school_id: int): + """ + This is a constructor function that initializes various attributes including session, auth, user_id, + school_id, and headers. + + Args: + auth (str): The authentication token used to access the API. It is required to start with the + string "Bearer ". + user_id (int): The user ID is an integer that identifies a specific user in the system. It is + likely used to retrieve or manipulate data related to that user. + school_id (int): The school ID is an integer that identifies a specific school within the system. + It is used to retrieve data specific to that school. + """ + if auth[:7] != "Bearer ": + raise exceptions.InvalidAuth( + "Auth needs to start with 'Bearer' (with capitalization)." + ) + + self.auth = auth + self.user_id = user_id + self.school_id = school_id + self._data: dict[objects.School, objects.Student] = {} + + self.headers = { + "Authorization": self.auth, + } | self.base_headers + + logger.debug("Obtaining information via self._get_data...") + self._get_data() + + def _get_request(self, url, *args, **kwargs) -> httpx.Response: + """ + This function sends an HTTP GET request to the specified URL with the custom headers and returns + the response. + + Args: + url: The URL of the HTTP request that the function will send a GET request to. + + Returns: + A HTTP response object of the type `httpx.Response`. + """ + logger.debug(f"[GET] request: {url=}, {kwargs}") + return self.session.get(url, headers=self.headers, *args, **kwargs) + + def _put_request(self, url, *args, **kwargs) -> httpx.Response: + """ + This function sends an HTTP PUT request to the specified URL with the custom headers and returns + the response. + + Args: + url: The URL of the HTTP request that the function will send a PUT request to. + + Returns: + A HTTP response object of the type `httpx.Response`. + """ + logger.debug(f"[PUT] request: {url=}, {kwargs}") + return self.session.put(url, headers=self.headers, *args, **kwargs) + + def _post_request(self, url, *args, **kwargs) -> httpx.Response: + """ + This function sends an HTTP POST request to the specified URL with the custom headers and returns + the response. + + Args: + url: The URL of the HTTP request that the function will send a POST request to. + + Returns: + A HTTP response object of the type `httpx.Response`. + """ + logger.debug(f"[POST] request: {url=}, {kwargs}") + return self.session.post(url, headers=self.headers, *args, **kwargs) + + def get_todo( + self, + add_dateless: bool = True, + completed: bool = None, + start: datetime.datetime = None, + end: datetime.datetime = None, + ) -> objects.Todo: + """ + The `get_todo` function retrieves a list of todos from the API based on specified parameters, such as + add_dateless, completed, start date, and end date. + + #### API Requests: 1 + + Args: + add_dateless (bool): The `add_dateless` parameter is a boolean flag that determines whether or not + to include dateless todos in the result. Defaults to True + completed (bool): The `completed` parameter is a boolean flag that indicates whether to include + completed todos in the result. If `completed` is set to `True`, the API will return both completed + and incomplete todos. If `completed` is set to `False`, only incomplete todos will be + returned. If completed is set to `None`, completed and incomplete todos will be returned. + start (datetime.datetime): The `start` parameter is a `datetime.datetime` object that represents + the start date for filtering the todos. If no start date is provided, it defaults to the current + date and time. + end (datetime.datetime): The `end` parameter is a `datetime.datetime` object that represents the + end date for filtering todos. If no `end` date is provided, it defaults to the current date plus 3 + weeks. + + Returns: + An object of type `objects.Todo`. + """ + if start is None: + start = datetime.datetime.now() + if end is None: + end = datetime.datetime.now() + datetime.timedelta(weeks=3) + params = { + "add_dateless": add_dateless, + "from": start.strftime("%Y-%m-%d"), + "to": end.strftime("%Y-%m-%d"), + } + if completed is not None: + params["completed"] = completed + r = self._get_request( + "https://api.satchelone.com/api/todos", params=params + ).json() + return objects.make_todo(r["todos"]) + + def get_task(self, task: objects.Task, obj: list = None) -> objects.DetailedTask: + """ + This function retrieves a detailed task object from the API based on a given task object and a list + of objects. + + #### API Requests: 1 + + Args: + task (objects.Task): The task parameter is an object of the Task class, which contains detailed information + about a specific task. + obj (list): The `obj` parameter is a list that contains two elements: the first element is the + class of the object that will be created and the second element is the type of task (e.g. + "homework", "test", "quiz"). If `obj` is not provided, it defaults to [objects.DetailedTask, objects.TaskTypes.HOMEWORK]. + + Returns: + An instance of the `DetailedTask` class. + """ + if obj is None: + obj = [objects.DetailedTask, objects.TaskTypes.HOMEWORK] + if obj[1].lower()[-1] != "s": + api_path = f"{obj[1].lower()}s" + else: + api_path = obj[1].lower() + + r = self._get_request( + f"https://api.satchelone.com/api/{api_path}/{task.class_task_id}" + ) + if r.status_code == 404: + raise exceptions.InvalidTask( + f"Task is not found! ({task.class_task_type=})" + ) + r = r.json() + return objects.Create.instantiate(obj[0], r[obj[1].lower()] | asdict(task)) + + def get_auto_detailed_task( + self, task: objects.Task + ) -> ( + objects.DetailedTask + | objects.Quiz + | objects.ClassTest + | objects.Classwork + | objects.FlexibleTask + ): + """ + This function takes in a task object and returns a more detailed task object based on its type. + + #### API Requests: 1 + + Args: + task (objects.Task): The task parameter is an instance of the Task class from the objects module. + It represents a task that needs to be retrieved or processed. + + Returns: + An object of one of the following types: + `objects.DetailedTask`, `objects.Quiz`, `objects.ClassTest`, `objects.Classwork`, or + `objects.FlexibleTask`. The specific type of object returned depends on the `class_task_type` + attribute of the `task` object passed as an argument to the function. + """ + if task.class_task_type == objects.TaskTypes.HOMEWORK: + return self.get_task(task) + elif task.class_task_type == objects.TaskTypes.QUIZ: + return self.get_quiz(task) + elif task.class_task_type == objects.TaskTypes.CLASSTEST: + return self.get_task( + task, [objects.ClassTest, "class_test"] + ) # no special details + elif task.class_task_type == objects.TaskTypes.CLASSWORK: + return self.get_task( + task, [objects.Classwork, objects.TaskTypes.CLASSWORK] + ) # no special details + elif task.class_task_type == objects.TaskTypes.FLEXIBLETASK: + return self.get_task( + task, [objects.FlexibleTask, "flexible_task"] + ) # no special details + else: + raise exceptions.InvalidTask( + f"Task could not be auto-detected! ({task.class_task_type=})" + ) + + def get_quiz(self, task: objects.Task) -> objects.Quiz: + """ + This function retrieves a quiz from the API and creates a Quiz object with its associated questions. + + #### API Requests: 2 + + Args: + task (objects.Task): The `task` parameter is an object of type `objects.Task`. + The `task` object is also passed to the `objects.Quiz` constructor as additional data. + + Returns: + an instance of the `Quiz` class. + """ + if task.is_detailed(): + raise exceptions.TaskAlreadyDetailed( + f"Task ID: {task.id} | Is already a detailed task!" + ) + r = self._get_request( + f"https://api.satchelone.com/api/quizzes/{task.class_task_id}" + ).json()["quiz"] + params = {"ids[]": r["question_ids"]} + nr = self._get_request( + "https://api.satchelone.com/api/quiz_questions", params=params + ).json() + + nqq = [ + objects.Create.instantiate(objects.Question, question) + for question in nr["quiz_questions"] + ] + return objects.Create.instantiate( + objects.Quiz, r | {"questions": nqq} | asdict(task) + ) + + def get_user(self, user_id: int = None) -> objects.User: + """ + Retrieves user information from an API and returns a User object. + + #### API Requests: 1 + + Args: + user_id (int): The `user_id` parameter is an optional integer that represents the ID of a user. + + Returns: + an instance of the `objects.User` class. + """ + r = self._get_request(f"https://api.satchelone.com/api/users/{user_id}") + if r.status_code == 404: + raise exceptions.InvalidUser(user_id) + return objects.Create.instantiate(objects.User, r["user"]) + + def get_current_student( + self, + cached: bool = True, + user_private_info: bool = True, + school: bool = False, + package: bool = False, + premium_features: bool = False, + ) -> objects.Student: + """ + Retrieves student information from the API, including optional additional + data such as user private info, school info, package info, and premium features. + + #### API Requests: 2 (0 if cached) + + Args: + cached (bool): The `cached` parameter is a boolean flag that determines whether to retrieve the + student information from a cache or make a new API request. If `cached` is set to `True` and the + `user_id` matches `self.user_id`, the method will return the student information from the cache. Defaults to True + user_private_info (bool): The `user_private_info` parameter determines whether to include the + user's private information in the response. Defaults to True + school (bool): The "school" parameter determines whether to include the school information of the + student in the response. Defaults to False + package (bool): The "package" parameter determines whether to include information about the + student's package in the response. Defaults to False + premium_features (bool): The `premium_features` parameter is a boolean flag that determines + whether to include premium features in the returned student object. Defaults to False + + Returns: + an instance of the `objects.Student` class. + """ + + if cached: + return self._data["student"] + + include = "" + if user_private_info: + include += "user_private_info," + if school: + include += "school," + if package: + include += "package," + if premium_features: + include += "premium_features," + + params = {"include": include} + response = self._get_request( + f"https://api.satchelone.com/api/students/{self.user_id}", params=params + ) + response = response.json() + + params = { + "student_ids[]": self.user_id, + } + + classes = [ + objects.Create.instantiate(objects.Class, c) + for c in self._get_request( + "https://api.satchelone.com/api/class_groups", params=params + ).json()["class_groups"] + ] + return objects.Create.instantiate( + objects.Student, + response["student"] + | response["user_private_infos"][0] + | {"classes": classes}, + ) + + def get_current_school(self, cached: bool = True) -> objects.School: + """ + This function returns the current school object. + This data was fetched when the class was created. + + #### API Requests: 2 (0 if cached) + + Returns: + an instance of the `School` class. + """ + if cached: + return self._data["school"] + + params = {"include": "school"} + response = self._get_request( + f"https://api.satchelone.com/api/students/{self.user_id}", params=params + ) + if response.status_code == 401: + raise exceptions.InvalidAuth(self.auth, self.user_id, self.school_id) + response = response.json() + subjects = [ + objects.Create.instantiate(objects.Subject, subject) + for subject in self._get_request( + "https://api.satchelone.com/api/subjects", + params={"school_id": self.school_id}, + ).json()["subjects"] + ] + return objects.Create.instantiate( + objects.School, response["schools"][0] | {"subjects": subjects} + ) + + def get_current_parents(self) -> list[objects.Parent]: + """ + This function retrieves the current parents associated with a student from an API and returns them + as a list of Parent objects. + + #### API Requests: 1 + + Returns: + an instance of the `Parent` class. + """ + params = {"ids[]": self._data["student"].parent_ids} + r = self._get_request("https://api.satchelone.com/api/parents", params=params) + return [ + objects.Create.instantiate(objects.Parent, user) + for user in r.json()["parents"] + ] + + def get_task_comments(self, task_id: int) -> dict: + """ + This function retrieves comments for a given task from the API. + + #### API Requests: 1 + + Args: + task (int): The task's id. + + Returns: + The comments as a dict object. # TODO AS ITS OWN OBJECT + """ + params = { + "commentable_id": task_id, + "commentable_type": "ClassTask", + } + + r = self._get_request("https://api.satchelone.com/api/comments", params=params) + r = r.json()["comments"] + logger.info( + """If you are using this feature and you have data from it, please open a Github Issue with this data! + (Reason: return data is currently a dict, want to make it a dataclass)""" + ) + return r + + def get_employee(self, id: int | list[int]) -> objects.Employee: + """ + This function retrieves an employee's data from the API using their ID and returns it as an Employee + object or a list of Employee objects. + + #### API Requests: 1 + + Args: + id (int): The id parameter is an integer that represents the employee. + + Returns: + The function `get_employee` returns an instance of `objects.Employee` if the `id` parameter + matches a single employee, or a list of `objects.Employee` instances if the `id` parameter is a list + and contains multiple employee ids. If the `id` parameter does not match any employee, the function raises an + `exceptions.InvalidUser` exception. + """ + + # if you make id = "", it returns some random teachers full (full names) data? (20 teachers? possibly admins?) + # params = {'ids[]': id} + r = self._get_request(f"https://api.satchelone.com/api/users/{id}") + if r.status_code == 404: + raise exceptions.InvalidUser(f"Employee not found! ({id=})") + try: + r = r.json()["user"] + return objects.Create.instantiate(objects.Employee, r) + except KeyError: + r = r.json()["users"] + return [objects.Create.instantiate(objects.Employee, user) for user in r] + + def get_calendar( + self, date: datetime.datetime = None + ) -> list[objects.PersonalCalendarTask]: + """ + The `get_calendar` function retrieves personal calendar tasks from the API based on a specified date + or the current date if none is provided. + + #### API Requests: 1 + + Args: + date (datetime.datetime): The `date` parameter is an optional parameter of type + `datetime.datetime`. If no value is provided for `date`, it defaults to the current date and time. + + Returns: + A list of objects of type `objects.PersonalCalendarTask`. + """ + if date is None: + date = datetime.datetime.now() + params = {"date": date.strftime("%Y-%m-%d")} + r = self._get_request( + "https://api.satchelone.com/api/personal_calendar_tasks", params=params + ) + return [ + objects.Create.instantiate(objects.PersonalCalendarTask, data) + for data in r.json()["personal_calendar_tasks"] + ] + + def get_school_calendar( # TODO: ADD FILTERS + self, date: datetime.datetime = None + ) -> list[objects.SchoolCalendarTask]: + """ + The `get_school_calendar` function retrieves the school calendar tasks for a given date or the + current date if none is provided. + + #### API Requests: 1 + + Args: + date (datetime.datetime): The `date` parameter is an optional parameter of type + `datetime.datetime`. If no value is provided for `date`, it defaults to the current date and time + obtained using `datetime.datetime.now()`. + + Returns: + A list of `objects.SchoolCalendarTask` objects. + """ + if date is None: + date = datetime.datetime.now() + params = { + "date": date.strftime("%Y-%m-%d"), + "subdomain": self._data["school"].subdomain, + } + r = self._get_request("https://api.satchelone.com/api/calendars", params=params) + return [ + objects.Create.instantiate(objects.SchoolCalendarTask, data) + for data in r.json()["calendars"] + ] + + def get_behaviour(self, limit: int = 20, offset: int = 0) -> objects.Behaviour: + """ + This function retrieves behaviour data for a student from the API. + + #### API Requests: 2 + + Args: + limit (int): The maximum number of behaviour report entries to retrieve in a single + request. Defaults to 20 + offset (int): The offset parameter is used to specify the starting point of the data to be + retrieved from the API. Defaults to 0 + + Returns: + an instance of the `Behaviour` class + """ + params = { + "student_id": self.user_id, + "limit": limit, + "offset": offset, + } + + r = self._get_request( + "https://api.satchelone.com/api/behaviour_breakdown_report_entries", + params=params, + ) + r = r.json() + praises = [ + objects.Create.instantiate(objects.Praise, praise) + for praise in r["student_kudos"]["student_praises"] + ] + psum = objects.Create.instantiate( + objects.PraiseSummary, + self._get_request( + f"https://api.satchelone.com/api/student_praise_summaries/{self.user_id}" + ).json()["student_praise_summary"], + ) + return objects.Create.instantiate( + objects.Behaviour, + r["student_kudos"] + | {"student_praises": praises} + | {"student_praise_summary": psum}, + ) + + def get_quiz_submission(self, quiz: objects.Quiz) -> objects.QuizSubmission: + """ + The function `get_quiz_submission` retrieves a detailed quiz submission object from an API. + + #### API Requests: 1 + + Args: + quiz (objects.Quiz): The parameter "quiz" is an object of type "objects.Quiz". + + Returns: + an instance of the `objects.QuizSubmission` class. + """ + if not quiz.is_detailed(): + raise exceptions.TaskNotDetailed( + f"Quiz ID: {quiz.id} | Is not a detailed task, you can fetch it's detailed version by using the function self.get_quiz()!" + ) + r = self._get_request( + f"https://api.satchelone.com/api/quiz_submissions/{quiz.submission_ids[0]}" + ) + return objects.Create.instantiate( + objects.QuizSubmission, r.json()["quiz_submission"] + ) # more sections: submission_events and submission_comments + + def put_quiz_answer( + self, quiz: objects.Quiz, question_id: int, answer: str, delay: int = 0 + ) -> bool: + """ + The `send_quiz_answer` function sends a quiz answer to the API and returns whether the + answer was correct or not. + + #### API Requests: 2< + + Args: + quiz (objects.Quiz): Represents a quiz that a user is taking. + question_id (int): The `question_id` parameter represents the ID of the question in the quiz that + the user is answering. + answer (str): The `answer` parameter is the answer that the user wants to submit for the quiz + question. + delay (int): How long to wait before sending the answer to the API. + + Returns: + The function `send_quiz_answer` returns a boolean value indicating whether the answer provided for + a quiz question was correct or not. + """ + if not quiz.is_detailed(): + raise exceptions.TaskNotDetailed( + f"Quiz ID: {quiz.id} | Is not a detailed task, you can fetch it's detailed version by using the function self.get_quiz()!" + ) + + api_id = f"{quiz.id}-{question_id}" + + question_data = self._get_request( + f"https://api.satchelone.com/api/quiz_submission_questions/{api_id}" + ) + question_data = question_data.json() + # check if question already done + attempts = 0 + atts_keys = list(question_data["quiz_submission_question"].keys()) + max_attempts = max(int(a.replace("attempt", "")) for a in atts_keys) + + for i in range(max_attempts): + try: + question_data["quiz_submission_question"][f"attempt{i}"].get("correct") + attempts += 1 + if attempts == quiz.max_attempts: + raise exceptions.QuestionAlreadyComplete( + f"Question {api_id=} is already complete!" + ) + except AttributeError: + attempt = f"attempt{i}" + break + + question_data["quiz_submission_question"][attempt] = { + "answer": None, + "start": datetime.datetime.now().isoformat(), + "correct": False, + } + + question_data = self._put_request( + f"https://api.satchelone.com/api/quiz_submission_questions/{api_id}", + json=question_data, + ).json() + + question_data["quiz_submission_question"][attempt] = { + "answer": answer, # answer can be obtained by using: quiz.get_question(question_id).correct_answer + } + + if delay: + logger.debug(f"Waiting for {delay} seconds before sending answer...") + time.sleep(delay) + + question_data = self._put_request( + f"https://api.satchelone.com/api/quiz_submission_questions/{api_id}", + json=question_data, + ).json() + + return question_data["quiz_submission_question"][attempt][ + "correct" + ] # was it correct or not + + # TODO: I HAVE NO WAY OF TESTING THIS RIGHT NOW + def post_comment( + self, message: str, task: objects.Task, skip_profanity_check: bool = False + ): + """ + Post a comment on a task, with an option to skip profanity check. + + #### API Requests: 1 + + Args: + message (str): The `message` parameter is a string that represents the content of the comment that + you want to post. + task (objects.Task): The `task` parameter is an object of type `objects.Task`. It represents the + task to which the comment is being posted. + skip_profanity_check (bool): The `skip_profanity_check` parameter is a boolean flag that indicates + whether the profanity check should be skipped when posting a comment. Defaults to False + + Returns: + An instance of the `objects.Comments` class. + """ + data = { + "comment": { + "message": message, + "created_at": None, + "skip_profanity_check": skip_profanity_check, + "user_id": None, + "user_type": None, + "attachment_ids": [], + "commentable_id": task.id, + "commentable_type": task.class_task_type, + } + } + + r = self._post_request("https://api.satchelone.com/api/comments", data=data) + r = r.json() + users = [ + objects.Create.instantiate(objects.CommentUser, user) for user in r["users"] + ] + commentable = { + "commentable": objects.Create.instantiate( + objects.CommentableTask, r["comment"]["commentable"] + ) + } + del r["comment"]["commentable"] + comments = [ + objects.Create.instantiate( + objects.Comment, r["comment"] | {"commentable": commentable} + ) + ] + return objects.Create.instantiate( + objects.Comments, {"users": users, "comments": comments} + ) + + def complete_task(self, task_id: int, state: bool): + """ + Updates the completion state of a task with the given task ID. + + #### API Requests: 1 + + Args: + task_id (int): The task_id parameter is an integer that represents the unique identifier of the + task that needs to be completed. + state (bool): The `state` parameter is a boolean value that represents the completion state of the + task. + """ + json_data = { + "todo": { + "completed": state, + }, + } + + self._put_request( + f"https://api.satchelone.com/api/todos/{task_id}", json=json_data + ) + + def view_task(self, task_id: int, eventable_type: str) -> bool: + """ + A "viewed" event for a specific task, and returns a boolean indicating the success of the request. + + #### API Requests: 1 + + Args: + task_id (int): The `task_id` parameter is an integer that represents the unique identifier of a + task. It is used to identify the specific task that has been viewed. + eventable_type (str): The `eventable_type` parameter is a string that represents the type of the + eventable object. In this case, it is used to specify the type of the object that is being viewed. + + Returns: + a boolean value. + """ + json_data = { + "event": { + "event_type": "viewed", + "eventable_type": eventable_type, + "eventable_id": task_id, + }, + } + + r = self._post_request("https://api.satchelone.com/api/events", json=json_data) + return bool(r.text) + + def reset_calendar_token(self): + self._post_request( + "https://api.satchelone.com/api/icalendars/reset_calendar_token" + ) + self._get_data() # refresh cache + + def get_timetable( + self, requestDate: datetime.datetime = None + ) -> objects.TimetableInterface: + """ + Retrieves a timetable for the current week. + + #### API Requests: 1 + + Args: + requestDate (datetime.datetime): The `requestDate` parameter is an optional parameter of type + `datetime.datetime`. If no `requestDate` is provided, the current date is used. + + Returns: + An instance of the `TimetableInterface` class from the `objects` module. + """ + if requestDate is None: + now = datetime.datetime.now() + requestDate = now - datetime.timedelta(days=now.weekday()) + + params = { + "requestDate": requestDate.strftime("%Y-%m-%d"), + } + + r = self._get_request( + f"https://api.satchelone.com/api/timetable/school/{self.school_id}/student/{self.user_id}", + params=params, + ) + r = r.json() + days = [] + for day in r["weeks"][0]["days"]: + lessons = [] + for lesson in day["lessons"]: + lesson["classGroup"] = objects.Create.instantiate( + objects.TimetableClassGroup, lesson["classGroup"] + ) + lesson["period"] = objects.Create.instantiate( + objects.TimetablePeriod, lesson["period"] + ) + lesson["teacher"] = objects.Create.instantiate( + objects.TimetableTeacher, lesson["teacher"] + ) + ctasks = [ + objects.Create.instantiate(objects.TimetableHomework, ctask) + for ctask in lesson["dueClassTasks"] + ] + lesson["dueClassTasks"] = ctasks + lessons.append( + objects.Create.instantiate(objects.TimetableLesson, lesson) + ) + days.append( + objects.Create.instantiate( + objects.TimetableDay, day | {"lessons": lessons} + ) + ) + timetable = objects.Create.instantiate( + objects.Timetable, r["weeks"][0] | {"days": days} + ) + return objects.Create.instantiate( + objects.TimetableInterface, r | {"weeks": [timetable]} + ) + + @classmethod + def get_public_schools( + cls, filter: str = "", limit: int = 20 + ) -> objects.PublicSchoolSearch: + """ + The function `get_public_schools` retrieves a list of public schools based on a filter and limit, + and returns an object containing the schools and metadata. + + #### API Requests: 1 + + Args: + filter (str): The "filter" parameter is used to specify a string search filter for the public schools. + limit (int): The `limit` parameter specifies the maximum number of public schools to retrieve from + the API. Defaults to 20. + + Returns: + an instance of the `objects.PublicSchoolSearch` class. + """ + params = {"filter": filter, "limit": limit} + r = cls.session.get( + "https://api.satchelone.com/api/public/school_search", + params=params, + headers=cls.base_headers, + ) + r = r.json() + schools = [ + objects.Create.instantiate(objects.PublicSchool, school) + for school in r["schools"] + ] + return objects.Create.instantiate( + objects.PublicSchoolSearch, {"schools": schools} | r["meta"] + ) + + @classmethod + def get_auth(cls, username: str, password: str, school_id: int) -> objects.Auth: + """ + The function `get_auth` sends a POST request to the Satchel One API to authenticate a user with + their username, password, and school ID. + + #### API Requests: 3 (+2, get_current_student) + + Args: + username (str): The `username` parameter is a string that represents the username of the user + trying to authenticate. + password (str): The `password` parameter is a string that represents the user's password. + school_id (int): The `school_id` parameter is an integer that represents the unique identifier of + a school. + + Returns: + an instance of the `Auth` class from the `objects` module. + """ + data = { + "grant_type": "password", + "username": username, + "password": password, + "school_id": school_id, + } + + params = { + "client_id": cls.client_id, + "client_secret": cls.client_secret, + } + + response = cls.session.post( + "https://api.satchelone.com/oauth/token", + params=params, + data=data, + ) + r = response.json() + if response.status_code == 401: + raise exceptions.InvalidCredentials(r, username, password, school_id) + return objects.Create.instantiate(objects.Auth, r) + + def _get_data(self) -> dict: + self._data["school"] = self.get_current_school(False) + self._data["student"] = self.get_current_student(False) + return self._data diff --git a/src/smhw_api/exceptions.py b/src/smhw_api/exceptions.py new file mode 100644 index 0000000..cdf40a4 --- /dev/null +++ b/src/smhw_api/exceptions.py @@ -0,0 +1,34 @@ +class InvalidTask(Exception): + pass + + +class InvalidQuiz(Exception): + pass + + +class TaskNotFound(Exception): + pass + + +class InvalidAuth(Exception): + pass + + +class InvalidUser(Exception): + pass + + +class QuestionAlreadyComplete(Exception): + pass + + +class InvalidCredentials(Exception): + pass + + +class TaskNotDetailed(Exception): + pass + + +class TaskAlreadyDetailed(Exception): + pass diff --git a/src/smhw_api/objects.py b/src/smhw_api/objects.py new file mode 100644 index 0000000..525d4ca --- /dev/null +++ b/src/smhw_api/objects.py @@ -0,0 +1,774 @@ +""" +If a variable has the type `Any`, this means that I haven't be able to check what the type is. +If you know, make a pull request or an issue. +""" + +import enum +from dataclasses import dataclass, field, fields +from datetime import datetime +from typing import Any + +from loguru import logger + + +def convert_datetime(var: str | datetime) -> datetime: + """ + This function converts a string or datetime object to a datetime object. + + Args: + var (str | datetime): The parameter `var` can be either a string or a `datetime` object. + + Returns: + The function `convert_datetime` takes a variable `var` which can be either a string or a datetime + object and returns a datetime object. If `var` is already a datetime object, it is returned as is. + Otherwise, it is assumed to be a string in ISO format and converted to a datetime object using the + `fromisoformat` method. + """ + if isinstance(var, datetime) or not isinstance(var, str): + return var + else: + return datetime.fromisoformat(var) + + +class Create: + classFieldCache = {} + + @classmethod + def instantiate(cls, classToInstantiate: object, argDict: dict): + """ + The function takes in a class and a dictionary of arguments, filters the arguments based on the + class's fields, and returns an instance of the class with the filtered arguments. + + Args: + classToInstantiate (object): The class object that needs to be instantiated. + argDict (dict): argDict is a dictionary that contains the arguments to be passed to the + constructor of the class that is being instantiated. The keys of the dictionary represent the names + of the arguments, and the values represent the values to be passed for those arguments. + + Returns: + An instance of the class specified in the `classToInstantiate` parameter, with the arguments + specified in the `argDict` parameter. The function first checks if the class has already been cached + in `classFieldCache`, and if not, it caches the fields of the class that can be initialized. It then + filters the arguments in `argDict` to only include those that correspond to the class fields. + """ + if classToInstantiate not in cls.classFieldCache: + cls.classFieldCache[classToInstantiate] = { + f.name for f in fields(classToInstantiate) if f.init + } + + fieldSet = cls.classFieldCache[classToInstantiate] + filteredArgDict = {k: v for k, v in argDict.items() if k in fieldSet} + return classToInstantiate(**filteredArgDict) + + +class TaskTypes(str, enum.Enum): + """All types of tasks""" + + HOMEWORK = "Homework" + QUIZ = "Quiz" + CLASSTEST = "ClassTest" + CLASSWORK = "Classwork" + FLEXIBLETASK = "FlexibleTask" + + +@dataclass(slots=True) +class BearerUser: + """The class BearerUser has attributes related to user information and activity, and uses a + post-initialization method to convert datetime objects. + """ + + id: int + email: str + last_activity_at: datetime + username: str + calendar_token: str + uid: str + last_user_activity_at: datetime + + def __post_init__(self): + self.last_activity_at = convert_datetime(self.last_activity_at) + self.last_user_activity_at = convert_datetime(self.last_user_activity_at) + + +@dataclass(slots=True) +class CommentUser: + id: int + title: str + backend_type: str + forename: str + surname: str + avatar: str + + full_name: str = field(default_factory=str, init=False) + + def __post_init__(self): + self.full_name: str = f"{self.title}. {self.forename} {self.surname}" + + +@dataclass(slots=True) +class CommentableTask: + id: int + type: str + + +@dataclass(slots=True) +class Comment: + id: int + message: str + created_at: datetime + commentable: CommentableTask + user_id: int + attachment_ids: list[int] + + +@dataclass(slots=True) +class Comments: + users: list[CommentUser] + comments: list[Comment] + + +@dataclass(slots=True) +class User: + """The class defines a User object with various attributes and methods, including a full name attribute + that is automatically generated based on the user's title, forename, and surname. + """ + + id: int + avatar: str + forename: str + school_id: int + surname: str + created_at: datetime + backend_type: str + updated_at: datetime + title: str + user_private_info_id: int + user_identity_id: int + + disabled: bool = field(default_factory=bool, init=False) + full_name: str = field(default_factory=str, init=False) + + def __post_init__(self): + self.created_at = convert_datetime(self.created_at) + self.updated_at = convert_datetime(self.updated_at) + self.full_name: str = f"{self.title}. {self.forename} {self.surname}" + + +@dataclass(slots=True) +class BaseCalendarTask: + id: int + due_on: datetime + issued_on: datetime + subject: str + teacher_id: int + teacher_name: str + class_task_type: str + + def __post_init__(self): + self.due_on = convert_datetime(self.due_on) + self.issued_on = convert_datetime(self.issued_on) + + +@dataclass(slots=True) +class PersonalCalendarTask(BaseCalendarTask): + id: int + class_task_id: int + class_group_name: str + class_task_title: str + submissions_count: int + for_partial_group: bool + + +@dataclass(slots=True) +class SchoolCalendarTask(BaseCalendarTask): + id: int + due_on: datetime + issued_on: datetime + subject: str + teacher_id: int + teacher_name: str + class_task_type: str + title: str + year: str + + +@dataclass(slots=True) +class BaseSubject: + """The class BaseSubject has two attributes, id and name.""" + + id: int + name: str + + +@dataclass(slots=True) +class Subject(BaseSubject): + """The Subject class inherits from the BaseSubject class and has two integer attributes, + school_private_info_id and standard_subject_id. + """ + + school_private_info_id: int + standard_subject_id: int + + +@dataclass(slots=True) +class Class(BaseSubject): + """This is a class that represents a group of students and teachers for a specific subject in a school, + with additional attributes such as class year, academic year ID, and group type. + """ + + class_year: str + academic_year_id: int + school_id: int + is_registration_group: bool + student_ids: list[int] + teacher_ids: list[int] + left_at: str + group_type: str + subject: str + + +@dataclass(slots=True) +class Auth: + smhw_token: str + access_token: str + token_type: str + expires_in: int + refresh_token: str + created_at: int + user_id: int + school_id: int + user_type: str + account_switch_enabled: bool + + +@dataclass(slots=True) +class _SchoolPremiumFeatures: + welfare_notes: bool + white_label_enabled: bool + custom_theme_enabled: bool + collins_content: bool + sanctions: bool + on_call_enabled: bool + + +@dataclass(slots=True) +class _CollinsSettings: + public_calendar_advert: bool + teacher_class_task_advert: bool + parent_class_task_advert: bool + student_class_task_advert: bool + + +@dataclass(slots=True) +class PublicSchool: + "Used for when searching for schools." + id: int + name: str + address: str + town: str + post_code: str + subdomain: str + is_active: bool + brand_color: str | None + + +@dataclass(slots=True) +class School: + """The class "School" contains attributes related to a school, such as its ID, name, address, and + employee and student IDs, as well as a list of subjects and a boolean indicating whether the school + has praise points enabled. + """ + + id: int + name: str + subdomain: str + address: str + town: str + post_code: str + country: str + phone_number: Any + email: str + website: str + twitter: str + facebook: str + instagram: str + school_phase_name: str + latitude: int + longitude: int + created_at: datetime + updated_at: datetime + logo_url: str + logo_name: str + premium_features: _SchoolPremiumFeatures + prospectus_url: str + prospectus_name: str + homepage_background_image_name: str + homepage_background_image_url: str + homepage_zones: bool + homepage_active: bool + homepage_background: str + student_zone_root_id: int + school_zone_root_id: int + parent_zone_root_id: int + links: dict # may be used? + employee_ids: list[int] + collins_settings: _CollinsSettings + brand_color: str + only_positive_kudos_enabled: bool + is_discussion_enabled: bool + share_classroom_enabled: bool + share_task_to_teams_enabled: bool + notice_types_enabled: bool + domains_for_email_import: str + domain = str # domains_for_email_import + school_private_info_id: int + time_zone: str + registration_group_ids: list[int] + has_o365_integration: bool + active_directory_enabled: bool + google_enabled: bool + google_drive_uploads_disabled: bool + dropbox_uploads_disabled: bool + one_drive_uploads_disabled: bool + hide_session_marks: bool + hide_lesson_marks: bool + satchel_classes_homework_ad: bool + root_directory_id: int + school_praise_info_id: int + is_active: bool + import_external_type: str + imports_enabled: bool + attendance_settings_id: int + class_group_ids: list[int] + seating_label_ids: list[int] + import_photos_type: str + early_access_enabled: bool + account_switch_enabled: bool + praise_points: bool # if school has praise_points enabled + kudos: bool + kudos_import: bool + kudos_writeback: bool + smart_seating: bool + core: bool + homework: bool + timetables: bool + attendance: bool + attendance_import_sessions: bool + attendance_writeback_sessions: bool + attendance_import_lessons: bool + attendance_writeback_lessons: bool + assessment: bool + detentions: bool + detentions_writeback: bool + documents: bool + xod_documents: bool + contact_scope_consented: bool + address_scope_consented: bool + show_staff_codes_for_public: bool + referred_incidents_enabled: bool + partners_page_enabled: bool + sanction_rule_ids: list[int] + classroom_emails_scope_enabled: bool + student_ids: list[int] + parent_ids: list[int] + pulse_promo: bool + announcement_category_ids: list[int] + subjects: list[Subject] + + def __post_init__(self): + self.created_at = convert_datetime(self.created_at) + self.updated_at = convert_datetime(self.updated_at) + + +@dataclass(slots=True) +class PublicSchoolSearch: + schools: list[PublicSchool] + selection_count: int + offset: int + + +@dataclass(slots=True) +class Student(User): + """The class "Student" contains attributes and methods related to a student user in a system, including + their parent IDs, year, gender, class group IDs, activity timestamps, calendar token, enrolled + classes, and invite code. + """ + + username: str + mobile_device_id: int + total_storage_used: int + root_folder_id: int + uid: str + has_filled_details: bool + intercom_enabled: bool + left_at: bool + sims_id: str + anonymous: bool + disabled: bool + created_at: datetime + parent_ids: list[int] + year: str + gender: str + class_group_ids: list[int] + last_activity_at: datetime + last_user_activity_at: datetime + calendar_token: str + classes: list[Class] + invite_code: str + + +@dataclass(slots=True) +class Employee(User): + pass + + +@dataclass(slots=True) +class Parent(User): + """The class "Parent" inherits from the class "User" and includes attributes for student IDs, student + names, and parent consent. + """ + + student_ids: list[int] + student_names: list[str] + parent_consent: bool + + +@dataclass(slots=True) +class Task: + """The class Task defines attributes and methods for a task, including due date, completion status, + task details, and submission information. + """ + + id: int + user_id: int + due_on: datetime + completed: bool + class_task_id: int + submission_type: bool + submission_status: Any + submission_grade: Any + class_task_title: str + class_task_description: str # only the start (in html) + class_group_name: str + class_task_type: str + subject: str + teacher_name: str + issued_on: datetime + submission_status: bool | None # not sure what this does + has_attachments: bool + + def __post_init__(self): + self.due_on = convert_datetime(self.due_on) + self.issued_on = convert_datetime(self.issued_on) + + def is_detailed(self) -> bool: + """Is the task detailed or not? + + This task is not detailed.""" + return False + + +@dataclass(slots=True) +class DetailedTask(Task): + """The class "DetailedTask" inherits from "Task" and includes additional attributes such as teacher_id, + submission_type, attachment_ids, web_links, description, and class_year. + + This class is only used when getting the task data from the Task page API itself and not todo. + """ + + teacher_id: int + class_group_name: str + submission_type: str + attachment_ids: list + web_links: list + description: str + class_year: str + class_group_name: str + + def is_detailed(self) -> bool: + """Is the task detailed or not? + + This task is not detailed.""" + return True + + +@dataclass(slots=True) +class QuizSubmission: + id: int + status: str + student_id: int + student_name: str + grade: str + student_avatar: str + created_at: datetime + quiz_id: int + updated_at: datetime + question_ids: list[int] + event_ids: list[int] + comment_ids: list[int] + + def __post_init__(self): + self.created_at = convert_datetime(self.created_at) + self.updated_at = convert_datetime(self.updated_at) + + +@dataclass(slots=True) +class Question: + """The class "Question" contains various attributes such as id, correct and incorrect answers, image + URLs, description, and creation date.""" + + id: int + correct_answer: str + incorrect_answers: list[str] + image_upload_id: int # assuming data types based off name + image_small_url: str # assuming data types based off name + image_xsmall_url: str # assuming data types based off name + image_large_url: str # assuming data types based off name + image_file_name: str # assuming data types based off name + description: str + created_at: datetime + position: int + + +@dataclass(slots=True) +class Quiz(DetailedTask): + """The Quiz class represents a quiz with various properties and methods, including the ability to + retrieve a specific question by its ID.""" + + completed: bool + questions_time_limit: int + random_order: bool + max_attempts: int + answered_by_students: bool + questions: list[Question] + submission_method_id: int # which attempt it is + submission_ids: list[int] + question_ids: list = field(default_factory=list) + + def get_question(self, question_id: int) -> Question: + for question in self.questions: + if question_id == question.id: + return question + + +@dataclass(slots=True) +class ClassTest(DetailedTask): + pass + + +@dataclass(slots=True) +class FlexibleTask(DetailedTask): + pass + + +@dataclass(slots=True) +class Classwork(DetailedTask): + pass + + +@dataclass(slots=True) +class Praise: + """The class "Praise" contains attributes related to a kudos event, including the staff member + involved, the reason for the kudos, and the date it occurred.""" + + id: int + points: int + academic_year_id: int + staff_member_id: int + kudos_reason_id: int + description: str + kudos_event_id: int + created_at: datetime + updated_at: datetime + deleted_at: datetime + staff_member_title: str + staff_member_forename: str + staff_member_surname: str + comments: str + positive: bool + source_id: str + happened_on: str + serious_incident: bool + full_name: str = field(default_factory=str, init=False) + + def __post_init__(self): + self.created_at = convert_datetime(self.created_at) + self.updated_at = convert_datetime(self.updated_at) + self.deleted_at = convert_datetime(self.deleted_at) + self.full_name: str = f"{self.staff_member_title}. {self.staff_member_forename} {self.staff_member_surname}" + + +@dataclass(slots=True) +class PraiseSummary: + """The class "PraiseSummary" contains attributes related to positive and negative feedback counts for a + student, including totals, monthly, weekly, and daily counts.""" + + id: int + student_id: int + total_positive_count: int + total_negative_count: int + total_count: int + month_positive_count: int + month_negative_count: int + month_count: int + week_positive_count: int + week_negative_count: int + week_count: int + day_count: int + day_positive_count: int + day_negative_count: int + + +@dataclass(slots=True) +class Behaviour: + """The class "Behaviour" contains lists of student praises and badges, as well as a summary of student + praises.""" + + student_praises: list[Praise] + student_badges: list + student_praise_summary: PraiseSummary + + +@dataclass(slots=True) +class TimetableClassGroup(BaseSubject): + subject: str + + +@dataclass(slots=True) +class TimetablePeriod: + startDateTime: datetime + endDateTime: datetime + utcStartTime: datetime + utcEndTime: datetime + session: str + + def __post_init__(self): + self.startDateTime = convert_datetime(self.startDateTime) + self.endDateTime = convert_datetime(self.endDateTime) + self.utcStartTime = convert_datetime(self.utcStartTime) + self.utcEndTime = convert_datetime(self.utcEndTime) + + +@dataclass(slots=True) +class TimetableHomework: + id: int + title: str + type: str + + +@dataclass(slots=True) +class TimetableTeacher: + title: str + forename: str + surname: str + + full_name: str = field(default_factory=str, init=False) + + def __post_init__(self): + self.full_name: str = f"{self.title}. {self.forename} {self.surname}" + + +@dataclass(slots=True) +class TimetableLesson: + id: int + url: str + classGroup: TimetableClassGroup + period: TimetablePeriod + room: str + teacher: TimetableTeacher + dueClassTasks: list[TimetableHomework] + + +@dataclass(slots=True) +class TimetableDay: + order: int + date: datetime + lessons: list[TimetableLesson] + registration_group: str + detentions: list[Any] + + def __post_init__(self): + self.date = datetime.strptime(self.date, "%Y-%m-%d") + + +@dataclass(slots=True) +class Timetable: + order: int + startDate: datetime + prevWeekStartDate: datetime + days: list[TimetableDay] + + def __post_init__(self): + self.startDate = datetime.strptime(self.startDate, "%Y-%m-%d") + self.prevWeekStartDate = datetime.strptime(self.prevWeekStartDate, "%Y-%m-%d") + + +@dataclass(slots=True) +class TimetableInterface: + numWeeks: int + earliestRequestDate: datetime + latestRequestDate: datetime + requestDate: datetime + firstDayOfWeekDate: datetime + weeks: list[Timetable] + + def __post_init__(self): + self.earliestRequestDate = datetime.strptime( + self.earliestRequestDate, "%Y-%m-%d" + ) + self.latestRequestDate = datetime.strptime(self.latestRequestDate, "%Y-%m-%d") + self.requestDate = datetime.strptime(self.requestDate, "%Y-%m-%d") + self.firstDayOfWeekDate = datetime.strptime(self.firstDayOfWeekDate, "%Y-%m-%d") + + +@dataclass(slots=True) +class Todo: + """The Todo class contains all tasks and categorizes tasks into different types such as homework, quiz, test, classwork, and + flexible tasks.""" + + tasks: list[Task] = field(default_factory=list) + homework: list[Task] = field(default_factory=list) + quiz: list[Task] = field(default_factory=list) + test: list[Task] = field(default_factory=list) + classwork: list[Task] = field(default_factory=list) + flexible_task: list[Task] = field(default_factory=list) + + def categorize(self): + """ + This function categorizes tasks based on their type and appends them to their respective lists. + + (This should not be run more than once as it may cause the catagories to have duplicate tasks!) + """ + for task in self.tasks: + if task.class_task_type == TaskTypes.HOMEWORK: + self.homework.append(task) + elif task.class_task_type == TaskTypes.QUIZ: + self.quiz.append(task) + elif task.class_task_type == TaskTypes.CLASSTEST: + self.test.append(task) + elif task.class_task_type == TaskTypes.CLASSWORK: + self.classwork.append(task) + elif task.class_task_type == TaskTypes.FLEXIBLETASK: + self.flexible_task.append(task) + else: + logger.info(f"Task could not be categorized! ({task.class_task_type})") + + +def make_todo(raw_tasks: list[dict]) -> Todo: + """ + The function takes a list of dictionaries representing tasks, creates Task objects from them, adds + them to a Todo object, categorizes the tasks, and returns the Todo object. + + Args: + raw_tasks (list[dict]): A list of dictionaries representing raw task data. Each dictionary should + contain information about a single task, such as its title, description, due date, and priority + level. + + Returns: + The function `make_todo` is returning an instance of the `Todo` class. + """ + td = Todo() + for task in raw_tasks: + td.tasks.append(Create.instantiate(Task, task)) + td.categorize() + return td diff --git a/src/smhw_api/requirements.txt b/src/smhw_api/requirements.txt new file mode 100644 index 0000000..ca5db48 --- /dev/null +++ b/src/smhw_api/requirements.txt @@ -0,0 +1,17 @@ +anyio==3.7.0 +attr==0.3.2 +attrs==23.1.0 +certifi==2023.5.7 +h11==0.14.0 +h2==4.1.0 +hpack==4.0.0 +httpcore==0.17.2 +httpx==0.24.1 +hyperframe==6.0.1 +idna==3.4 +iniconfig==2.0.0 +loguru==0.7.0 +packaging==23.1 +pluggy==1.2.0 +pytest==7.4.0 +sniffio==1.3.0 diff --git a/src/smhw_api/skeleton.py b/src/smhw_api/skeleton.py deleted file mode 100644 index 9da156f..0000000 --- a/src/smhw_api/skeleton.py +++ /dev/null @@ -1,149 +0,0 @@ -""" -This is a skeleton file that can serve as a starting point for a Python -console script. To run this script uncomment the following lines in the -``[options.entry_points]`` section in ``setup.cfg``:: - - console_scripts = - fibonacci = smhw_api.skeleton:run - -Then run ``pip install .`` (or ``pip install -e .`` for editable mode) -which will install the command ``fibonacci`` inside your current environment. - -Besides console scripts, the header (i.e. until ``_logger``...) of this file can -also be used as template for Python modules. - -Note: - This file can be renamed depending on your needs or safely removed if not needed. - -References: - - https://setuptools.pypa.io/en/latest/userguide/entry_point.html - - https://pip.pypa.io/en/stable/reference/pip_install -""" - -import argparse -import logging -import sys - -from smhw_api import __version__ - -__author__ = "EpicGamerCodes" -__copyright__ = "EpicGamerCodes" -__license__ = "MIT" - -_logger = logging.getLogger(__name__) - - -# ---- Python API ---- -# The functions defined in this section can be imported by users in their -# Python scripts/interactive interpreter, e.g. via -# `from smhw_api.skeleton import fib`, -# when using this Python module as a library. - - -def fib(n): - """Fibonacci example function - - Args: - n (int): integer - - Returns: - int: n-th Fibonacci number - """ - assert n > 0 - a, b = 1, 1 - for _i in range(n - 1): - a, b = b, a + b - return a - - -# ---- CLI ---- -# The functions defined in this section are wrappers around the main Python -# API allowing them to be called directly from the terminal as a CLI -# executable/script. - - -def parse_args(args): - """Parse command line parameters - - Args: - args (List[str]): command line parameters as list of strings - (for example ``["--help"]``). - - Returns: - :obj:`argparse.Namespace`: command line parameters namespace - """ - parser = argparse.ArgumentParser(description="Just a Fibonacci demonstration") - parser.add_argument( - "--version", - action="version", - version=f"smhw-api {__version__}", - ) - parser.add_argument(dest="n", help="n-th Fibonacci number", type=int, metavar="INT") - parser.add_argument( - "-v", - "--verbose", - dest="loglevel", - help="set loglevel to INFO", - action="store_const", - const=logging.INFO, - ) - parser.add_argument( - "-vv", - "--very-verbose", - dest="loglevel", - help="set loglevel to DEBUG", - action="store_const", - const=logging.DEBUG, - ) - return parser.parse_args(args) - - -def setup_logging(loglevel): - """Setup basic logging - - Args: - loglevel (int): minimum loglevel for emitting messages - """ - logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" - logging.basicConfig( - level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S" - ) - - -def main(args): - """Wrapper allowing :func:`fib` to be called with string arguments in a CLI fashion - - Instead of returning the value from :func:`fib`, it prints the result to the - ``stdout`` in a nicely formatted message. - - Args: - args (List[str]): command line parameters as list of strings - (for example ``["--verbose", "42"]``). - """ - args = parse_args(args) - setup_logging(args.loglevel) - _logger.debug("Starting crazy calculations...") - print(f"The {args.n}-th Fibonacci number is {fib(args.n)}") - _logger.info("Script ends here") - - -def run(): - """Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv` - - This function can be used as entry point to create console scripts with setuptools. - """ - main(sys.argv[1:]) - - -if __name__ == "__main__": - # ^ This is a guard statement that will prevent the following code from - # being executed in the case someone imports this file instead of - # executing it as a script. - # https://docs.python.org/3/library/__main__.html - - # After installing your project with pip, users can also run your Python - # modules as scripts via the ``-m`` flag, as defined in PEP 338:: - # - # python -m smhw_api.skeleton 42 - # - run() diff --git a/tests/test_skeleton.py b/tests/test_skeleton.py index 1fcd85c..1eedd80 100644 --- a/tests/test_skeleton.py +++ b/tests/test_skeleton.py @@ -1,25 +1,13 @@ import pytest -from smhw_api.skeleton import fib, main +import smhw_api as api __author__ = "EpicGamerCodes" __copyright__ = "EpicGamerCodes" -__license__ = "MIT" +__license__ = "GPL-3.0-or-later" -def test_fib(): +def test_server(): """API Tests""" - assert fib(1) == 1 - assert fib(2) == 1 - assert fib(7) == 13 - with pytest.raises(AssertionError): - fib(-10) - - -def test_main(capsys): - """CLI Tests""" - # capsys is a pytest fixture that allows asserts against stdout/stderr - # https://docs.pytest.org/en/stable/capture.html - main(["7"]) - captured = capsys.readouterr() - assert "The 7-th Fibonacci number is 13" in captured.out + with pytest.raises(api.exceptions.InvalidAuth): + api.Server("Should fail - Test Auth", 0, 0)