├── .github └── workflows │ ├── pull_request.yml │ └── push.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── docs ├── .gitignore ├── Makefile ├── _static │ └── .gitkeep ├── _templates │ ├── .gitkeep │ ├── autosummary │ │ ├── class.rst │ │ ├── exception.rst │ │ └── module.rst │ └── versioning.html ├── conf.py ├── index.rst ├── make.bat └── redirect.html ├── mycqu ├── __init__.py ├── _lib_wrapper │ ├── __init__.py │ ├── dataclass.py │ └── encrypt.py ├── auth.py ├── card.py ├── course.py ├── exam.py ├── mycqu.py ├── score.py ├── user.py └── utils │ ├── __init__.py │ └── datetimes.py ├── mypy.ini └── pyproject.toml /.github/workflows/pull_request.yml: -------------------------------------------------------------------------------- 1 | name: "Pull Request Docs Check" 2 | on: 3 | - pull_request 4 | 5 | jobs: 6 | docs: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | - uses: Hagb/sphinx-action@master 11 | with: 12 | docs-folder: "docs/" 13 | -------------------------------------------------------------------------------- /.github/workflows/push.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - dev 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - run: git branch --track dev origin/dev && git branch --track master origin/master 17 | # Standard drop-in approach that should work for most people. 18 | - uses: Hagb/sphinx-action@master 19 | with: 20 | docs-folder: "." 21 | build-command: "bash -c 'cd docs && git config --global --add safe.directory /github/workspace && sphinx-multiversion . _build 2> >(tee /tmp/sphinx-log >&2) && cp redirect.html _build/index.html'" 22 | pre-build-command: "pip install pycryptodome beautifulsoup4 sphinx-multiversion && apt-get update -y && apt-get install -y git" 23 | - name: Commit documentation changes 24 | run: | 25 | git clone https://github.com/$GITHUB_REPOSITORY.git --branch gh-pages --single-branch gh-pages 26 | find gh-pages/ -maxdepth 1 -mindepth 1 ! -name CNAME ! -name .git -exec rm -r '{}' ';' 27 | cp -r docs/_build/* gh-pages/ 28 | cd gh-pages 29 | touch .nojekyll 30 | git config --local user.email "action@github.com" 31 | git config --local user.name "GitHub Action" 32 | git add . 33 | git commit -m "Update documentation" -a || true 34 | # The above command will fail if no changes were present, so we ignore 35 | # that. 36 | - name: Push changes 37 | uses: ad-m/github-push-action@8407731efefc0d8f72af254c74276b7a90be36e1 38 | with: 39 | branch: gh-pages 40 | directory: gh-pages 41 | github_token: ${{ secrets.GITHUB_TOKEN }} 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | /poetry.lock 3 | /dist 4 | /.vscode 5 | /.*_cache 6 | /test.py 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pymycqu 2 | 3 | **由于作者毕业,本仓库不再维护,保留原样。您可以选用 [321CQU 团队维护的 pymycqu](https://github.com/321CQU/pymycqu) 或使用 Rust 开发的 [rsmycqu](https://github.com/321CQU/rsmycqu)。** 4 | 5 | 这个库对重庆大学 和统一身份认证的部分 web api 进行了封装,同时整理了相关数据模型。 6 | 7 | Work in progress... 欢迎反馈和补充 8 | 9 | 感谢 项目提供了 的登陆方式。 10 | 11 | ## 安装 12 | 13 | ```bash 14 | pip install mycqu 15 | ``` 16 | 17 | ## 例子及文档 18 | 19 | 见 . 20 | 21 | ## 许可 22 | 23 | AGPL 3.0 24 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | /_build/ 2 | /_stubs/ 3 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/_static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hagb/pymycqu/a5fbda092e9d88cd57183d72b04942512df29c13/docs/_static/.gitkeep -------------------------------------------------------------------------------- /docs/_templates/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hagb/pymycqu/a5fbda092e9d88cd57183d72b04942512df29c13/docs/_templates/.gitkeep -------------------------------------------------------------------------------- /docs/_templates/autosummary/class.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. currentmodule:: {{ module }} 4 | 5 | .. autoclass:: {{ objname }} 6 | :members: 7 | 8 | {% block methods %} 9 | {% if methods %} 10 | .. rubric:: {{ _('Methods') }} 11 | 12 | .. autosummary:: 13 | {% for item in methods %} 14 | ~{{ name }}.{{ item }} 15 | {%- endfor %} 16 | {% endif %} 17 | {% endblock %} 18 | 19 | {% block attributes %} 20 | {% if attributes %} 21 | .. rubric:: {{ _('Attributes') }} 22 | 23 | .. autosummary:: 24 | {% for item in attributes %} 25 | ~{{ name }}.{{ item }} 26 | {%- endfor %} 27 | {% endif %} 28 | {% endblock %} 29 | 30 | .. rubric:: {{ _('Details') }} 31 | 32 | -------------------------------------------------------------------------------- /docs/_templates/autosummary/exception.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. currentmodule:: {{ module }} 4 | 5 | .. autoclass:: {{ objname }} 6 | :members: 7 | 8 | -------------------------------------------------------------------------------- /docs/_templates/autosummary/module.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. automodule:: {{ fullname }} 4 | 5 | {% block attributes %} 6 | {% if attributes %} 7 | .. rubric:: {{ _('Module Attributes') }} 8 | 9 | .. autosummary:: 10 | :toctree: 11 | {% for item in attributes %} 12 | {{ item }} 13 | {%- endfor %} 14 | {% endif %} 15 | {% endblock %} 16 | 17 | {% block functions %} 18 | {% if functions %} 19 | .. rubric:: {{ _('Functions') }} 20 | 21 | .. autosummary:: 22 | :toctree: 23 | {% for item in functions %} 24 | {{ item }} 25 | {%- endfor %} 26 | {% endif %} 27 | {% endblock %} 28 | 29 | {% block classes %} 30 | {% if classes %} 31 | .. rubric:: {{ _('Classes') }} 32 | 33 | .. autosummary:: 34 | :toctree: 35 | {% for item in classes %} 36 | {{ item }} 37 | {%- endfor %} 38 | {% endif %} 39 | {% endblock %} 40 | 41 | {% block exceptions %} 42 | {% if exceptions %} 43 | .. rubric:: {{ _('Exceptions') }} 44 | 45 | .. autosummary:: 46 | :template: autosummary/exception.rst 47 | :toctree: 48 | 49 | {% for item in exceptions %} 50 | {{ item }} 51 | {%- endfor %} 52 | {% endif %} 53 | {% endblock %} 54 | 55 | {% block modules %} 56 | {% if modules %} 57 | .. rubric:: Modules 58 | 59 | .. autosummary:: 60 | :toctree: 61 | :recursive: 62 | {% for item in modules %} 63 | {{ item }} 64 | {%- endfor %} 65 | {% endif %} 66 | {% endblock %} 67 | -------------------------------------------------------------------------------- /docs/_templates/versioning.html: -------------------------------------------------------------------------------- 1 | {% if versions %} 2 |

{{ _('Versions') }}

3 |
    4 | {%- for item in versions|reverse %} 5 |
  • {{ item.name }}
  • 6 | {%- endfor %} 7 |
8 | {% endif %} 9 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | import pkg_resources 16 | import subprocess 17 | import sphinx_multiversion 18 | sys.path.insert(0, os.path.abspath('..')) 19 | 20 | 21 | # -- Project information ----------------------------------------------------- 22 | 23 | project = 'pymycqu' 24 | copyright = '2021, Hagb' 25 | author = 'Hagb' 26 | # The full version, including alpha/beta/rc tags 27 | 28 | # -- General configuration --------------------------------------------------- 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | 34 | extensions = ["sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx_multiversion"] 35 | html_sidebars = {'**': ['localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html', 'versioning.html']} 36 | 37 | if not hasattr(sphinx_multiversion.sphinx, "config_inited_hooked"): 38 | old_config_inited = sphinx_multiversion.sphinx.config_inited 39 | def config_inited(app, config): 40 | old_config_inited(app, config) 41 | config.release = config.smv_current_version 42 | sphinx_multiversion.sphinx.config_inited = config_inited 43 | sphinx_multiversion.sphinx.config_inited_hooked = True 44 | 45 | smv_tag_whitelist = r'^v\d+.*$' 46 | smv_branch_whitelist = r'^master|dev$' 47 | smv_remote_whitelist = None 48 | 49 | #autodoc_default_flags = ['members', 'attributes'] 50 | autosummary_generate = True 51 | autosummary_ignore_module_all = False 52 | #autosummary_imported_members = True 53 | # Add any paths that contain templates here, relative to this directory. 54 | templates_path = ['_templates'] 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | # 59 | # This is also used if you do content translation via gettext catalogs. 60 | # Usually you set "language" from the command line for these cases. 61 | language = 'zh_CN' 62 | 63 | # List of patterns, relative to source directory, that match files and 64 | # directories to ignore when looking for source files. 65 | # This pattern also affects html_static_path and html_extra_path. 66 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 67 | 68 | 69 | # -- Options for HTML output ------------------------------------------------- 70 | 71 | # The theme to use for HTML and HTML Help pages. See the documentation for 72 | # a list of builtin themes. 73 | # 74 | #html_theme = 'alabaster' 75 | html_theme = "classic" 76 | # Add any paths that contain custom static files (such as style sheets) here, 77 | # relative to this directory. They are copied after the builtin static files, 78 | # so a file named "default.css" will overwrite the builtin "default.css". 79 | html_static_path = ['_static'] 80 | 81 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. pymycqu documentation master file, created by 2 | sphinx-quickstart on Tue Nov 30 12:43:54 2021. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | 开始 7 | ==== 8 | 9 | **由于作者毕业,本仓库不再维护,保留原样。** 您可以选用 `321CQU 团队维护的 pymycqu `__ 或使用 Rust 开发的 `rsmycqu `__ 。 10 | 11 | 12 | 安装 13 | ---- 14 | 15 | .. code-block:: shell 16 | 17 | pip install mycqu 18 | 19 | 考表 20 | ---- 21 | 22 | 获取考表的例子,主要使用了 :py:func:`mycqu.exam.Exam.fetch` 方法从 23 | https://my.cqu.edu.cn 上获取考试数据并生成 :py:class:`mycqu.exam.Exam` 对象: 24 | 25 | .. code-block:: python 26 | 27 | from mycqu.exam import Exam 28 | from datetime import date 29 | exams = Exam.fetch("201xxxxx") # 获取学号 201xxxxx 的本学期考表,返回 Exam 对象的列表 30 | today = date.today() 31 | print("之后的考试:") 32 | for exam in exams: 33 | if exam.date >= today: 34 | print(f'科目:{exam.course.name}, 教室:{exam.room}, ' 35 | f'时间: {exam.date.strftime("%Y-%m-%d")} {exam.start_time.strftime("%H:%M")}') 36 | 37 | 输出样例: 38 | 39 | .. code-block:: 40 | 41 | 之后的考试: 42 | 科目:图像处理中的数学方法, 教室:d1242, 时间: 2021-12-06 14:25 43 | 44 | 课表 45 | ---- 46 | 47 | 与考表不同的是,获取课表等数据需要先进行登录: 48 | 49 | * 如果同一帐号连续尝试三次使用错误密码登录, 50 | 那么再次登录时还需要输入二维码,此时 :py:func:`mycqu.auth.login` 会抛出 51 | :py:class:`mycqu.auth.NeedCaptcha` 异常,捕获它之后可以获取验证图片,输入验证码后继续登录 52 | 53 | * 在统一身份认证号登录后还需要给 my.cqu.edu.cn 进行授权认证,使用 :py:func:`mycqu.mycqu.access_mycqu` 54 | 55 | .. code-block:: python 56 | 57 | from mycqu.auth import login, NeedCaptcha 58 | from mycqu.mycqu import access_mycqu 59 | from requests import Session 60 | 61 | session = Session() 62 | try: 63 | login(session, "统一身份认证号", "统一身份认证密码") # 需要登陆 64 | except NeedCaptcha as e: # 需要输入验证码的情况 65 | with open("captcha.jpg", "wb") as file: 66 | file.write(e.image) 67 | print("输入 captcha.jpg 处的验证码并回车: ", end="") 68 | e.after_captcha(input()) 69 | access_mycqu(session) 70 | 71 | 之后就可以拿 ``session`` 去获取课表了,下面的代码用 :py:func:`mycqu.course.CourseTimetable.fetch` 72 | 获取了整个学期的课表,并从中筛选出第九周的课表 73 | 74 | .. code-block:: python 75 | 76 | timetables = CourseTimetable.fetch(session, "201xxxxx") # 获取学号 201xxxxx 的本学期课表 77 | week = 9 78 | print(f"第 {week} 周的课") 79 | weekdays = ["一", "二", "三", "四", "五", "六", "日"] 80 | for timetable in timetables: 81 | for start, end in timetable.weeks: 82 | if start <= week <= end: 83 | break 84 | else: 85 | continue 86 | if timetable.day_time: 87 | print(f"科目:{timetable.course.name}, 教室:{timetable.classroom}, " 88 | f"周{weekdays[timetable.day_time.weekday]} {timetable.day_time.period[0]}~{timetable.day_time.period[1]} 节课") 89 | elif timetable.whole_week: 90 | print(f"科目:{timetable.course.name}, 地点: {timetable.classroom}, 全周时间") 91 | else: 92 | print(f"科目:{timetable.course.name}, 无明确时间") 93 | 94 | 输出样例: 95 | 96 | .. code-block:: 97 | 98 | 第 9 周的课 99 | 科目:偏微分方程, 教室:d1339, 周三 3~4 节课 100 | 科目:偏微分方程, 教室:d1339, 周一 1~2 节课 101 | 科目:复变函数, 教室:d1335, 周四 3~4 节课 102 | 科目:复变函数, 教室:d1335, 周二 6~7 节课 103 | 科目:运筹学, 教室:d1337, 周二 1~2 节课 104 | 科目:运筹学, 教室:dyc410, 周五 1~2 节课 105 | 科目:图像处理中的数学方法, 教室:d1329, 周三 6~7 节课 106 | 科目:图像处理中的数学方法, 教室:d1329, 周一 6~7 节课 107 | 科目:数据结构, 教室:d1339, 周二 10~11 节课 108 | 科目:数据结构, 教室:d1142, 周一 3~4 节课 109 | 科目:数据结构, 教室:数学实验中心, 周四 6~9 节课 110 | 科目:java程序设计, 教室:d1518, 周三 1~2 节课 111 | 科目:java程序设计, 教室:d1518, 周五 3~4 节课 112 | 113 | Indices and tables 114 | ================== 115 | 116 | * :ref:`genindex` 117 | * :ref:`modindex` 118 | * :ref:`search` 119 | 120 | API 文档 121 | ======== 122 | 123 | .. autosummary:: 124 | :toctree: _stubs 125 | :recursive: 126 | 127 | mycqu.auth 128 | mycqu.course 129 | mycqu.exam 130 | mycqu.mycqu 131 | mycqu.score 132 | mycqu.user 133 | 134 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.https://www.sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/redirect.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Redirecting to master/ 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /mycqu/__init__.py: -------------------------------------------------------------------------------- 1 | from . import auth, course, exam, mycqu, score 2 | __all__ = ("auth", "course", "exam", "mycqu", "user", "score") 3 | -------------------------------------------------------------------------------- /mycqu/_lib_wrapper/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hagb/pymycqu/a5fbda092e9d88cd57183d72b04942512df29c13/mycqu/_lib_wrapper/__init__.py -------------------------------------------------------------------------------- /mycqu/_lib_wrapper/dataclass.py: -------------------------------------------------------------------------------- 1 | """A workaround to make auto-completion work for dataclass of pydantic 2 | 3 | https://github.com/samuelcolvin/pydantic/issues/650#issuecomment-709945440 4 | """ 5 | 6 | from typing import TYPE_CHECKING 7 | 8 | # Trick 9 | if TYPE_CHECKING: 10 | from dataclasses import dataclass 11 | else: 12 | from pydantic.dataclasses import dataclass 13 | 14 | __all__ = ("dataclass",) 15 | -------------------------------------------------------------------------------- /mycqu/_lib_wrapper/encrypt.py: -------------------------------------------------------------------------------- 1 | """从两种模块不同的模块名字中加载加密模块 2 | """ 3 | from typing import Callable 4 | pad: Callable[[bytes], bytes] 5 | aes_cbc_encryptor: Callable[[bytes, bytes], Callable[[bytes], bytes]] 6 | aes_ecb_encryptor: Callable[[bytes], Callable[[bytes], bytes]] 7 | try: 8 | from Cryptodome.Cipher import AES as AES_ 9 | from Cryptodome.Util.Padding import pad as pad_ 10 | except (OSError, ImportError): 11 | try: 12 | from Crypto.Cipher import AES as AES__ 13 | from Crypto.Util.Padding import pad as pad__ 14 | except (OSError, ImportError): 15 | try: 16 | from pyaes.util import append_PKCS7_padding # type: ignore 17 | from pyaes import AESModeOfOperationCBC # type: ignore 18 | from pyaes import AESModeOfOperationECB 19 | 20 | def aes_cbc_encryptor(key, iv): 21 | encrypt = AESModeOfOperationCBC(key, iv).encrypt 22 | return lambda x: b''.join(encrypt(x[i: i+16]) for i in range(0, len(x), 16)) 23 | 24 | def aes_ecb_encryptor(key): 25 | encrypt = AESModeOfOperationECB(key).encrypt 26 | return lambda x: b''.join(encrypt(x[i: i+16]) for i in range(0, len(x), 16)) 27 | pad = append_PKCS7_padding 28 | except ImportError: 29 | raise ImportError( # pylint: ignore disable=raise-missing-from 30 | "Please install pyryptodome, pyryptodomex or pyaes") 31 | else: 32 | def pad(x): 33 | return pad__(x, 16, style='pkcs7') 34 | 35 | def aes_cbc_encryptor(key, iv): 36 | return AES__.new(key=key, iv=iv, mode=AES__.MODE_CBC).encrypt 37 | 38 | def aes_ecb_encryptor(key): 39 | return AES__.new(key, AES__.MODE_ECB).encrypt 40 | else: 41 | def pad(x): 42 | return pad_(x, 16, style='pkcs7') 43 | 44 | def aes_cbc_encryptor(key, iv): 45 | return AES_.new(key=key, iv=iv, mode=AES_.MODE_CBC).encrypt 46 | 47 | def aes_ecb_encryptor(key): 48 | return AES_.new(key, AES_.MODE_ECB).encrypt 49 | 50 | __all__ = ("aes_cbc_encryptor", "aes_ecb_encryptor", "pad") 51 | -------------------------------------------------------------------------------- /mycqu/auth.py: -------------------------------------------------------------------------------- 1 | """统一身份认证相关的模块 2 | """ 3 | from typing import Dict, Optional, Callable 4 | import random 5 | import re 6 | from base64 import b64encode 7 | from html.parser import HTMLParser 8 | from urllib.parse import parse_qs, urlsplit 9 | from requests import Session, Response, cookies 10 | from ._lib_wrapper.encrypt import pad, aes_cbc_encryptor 11 | 12 | __all__ = ("NotAllowedService", "NeedCaptcha", "InvaildCaptcha", 13 | "IncorrectLoginCredentials", "UnknownAuthserverException", "NotLogined", 14 | "is_logined", "logout", "access_service", "access_sso_service", "login") 15 | 16 | AUTHSERVER_URL = "http://authserver.cqu.edu.cn/authserver/login" 17 | AUTHSERVER_CAPTCHA_DETERMINE_URL = "http://authserver.cqu.edu.cn/authserver/needCaptcha.html" 18 | AUTHSERVER_CAPTCHA_IMAGE_URL = "http://authserver.cqu.edu.cn/authserver/captcha.html" 19 | AUTHSERVER_LOGOUT_URL = "http://authserver.cqu.edu.cn/authserver/logout" 20 | SSO_LOGIN_URL = "https://sso.cqu.edu.cn/login" 21 | _CHAR_SET = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' 22 | 23 | 24 | def _random_str(length: int): 25 | return ''.join(random.choices(_CHAR_SET, k=length)) 26 | 27 | 28 | class NotAllowedService(Exception): 29 | """试图认证不允许的服务时抛出 30 | """ 31 | 32 | 33 | class NeedCaptcha(Exception): 34 | """登录统一身份认证时需要输入验证码时拋出 35 | """ 36 | 37 | def __init__(self, image: bytes, image_type: str, after_captcha: Callable[[str], Response]): 38 | super().__init__("captcha is needed") 39 | self.image: bytes = image 40 | """验证码图片文件数据""" 41 | self.image_type: str = image_type 42 | """验证码图片 MIME 类型""" 43 | self.after_captcha: Callable[[str], Response] = after_captcha 44 | """将验证码传入,调用以继续进行登陆""" 45 | 46 | 47 | class InvaildCaptcha(Exception): 48 | """登录统一身份认证输入了无效验证码时抛出 49 | """ 50 | 51 | def __init__(self): 52 | super().__init__("invaild captcha") 53 | 54 | 55 | class IncorrectLoginCredentials(Exception): 56 | """使用无效的的登录凭据(如错误的用户、密码) 57 | """ 58 | 59 | def __init__(self): 60 | super().__init__("incorrect username or password") 61 | 62 | 63 | class UnknownAuthserverException(Exception): 64 | """登录或认证服务过程中未知错误 65 | """ 66 | 67 | 68 | class NotLogined(Exception): 69 | """未登陆或登陆过期的会话被用于进行需要统一身份认证登陆的操作 70 | """ 71 | 72 | def __init__(self): 73 | super().__init__("not in logined status") 74 | 75 | 76 | class MultiSessionConflict(Exception): 77 | """当前用户启用单处登录,并且存在其他登录会话时抛出""" 78 | 79 | def __init__(self, kick: Callable[[], Response], cancel: Callable[[], Response]): 80 | super().__init__("单处登录 enabled, kick other sessions of the user or cancel") 81 | self.kick: Callable[[], Response] = kick 82 | """踢掉其他会话并登录""" 83 | self.cancel: Callable[[], Response] = cancel 84 | """取消登录""" 85 | 86 | 87 | class AuthPageParser(HTMLParser): 88 | _SALT_RE: re.Pattern = re.compile('var pwdDefaultEncryptSalt = "([^"]+)"') 89 | 90 | def __init__(self): 91 | super().__init__() 92 | self.input_data: Dict[str, Optional[str]] = \ 93 | {'lt': None, 'dllt': None, 94 | 'execution': None, '_eventId': None, 'rmShown': None} 95 | """几个关键的标签数据""" 96 | self.salt: Optional[str] = None 97 | """加密所用的盐""" 98 | self._js_start: bool = False 99 | self._js_end: bool = False 100 | self._error: bool = False 101 | self._error_head: bool = False 102 | 103 | def handle_starttag(self, tag, attrs): 104 | if tag == 'input': 105 | name: Optional[str] = None 106 | value: Optional[str] = None 107 | for attr in attrs: 108 | if attr[0] == 'name': 109 | if attr[1] in self.input_data: 110 | name = attr[1] 111 | else: 112 | break 113 | elif attr[0] == 'value': 114 | value = attr[1] 115 | if name: 116 | self.input_data[name] = value 117 | elif tag == 'script' and attrs and attrs[0] == ("type", "text/javascript"): 118 | self._js_start = True 119 | elif tag == "div" and attrs == [("id", "msg"), ("class", "errors")]: 120 | self._error = True 121 | elif tag == 'h2' and self._error: 122 | self._error_head = True 123 | 124 | def handle_data(self, data): 125 | if self._js_start and not self._js_end: 126 | match = self._SALT_RE.search(data) 127 | if match: 128 | self.salt = match[1] 129 | self._js_end = True 130 | elif self._error_head: 131 | error_str = data.strip() 132 | if error_str == "应用未注册": 133 | raise NotAllowedService(error_str) 134 | raise UnknownAuthserverException( 135 | "Error message before login: "+error_str) 136 | 137 | 138 | class LoginedPageParser(HTMLParser): # pylint: ignore disable=missing-class-docstring 139 | MSG_ATTRS = [("id", "msg"), ("class", "login_auth_error")] 140 | KICK_TABLE_ATTRS = [("class", "kick_table")] 141 | KICK_POST_ATTRS = [('method', 'post'), ('id', 'continue')] 142 | CANCEL_POST_ATTRS = [('method', 'post'), ('id', 'cancel')] 143 | 144 | def __init__(self, status_code: int): 145 | super().__init__() 146 | self._msg: bool = False 147 | self._kick: bool = False 148 | self._waiting_kick_excution: bool = False 149 | self._kick_execution: str = "" 150 | self._waiting_cancel_excution: bool = False 151 | self._cancel_execution: str = "" 152 | self.status_code: int = status_code 153 | 154 | def handle_starttag(self, tag, attrs): 155 | if tag == "span" and attrs == self.MSG_ATTRS: 156 | self._msg = True 157 | elif tag == "table" and attrs == self.KICK_TABLE_ATTRS: 158 | self._kick = True 159 | elif tag == "form" and attrs == self.CANCEL_POST_ATTRS: 160 | self._waiting_cancel_excution = True 161 | elif tag == "form" and attrs == self.KICK_POST_ATTRS: 162 | self._waiting_kick_excution = True 163 | elif tag == "input" and ("name", "execution") in attrs: 164 | if self._waiting_kick_excution: 165 | for key, value in attrs: 166 | if key == "value": 167 | self._kick_execution = value 168 | self._waiting_kick_excution = False 169 | elif self._waiting_cancel_excution: 170 | for key, value in attrs: 171 | if key == "value": 172 | self._cancel_execution = value 173 | self._waiting_cancel_excution = False 174 | 175 | def handle_data(self, data): 176 | if self._msg: 177 | error_str = data.strip() 178 | if error_str == "无效的验证码": 179 | raise InvaildCaptcha() 180 | elif error_str == "您提供的用户名或者密码有误": 181 | raise IncorrectLoginCredentials() 182 | else: 183 | raise UnknownAuthserverException( 184 | f"status code {self.status_code} is got (302 expected)" 185 | f" when sending login post, {error_str}" 186 | ) 187 | 188 | 189 | def get_formdata(html: str, username: str, password: str) -> Dict[str, Optional[str]]: 190 | # from https://github.com/CQULHW/CQUQueryGrade 191 | parser = AuthPageParser() 192 | parser.feed(html) 193 | if not parser.salt: 194 | ValueError("无法获取盐") 195 | passwd_pkcs7 = pad((_random_str(64)+str(password)).encode()) 196 | encryptor = aes_cbc_encryptor( 197 | parser.salt.encode(), _random_str(16).encode()) 198 | passwd_encrypted = b64encode(encryptor(passwd_pkcs7)).decode() 199 | parser.input_data['username'] = username 200 | parser.input_data['password'] = passwd_encrypted 201 | return parser.input_data 202 | 203 | 204 | def is_logined(session: Session) -> bool: 205 | """判断是否处于统一身份认证登陆状态 206 | 207 | :param session: 会话 208 | :type session: Session 209 | :return: :obj:`True` 如果处于登陆状态,:obj:`False` 如果处于未登陆或登陆过期状态 210 | :rtype: bool 211 | """ 212 | return session.get(AUTHSERVER_URL, allow_redirects=False).status_code == 302 213 | 214 | 215 | def logout(session: Session) -> None: 216 | """注销统一身份认证登录状态 217 | 218 | :param session: 进行过登录的会话 219 | :type session: Session 220 | """ 221 | session.get("http://authserver.cqu.edu.cn/authserver/logout") 222 | 223 | 224 | def access_sso_service(session: Session, service: str) -> Response: 225 | class ArriveService(Exception): 226 | def __init__(self, response: Response): 227 | super().__init__() 228 | self.response: Response = response 229 | 230 | def response_hook(response: Response, *args, **kwargs): 231 | if response.url.startswith(SSO_LOGIN_URL) and response.status_code != 302: 232 | assert '
adapter
' in response.text 233 | response.headers['Location'] = './clientredirect?client_name=adapter' 234 | response.status_code = 302 235 | return response 236 | if response.url.startswith(AUTHSERVER_URL) and response.status_code != 302: 237 | raise NotLogined() 238 | if response.url.startswith(service): 239 | cookies.merge_cookies(session.cookies, response.cookies) 240 | raise ArriveService(response) 241 | 242 | try: 243 | assert not session.get(SSO_LOGIN_URL, 244 | params={"service": service}, 245 | allow_redirects=True, 246 | hooks={"response": response_hook} 247 | ) 248 | except ArriveService as arrive_service: 249 | return arrive_service.response 250 | 251 | 252 | def access_service(session: Session, service: str) -> Response: 253 | resp = session.get(AUTHSERVER_URL, 254 | params={"service": service}, 255 | allow_redirects=False) 256 | if resp.status_code != 302: 257 | AuthPageParser().feed(resp.text) 258 | raise NotLogined() 259 | return session.get(url=resp.headers['Location'], allow_redirects=False) 260 | 261 | 262 | def login(session: Session, 263 | username: str, 264 | password: str, 265 | service: Optional[str] = None, 266 | timeout: int = 10, 267 | force_relogin: bool = False, 268 | captcha_callback: Optional[ 269 | Callable[[bytes, str], Optional[str]]] = None, 270 | keep_longer: bool = False, 271 | kick_others: bool = False 272 | ) -> Response: 273 | """登录统一身份认证 274 | 275 | :param session: 用于登录统一身份认证的会话 276 | :type session: Session 277 | :param username: 统一身份认证号或学工号 278 | :type username: str 279 | :param password: 统一身份认证密码 280 | :type password: str 281 | :param service: 需要登录的服务,默认(:obj:`None`)则先不登陆任何服务 282 | :type service: Optional[str], optional 283 | :param timeout: 连接超时时限,默认为 10(单位秒) 284 | :type timeout: int, optional 285 | :param force_relogin: 强制重登,当会话中已经有有效的登陆 cookies 时依然重新登录,默认为 :obj:`False` 286 | :type force_relogin: bool, optional 287 | :param captcha_callback: 需要输入验证码时调用的回调函数,默认为 :obj:`None` 即不设置回调; 288 | 当需要输入验证码,但回调没有设置或回调返回 :obj:`None` 时,抛出异常 :class:`NeedCaptcha`; 289 | 该函数接受一个 :class:`bytes` 型参数为验证码图片的文件数据,一个 :class:`str` 型参数为图片的 MIME 类型, 290 | 返回验证码文本或 :obj:`None`。 291 | :type captcha_callback: Optional[Callable[[bytes, str], Optional[str]]], optional 292 | :param keep_longer: 保持更长时间的登录状态(保持一周) 293 | :type keep_longer: bool 294 | :param kick_others: 当目标用户开启了“单处登录”并有其他登录会话时,踢出其他会话并登录单前会话;若该参数为 :obj:`False` 则抛出 295 | :class:`MultiSessionConflict` 296 | :type kick_others: bool 297 | :raises UnknownAuthserverException: 未知认证错误 298 | :raises InvaildCaptcha: 无效的验证码 299 | :raises IncorrectLoginCredentials: 错误的登陆凭据(如错误的密码、用户名) 300 | :raises NeedCaptcha: 需要提供验证码,获得验证码文本之后可调用所抛出异常的 :func:`NeedCaptcha.after_captcha` 函数来继续登陆 301 | :raises MultiSessionConflict: 和其他会话冲突 302 | :return: 登陆了统一身份认证后所跳转到的地址的 :class:`Response` 303 | :rtype: Response 304 | """ 305 | def get_login_page(): 306 | return session.get( 307 | url=AUTHSERVER_URL, 308 | params=None if service is None else {"service": service}, 309 | allow_redirects=False, 310 | timeout=timeout) 311 | login_page = get_login_page() 312 | if login_page.status_code == 302: 313 | if not force_relogin: 314 | return login_page 315 | else: 316 | logout(session) 317 | login_page = get_login_page() 318 | elif login_page.status_code != 200: 319 | raise UnknownAuthserverException() 320 | try: 321 | formdata = get_formdata(login_page.text, username, password) 322 | except ValueError: 323 | logout(session) 324 | formdata = get_formdata(get_login_page().text, username, password) 325 | if keep_longer: 326 | formdata['rememberMe'] = 'on' 327 | 328 | def after_captcha(captcha_str: Optional[str]): 329 | if captcha_str is None: 330 | if "captchaResponse" in formdata: 331 | del formdata["captchaResponse"] 332 | else: 333 | formdata["captchaResponse"] = captcha_str 334 | login_resp = session.post( 335 | url=AUTHSERVER_URL, data=formdata, allow_redirects=False) 336 | 337 | def redirect_to_service(): 338 | return session.get(url=login_resp.headers['Location'], allow_redirects=False) 339 | 340 | if login_resp.status_code != 302: 341 | parser = LoginedPageParser(login_resp.status_code) 342 | parser.feed(login_resp.text) 343 | 344 | if parser._kick: # pylint: ignore disable=protected-access 345 | def kick(): 346 | nonlocal login_resp 347 | # pylint: ignore disable=protected-access 348 | login_resp = session.post( 349 | url=AUTHSERVER_URL, 350 | data={"execution": parser._kick_execution, 351 | "_eventId": "continue"}, 352 | allow_redirects=False, 353 | timeout=timeout) 354 | return redirect_to_service() 355 | 356 | if kick_others: 357 | return kick() 358 | else: 359 | def cancel(): 360 | # pylint: ignore disable=protected-access 361 | return session.post( 362 | url=AUTHSERVER_URL, 363 | data={"execution": parser._cancel_execution, 364 | "_eventId": "cancel"}, 365 | allow_redirects=False, 366 | timeout=timeout) 367 | raise MultiSessionConflict(kick=kick, cancel=cancel) 368 | raise UnknownAuthserverException( 369 | f"status code {login_resp.status_code} is got (302 expected) when sending login post, " 370 | "but can not find the element span.login_auth_error#msg") 371 | return redirect_to_service() 372 | 373 | captcha_str = None 374 | if session.get(AUTHSERVER_CAPTCHA_DETERMINE_URL, params={"username": username}).text == "true": 375 | captcha_img_resp = session.get(AUTHSERVER_CAPTCHA_IMAGE_URL) 376 | if captcha_callback is None: 377 | raise NeedCaptcha(captcha_img_resp.content, 378 | captcha_img_resp.headers["Content-Type"], 379 | after_captcha) 380 | captcha_str = captcha_callback( 381 | captcha_img_resp.content, captcha_img_resp.headers["Content-Type"]) 382 | if captcha_str is None: 383 | raise NeedCaptcha(captcha_img_resp.content, 384 | captcha_img_resp.headers["Content-Type"], 385 | after_captcha) 386 | return after_captcha(captcha_str) 387 | -------------------------------------------------------------------------------- /mycqu/card.py: -------------------------------------------------------------------------------- 1 | """ 2 | 校园卡余额、水电费查询相关模块 3 | """ 4 | from __future__ import annotations 5 | 6 | import requests 7 | from requests import Session 8 | import json 9 | from typing import Any, Dict, Optional, Tuple, List, Union, ClassVar 10 | from ._lib_wrapper.dataclass import dataclass 11 | from html.parser import HTMLParser 12 | 13 | __all__ = ("EnergyFees",) 14 | 15 | LOGIN_URL = 'http://authserver.cqu.edu.cn/authserver/login?service=http://card.cqu.edu.cn:7280/ias/prelogin?sysid=FWDT' 16 | 17 | # 缴费大厅页面的不同缴费项目的id不同,虎溪和老校区不同 18 | FEE_ITEM_ID = {'Huxi': '182', 19 | 'Old': '181'} 20 | 21 | 22 | class NetworkError(Exception): 23 | """ 24 | 当访问相关网页时statue code不为200时抛出 25 | """ 26 | 27 | 28 | class TicketGetError(Exception): 29 | """ 30 | 当未能从网页对应位置中获取到ticket时抛出 31 | """ 32 | 33 | 34 | class ParseError(Exception): 35 | """ 36 | 当从返回数据解析所需值失败时抛出 37 | """ 38 | 39 | 40 | class FeeAcquisitionFailed(Exception): 41 | """ 42 | 当网页获取水电费状态码不为success时抛出 43 | """ 44 | def __init__(self, error_msg): 45 | super().__init__("获取水电费发生异常,返回状态:" + error_msg) 46 | 47 | 48 | class CardPageParser(HTMLParser): 49 | def __init__(self): 50 | super().__init__() 51 | self._starttag: bool = False 52 | self.ssoticket_id: str = "" 53 | 54 | def handle_starttag(self, tag, attrs): 55 | if not self._starttag and tag == 'input' and ('name', 'ssoticketid') in attrs: 56 | self._starttag = True 57 | for key, val in attrs: 58 | if key == "value": 59 | self.ssoticket_id = val 60 | break 61 | 62 | 63 | def get_fees_info_raw(session: Session, isHuxi: bool, room: str): 64 | """ 从card.cqu.edu.cn获取水电费详情 65 | 66 | :param session: 登录了统一身份认证(:func:`.auth.login`)的 requests 会话 67 | :type session: Session 68 | :param isHuxi: 房间号是否为虎溪校区的房间 69 | :type isHuxi: bool 70 | :param room: 需要获取水电费详情的宿舍 71 | :type room: str 72 | :raises NetworkError: 当访问相关网页时statue code不为200时抛出 73 | :raises TicketGetError: 当未能从网页对应位置中获取到ticket时抛出 74 | :raises ParseError: 当从返回数据解析所需值失败时抛出 75 | :raises FeeAcquisitionFailed: 当网页获取水电费状态码不为success时抛出 76 | :return: 反序列化获取水电费信息的json 77 | :rtype: dict 78 | """ 79 | res = session.get(LOGIN_URL) 80 | 81 | # 获取ssoticketid 82 | parser = CardPageParser() 83 | parser.feed(res.text) 84 | ssoticket_id = parser.ssoticket_id 85 | get_hall_ticket(session, ssoticket_id) 86 | ticket = get_ticket(session) 87 | synjones_auth = get_synjones_auth(ticket) 88 | return get_fee_data(synjones_auth, room, FEE_ITEM_ID['Huxi'] if isHuxi else FEE_ITEM_ID['Old']) 89 | 90 | 91 | @dataclass 92 | class EnergyFees: 93 | """ 94 | 某宿舍的水电费相关信息 95 | """ 96 | balance: float 97 | """账户余额""" 98 | electricity_subsidy: float 99 | """电剩余补助""" 100 | water_subsidy: float 101 | """水剩余补助""" 102 | 103 | @staticmethod 104 | def from_dict(data: dict[str, Any]) -> EnergyFees: 105 | """从反序列化的(一个)水电费 json 中获取水电费信息 106 | 107 | :param data: json 反序列化得到的字典 108 | :type data: dict[str, Any] 109 | :return: 学期信息对象 110 | :rtype: EnergyFees 111 | """ 112 | return EnergyFees( 113 | balance=data["剩余金额"], 114 | electricity_subsidy=data["电剩余补助"], 115 | water_subsidy=data["水剩余补助"] 116 | ) 117 | 118 | @staticmethod 119 | def fetch(session: Session, isHuxi: bool, room: str) -> EnergyFees: 120 | """从 card.cqu.edu.cn 上获取当前水电费信息,需要登录了统一身份认证的会话 121 | 122 | :param session: 登录了统一身份认证(:func:`.auth.login`)的 requests 会话 123 | :type session: Session 124 | :raises NetworkError: 当访问相关网页时statue code不为200时抛出 125 | :raises TicketGetError: 当未能从网页对应位置中获取到ticket时抛出 126 | :raises ParseError: 当从返回数据解析所需值失败时抛出 127 | :raises FeeAcquisitionFailed: 当网页获取水电费状态码不为success时抛出 128 | :return: 返回相关宿舍的水电费信息 129 | :rtype: EnergyFees 130 | """ 131 | return EnergyFees.from_dict(get_fees_info_raw(session, isHuxi, room)["map"]["showData"]) 132 | 133 | 134 | # 获取hallticket 135 | def get_hall_ticket(session, ssoticket_id): 136 | url = 'http://card.cqu.edu.cn/cassyno/index' 137 | data = { 138 | 'errorcode': '1', 139 | 'continueurl': 'http://card.cqu.edu.cn/cassyno/index', 140 | 'ssoticketid': ssoticket_id, 141 | } 142 | r = session.post(url, data=data) 143 | if r.status_code != 200: 144 | raise NetworkError() 145 | return session 146 | 147 | 148 | # 利用登录之后的cookie获取一卡通的关键ticket 149 | def get_ticket(session): 150 | url = 'http://card.cqu.edu.cn/Page/Page' 151 | data = { 152 | 'EMenuName': '电费、网费', 153 | 'MenuName': '电费、网费', 154 | 'Url': 'http%3a%2f%2fcard.cqu.edu.cn%3a8080%2fblade-auth%2ftoken%2fthirdToToken%2ffwdt', 155 | 'apptype': '4', 156 | 'flowID': '10002' 157 | } 158 | r = session.post(url, data=data) 159 | if r.status_code != 200: 160 | raise NetworkError() 161 | ticket_start = r.text.find('ticket=') 162 | if ticket_start > 0: 163 | ticket_end = r.text.find("'", ticket_start) 164 | ticket = r.text[ticket_start + len('ticket='): ticket_end] 165 | return ticket 166 | else: 167 | raise TicketGetError() 168 | 169 | 170 | # 利用ticket获取一卡通关键cookie 171 | def get_synjones_auth(ticket): 172 | url = 'http://card.cqu.edu.cn:8080/blade-auth/token/fwdt' 173 | data = {'ticket': ticket} 174 | r = requests.post(url, data=data) 175 | if r.status_code != 200: 176 | raise NetworkError() 177 | try: 178 | dic = json.loads(r.text) 179 | token = dic['data']['access_token'] 180 | except: 181 | raise ParseError() 182 | else: 183 | return 'bearer ' + token 184 | 185 | 186 | # 利用关键cookie获取水电费dic 187 | def get_fee_data(synjones_auth, room, fee_item_id): 188 | url = "http://card.cqu.edu.cn:8080/charge/feeitem/getThirdData" 189 | data = { 190 | 'feeitemid': fee_item_id, 191 | 'json': 'true', 192 | 'level': '2', 193 | 'room': room, 194 | 'type': 'IEC', 195 | } 196 | cookie = {'synjones-auth': synjones_auth} 197 | r = requests.post(url, data=data, cookies=cookie) 198 | if r.status_code != 200: 199 | raise NetworkError() 200 | dic = json.loads(r.text) 201 | if dic['msg'] == 'success': 202 | return dic 203 | else: 204 | raise FeeAcquisitionFailed(dic['msg']) 205 | 206 | -------------------------------------------------------------------------------- /mycqu/course.py: -------------------------------------------------------------------------------- 1 | """课程相关的模块 2 | """ 3 | from __future__ import annotations 4 | from typing import Any, Dict, Optional, Tuple, List, Union, ClassVar 5 | # from pydantic.dataclasses import dataclass 6 | import re 7 | from datetime import date 8 | from functools import lru_cache 9 | from requests import Session, get 10 | from ._lib_wrapper.dataclass import dataclass 11 | from .utils.datetimes import parse_period_str, parse_weeks_str, parse_weekday_str, date_from_str 12 | from .mycqu import MycquUnauthorized 13 | 14 | 15 | __all__ = ("CQUSession", "CQUSessionInfo", 16 | "CourseTimetable", "CourseDayTime", "Course") 17 | 18 | CQUSESSIONS_URL = "https://my.cqu.edu.cn/api/timetable/optionFinder/session?blankOption=false" 19 | CUR_SESSION_URL = "https://my.cqu.edu.cn/api/resourceapi/session/cur-active-session" 20 | ALL_SESSIONSINFO_URL = "https://my.cqu.edu.cn/api/resourceapi/session/list" 21 | TIMETABLE_URL = "https://my.cqu.edu.cn/api/timetable/class/timetable/student/table-detail" 22 | 23 | 24 | def get_course_raw(session: Session, code: str, cqu_session: Optional[Union[CQUSession, str]] = None): 25 | """从 my.cqu.edu.cn 上获取学生或老师的课表 26 | 27 | :param session: 登录了统一身份认证(:func:`.auth.login`)并在 mycqu 进行了认证(:func:`.mycqu.access_mycqu`)的 requests 会话 28 | :type session: Session 29 | :param code: 学生或教师的学工号 30 | :type code: str 31 | :param cqu_session: 需要获取课表的学期,留空获取当前年级的课表 32 | :type cqu_session: Optional[Union[CQUSession, str]], optional 33 | :raises MycquUnauthorized: 若会话未在 my.cqu.edu.cn 进行认证 34 | :return: 反序列化获取课表的json 35 | :rtype: List[CourseTimetable] 36 | """ 37 | if cqu_session is None: 38 | cqu_session = CQUSessionInfo.fetch(session).session 39 | elif isinstance(cqu_session, str): 40 | cqu_session = CQUSession.from_str(cqu_session) 41 | assert isinstance(cqu_session, CQUSession) 42 | resp = session.post(TIMETABLE_URL, 43 | params={"sessionId": cqu_session.get_id()}, 44 | json=[code], 45 | ) 46 | if resp.status_code == 401: 47 | raise MycquUnauthorized() 48 | return resp.json()['classTimetableVOList'] 49 | 50 | 51 | @dataclass(order=True, frozen=True) 52 | class CQUSession: 53 | """重大的某一学期 54 | """ 55 | year: int 56 | """主要行课年份""" 57 | is_autumn: bool 58 | """是否为秋冬季学期""" 59 | SESSION_RE: ClassVar = re.compile("^([0-9]{4})年?(春|秋)$") 60 | _SPECIAL_IDS: ClassVar[Tuple[int, ...]] = ( 61 | 239259, 102, 101, 103, 1028, 1029, 1030, 1032) # 2015 ~ 2018 62 | 63 | @lru_cache(maxsize=32) # type: ignore 64 | def __new__(cls, year: int, is_autumn: bool): # pylint: disable=unused-argument 65 | return super(CQUSession, cls).__new__(cls) 66 | 67 | def __str__(self): 68 | return str(self.year) + ('秋' if self.is_autumn else '春') 69 | 70 | def get_id(self) -> int: 71 | """获取该学期在 my.cqu.edu.cn 中的 id 72 | 73 | >>> CQUSession(2021, True).get_id() 74 | 1038 75 | 76 | :return: 学期的 id 77 | :rtype: int 78 | """ 79 | if self.year >= 2019: 80 | return (self.year - 1503) * 2 + int(self.is_autumn) + 1 81 | elif 2015 <= self.year <= 2018: 82 | return self._SPECIAL_IDS[(self.year - 2015) * 2 + int(self.is_autumn)] 83 | else: 84 | return (2015 - self.year) * 2 - int(self.is_autumn) 85 | 86 | @staticmethod 87 | def from_str(string: str) -> CQUSession: 88 | """从学期字符串中解析学期 89 | 90 | >>> CQUSession.from_str("2021春") 91 | CQUSession(year=2021, is_autumn=False) 92 | >>> CQUSession.from_str("2020年秋") 93 | CQUSession(year=2020, is_autumn=True) 94 | 95 | :param string: 学期字符串,如“2021春”、“2020年秋” 96 | :type string: str 97 | :raises ValueError: 字符串不是一个预期中的学期字符串时抛出 98 | :return: 对应的学期 99 | :rtype: CQUSession 100 | """ 101 | match = CQUSession.SESSION_RE.match(string) 102 | if match: 103 | return CQUSession( 104 | year=match[1], 105 | is_autumn=match[2] == "秋" 106 | ) 107 | else: 108 | raise ValueError(f"string {string} is not a session") 109 | 110 | @staticmethod 111 | def fetch() -> List[CQUSession]: 112 | """从 my.cqu.edu.cn 上获取各个学期 113 | 114 | :return: 各个学期组成的列表 115 | :rtype: List[CQUSession] 116 | """ 117 | session_list = [] 118 | for session in get(CQUSESSIONS_URL).json(): 119 | session_list.append(CQUSession.from_str(session["name"])) 120 | return session_list 121 | 122 | 123 | @dataclass 124 | class CQUSessionInfo: 125 | """某学期的一些额外信息 126 | """ 127 | session: CQUSession 128 | """对应的学期""" 129 | begin_date: date 130 | """学期的开始日期""" 131 | end_date: date 132 | """学期的结束日期""" 133 | 134 | @staticmethod 135 | def from_dict(data: dict[str, Any]) -> CQUSessionInfo: 136 | """从反序列化的(一个)学期信息 json 中获取学期信息 137 | 138 | :param data: json 反序列化得到的字典 139 | :type data: dict[str, Any] 140 | :return: 学期信息对象 141 | :rtype: CQUSessionInfo 142 | """ 143 | return CQUSessionInfo( 144 | session=CQUSession(year=data["year"], 145 | is_autumn=data["term"] == "秋"), 146 | begin_date=date_from_str(data["beginDate"]), 147 | end_date=date_from_str(data["endDate"]) 148 | ) 149 | 150 | @staticmethod 151 | def fetch_all(session: Session) -> List[CQUSessionInfo]: 152 | """获取所有学期信息 153 | 154 | :param session: 登录了统一身份认证(:func:`.auth.login`)并在 mycqu 进行了认证(:func:`.mycqu.access_mycqu`)的 requests 会话 155 | :type session: Session 156 | :return: 按时间降序排序的学期(最新学期可能尚未到来,其信息准确度也无法保障!) 157 | :rtype: List[CQUSessionInfo] 158 | """ 159 | resp = session.get(ALL_SESSIONSINFO_URL) 160 | if resp.status_code == 401: 161 | raise MycquUnauthorized() 162 | cqusesions: List[CQUSessionInfo] = [] 163 | for data in resp.json()['sessionVOList']: 164 | if not data['beginDate']: 165 | break 166 | cqusesions.append(CQUSessionInfo.from_dict(data)) 167 | return cqusesions 168 | 169 | @staticmethod 170 | def fetch(session: Session) -> CQUSessionInfo: 171 | """从 my.cqu.edu.cn 上获取当前学期的学期信息,需要登录并认证了 mycqu 的会话 172 | 173 | :param session: 登录了统一身份认证(:func:`.auth.login`)并在 mycqu 进行了认证(:func:`.mycqu.access_mycqu`)的 requests 会话 174 | :type session: Session 175 | :raises MycquUnauthorized: 若会话未在 my.cqu.edu.cn 认证 176 | :return: 本学期信息对象 177 | :rtype: CQUSessionInfo 178 | """ 179 | resp = session.get(CUR_SESSION_URL) 180 | if resp.status_code == 401: 181 | raise MycquUnauthorized() 182 | return CQUSessionInfo.from_dict(resp.json()["data"]) 183 | 184 | 185 | @dataclass 186 | class CourseDayTime: 187 | """课程一次的星期和节次 188 | """ 189 | weekday: int 190 | """星期,0 为周一,6 为周日,此与 :attr:`datetime.date.day` 一致""" 191 | period: Tuple[int, int] 192 | """节次,第一个元素为开始节次,第二个元素为结束节次(该节次也包括在范围内)。 193 | 只有一节课时,两个元素相同。 194 | """ 195 | 196 | @staticmethod 197 | def from_dict(data: Dict[str, Any]) -> Optional[CourseDayTime]: 198 | """从反序列化的(一个)课表 json 中获取课程的星期和节次 199 | 200 | :param data: 反序列化成字典的课表 json 201 | :type data: Dict[str, Any] 202 | :return: 若其中有课程的星期和节次则返回相应对象,否则返回 :obj:`None` 203 | :rtype: Optional[CourseDayTime] 204 | """ 205 | if data.get("periodFormat") and data.get("weekDayFormat"): 206 | return CourseDayTime( 207 | weekday=parse_weekday_str(data["weekDayFormat"]), 208 | period=parse_period_str(data["periodFormat"]) 209 | ) 210 | return None 211 | 212 | 213 | @dataclass 214 | class Course: 215 | """与具体行课时间无关的课程信息 216 | """ 217 | name: str 218 | """课程名称""" 219 | code: str 220 | """课程代码""" 221 | course_num: Optional[str] 222 | """教学班号,在无法获取时(如考表 :class:`.exam.Exam` 中)设为 :obj:`None`""" 223 | dept: Optional[str] 224 | """开课学院, 在无法获取时(如成绩 :class:`.score.Score`中)设为 :obj:`None`""" 225 | credit: Optional[float] 226 | """学分,无法获取到则为 :obj:`None`(如在考表 :class:`.exam.Exam` 中)""" 227 | instructor: Optional[str] 228 | """教师""" 229 | session: Optional[CQUSession] 230 | """学期,无法获取时则为 :obj:`None`""" 231 | 232 | @staticmethod 233 | def from_dict(data: Dict[str, Any], 234 | session: Optional[Union[str, CQUSession]] = None) -> Course: 235 | """从反序列化的(一个)课表或考表 json 中返回课程 236 | 237 | :param data: 反序列化成字典的课表或考表 json 238 | :type data: Dict[str, Any] 239 | :param session: 学期字符串或学期对象,留空则尝试从 ``data`` 中获取 240 | :type session: Optional[Union[str, CQUSession]], optional 241 | :return: 对应的课程对象 242 | :rtype: Course 243 | """ 244 | if session is None and not data.get("session") is None: 245 | session = CQUSession.from_str(data["session"]) 246 | if isinstance(session, str): 247 | session = CQUSession.from_str(session) 248 | assert isinstance(session, CQUSession) or session is None 249 | return Course( 250 | name=data["courseName"], 251 | code=data["courseCode"], 252 | course_num=data.get("classNbr"), 253 | dept=data.get( 254 | "courseDepartmentName") or data.get("courseDeptShortName"), 255 | credit=data.get("credit") or data.get("courseCredit"), 256 | instructor=data.get("instructorName"), 257 | session=session, 258 | ) 259 | 260 | 261 | @dataclass 262 | class CourseTimetable: 263 | """课表对象,一个对象存储有相同课程、相同行课节次和相同星期的一批行课安排 264 | """ 265 | course: Course 266 | """对应的课程""" 267 | stu_num: int 268 | """学生数""" 269 | classroom: Optional[str] 270 | """行课地点,无则为 :obj:`None`""" 271 | weeks: List[Tuple[int, int]] 272 | """行课周数,列表中每个元组 (a,b) 代表一个周数范围 a~b(包含 a, b),在单独的一周则有 b=a""" 273 | day_time: Optional[CourseDayTime] 274 | """行课的星期和节次,若时间是整周(如真实地占用整周的军训和某些实习、虚拟地使用一周的思修实践) 275 | 则为 :obj:`None`""" 276 | whole_week: bool 277 | """是否真实地占用整周(如军训和某些实习是真实地占用、思修实践是“虚拟地占用”)""" 278 | 279 | @staticmethod 280 | def from_dict(data: Dict[str, Any]) -> CourseTimetable: 281 | """从反序列化的一个课表 json 中获取课表 282 | 283 | :param data: 反序列化成字典的课表 json 284 | :type data: Dict[str, Any] 285 | :return: 课表对象 286 | :rtype: CourseTimetable 287 | """ 288 | return CourseTimetable( 289 | course=Course.from_dict(data), 290 | stu_num=data["selectedStuNum"], 291 | classroom=data["roomName"], 292 | weeks=parse_weeks_str(data.get("weeks") 293 | or data.get("teachingWeekFormat")), # type: ignore 294 | day_time=CourseDayTime.from_dict(data), 295 | whole_week=bool(data["wholeWeekOccupy"]) 296 | ) 297 | 298 | @staticmethod 299 | def fetch(session: Session, code: str, cqu_session: Optional[Union[CQUSession, str]] = None)\ 300 | -> List[CourseTimetable]: 301 | """从 my.cqu.edu.cn 上获取学生或老师的课表 302 | 303 | :param session: 登录了统一身份认证(:func:`.auth.login`)并在 mycqu 进行了认证(:func:`.mycqu.access_mycqu`)的 requests 会话 304 | :type session: Session 305 | :param code: 学生或教师的学工号 306 | :type code: str 307 | :param cqu_session: 需要获取课表的学期,留空获取当前年级的课表 308 | :type cqu_session: Optional[Union[CQUSession, str]], optional 309 | :raises MycquUnauthorized: 若会话未在 my.cqu.edu.cn 进行认证 310 | :return: 获取的课表对象的列表 311 | :rtype: List[CourseTimetable] 312 | """ 313 | resp = get_course_raw(session, code, cqu_session) 314 | return [CourseTimetable.from_dict(timetable) for timetable in resp 315 | if timetable["teachingWeekFormat"] 316 | ] 317 | -------------------------------------------------------------------------------- /mycqu/exam.py: -------------------------------------------------------------------------------- 1 | """考试相关的模块 2 | """ 3 | from __future__ import annotations 4 | from typing import Dict, Any, Optional, List 5 | from datetime import date, time 6 | import requests 7 | from .course import Course 8 | from .utils.datetimes import date_from_str, time_from_str 9 | # from pydantic.dataclasses import dataclass 10 | from ._lib_wrapper.dataclass import dataclass 11 | from ._lib_wrapper.encrypt import pad, aes_ecb_encryptor 12 | 13 | __all__ = ("Exam",) 14 | 15 | __exam_encryptor = aes_ecb_encryptor("cquisse123456789".encode()) 16 | EXAM_LIST_URL = "https://my.cqu.edu.cn/api/exam/examTask/get-student-exam-list-outside" 17 | 18 | 19 | def get_exam_raw(student_id: str, session: Optional[requests.Session] = None) -> Dict[str, Any]: 20 | """获取考表的原始 json 数据(被反序列化为 python 字典对象) 21 | 22 | :param student_id: 学号 23 | :type student_id: str 24 | :param session: 用于请求的 requests session 25 | :type session: requests.Session, optional 26 | :return: 反序列化后的课表 json 数据 27 | :rtype: Dict[str, Any] 28 | """ 29 | return (session or requests).get(EXAM_LIST_URL, 30 | params={"studentId": 31 | __exam_encryptor( 32 | pad(student_id.encode())).hex().upper() 33 | } 34 | ).json() 35 | 36 | 37 | @dataclass 38 | class Invigilator: 39 | """监考员信息 40 | """ 41 | name: str 42 | """监考员姓名""" 43 | dept: str 44 | """监考员所在学院(可能是简称,如 :obj:`"数统"`)""" 45 | 46 | @staticmethod 47 | def from_dict(data: Dict[str, Optional[str]]) -> Invigilator: 48 | """从反序列化后的 json 数据中一名正/副监考员的数据中生成 :class:`Invigilator` 对象。 49 | 50 | :param data: 反序列化后的 json 数据中的一次考试数据 51 | :type data: Dict[str, Optional[str]] 52 | :return: 对应的 :class:`Invigilator` 对象 53 | :rtype: Invigilator 54 | """ 55 | return Invigilator( 56 | name=data["instructor"], # type: ignore 57 | dept=data["instDeptShortName"] # type: ignore 58 | ) 59 | 60 | 61 | @dataclass 62 | class Exam: 63 | """考试信息 64 | """ 65 | course: Course 66 | """考试对应的课程,其中学分 :attr:`credit`、教师 :attr:`instructor`、教学班号 :attr:`course_num` 可能无法获取(其值会设置为 :obj:`None`)""" 67 | batch: str 68 | """考试批次,如 :obj:`"非集中考试周"`""" 69 | batch_id: int 70 | """选课系统中考试批次的内部id""" 71 | building: str 72 | """考场楼栋""" 73 | floor: int 74 | """考场楼层""" 75 | room: str 76 | """考场地点""" 77 | stu_num: int 78 | """考场人数""" 79 | date: date 80 | """考试日期""" 81 | start_time: time 82 | """考试开始时间""" 83 | end_time: time 84 | """考试结束时间""" 85 | week: int 86 | """周次""" 87 | weekday: int 88 | """星期,0为周一,6为周日""" 89 | stu_id: str 90 | """考生学号""" 91 | seat_num: int 92 | """考生座号""" 93 | chief_invi: List[Invigilator] 94 | """监考员""" 95 | asst_invi: Optional[List[Invigilator]] 96 | """副监考员""" 97 | 98 | @staticmethod 99 | def from_dict(data: Dict[str, Any]) -> Exam: 100 | """从反序列化后的 json 数据中的一次考试数据生成 :class:`Exam` 对象 101 | 102 | :param data: 反序列化后的 json 数据中的一次考试数据 103 | :type data: Dict[str, Any] 104 | :return: 对应的 :class:`Exam` 对象 105 | :rtype: [type] 106 | """ 107 | course = Course.from_dict(data) 108 | return Exam( 109 | course=course, 110 | batch=data["batchName"], 111 | batch_id=data["batchId"], 112 | building=data["buildingName"], 113 | room=data["roomName"], 114 | floor=data["floorNum"], 115 | date=date_from_str(data["examDate"]), 116 | start_time=time_from_str(data["startTime"]), 117 | end_time=time_from_str(data["endTime"]), 118 | week=data["week"], 119 | weekday=int(data["weekDay"]) - 1, 120 | stu_id=data["studentId"], 121 | seat_num=data["seatNum"], 122 | stu_num=data["examStuNum"], 123 | chief_invi=[Invigilator.from_dict(invi) 124 | for invi in data["simpleChiefinvigilatorVOS"]], 125 | asst_invi=data["simpleAssistantInviVOS"] and [Invigilator.from_dict(invi) 126 | for invi in data["simpleAssistantInviVOS"]] 127 | ) 128 | 129 | @staticmethod 130 | def fetch(student_id: str) -> List[Exam]: 131 | """从 my.cqu.edu.cn 上获取指定学生的考表 132 | 133 | :param student_id: 学生学号 134 | :type student_id: str 135 | :return: 本学期的考表 136 | :rtype: List[Exam] 137 | """ 138 | return [Exam.from_dict(exam) 139 | for exam in get_exam_raw(student_id)["data"]["content"]] 140 | -------------------------------------------------------------------------------- /mycqu/mycqu.py: -------------------------------------------------------------------------------- 1 | """my.cqu.edu.cn 认证相关的模块 2 | """ 3 | from typing import Dict 4 | import re 5 | from requests import Session 6 | from .auth import access_sso_service 7 | __all__ = ("access_mycqu",) 8 | 9 | MYCQU_TOKEN_INDEX_URL = "https://my.cqu.edu.cn/enroll/token-index" 10 | MYCQU_TOKEN_URL = "https://my.cqu.edu.cn/authserver/oauth/token" 11 | MYCQU_AUTHORIZE_URL = f"https://my.cqu.edu.cn/authserver/oauth/authorize?client_id=enroll-prod&response_type=code&scope=all&state=&redirect_uri={MYCQU_TOKEN_INDEX_URL}" 12 | MYCQU_SERVICE_URL = "https://my.cqu.edu.cn/authserver/authentication/cas" 13 | CODE_RE = re.compile(r"\?code=([^&]+)&") 14 | 15 | 16 | class MycquUnauthorized(Exception): 17 | def __init__(self): 18 | super().__init__("Unanthorized in mycqu, auth.login firstly and then mycqu.access_mycqu") 19 | 20 | 21 | def get_oauth_token(session: Session) -> str: 22 | # from https://github.com/CQULHW/CQUQueryGrade 23 | resp = session.get(MYCQU_AUTHORIZE_URL, allow_redirects=False) 24 | match = CODE_RE.search(resp.headers['Location']) 25 | assert match 26 | token_data = { 27 | 'client_id': 'enroll-prod', 28 | 'client_secret': 'app-a-1234', 29 | 'code': match[1], 30 | 'redirect_uri': MYCQU_TOKEN_INDEX_URL, 31 | 'grant_type': 'authorization_code' 32 | } 33 | access_token = session.post(MYCQU_TOKEN_URL, data=token_data) 34 | return "Bearer " + access_token.json()['access_token'] 35 | 36 | 37 | def access_mycqu(session: Session, add_to_header: bool = True) -> Dict[str, str]: 38 | """用登陆了统一身份认证的会话在 my.cqu.edu.cn 进行认证 39 | 40 | :param session: 登陆了统一身份认证的会话 41 | :type session: Session 42 | :param add_to_header: 是否将 mycqu 的认证信息写入会话属性,默认为 :obj:`True` 43 | :type add_to_header: bool, optional 44 | :return: mycqu 认证信息的请求头,当 ``add_to_header`` 参数为 :obj:`True` 时无需手动使用该返回值 45 | :rtype: Dict[str, str] 46 | """ 47 | if "Authorization" in session.headers: 48 | del session.headers["Authorization"] 49 | access_sso_service(session, MYCQU_SERVICE_URL) 50 | token = get_oauth_token(session) 51 | if add_to_header: 52 | session.headers["Authorization"] = token 53 | return {"Authorization": token} 54 | -------------------------------------------------------------------------------- /mycqu/score.py: -------------------------------------------------------------------------------- 1 | """ 2 | 成绩相关模块 3 | """ 4 | from __future__ import annotations 5 | import json 6 | from typing import Dict, Any, Union, Optional, List 7 | import requests 8 | from requests import Session 9 | from ._lib_wrapper.dataclass import dataclass 10 | from .course import Course, CQUSession 11 | from .mycqu import MycquUnauthorized 12 | 13 | __all__ = ("Score", "GpaRanking") 14 | 15 | 16 | class CQUWebsiteError(Exception): 17 | def __init__(self, error_msg): 18 | super().__init__('CQU website return error: ' + error_msg) 19 | 20 | 21 | def get_score_raw(auth: Union[Session, str]): 22 | """ 23 | 获取学生原始成绩 24 | :param auth: 登陆后获取的authorization或者调用过mycqu.access_mycqu的session 25 | :type auth: Union[Session, str] 26 | :return: 反序列化获取的score列表 27 | :rtype: Dict 28 | """ 29 | if isinstance(auth, requests.Session): 30 | res = auth.get('https://my.cqu.edu.cn/api/sam/score/student/score') 31 | else: 32 | authorization = auth 33 | headers = { 34 | 'Referer': 'https://my.cqu.edu.cn/sam/home', 35 | 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)', 36 | 'Authorization': authorization 37 | } 38 | res = requests.get( 39 | 'https://my.cqu.edu.cn/api/sam/score/student/score', headers=headers) 40 | 41 | content = json.loads(res.content) 42 | if content['status'] == 'error': 43 | raise CQUWebsiteError(content['msg']) 44 | if res.status_code == 401: 45 | raise MycquUnauthorized() 46 | return content['data'] 47 | 48 | 49 | def get_gpa_ranking_raw(auth: Union[Session, str]): 50 | """ 51 | 获取学生绩点排名 52 | 53 | :param auth: 登陆后获取的authorization或者调用过mycqu.access_mycqu的session 54 | :type auth: Union[Session, str] 55 | :return: 反序列化获取的绩点、排名 56 | :rtype: Dict 57 | """ 58 | if isinstance(auth, requests.Session): 59 | res = auth.get('https://my.cqu.edu.cn/api/sam/score/student/studentGpaRanking') 60 | else: 61 | authorization = auth 62 | headers = { 63 | 'Referer': 'https://my.cqu.edu.cn/sam/home', 64 | 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)', 65 | 'Authorization': authorization 66 | } 67 | res = requests.get( 68 | 'https://my.cqu.edu.cn/api/sam/score/student/studentGpaRanking', headers=headers) 69 | 70 | content = json.loads(res.content) 71 | if content['status'] == 'error': 72 | raise CQUWebsiteError(content['msg']) 73 | if res.status_code == 401: 74 | raise MycquUnauthorized() 75 | return content['data'] 76 | 77 | 78 | @dataclass 79 | class Score: 80 | """ 81 | 成绩对象 82 | """ 83 | session: CQUSession 84 | """学期""" 85 | course: Course 86 | """课程""" 87 | score: Optional[str] 88 | """成绩,可能为数字,也可能为字符(优、良等)""" 89 | study_nature: str 90 | """初修/重修""" 91 | course_nature: str 92 | """必修/选修""" 93 | 94 | @staticmethod 95 | def from_dict(data: Dict[str, Any]) -> Score: 96 | """ 97 | 从反序列化的字典生成Score对象 98 | 99 | @param: data 100 | @type: dict 101 | @return: 返回成绩对象 102 | @rtype: Score 103 | """ 104 | return Score( 105 | session=CQUSession.from_str(data["sessionName"]), 106 | course=Course.from_dict(data), 107 | score=data['effectiveScoreShow'], 108 | study_nature=data['studyNature'], 109 | course_nature=data['courseNature'] 110 | ) 111 | 112 | @staticmethod 113 | def fetch(auth: Union[str, Session]) -> List[Score]: 114 | """ 115 | 从网站获取成绩信息 116 | :param auth: 登陆后获取的 authorization 或者调用过 :func:`.mycqu.access_mycqu` 的 Session 117 | :type auth: Union[Session, str] 118 | :return: 返回成绩对象 119 | :rtype: List[Score] 120 | :raises CQUWebsiteError: 查询时教务网报错 121 | """ 122 | temp = get_score_raw(auth) 123 | score = [] 124 | for courses in temp.values(): 125 | for course in courses['stuScoreHomePgVoS']: 126 | score.append(Score.from_dict(course)) 127 | return score 128 | 129 | 130 | @dataclass 131 | class GpaRanking: 132 | """ 133 | 绩点对象 134 | """ 135 | gpa: float 136 | """学生总绩点""" 137 | majorRanking: Optional[int] 138 | """专业排名""" 139 | gradeRanking: Optional[int] 140 | """年级排名""" 141 | classRanking: Optional[int] 142 | """班级排名""" 143 | 144 | @staticmethod 145 | def from_dict(data: Dict[str, Any]) -> GpaRanking: 146 | """ 147 | 从反序列化的字典生成GpaRanking对象 148 | 149 | @param: data 150 | @type: dict 151 | @return: 返回绩点排名对象 152 | @rtype: GpaRanking 153 | """ 154 | return GpaRanking( 155 | gpa=float(data['gpa']), 156 | majorRanking=data['majorRanking'] and int(data['majorRanking']), 157 | gradeRanking=data['gradeRanking'] and int(data['gradeRanking']), 158 | classRanking=data['classRanking'] and int(data['classRanking']) 159 | ) 160 | 161 | @staticmethod 162 | def fetch(auth: Union[str, Session]) -> GpaRanking: 163 | """ 164 | 从网站获取绩点排名信息 165 | 166 | :param auth: 登陆后获取的 authorization 或者调用过 :func:`.mycqu.access_mycqu` 的 Session 167 | :type auth: Union[Session, str] 168 | :return: 返回绩点排名对象 169 | :rtype: GpaRanking 170 | :raises CQUWebsiteError: 查询时教务网报错 171 | """ 172 | return GpaRanking.from_dict(get_gpa_ranking_raw(auth)) 173 | -------------------------------------------------------------------------------- /mycqu/user.py: -------------------------------------------------------------------------------- 1 | """用户信息相关的模块 2 | """ 3 | from __future__ import annotations 4 | from requests import Session 5 | from ._lib_wrapper.dataclass import dataclass 6 | from .mycqu import MycquUnauthorized 7 | __all__ = ("User",) 8 | 9 | 10 | @dataclass 11 | class User: 12 | """用户信息""" 13 | 14 | name: str 15 | """姓名""" 16 | uniform_id: str 17 | """统一身份认证号""" 18 | code: str 19 | """学工号""" 20 | role: str 21 | """身份,已知取值有学生 :obj:`"student"`、教师 :obj:`"instructor`"`""" 22 | email: str 23 | "电子邮箱" 24 | phone_number: str 25 | "电话号码" 26 | 27 | @staticmethod 28 | def fetch_self(session: Session) -> User: 29 | """从在 mycqu 认证了的会话获取当前登录用户的信息 30 | 31 | :param session: 登陆了统一身份认证的会话 32 | :type session: Session 33 | :raises MycquUnauthorized: 若会话未在 my.cqu.edu.cn 进行认证 34 | :return: 当前用户信息 35 | :rtype: User 36 | """ 37 | resp = session.get("https://my.cqu.edu.cn/authserver/simple-user") 38 | if resp.status_code == 401: 39 | raise MycquUnauthorized() 40 | data = resp.json() 41 | return User( 42 | name=data["name"], 43 | code=data["code"], 44 | uniform_id=data["username"], 45 | role=data["type"], 46 | email=data["email"], 47 | phone_number=data["phoneNumber"] 48 | ) 49 | -------------------------------------------------------------------------------- /mycqu/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hagb/pymycqu/a5fbda092e9d88cd57183d72b04942512df29c13/mycqu/utils/__init__.py -------------------------------------------------------------------------------- /mycqu/utils/datetimes.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple, Dict 2 | from datetime import date, time, datetime 3 | import pytz 4 | TIMEZONE = datetime.now(pytz.timezone("Asia/Shanghai")).tzinfo 5 | WEEKDAY: Dict[str, int] = { 6 | "一": 0, 7 | "二": 1, 8 | "三": 2, 9 | "四": 3, 10 | "五": 4, 11 | "六": 5, 12 | "日": 6 13 | } 14 | 15 | 16 | def time_from_str(string: str) -> time: 17 | hour, minute = map(int, string.split(":")) 18 | return time(hour, minute, tzinfo=TIMEZONE) 19 | 20 | 21 | def parse_period_str(string: str) -> Tuple[int, int]: 22 | period = tuple(map(int, string.split("-"))) 23 | assert len(period) == 1 or len(period) == 2 24 | return period[0], (period[1] if len(period) == 2 else period[0]) 25 | 26 | 27 | def parse_weeks_str(string: str) -> List[Tuple[int, int]]: 28 | return [parse_period_str(unit) for unit in string.split(',')] 29 | 30 | 31 | def parse_weekday_str(string: str) -> int: 32 | return WEEKDAY[string] 33 | 34 | 35 | def date_from_str(string: str) -> date: 36 | return date.fromisoformat(string) 37 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | plugins = pydantic.mypy 3 | 4 | follow_imports = silent 5 | warn_redundant_casts = True 6 | warn_unused_ignores = True 7 | #disallow_any_generics = True 8 | check_untyped_defs = True 9 | no_implicit_reexport = True 10 | 11 | [pydantic-mypy] 12 | init_forbid_extra = True 13 | init_typed = True 14 | warn_required_dynamic_aliases = True 15 | warn_untyped_fields = True 16 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "mycqu" 3 | version = "0.5.0" 4 | description = "重庆重庆大学新教务网及相关 api 的封装" 5 | authors = ["Hagb "] 6 | license = "AGPL-3.0-or-later" 7 | readme = "README.md" 8 | homepage = "https://pymycqu.hagb.name" 9 | repository = "https://github.com/Hagb/pymycqu" 10 | documentation = "https://pymycqu.hagb.name" 11 | keywords = ["cqu", "Chongqing University", "data model"] 12 | classifiers = [ 13 | "Development Status :: 4 - Beta", 14 | "Natural Language :: Chinese (Simplified)", 15 | "Operating System :: OS Independent", 16 | "Topic :: Internet :: WWW/HTTP", 17 | "Topic :: Software Development :: Libraries", 18 | ] 19 | 20 | [tool.poetry.dependencies] 21 | python = "^3.7" 22 | requests = "^2" 23 | pydantic = "^1" 24 | pycryptodome = {version = "^3", optional = true} 25 | pycryptodomex = {version = "^3", optional = true} 26 | pyaes = ">= 1.2.0" 27 | pytz = "*" 28 | 29 | [tool.poetry.extras] 30 | 31 | pycryptodome = ["pycryptodome"] 32 | pycryptodomex = ["pycryptodomex"] 33 | #pyaes = ["pyaes"] 34 | 35 | [tool.poetry.dev-dependencies] 36 | 37 | sphinx-multiversion = "^0" 38 | sphinx = "^4" 39 | 40 | [build-system] 41 | requires = ["poetry-core>=1.0.0"] 42 | build-backend = "poetry.core.masonry.api" 43 | --------------------------------------------------------------------------------