Deploy updated SCU course catcher
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +13 -0
- .gitattributes +2 -0
- .github/workflows/linux-tests.yml +25 -0
- .gitignore +13 -0
- .python-version +1 -0
- Dockerfile +34 -0
- LICENSE +674 -0
- README.md +217 -6
- app.py +1 -0
- build_exe.py +33 -0
- core/__init__.py +1 -0
- core/config.py +142 -0
- core/course_bot.py +507 -0
- core/course_runner.py +303 -0
- core/database.py +482 -0
- core/db.py +551 -0
- core/security.py +23 -0
- core/task_manager.py +154 -0
- course_catcher/__init__.py +5 -0
- course_catcher/automation.py +399 -0
- course_catcher/config.py +57 -0
- course_catcher/db.py +625 -0
- course_catcher/security.py +33 -0
- course_catcher/task_manager.py +98 -0
- course_catcher/web.py +457 -0
- ensure_package_exist.py +29 -0
- favicon.ico +3 -0
- initialize.py +135 -0
- initialize_plus.pyw +349 -0
- javascript/check_result.js +13 -0
- javascript/select_course.js +32 -0
- main.py +15 -0
- ocr_provider/captcha_model.onnx +3 -0
- ocr_provider/captcha_model.onnx.data +3 -0
- onnx_inference.py +57 -0
- pyproject.toml +15 -0
- requirements.txt +7 -0
- space_app.py +520 -0
- static/app.js +127 -0
- static/style.css +704 -0
- templates/admin.html +227 -0
- templates/admin_dashboard.html +262 -0
- templates/admin_login.html +50 -0
- templates/base.html +34 -0
- templates/dashboard.html +159 -0
- templates/login.html +50 -0
- tests/__init__.py +1 -0
- tests/helpers.py +19 -0
- tests/test_config.py +37 -0
- tests/test_course_bot.py +128 -0
.dockerignore
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.venv
|
| 3 |
+
__pycache__
|
| 4 |
+
*.pyc
|
| 5 |
+
*.pyo
|
| 6 |
+
*.pyd
|
| 7 |
+
data
|
| 8 |
+
build
|
| 9 |
+
dist
|
| 10 |
+
course_catcher
|
| 11 |
+
core/database.py
|
| 12 |
+
core/course_runner.py
|
| 13 |
+
templates/admin.html
|
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
favicon.ico filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
ocr_provider/captcha_model.onnx.data filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/linux-tests.yml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: linux-tests
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
pull_request:
|
| 6 |
+
|
| 7 |
+
jobs:
|
| 8 |
+
unittest:
|
| 9 |
+
runs-on: ubuntu-latest
|
| 10 |
+
steps:
|
| 11 |
+
- name: Checkout
|
| 12 |
+
uses: actions/checkout@v4
|
| 13 |
+
|
| 14 |
+
- name: Setup Python
|
| 15 |
+
uses: actions/setup-python@v5
|
| 16 |
+
with:
|
| 17 |
+
python-version: '3.11'
|
| 18 |
+
|
| 19 |
+
- name: Install dependencies
|
| 20 |
+
run: |
|
| 21 |
+
python -m pip install --upgrade pip
|
| 22 |
+
pip install -r requirements.txt
|
| 23 |
+
|
| 24 |
+
- name: Run unit tests
|
| 25 |
+
run: python -m unittest discover -s tests -v
|
.gitignore
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
user_data.json
|
| 2 |
+
build
|
| 3 |
+
main.spec
|
| 4 |
+
__pycache__
|
| 5 |
+
setting.json
|
| 6 |
+
.idea
|
| 7 |
+
.venv
|
| 8 |
+
dist
|
| 9 |
+
data/
|
| 10 |
+
runtime/
|
| 11 |
+
*.db
|
| 12 |
+
*.sqlite3
|
| 13 |
+
tests/.tmp/
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.11
|
Dockerfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PIP_NO_CACHE_DIR=1 \
|
| 6 |
+
HOME=/home/user \
|
| 7 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 8 |
+
CHROME_BIN=/usr/bin/chromium \
|
| 9 |
+
CHROMEDRIVER_PATH=/usr/bin/chromedriver \
|
| 10 |
+
DATA_DIR=/data
|
| 11 |
+
|
| 12 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 13 |
+
chromium \
|
| 14 |
+
chromium-driver \
|
| 15 |
+
fonts-noto-cjk \
|
| 16 |
+
fonts-noto-color-emoji \
|
| 17 |
+
ca-certificates \
|
| 18 |
+
&& useradd -m -u 1000 user \
|
| 19 |
+
&& mkdir -p /data \
|
| 20 |
+
&& chmod 777 /data \
|
| 21 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 22 |
+
|
| 23 |
+
WORKDIR ${HOME}/app
|
| 24 |
+
USER user
|
| 25 |
+
|
| 26 |
+
COPY --chown=user requirements.txt ./
|
| 27 |
+
RUN pip install --upgrade --user pip && pip install --user -r requirements.txt
|
| 28 |
+
|
| 29 |
+
COPY --chown=user . .
|
| 30 |
+
RUN mkdir -p ${HOME}/app/data
|
| 31 |
+
|
| 32 |
+
EXPOSE 7860
|
| 33 |
+
|
| 34 |
+
CMD ["sh", "-c", "gunicorn --bind 0.0.0.0:${PORT:-7860} --workers 1 --threads 8 --timeout 180 app:app"]
|
LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 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 General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works.
|
| 12 |
+
|
| 13 |
+
The licenses for most software and other practical works are designed
|
| 14 |
+
to take away your freedom to share and change the works. By contrast,
|
| 15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
| 16 |
+
share and change all versions of a program--to make sure it remains free
|
| 17 |
+
software for all its users. We, the Free Software Foundation, use the
|
| 18 |
+
GNU General Public License for most of our software; it applies also to
|
| 19 |
+
any other work released this way by its authors. You can apply it to
|
| 20 |
+
your programs, too.
|
| 21 |
+
|
| 22 |
+
When we speak of free software, we are referring to freedom, not
|
| 23 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 24 |
+
have the freedom to distribute copies of free software (and charge for
|
| 25 |
+
them if you wish), that you receive source code or can get it if you
|
| 26 |
+
want it, that you can change the software or use pieces of it in new
|
| 27 |
+
free programs, and that you know you can do these things.
|
| 28 |
+
|
| 29 |
+
To protect your rights, we need to prevent others from denying you
|
| 30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
| 31 |
+
certain responsibilities if you distribute copies of the software, or if
|
| 32 |
+
you modify it: responsibilities to respect the freedom of others.
|
| 33 |
+
|
| 34 |
+
For example, if you distribute copies of such a program, whether
|
| 35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
| 36 |
+
freedoms that you received. You must make sure that they, too, receive
|
| 37 |
+
or can get the source code. And you must show them these terms so they
|
| 38 |
+
know their rights.
|
| 39 |
+
|
| 40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
| 41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
| 42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
| 43 |
+
|
| 44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
| 45 |
+
that there is no warranty for this free software. For both users' and
|
| 46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
| 47 |
+
changed, so that their problems will not be attributed erroneously to
|
| 48 |
+
authors of previous versions.
|
| 49 |
+
|
| 50 |
+
Some devices are designed to deny users access to install or run
|
| 51 |
+
modified versions of the software inside them, although the manufacturer
|
| 52 |
+
can do so. This is fundamentally incompatible with the aim of
|
| 53 |
+
protecting users' freedom to change the software. The systematic
|
| 54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
| 55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
| 56 |
+
have designed this version of the GPL to prohibit the practice for those
|
| 57 |
+
products. If such problems arise substantially in other domains, we
|
| 58 |
+
stand ready to extend this provision to those domains in future versions
|
| 59 |
+
of the GPL, as needed to protect the freedom of users.
|
| 60 |
+
|
| 61 |
+
Finally, every program is threatened constantly by software patents.
|
| 62 |
+
States should not allow patents to restrict development and use of
|
| 63 |
+
software on general-purpose computers, but in those that do, we wish to
|
| 64 |
+
avoid the special danger that patents applied to a free program could
|
| 65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
| 66 |
+
patents cannot be used to render the program non-free.
|
| 67 |
+
|
| 68 |
+
The precise terms and conditions for copying, distribution and
|
| 69 |
+
modification follow.
|
| 70 |
+
|
| 71 |
+
TERMS AND CONDITIONS
|
| 72 |
+
|
| 73 |
+
0. Definitions.
|
| 74 |
+
|
| 75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
| 76 |
+
|
| 77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 78 |
+
works, such as semiconductor masks.
|
| 79 |
+
|
| 80 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 82 |
+
"recipients" may be individuals or organizations.
|
| 83 |
+
|
| 84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 85 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 86 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 87 |
+
earlier work or a work "based on" the earlier work.
|
| 88 |
+
|
| 89 |
+
A "covered work" means either the unmodified Program or a work based
|
| 90 |
+
on the Program.
|
| 91 |
+
|
| 92 |
+
To "propagate" a work means to do anything with it that, without
|
| 93 |
+
permission, would make you directly or secondarily liable for
|
| 94 |
+
infringement under applicable copyright law, except executing it on a
|
| 95 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 96 |
+
distribution (with or without modification), making available to the
|
| 97 |
+
public, and in some countries other activities as well.
|
| 98 |
+
|
| 99 |
+
To "convey" a work means any kind of propagation that enables other
|
| 100 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 102 |
+
|
| 103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 104 |
+
to the extent that it includes a convenient and prominently visible
|
| 105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 106 |
+
tells the user that there is no warranty for the work (except to the
|
| 107 |
+
extent that warranties are provided), that licensees may convey the
|
| 108 |
+
work under this License, and how to view a copy of this License. If
|
| 109 |
+
the interface presents a list of user commands or options, such as a
|
| 110 |
+
menu, a prominent item in the list meets this criterion.
|
| 111 |
+
|
| 112 |
+
1. Source Code.
|
| 113 |
+
|
| 114 |
+
The "source code" for a work means the preferred form of the work
|
| 115 |
+
for making modifications to it. "Object code" means any non-source
|
| 116 |
+
form of a work.
|
| 117 |
+
|
| 118 |
+
A "Standard Interface" means an interface that either is an official
|
| 119 |
+
standard defined by a recognized standards body, or, in the case of
|
| 120 |
+
interfaces specified for a particular programming language, one that
|
| 121 |
+
is widely used among developers working in that language.
|
| 122 |
+
|
| 123 |
+
The "System Libraries" of an executable work include anything, other
|
| 124 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 125 |
+
packaging a Major Component, but which is not part of that Major
|
| 126 |
+
Component, and (b) serves only to enable use of the work with that
|
| 127 |
+
Major Component, or to implement a Standard Interface for which an
|
| 128 |
+
implementation is available to the public in source code form. A
|
| 129 |
+
"Major Component", in this context, means a major essential component
|
| 130 |
+
(kernel, window system, and so on) of the specific operating system
|
| 131 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 132 |
+
produce the work, or an object code interpreter used to run it.
|
| 133 |
+
|
| 134 |
+
The "Corresponding Source" for a work in object code form means all
|
| 135 |
+
the source code needed to generate, install, and (for an executable
|
| 136 |
+
work) run the object code and to modify the work, including scripts to
|
| 137 |
+
control those activities. However, it does not include the work's
|
| 138 |
+
System Libraries, or general-purpose tools or generally available free
|
| 139 |
+
programs which are used unmodified in performing those activities but
|
| 140 |
+
which are not part of the work. For example, Corresponding Source
|
| 141 |
+
includes interface definition files associated with source files for
|
| 142 |
+
the work, and the source code for shared libraries and dynamically
|
| 143 |
+
linked subprograms that the work is specifically designed to require,
|
| 144 |
+
such as by intimate data communication or control flow between those
|
| 145 |
+
subprograms and other parts of the work.
|
| 146 |
+
|
| 147 |
+
The Corresponding Source need not include anything that users
|
| 148 |
+
can regenerate automatically from other parts of the Corresponding
|
| 149 |
+
Source.
|
| 150 |
+
|
| 151 |
+
The Corresponding Source for a work in source code form is that
|
| 152 |
+
same work.
|
| 153 |
+
|
| 154 |
+
2. Basic Permissions.
|
| 155 |
+
|
| 156 |
+
All rights granted under this License are granted for the term of
|
| 157 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 158 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 159 |
+
permission to run the unmodified Program. The output from running a
|
| 160 |
+
covered work is covered by this License only if the output, given its
|
| 161 |
+
content, constitutes a covered work. This License acknowledges your
|
| 162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 163 |
+
|
| 164 |
+
You may make, run and propagate covered works that you do not
|
| 165 |
+
convey, without conditions so long as your license otherwise remains
|
| 166 |
+
in force. You may convey covered works to others for the sole purpose
|
| 167 |
+
of having them make modifications exclusively for you, or provide you
|
| 168 |
+
with facilities for running those works, provided that you comply with
|
| 169 |
+
the terms of this License in conveying all material for which you do
|
| 170 |
+
not control copyright. Those thus making or running the covered works
|
| 171 |
+
for you must do so exclusively on your behalf, under your direction
|
| 172 |
+
and control, on terms that prohibit them from making any copies of
|
| 173 |
+
your copyrighted material outside their relationship with you.
|
| 174 |
+
|
| 175 |
+
Conveying under any other circumstances is permitted solely under
|
| 176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 177 |
+
makes it unnecessary.
|
| 178 |
+
|
| 179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 180 |
+
|
| 181 |
+
No covered work shall be deemed part of an effective technological
|
| 182 |
+
measure under any applicable law fulfilling obligations under article
|
| 183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 184 |
+
similar laws prohibiting or restricting circumvention of such
|
| 185 |
+
measures.
|
| 186 |
+
|
| 187 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 188 |
+
circumvention of technological measures to the extent such circumvention
|
| 189 |
+
is effected by exercising rights under this License with respect to
|
| 190 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 191 |
+
modification of the work as a means of enforcing, against the work's
|
| 192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 193 |
+
technological measures.
|
| 194 |
+
|
| 195 |
+
4. Conveying Verbatim Copies.
|
| 196 |
+
|
| 197 |
+
You may convey verbatim copies of the Program's source code as you
|
| 198 |
+
receive it, in any medium, provided that you conspicuously and
|
| 199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 200 |
+
keep intact all notices stating that this License and any
|
| 201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 202 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 203 |
+
recipients a copy of this License along with the Program.
|
| 204 |
+
|
| 205 |
+
You may charge any price or no price for each copy that you convey,
|
| 206 |
+
and you may offer support or warranty protection for a fee.
|
| 207 |
+
|
| 208 |
+
5. Conveying Modified Source Versions.
|
| 209 |
+
|
| 210 |
+
You may convey a work based on the Program, or the modifications to
|
| 211 |
+
produce it from the Program, in the form of source code under the
|
| 212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 213 |
+
|
| 214 |
+
a) The work must carry prominent notices stating that you modified
|
| 215 |
+
it, and giving a relevant date.
|
| 216 |
+
|
| 217 |
+
b) The work must carry prominent notices stating that it is
|
| 218 |
+
released under this License and any conditions added under section
|
| 219 |
+
7. This requirement modifies the requirement in section 4 to
|
| 220 |
+
"keep intact all notices".
|
| 221 |
+
|
| 222 |
+
c) You must license the entire work, as a whole, under this
|
| 223 |
+
License to anyone who comes into possession of a copy. This
|
| 224 |
+
License will therefore apply, along with any applicable section 7
|
| 225 |
+
additional terms, to the whole of the work, and all its parts,
|
| 226 |
+
regardless of how they are packaged. This License gives no
|
| 227 |
+
permission to license the work in any other way, but it does not
|
| 228 |
+
invalidate such permission if you have separately received it.
|
| 229 |
+
|
| 230 |
+
d) If the work has interactive user interfaces, each must display
|
| 231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 233 |
+
work need not make them do so.
|
| 234 |
+
|
| 235 |
+
A compilation of a covered work with other separate and independent
|
| 236 |
+
works, which are not by their nature extensions of the covered work,
|
| 237 |
+
and which are not combined with it such as to form a larger program,
|
| 238 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 240 |
+
used to limit the access or legal rights of the compilation's users
|
| 241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 242 |
+
in an aggregate does not cause this License to apply to the other
|
| 243 |
+
parts of the aggregate.
|
| 244 |
+
|
| 245 |
+
6. Conveying Non-Source Forms.
|
| 246 |
+
|
| 247 |
+
You may convey a covered work in object code form under the terms
|
| 248 |
+
of sections 4 and 5, provided that you also convey the
|
| 249 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 250 |
+
in one of these ways:
|
| 251 |
+
|
| 252 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 253 |
+
(including a physical distribution medium), accompanied by the
|
| 254 |
+
Corresponding Source fixed on a durable physical medium
|
| 255 |
+
customarily used for software interchange.
|
| 256 |
+
|
| 257 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 258 |
+
(including a physical distribution medium), accompanied by a
|
| 259 |
+
written offer, valid for at least three years and valid for as
|
| 260 |
+
long as you offer spare parts or customer support for that product
|
| 261 |
+
model, to give anyone who possesses the object code either (1) a
|
| 262 |
+
copy of the Corresponding Source for all the software in the
|
| 263 |
+
product that is covered by this License, on a durable physical
|
| 264 |
+
medium customarily used for software interchange, for a price no
|
| 265 |
+
more than your reasonable cost of physically performing this
|
| 266 |
+
conveying of source, or (2) access to copy the
|
| 267 |
+
Corresponding Source from a network server at no charge.
|
| 268 |
+
|
| 269 |
+
c) Convey individual copies of the object code with a copy of the
|
| 270 |
+
written offer to provide the Corresponding Source. This
|
| 271 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 272 |
+
only if you received the object code with such an offer, in accord
|
| 273 |
+
with subsection 6b.
|
| 274 |
+
|
| 275 |
+
d) Convey the object code by offering access from a designated
|
| 276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 277 |
+
Corresponding Source in the same way through the same place at no
|
| 278 |
+
further charge. You need not require recipients to copy the
|
| 279 |
+
Corresponding Source along with the object code. If the place to
|
| 280 |
+
copy the object code is a network server, the Corresponding Source
|
| 281 |
+
may be on a different server (operated by you or a third party)
|
| 282 |
+
that supports equivalent copying facilities, provided you maintain
|
| 283 |
+
clear directions next to the object code saying where to find the
|
| 284 |
+
Corresponding Source. Regardless of what server hosts the
|
| 285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 286 |
+
available for as long as needed to satisfy these requirements.
|
| 287 |
+
|
| 288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 289 |
+
you inform other peers where the object code and Corresponding
|
| 290 |
+
Source of the work are being offered to the general public at no
|
| 291 |
+
charge under subsection 6d.
|
| 292 |
+
|
| 293 |
+
A separable portion of the object code, whose source code is excluded
|
| 294 |
+
from the Corresponding Source as a System Library, need not be
|
| 295 |
+
included in conveying the object code work.
|
| 296 |
+
|
| 297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 298 |
+
tangible personal property which is normally used for personal, family,
|
| 299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 302 |
+
product received by a particular user, "normally used" refers to a
|
| 303 |
+
typical or common use of that class of product, regardless of the status
|
| 304 |
+
of the particular user or of the way in which the particular user
|
| 305 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 306 |
+
is a consumer product regardless of whether the product has substantial
|
| 307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 308 |
+
the only significant mode of use of the product.
|
| 309 |
+
|
| 310 |
+
"Installation Information" for a User Product means any methods,
|
| 311 |
+
procedures, authorization keys, or other information required to install
|
| 312 |
+
and execute modified versions of a covered work in that User Product from
|
| 313 |
+
a modified version of its Corresponding Source. The information must
|
| 314 |
+
suffice to ensure that the continued functioning of the modified object
|
| 315 |
+
code is in no case prevented or interfered with solely because
|
| 316 |
+
modification has been made.
|
| 317 |
+
|
| 318 |
+
If you convey an object code work under this section in, or with, or
|
| 319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 320 |
+
part of a transaction in which the right of possession and use of the
|
| 321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 322 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 323 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 324 |
+
by the Installation Information. But this requirement does not apply
|
| 325 |
+
if neither you nor any third party retains the ability to install
|
| 326 |
+
modified object code on the User Product (for example, the work has
|
| 327 |
+
been installed in ROM).
|
| 328 |
+
|
| 329 |
+
The requirement to provide Installation Information does not include a
|
| 330 |
+
requirement to continue to provide support service, warranty, or updates
|
| 331 |
+
for a work that has been modified or installed by the recipient, or for
|
| 332 |
+
the User Product in which it has been modified or installed. Access to a
|
| 333 |
+
network may be denied when the modification itself materially and
|
| 334 |
+
adversely affects the operation of the network or violates the rules and
|
| 335 |
+
protocols for communication across the network.
|
| 336 |
+
|
| 337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 338 |
+
in accord with this section must be in a format that is publicly
|
| 339 |
+
documented (and with an implementation available to the public in
|
| 340 |
+
source code form), and must require no special password or key for
|
| 341 |
+
unpacking, reading or copying.
|
| 342 |
+
|
| 343 |
+
7. Additional Terms.
|
| 344 |
+
|
| 345 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 346 |
+
License by making exceptions from one or more of its conditions.
|
| 347 |
+
Additional permissions that are applicable to the entire Program shall
|
| 348 |
+
be treated as though they were included in this License, to the extent
|
| 349 |
+
that they are valid under applicable law. If additional permissions
|
| 350 |
+
apply only to part of the Program, that part may be used separately
|
| 351 |
+
under those permissions, but the entire Program remains governed by
|
| 352 |
+
this License without regard to the additional permissions.
|
| 353 |
+
|
| 354 |
+
When you convey a copy of a covered work, you may at your option
|
| 355 |
+
remove any additional permissions from that copy, or from any part of
|
| 356 |
+
it. (Additional permissions may be written to require their own
|
| 357 |
+
removal in certain cases when you modify the work.) You may place
|
| 358 |
+
additional permissions on material, added by you to a covered work,
|
| 359 |
+
for which you have or can give appropriate copyright permission.
|
| 360 |
+
|
| 361 |
+
Notwithstanding any other provision of this License, for material you
|
| 362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 363 |
+
that material) supplement the terms of this License with terms:
|
| 364 |
+
|
| 365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 366 |
+
terms of sections 15 and 16 of this License; or
|
| 367 |
+
|
| 368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 369 |
+
author attributions in that material or in the Appropriate Legal
|
| 370 |
+
Notices displayed by works containing it; or
|
| 371 |
+
|
| 372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 373 |
+
requiring that modified versions of such material be marked in
|
| 374 |
+
reasonable ways as different from the original version; or
|
| 375 |
+
|
| 376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 377 |
+
authors of the material; or
|
| 378 |
+
|
| 379 |
+
e) Declining to grant rights under trademark law for use of some
|
| 380 |
+
trade names, trademarks, or service marks; or
|
| 381 |
+
|
| 382 |
+
f) Requiring indemnification of licensors and authors of that
|
| 383 |
+
material by anyone who conveys the material (or modified versions of
|
| 384 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 385 |
+
any liability that these contractual assumptions directly impose on
|
| 386 |
+
those licensors and authors.
|
| 387 |
+
|
| 388 |
+
All other non-permissive additional terms are considered "further
|
| 389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 390 |
+
received it, or any part of it, contains a notice stating that it is
|
| 391 |
+
governed by this License along with a term that is a further
|
| 392 |
+
restriction, you may remove that term. If a license document contains
|
| 393 |
+
a further restriction but permits relicensing or conveying under this
|
| 394 |
+
License, you may add to a covered work material governed by the terms
|
| 395 |
+
of that license document, provided that the further restriction does
|
| 396 |
+
not survive such relicensing or conveying.
|
| 397 |
+
|
| 398 |
+
If you add terms to a covered work in accord with this section, you
|
| 399 |
+
must place, in the relevant source files, a statement of the
|
| 400 |
+
additional terms that apply to those files, or a notice indicating
|
| 401 |
+
where to find the applicable terms.
|
| 402 |
+
|
| 403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 404 |
+
form of a separately written license, or stated as exceptions;
|
| 405 |
+
the above requirements apply either way.
|
| 406 |
+
|
| 407 |
+
8. Termination.
|
| 408 |
+
|
| 409 |
+
You may not propagate or modify a covered work except as expressly
|
| 410 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 411 |
+
modify it is void, and will automatically terminate your rights under
|
| 412 |
+
this License (including any patent licenses granted under the third
|
| 413 |
+
paragraph of section 11).
|
| 414 |
+
|
| 415 |
+
However, if you cease all violation of this License, then your
|
| 416 |
+
license from a particular copyright holder is reinstated (a)
|
| 417 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 419 |
+
holder fails to notify you of the violation by some reasonable means
|
| 420 |
+
prior to 60 days after the cessation.
|
| 421 |
+
|
| 422 |
+
Moreover, your license from a particular copyright holder is
|
| 423 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 424 |
+
violation by some reasonable means, this is the first time you have
|
| 425 |
+
received notice of violation of this License (for any work) from that
|
| 426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 427 |
+
your receipt of the notice.
|
| 428 |
+
|
| 429 |
+
Termination of your rights under this section does not terminate the
|
| 430 |
+
licenses of parties who have received copies or rights from you under
|
| 431 |
+
this License. If your rights have been terminated and not permanently
|
| 432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 433 |
+
material under section 10.
|
| 434 |
+
|
| 435 |
+
9. Acceptance Not Required for Having Copies.
|
| 436 |
+
|
| 437 |
+
You are not required to accept this License in order to receive or
|
| 438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 440 |
+
to receive a copy likewise does not require acceptance. However,
|
| 441 |
+
nothing other than this License grants you permission to propagate or
|
| 442 |
+
modify any covered work. These actions infringe copyright if you do
|
| 443 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 444 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 445 |
+
|
| 446 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 447 |
+
|
| 448 |
+
Each time you convey a covered work, the recipient automatically
|
| 449 |
+
receives a license from the original licensors, to run, modify and
|
| 450 |
+
propagate that work, subject to this License. You are not responsible
|
| 451 |
+
for enforcing compliance by third parties with this License.
|
| 452 |
+
|
| 453 |
+
An "entity transaction" is a transaction transferring control of an
|
| 454 |
+
organization, or substantially all assets of one, or subdividing an
|
| 455 |
+
organization, or merging organizations. If propagation of a covered
|
| 456 |
+
work results from an entity transaction, each party to that
|
| 457 |
+
transaction who receives a copy of the work also receives whatever
|
| 458 |
+
licenses to the work the party's predecessor in interest had or could
|
| 459 |
+
give under the previous paragraph, plus a right to possession of the
|
| 460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 461 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 462 |
+
|
| 463 |
+
You may not impose any further restrictions on the exercise of the
|
| 464 |
+
rights granted or affirmed under this License. For example, you may
|
| 465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 466 |
+
rights granted under this License, and you may not initiate litigation
|
| 467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 468 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 469 |
+
sale, or importing the Program or any portion of it.
|
| 470 |
+
|
| 471 |
+
11. Patents.
|
| 472 |
+
|
| 473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 474 |
+
License of the Program or a work on which the Program is based. The
|
| 475 |
+
work thus licensed is called the contributor's "contributor version".
|
| 476 |
+
|
| 477 |
+
A contributor's "essential patent claims" are all patent claims
|
| 478 |
+
owned or controlled by the contributor, whether already acquired or
|
| 479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 480 |
+
by this License, of making, using, or selling its contributor version,
|
| 481 |
+
but do not include claims that would be infringed only as a
|
| 482 |
+
consequence of further modification of the contributor version. For
|
| 483 |
+
purposes of this definition, "control" includes the right to grant
|
| 484 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 485 |
+
this License.
|
| 486 |
+
|
| 487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 488 |
+
patent license under the contributor's essential patent claims, to
|
| 489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 490 |
+
propagate the contents of its contributor version.
|
| 491 |
+
|
| 492 |
+
In the following three paragraphs, a "patent license" is any express
|
| 493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 494 |
+
(such as an express permission to practice a patent or covenant not to
|
| 495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 496 |
+
party means to make such an agreement or commitment not to enforce a
|
| 497 |
+
patent against the party.
|
| 498 |
+
|
| 499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 500 |
+
and the Corresponding Source of the work is not available for anyone
|
| 501 |
+
to copy, free of charge and under the terms of this License, through a
|
| 502 |
+
publicly available network server or other readily accessible means,
|
| 503 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 506 |
+
consistent with the requirements of this License, to extend the patent
|
| 507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 508 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 509 |
+
covered work in a country, or your recipient's use of the covered work
|
| 510 |
+
in a country, would infringe one or more identifiable patents in that
|
| 511 |
+
country that you have reason to believe are valid.
|
| 512 |
+
|
| 513 |
+
If, pursuant to or in connection with a single transaction or
|
| 514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 515 |
+
covered work, and grant a patent license to some of the parties
|
| 516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 517 |
+
or convey a specific copy of the covered work, then the patent license
|
| 518 |
+
you grant is automatically extended to all recipients of the covered
|
| 519 |
+
work and works based on it.
|
| 520 |
+
|
| 521 |
+
A patent license is "discriminatory" if it does not include within
|
| 522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 524 |
+
specifically granted under this License. You may not convey a covered
|
| 525 |
+
work if you are a party to an arrangement with a third party that is
|
| 526 |
+
in the business of distributing software, under which you make payment
|
| 527 |
+
to the third party based on the extent of your activity of conveying
|
| 528 |
+
the work, and under which the third party grants, to any of the
|
| 529 |
+
parties who would receive the covered work from you, a discriminatory
|
| 530 |
+
patent license (a) in connection with copies of the covered work
|
| 531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 532 |
+
for and in connection with specific products or compilations that
|
| 533 |
+
contain the covered work, unless you entered into that arrangement,
|
| 534 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 535 |
+
|
| 536 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 537 |
+
any implied license or other defenses to infringement that may
|
| 538 |
+
otherwise be available to you under applicable patent law.
|
| 539 |
+
|
| 540 |
+
12. No Surrender of Others' Freedom.
|
| 541 |
+
|
| 542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 543 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 546 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 548 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 549 |
+
the Program, the only way you could satisfy both those terms and this
|
| 550 |
+
License would be to refrain entirely from conveying the Program.
|
| 551 |
+
|
| 552 |
+
13. Use with the GNU Affero General Public License.
|
| 553 |
+
|
| 554 |
+
Notwithstanding any other provision of this License, you have
|
| 555 |
+
permission to link or combine any covered work with a work licensed
|
| 556 |
+
under version 3 of the GNU Affero General Public License into a single
|
| 557 |
+
combined work, and to convey the resulting work. The terms of this
|
| 558 |
+
License will continue to apply to the part which is the covered work,
|
| 559 |
+
but the special requirements of the GNU Affero General Public License,
|
| 560 |
+
section 13, concerning interaction through a network will apply to the
|
| 561 |
+
combination as such.
|
| 562 |
+
|
| 563 |
+
14. Revised Versions of this License.
|
| 564 |
+
|
| 565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 566 |
+
the GNU General Public License from time to time. Such new versions will
|
| 567 |
+
be similar in spirit to the present version, but may differ in detail to
|
| 568 |
+
address new problems or concerns.
|
| 569 |
+
|
| 570 |
+
Each version is given a distinguishing version number. If the
|
| 571 |
+
Program specifies that a certain numbered version of the GNU General
|
| 572 |
+
Public License "or any later version" applies to it, you have the
|
| 573 |
+
option of following the terms and conditions either of that numbered
|
| 574 |
+
version or of any later version published by the Free Software
|
| 575 |
+
Foundation. If the Program does not specify a version number of the
|
| 576 |
+
GNU General Public License, you may choose any version ever published
|
| 577 |
+
by the Free Software Foundation.
|
| 578 |
+
|
| 579 |
+
If the Program specifies that a proxy can decide which future
|
| 580 |
+
versions of the GNU General Public License can be used, that proxy's
|
| 581 |
+
public statement of acceptance of a version permanently authorizes you
|
| 582 |
+
to choose that version for the Program.
|
| 583 |
+
|
| 584 |
+
Later license versions may give you additional or different
|
| 585 |
+
permissions. However, no additional obligations are imposed on any
|
| 586 |
+
author or copyright holder as a result of your choosing to follow a
|
| 587 |
+
later version.
|
| 588 |
+
|
| 589 |
+
15. Disclaimer of Warranty.
|
| 590 |
+
|
| 591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 599 |
+
|
| 600 |
+
16. Limitation of Liability.
|
| 601 |
+
|
| 602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 610 |
+
SUCH DAMAGES.
|
| 611 |
+
|
| 612 |
+
17. Interpretation of Sections 15 and 16.
|
| 613 |
+
|
| 614 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 615 |
+
above cannot be given local legal effect according to their terms,
|
| 616 |
+
reviewing courts shall apply local law that most closely approximates
|
| 617 |
+
an absolute waiver of all civil liability in connection with the
|
| 618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 619 |
+
copy of the Program in return for a fee.
|
| 620 |
+
|
| 621 |
+
END OF TERMS AND CONDITIONS
|
| 622 |
+
|
| 623 |
+
How to Apply These Terms to Your New Programs
|
| 624 |
+
|
| 625 |
+
If you develop a new program, and you want it to be of the greatest
|
| 626 |
+
possible use to the public, the best way to achieve this is to make it
|
| 627 |
+
free software which everyone can redistribute and change under these terms.
|
| 628 |
+
|
| 629 |
+
To do so, attach the following notices to the program. It is safest
|
| 630 |
+
to attach them to the start of each source file to most effectively
|
| 631 |
+
state the exclusion of warranty; and each file should have at least
|
| 632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 633 |
+
|
| 634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 635 |
+
Copyright (C) <year> <name of author>
|
| 636 |
+
|
| 637 |
+
This program is free software: you can redistribute it and/or modify
|
| 638 |
+
it under the terms of the GNU General Public License as published by
|
| 639 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 640 |
+
(at your option) any later version.
|
| 641 |
+
|
| 642 |
+
This program is distributed in the hope that it will be useful,
|
| 643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 645 |
+
GNU General Public License for more details.
|
| 646 |
+
|
| 647 |
+
You should have received a copy of the GNU General Public License
|
| 648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 649 |
+
|
| 650 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 651 |
+
|
| 652 |
+
If the program does terminal interaction, make it output a short
|
| 653 |
+
notice like this when it starts in an interactive mode:
|
| 654 |
+
|
| 655 |
+
<program> Copyright (C) <year> <name of author>
|
| 656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 657 |
+
This is free software, and you are welcome to redistribute it
|
| 658 |
+
under certain conditions; type `show c' for details.
|
| 659 |
+
|
| 660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
| 661 |
+
parts of the General Public License. Of course, your program's commands
|
| 662 |
+
might be different; for a GUI interface, you would use an "about box".
|
| 663 |
+
|
| 664 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
| 667 |
+
<https://www.gnu.org/licenses/>.
|
| 668 |
+
|
| 669 |
+
The GNU General Public License does not permit incorporating your program
|
| 670 |
+
into proprietary programs. If your program is a subroutine library, you
|
| 671 |
+
may consider it more useful to permit linking proprietary applications with
|
| 672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
| 673 |
+
Public License instead of this License. But first, please read
|
| 674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
|
@@ -1,11 +1,222 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
-
short_description: SCU Auto Course Catcher
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Advanced SCU Course Catcher
|
| 3 |
+
emoji: 🐳
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Advanced SCU Course Catcher
|
| 12 |
+
|
| 13 |
+
这是一个面向 Hugging Face Space 的四川大学选课系统 Web 版抢课面板。当前版本已经从单机脚本改造成了可部署、可并行、可多用户管理的 Flask + Selenium 服务,支持普通用户端和管理员端分离运行。
|
| 14 |
+
|
| 15 |
+
## 当前能力
|
| 16 |
+
|
| 17 |
+
- 普通用户入口:`/login`
|
| 18 |
+
用户使用 `学号 + 密码` 登录,只能看到自己的课程、任务状态和实时日志。
|
| 19 |
+
- 管理员入口:`/admin`
|
| 20 |
+
管理员使用 `账号 + 密码` 登录。此入口不会在用户登录页展示。
|
| 21 |
+
- 多管理员体系
|
| 22 |
+
支持多位普通管理员,支持 1 位超级管理员。超级管理员账号和密码由环境变量 `ADMIN`、`PASSWORD` 提供。
|
| 23 |
+
- 多用户管理
|
| 24 |
+
管理员可以手动录入用户账号、重置密码、启用/禁用用户、查看所有课程目标。
|
| 25 |
+
- 课程录入
|
| 26 |
+
用户自己填写 `课程号` 和 `课序号`,管理员可见全部内容,也可以代为录入和修改。
|
| 27 |
+
- 实时日志
|
| 28 |
+
用户和管理员都可以实时看到程序日志,前端通过 SSE 持续推送。
|
| 29 |
+
- 并行调度
|
| 30 |
+
多用户任务由后台任务调度器并行执行,管理员可以在后台动态设置并行数。
|
| 31 |
+
- Hugging Face Space 适配
|
| 32 |
+
使用 Docker Space 运行,内置 Chromium、chromedriver、中文字体和无头浏览器配置。
|
| 33 |
+
- 登录验证码与提交验证码 OCR
|
| 34 |
+
登录阶段和提交选课阶段都支持验证码 OCR 自动识别。
|
| 35 |
+
- Selenium 自恢复
|
| 36 |
+
单个 Selenium 会话连续错误达到 5 次时,会自动重建浏览器;连续重建 5 个会话仍失败时,任务才会终止。
|
| 37 |
+
|
| 38 |
+
## 运行结构
|
| 39 |
+
|
| 40 |
+
当前实际运行入口和核心模块如下:
|
| 41 |
+
|
| 42 |
+
- `app.py`
|
| 43 |
+
Hugging Face / gunicorn 使用的 WSGI 入口。
|
| 44 |
+
- `space_app.py`
|
| 45 |
+
Flask 路由、页面渲染、登录鉴权、SSE 日志流。
|
| 46 |
+
- `core/config.py`
|
| 47 |
+
运行配置与内部密钥管理。
|
| 48 |
+
- `core/db.py`
|
| 49 |
+
SQLite 数据层。
|
| 50 |
+
- `core/task_manager.py`
|
| 51 |
+
并行调度、任务生命周期管理。
|
| 52 |
+
- `core/course_bot.py`
|
| 53 |
+
Selenium 抢课核心逻辑、验证码识别、重试与重建策略。
|
| 54 |
+
- `webdriver_utils.py`
|
| 55 |
+
Chromium / chromedriver 初始化。
|
| 56 |
+
- `templates/` + `static/`
|
| 57 |
+
用户端、管理员端和响应式前端页面。
|
| 58 |
+
|
| 59 |
+
## 环境变量
|
| 60 |
+
|
| 61 |
+
为了减少 Space 配置复杂度,当前只保留少量必要环境变量。
|
| 62 |
+
|
| 63 |
+
### 必填
|
| 64 |
+
|
| 65 |
+
- `ADMIN`
|
| 66 |
+
超级管理员账号。
|
| 67 |
+
- `PASSWORD`
|
| 68 |
+
超级管理员密码。
|
| 69 |
+
|
| 70 |
+
### 可选
|
| 71 |
+
|
| 72 |
+
- `DATA_DIR`
|
| 73 |
+
数据目录,默认会使用仓库下的 `data/`。在 Hugging Face Space 中建议保持为 `/data`。
|
| 74 |
+
- `CHROME_BIN`
|
| 75 |
+
自定义 Chromium 路径。默认会自动尝试 `/usr/bin/chromium`。
|
| 76 |
+
- `CHROMEDRIVER_PATH`
|
| 77 |
+
自定义 chromedriver 路径。默认会自动尝试 `/usr/bin/chromedriver`。
|
| 78 |
+
|
| 79 |
+
### 不需要再手动配置的内容
|
| 80 |
+
|
| 81 |
+
以下内容已经改为自动生成或写入程序默认值,不需要再手工配置环境变量:
|
| 82 |
+
|
| 83 |
+
- Flask session secret
|
| 84 |
+
- 用户密码加密密钥
|
| 85 |
+
- 默认并行数
|
| 86 |
+
- 登录重试次数
|
| 87 |
+
- Selenium 会话错误阈值
|
| 88 |
+
- Selenium 会话重建阈值
|
| 89 |
+
- 提交验证码重试次数
|
| 90 |
+
- 页面超时时间
|
| 91 |
+
- 日志页容量
|
| 92 |
+
|
| 93 |
+
程序会在 `DATA_DIR/.app_secrets.json` 中自动持久化内部密钥。这样即使以后修改 `ADMIN` 或 `PASSWORD`,也不会导致历史用户密码全部失效。
|
| 94 |
+
|
| 95 |
+
## Hugging Face Space 部署
|
| 96 |
+
|
| 97 |
+
### 1. 创建 Space
|
| 98 |
+
|
| 99 |
+
在 Hugging Face 上创建一个新的 Space:
|
| 100 |
+
|
| 101 |
+
- SDK 选择 `Docker`
|
| 102 |
+
- 端口使用 `7860`
|
| 103 |
+
- 仓库内容直接推送本项目即可
|
| 104 |
+
|
| 105 |
+
本仓库根目录已经提供好 `README.md` 的 Space metadata 和 `Dockerfile`。
|
| 106 |
+
|
| 107 |
+
### 2. 设置 Space Secrets
|
| 108 |
+
|
| 109 |
+
进入 `Settings -> Variables and secrets`,至少配置:
|
| 110 |
+
|
| 111 |
+
- `ADMIN=你的超级管理员账号`
|
| 112 |
+
- `PASSWORD=你的超级管理员密码`
|
| 113 |
+
|
| 114 |
+
通常不需要再设置其他环境变量。
|
| 115 |
+
|
| 116 |
+
如果你想显式指定数据目录,也可以增加:
|
| 117 |
+
|
| 118 |
+
- `DATA_DIR=/data`
|
| 119 |
+
|
| 120 |
+
### 3. 开启持久化存储
|
| 121 |
+
|
| 122 |
+
如果你希望以下数据在 Space 重启后仍然保留,建议在 Space 设置里开启 Persistent Storage:
|
| 123 |
+
|
| 124 |
+
- 用户账号
|
| 125 |
+
- 管理员账号
|
| 126 |
+
- 课程目标
|
| 127 |
+
- 任务历史
|
| 128 |
+
- 运行日志
|
| 129 |
+
- 自动生成的内部密钥文件
|
| 130 |
+
|
| 131 |
+
当前 Dockerfile 已按 `/data` 目录进行适配,并预先处理了目录权限,方便在 Space 中直接持久化。
|
| 132 |
+
|
| 133 |
+
### 4. 推送部署
|
| 134 |
+
|
| 135 |
+
如果你使用 git 推送到 Hugging Face Space,可以参考:
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
git remote add space https://huggingface.co/spaces/<your-name>/<your-space>
|
| 139 |
+
git push space main
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
### 5. 启动方式
|
| 143 |
+
|
| 144 |
+
容器启动命令已经写入 `Dockerfile`:
|
| 145 |
+
|
| 146 |
+
```bash
|
| 147 |
+
gunicorn --bind 0.0.0.0:${PORT:-7860} --workers 1 --threads 8 --timeout 180 app:app
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
这里使用 `1` 个 gunicorn worker,是为了避免多进程情况下每个进程都各自启动一套本地任务调度器。并发能力由应用内部的线程调度和管理员可配置的任务并行数控制。
|
| 151 |
+
|
| 152 |
+
## Space 端建议配置
|
| 153 |
+
|
| 154 |
+
推荐的初始运行策略:
|
| 155 |
+
|
| 156 |
+
- 后台并行数先设置为 `1` 或 `2`
|
| 157 |
+
- 只有在 Space CPU / 内存足够稳定时,再逐步提升
|
| 158 |
+
- 在真实高峰前,先做一次小规模联调
|
| 159 |
+
|
| 160 |
+
对于 CPU 较小的 Space,同时拉起过多 Chromium 会明显增加失败率,因此管理员后台提供了并行数动态调整功能。
|
| 161 |
+
|
| 162 |
+
## 管理员联调清单
|
| 163 |
+
|
| 164 |
+
部署到 Space 后,建议按以下顺序联调:
|
| 165 |
+
|
| 166 |
+
1. 访问 `/admin`,使用 `ADMIN` / `PASSWORD` 登录超级管理员。
|
| 167 |
+
2. 在管理员后台创建 1 个普通管理员、2 个测试用户。
|
| 168 |
+
3. 为两个测试用户分别录入不同课程号和课序号。
|
| 169 |
+
4. 将并行数设置为 `2`。
|
| 170 |
+
5. 分别触发两个用户任务,确认两条任务都能进入队列,并按并行数启动。
|
| 171 |
+
6. 在管理员日志面板确认日志持续刷新,且可以看到不同学号的执行记录。
|
| 172 |
+
7. 使用用户账号访问 `/login`,确认用户只能看到自己的课程和日志。
|
| 173 |
+
8. 在任务运行过程中测试停止任务,确认状态能变为“停止中”并最终收敛。
|
| 174 |
+
9. 如果学校页面出现提交验证码,确认日志中能看到提交阶段验证码识别提示。
|
| 175 |
+
|
| 176 |
+
## 自动化测试
|
| 177 |
+
|
| 178 |
+
仓库当前已补充以下自动化测试:
|
| 179 |
+
|
| 180 |
+
- `tests/test_config.py`
|
| 181 |
+
验证内部密钥在超级管理员账号变更后依然保持稳定。
|
| 182 |
+
- `tests/test_course_bot.py`
|
| 183 |
+
验证 Selenium 会话错误累计后会触发浏览器重建,并验证提交阶段验证码分支。
|
| 184 |
+
- `tests/test_task_manager.py`
|
| 185 |
+
验证任务调度器会严格遵守管理员设置的并行上限。
|
| 186 |
+
- `.github/workflows/linux-tests.yml`
|
| 187 |
+
在 `ubuntu-latest` 上自动运行上述测试,避免关键逻辑只在 Windows 本地验证。
|
| 188 |
+
|
| 189 |
+
本地运行测试:
|
| 190 |
+
|
| 191 |
+
```bash
|
| 192 |
+
python -m unittest discover -s tests -v
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
## 本地运行
|
| 196 |
+
|
| 197 |
+
### 直接运行
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
pip install -r requirements.txt
|
| 201 |
+
set ADMIN=admin
|
| 202 |
+
set PASSWORD=change-me
|
| 203 |
+
python main.py
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
### Docker 运行
|
| 207 |
+
|
| 208 |
+
```bash
|
| 209 |
+
docker build -t advanced-scu-course-catcher .
|
| 210 |
+
docker run --rm -p 7860:7860 \
|
| 211 |
+
-e ADMIN=admin \
|
| 212 |
+
-e PASSWORD=change-me \
|
| 213 |
+
advanced-scu-course-catcher
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
## 重要说明
|
| 217 |
+
|
| 218 |
+
- 本项目当前的任务模型是“持续轮询直到成功、手动停止或达到错误上限”。
|
| 219 |
+
- 用户密码会以应用内部密钥加密后保存在数据库中,用于后台自动登录教务系统。
|
| 220 |
+
- 管理员可以看到全部用户、课程和日志,请在实际使用前明确权限边界。
|
| 221 |
+
- 如果学校选课页面 DOM 结构变化较大,需要同步更新 `core/course_bot.py` 中的选择器以及 `javascript/` 下的辅助脚本。
|
| 222 |
+
- `course_catcher/` 目录是仓库中保留的旧实现,当前运行链路以 `space_app.py + core/*` 为准。
|
app.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from space_app import app
|
build_exe.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from PyInstaller.__main__ import run as pyinstaller_run
|
| 4 |
+
|
| 5 |
+
def main():
|
| 6 |
+
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
| 7 |
+
|
| 8 |
+
pyinstaller_run([
|
| 9 |
+
'main.py',
|
| 10 |
+
'--name=SCU_Course_Catcher',
|
| 11 |
+
'--onefile',
|
| 12 |
+
#'--windowed', #need console
|
| 13 |
+
'--icon=favicon.ico',
|
| 14 |
+
'--add-data=javascript;javascript',
|
| 15 |
+
'--add-data=ocr_provider;ocr_provider',
|
| 16 |
+
'--add-data=webdriver_utils.py;.',
|
| 17 |
+
'--add-data=type_defs.py;.',
|
| 18 |
+
'--add-data=ensure_package_exist.py;.',
|
| 19 |
+
'--add-data=initialize.py;.',
|
| 20 |
+
'--add-data=onnx_inference.py;.',
|
| 21 |
+
'--hidden-import=selenium',
|
| 22 |
+
'--hidden-import=fake_useragent',
|
| 23 |
+
'--hidden-import=dataclasses_json',
|
| 24 |
+
'--hidden-import=onnxruntime',
|
| 25 |
+
'--collect-data=fake_useragent',
|
| 26 |
+
'--collect-submodules=fake_useragent',
|
| 27 |
+
'--collect-data=onnxruntime',
|
| 28 |
+
'--collect-submodules=onnxruntime',
|
| 29 |
+
'--clean',
|
| 30 |
+
])
|
| 31 |
+
|
| 32 |
+
if __name__ == '__main__':
|
| 33 |
+
main()
|
core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Core application package for the Hugging Face Space web service."""
|
core/config.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import secrets
|
| 6 |
+
import shutil
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from cryptography.fernet import Fernet
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
DEFAULT_PARALLEL_LIMIT = 2
|
| 14 |
+
POLL_INTERVAL_SECONDS = 10
|
| 15 |
+
LOGIN_RETRY_LIMIT = 6
|
| 16 |
+
TASK_BACKOFF_SECONDS = 6
|
| 17 |
+
BROWSER_PAGE_TIMEOUT = 40
|
| 18 |
+
LOGS_PAGE_SIZE = 180
|
| 19 |
+
SELENIUM_ERROR_LIMIT = 5
|
| 20 |
+
SELENIUM_RESTART_LIMIT = 5
|
| 21 |
+
SUBMIT_CAPTCHA_RETRY_LIMIT = 5
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _pick_binary(env_name: str, *fallbacks: str) -> str:
|
| 25 |
+
env_value = os.getenv(env_name)
|
| 26 |
+
if env_value:
|
| 27 |
+
return env_value
|
| 28 |
+
for candidate in fallbacks:
|
| 29 |
+
if not candidate:
|
| 30 |
+
continue
|
| 31 |
+
if Path(candidate).exists():
|
| 32 |
+
return candidate
|
| 33 |
+
resolved = shutil.which(candidate)
|
| 34 |
+
if resolved:
|
| 35 |
+
return resolved
|
| 36 |
+
return fallbacks[0] if fallbacks else ""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _load_or_create_internal_secrets(data_dir: Path) -> tuple[str, str]:
|
| 40 |
+
secret_file = data_dir / ".app_secrets.json"
|
| 41 |
+
payload: dict[str, str] = {}
|
| 42 |
+
|
| 43 |
+
if secret_file.exists():
|
| 44 |
+
try:
|
| 45 |
+
raw_payload = json.loads(secret_file.read_text(encoding="utf-8"))
|
| 46 |
+
if isinstance(raw_payload, dict):
|
| 47 |
+
payload = {
|
| 48 |
+
str(key): str(value)
|
| 49 |
+
for key, value in raw_payload.items()
|
| 50 |
+
if isinstance(value, str)
|
| 51 |
+
}
|
| 52 |
+
except (OSError, json.JSONDecodeError):
|
| 53 |
+
payload = {}
|
| 54 |
+
|
| 55 |
+
session_secret = payload.get("session_secret", "").strip()
|
| 56 |
+
encryption_key = payload.get("encryption_key", "").strip()
|
| 57 |
+
changed = False
|
| 58 |
+
|
| 59 |
+
if not session_secret:
|
| 60 |
+
session_secret = secrets.token_hex(32)
|
| 61 |
+
changed = True
|
| 62 |
+
if not encryption_key:
|
| 63 |
+
encryption_key = Fernet.generate_key().decode("utf-8")
|
| 64 |
+
changed = True
|
| 65 |
+
|
| 66 |
+
if changed or not secret_file.exists():
|
| 67 |
+
secret_file.write_text(
|
| 68 |
+
json.dumps(
|
| 69 |
+
{
|
| 70 |
+
"session_secret": session_secret,
|
| 71 |
+
"encryption_key": encryption_key,
|
| 72 |
+
},
|
| 73 |
+
ensure_ascii=False,
|
| 74 |
+
indent=2,
|
| 75 |
+
),
|
| 76 |
+
encoding="utf-8",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
return session_secret, encryption_key
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass(slots=True)
|
| 83 |
+
class AppConfig:
|
| 84 |
+
root_dir: Path
|
| 85 |
+
data_dir: Path
|
| 86 |
+
db_path: Path
|
| 87 |
+
session_secret: str
|
| 88 |
+
encryption_key: str
|
| 89 |
+
super_admin_username: str
|
| 90 |
+
super_admin_password: str
|
| 91 |
+
default_parallel_limit: int
|
| 92 |
+
poll_interval_seconds: int
|
| 93 |
+
login_retry_limit: int
|
| 94 |
+
task_backoff_seconds: int
|
| 95 |
+
browser_page_timeout: int
|
| 96 |
+
logs_page_size: int
|
| 97 |
+
selenium_error_limit: int
|
| 98 |
+
selenium_restart_limit: int
|
| 99 |
+
submit_captcha_retry_limit: int
|
| 100 |
+
chrome_binary: str
|
| 101 |
+
chromedriver_path: str
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def load(cls) -> "AppConfig":
|
| 105 |
+
root_dir = Path(__file__).resolve().parent.parent
|
| 106 |
+
data_dir = Path(os.getenv("DATA_DIR", str(root_dir / "data"))).resolve()
|
| 107 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 108 |
+
|
| 109 |
+
super_admin_username = os.getenv("ADMIN", "superadmin")
|
| 110 |
+
super_admin_password = os.getenv("PASSWORD", "change-me-in-hf-space")
|
| 111 |
+
session_secret, encryption_key = _load_or_create_internal_secrets(data_dir)
|
| 112 |
+
|
| 113 |
+
return cls(
|
| 114 |
+
root_dir=root_dir,
|
| 115 |
+
data_dir=data_dir,
|
| 116 |
+
db_path=data_dir / "course_catcher.db",
|
| 117 |
+
session_secret=session_secret,
|
| 118 |
+
encryption_key=encryption_key,
|
| 119 |
+
super_admin_username=super_admin_username,
|
| 120 |
+
super_admin_password=super_admin_password,
|
| 121 |
+
default_parallel_limit=DEFAULT_PARALLEL_LIMIT,
|
| 122 |
+
poll_interval_seconds=POLL_INTERVAL_SECONDS,
|
| 123 |
+
login_retry_limit=LOGIN_RETRY_LIMIT,
|
| 124 |
+
task_backoff_seconds=TASK_BACKOFF_SECONDS,
|
| 125 |
+
browser_page_timeout=BROWSER_PAGE_TIMEOUT,
|
| 126 |
+
logs_page_size=LOGS_PAGE_SIZE,
|
| 127 |
+
selenium_error_limit=SELENIUM_ERROR_LIMIT,
|
| 128 |
+
selenium_restart_limit=SELENIUM_RESTART_LIMIT,
|
| 129 |
+
submit_captcha_retry_limit=SUBMIT_CAPTCHA_RETRY_LIMIT,
|
| 130 |
+
chrome_binary=_pick_binary(
|
| 131 |
+
"CHROME_BIN",
|
| 132 |
+
"/usr/bin/chromium",
|
| 133 |
+
"/usr/bin/chromium-browser",
|
| 134 |
+
"chromium",
|
| 135 |
+
"chromium-browser",
|
| 136 |
+
),
|
| 137 |
+
chromedriver_path=_pick_binary(
|
| 138 |
+
"CHROMEDRIVER_PATH",
|
| 139 |
+
"/usr/bin/chromedriver",
|
| 140 |
+
"chrom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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Callable
|
| 10 |
+
|
| 11 |
+
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException
|
| 12 |
+
from selenium.webdriver.common.by import By
|
| 13 |
+
from selenium.webdriver.remote.webdriver import WebDriver
|
| 14 |
+
from selenium.webdriver.support.wait import WebDriverWait
|
| 15 |
+
|
| 16 |
+
import onnx_inference
|
| 17 |
+
import webdriver_utils
|
| 18 |
+
from core.db import Database
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
URL_LOGIN = "http://id.scu.edu.cn/enduser/sp/sso/scdxplugin_jwt23?enterpriseId=scdx&target_url=index"
|
| 22 |
+
URL_SELECT_COURSE = "http://zhjw.scu.edu.cn/student/courseSelect/courseSelect/index"
|
| 23 |
+
LOGIN_SUCCESS_PREFIXES = (
|
| 24 |
+
"http://zhjw.scu.edu.cn/index",
|
| 25 |
+
"http://zhjw.scu.edu.cn/",
|
| 26 |
+
"https://zhjw.scu.edu.cn/index",
|
| 27 |
+
"https://zhjw.scu.edu.cn/",
|
| 28 |
+
)
|
| 29 |
+
CATEGORY_META = {
|
| 30 |
+
"plan": {"label": "方案选课", "tab_id": "faxk"},
|
| 31 |
+
"free": {"label": "自由选课", "tab_id": "zyxk"},
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
LOGIN_STUDENT_SELECTORS = [
|
| 35 |
+
(By.XPATH, "//*[@id='app']//form//input[@type='text']"),
|
| 36 |
+
(By.XPATH, "//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[1]/div/div/div[2]/div/input"),
|
| 37 |
+
]
|
| 38 |
+
LOGIN_PASSWORD_SELECTORS = [
|
| 39 |
+
(By.XPATH, "//*[@id='app']//form//input[@type='password']"),
|
| 40 |
+
(By.XPATH, "//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[2]/div/div/div[2]/div/input"),
|
| 41 |
+
]
|
| 42 |
+
LOGIN_CAPTCHA_INPUT_SELECTORS = [
|
| 43 |
+
(By.XPATH, "//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[3]//input"),
|
| 44 |
+
(By.XPATH, "//*[@id='app']//form//input[contains(@placeholder, '验证码')]"),
|
| 45 |
+
]
|
| 46 |
+
LOGIN_CAPTCHA_IMAGE_SELECTORS = [
|
| 47 |
+
(By.XPATH, "//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[3]//img"),
|
| 48 |
+
(By.XPATH, "//*[@id='app']//form//img"),
|
| 49 |
+
]
|
| 50 |
+
LOGIN_BUTTON_SELECTORS = [
|
| 51 |
+
(By.XPATH, "//*[@id='app']//form//button"),
|
| 52 |
+
(By.XPATH, "//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[4]/div/button"),
|
| 53 |
+
]
|
| 54 |
+
SUBMIT_CAPTCHA_IMAGE_SELECTORS = [
|
| 55 |
+
(By.XPATH, "//div[contains(@class,'dialog') or contains(@class,'modal') or contains(@class,'popup')]//img[contains(@src,'base64') or contains(translate(@src,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'captcha')]"),
|
| 56 |
+
(By.XPATH, "//img[contains(@src,'base64')]"),
|
| 57 |
+
(By.XPATH, "//img[contains(translate(@alt,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'captcha') or contains(translate(@class,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'captcha')]"),
|
| 58 |
+
]
|
| 59 |
+
SUBMIT_CAPTCHA_INPUT_SELECTORS = [
|
| 60 |
+
(By.XPATH, "//input[contains(@placeholder,'验证码')]"),
|
| 61 |
+
(By.XPATH, "//input[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'captcha')]"),
|
| 62 |
+
(By.XPATH, "//input[contains(translate(@name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'captcha')]"),
|
| 63 |
+
]
|
| 64 |
+
SUBMIT_CAPTCHA_BUTTON_SELECTORS = [
|
| 65 |
+
(By.XPATH, "//button[contains(.,'确定') or contains(.,'提交') or contains(.,'确认') or contains(.,'验证')]"),
|
| 66 |
+
(By.XPATH, "//input[(@type='button' or @type='submit') and (contains(@value,'确定') or contains(@value,'提交') or contains(@value,'确认') or contains(@value,'验证'))]"),
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class FatalCredentialsError(Exception):
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class RecoverableAutomationError(Exception):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass(slots=True)
|
| 79 |
+
class TaskResult:
|
| 80 |
+
status: str
|
| 81 |
+
error: str = ""
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class CourseBot:
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
*,
|
| 88 |
+
config,
|
| 89 |
+
store: Database,
|
| 90 |
+
task_id: int,
|
| 91 |
+
user: dict,
|
| 92 |
+
password: str,
|
| 93 |
+
logger: Callable[[str, str], None],
|
| 94 |
+
) -> None:
|
| 95 |
+
self.config = config
|
| 96 |
+
self.store = store
|
| 97 |
+
self.task_id = task_id
|
| 98 |
+
self.user = user
|
| 99 |
+
self.password = password
|
| 100 |
+
self.logger = logger
|
| 101 |
+
self.root_dir = Path(__file__).resolve().parent.parent
|
| 102 |
+
self.select_course_js = (self.root_dir / "javascript" / "select_course.js").read_text(encoding="utf-8")
|
| 103 |
+
self.check_result_js = (self.root_dir / "javascript" / "check_result.js").read_text(encoding="utf-8")
|
| 104 |
+
self.captcha_solver = onnx_inference.CaptchaONNXInference(
|
| 105 |
+
model_path=str(self.root_dir / "ocr_provider" / "captcha_model.onnx")
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def run(self, stop_event) -> TaskResult:
|
| 109 |
+
exhausted_sessions = 0
|
| 110 |
+
while not stop_event.is_set():
|
| 111 |
+
courses = self.store.list_courses_for_user(self.user["id"])
|
| 112 |
+
if not courses:
|
| 113 |
+
self.logger("INFO", "当前没有待抢课程,任务自动结束。")
|
| 114 |
+
return TaskResult(status="completed")
|
| 115 |
+
|
| 116 |
+
driver: WebDriver | None = None
|
| 117 |
+
session_ready = False
|
| 118 |
+
session_error_count = 0
|
| 119 |
+
try:
|
| 120 |
+
self.logger(
|
| 121 |
+
"INFO",
|
| 122 |
+
f"启动新的 Selenium 会话。��计已重建 {exhausted_sessions}/{self.config.selenium_restart_limit} 次。",
|
| 123 |
+
)
|
| 124 |
+
driver = webdriver_utils.configure_browser(
|
| 125 |
+
chrome_binary=self.config.chrome_binary,
|
| 126 |
+
chromedriver_path=self.config.chromedriver_path,
|
| 127 |
+
page_timeout=self.config.browser_page_timeout,
|
| 128 |
+
)
|
| 129 |
+
wait = WebDriverWait(driver, self.config.browser_page_timeout, 0.5)
|
| 130 |
+
|
| 131 |
+
while not stop_event.is_set():
|
| 132 |
+
try:
|
| 133 |
+
if not session_ready:
|
| 134 |
+
self._login(driver, wait)
|
| 135 |
+
session_ready = True
|
| 136 |
+
|
| 137 |
+
current_courses = self.store.list_courses_for_user(self.user["id"])
|
| 138 |
+
if not current_courses:
|
| 139 |
+
self.logger("INFO", "所有目标课程都已经从队列中移除,任务完成。")
|
| 140 |
+
return TaskResult(status="completed")
|
| 141 |
+
|
| 142 |
+
if not self._goto_select_course(driver, wait):
|
| 143 |
+
session_error_count = 0
|
| 144 |
+
self._sleep_with_cancel(stop_event, self.config.poll_interval_seconds, "当前不是选课时段,等待下一轮检查。")
|
| 145 |
+
continue
|
| 146 |
+
|
| 147 |
+
attempts = 0
|
| 148 |
+
successes = 0
|
| 149 |
+
grouped_courses = {"plan": [], "free": []}
|
| 150 |
+
for course in current_courses:
|
| 151 |
+
grouped_courses[course["category"]].append(course)
|
| 152 |
+
|
| 153 |
+
for category, items in grouped_courses.items():
|
| 154 |
+
if not items:
|
| 155 |
+
continue
|
| 156 |
+
for course in items:
|
| 157 |
+
if stop_event.is_set():
|
| 158 |
+
break
|
| 159 |
+
attempts += 1
|
| 160 |
+
if self._attempt_single_course(driver, wait, course):
|
| 161 |
+
successes += 1
|
| 162 |
+
|
| 163 |
+
if attempts == 0:
|
| 164 |
+
self.logger("INFO", "没有可执行的课程项目,下一轮将自动重试。")
|
| 165 |
+
elif successes == 0:
|
| 166 |
+
self.logger("INFO", "本轮没有抢到目标课程,准备稍后重试。")
|
| 167 |
+
else:
|
| 168 |
+
self.logger("INFO", f"本轮处理 {attempts} 门课程,成功更新 {successes} 门。")
|
| 169 |
+
|
| 170 |
+
session_error_count = 0
|
| 171 |
+
if exhausted_sessions:
|
| 172 |
+
self.logger("INFO", "当前 Selenium 会话已恢复稳定,浏览器重建错误计数已清零。")
|
| 173 |
+
exhausted_sessions = 0
|
| 174 |
+
|
| 175 |
+
if not self.store.list_courses_for_user(self.user["id"]):
|
| 176 |
+
self.logger("INFO", "全部课程均已处理完成。")
|
| 177 |
+
return TaskResult(status="completed")
|
| 178 |
+
|
| 179 |
+
self._sleep_with_cancel(stop_event, self.config.poll_interval_seconds, "等待下一轮刷新。")
|
| 180 |
+
except FatalCredentialsError as exc:
|
| 181 |
+
self.logger("ERROR", str(exc))
|
| 182 |
+
return TaskResult(status="failed", error=str(exc))
|
| 183 |
+
except RecoverableAutomationError as exc:
|
| 184 |
+
session_ready = False
|
| 185 |
+
session_error_count += 1
|
| 186 |
+
self.logger(
|
| 187 |
+
"WARNING",
|
| 188 |
+
f"当前 Selenium 会话第 {session_error_count}/{self.config.selenium_error_limit} 次可恢复错误: {exc}",
|
| 189 |
+
)
|
| 190 |
+
if session_error_count < self.config.selenium_error_limit:
|
| 191 |
+
self._sleep_with_cancel(
|
| 192 |
+
stop_event,
|
| 193 |
+
self.config.task_backoff_seconds,
|
| 194 |
+
"将在当前 Selenium 会话内继续重试",
|
| 195 |
+
)
|
| 196 |
+
continue
|
| 197 |
+
|
| 198 |
+
exhausted_sessions += 1
|
| 199 |
+
if exhausted_sessions >= self.config.selenium_restart_limit:
|
| 200 |
+
message = (
|
| 201 |
+
f"Selenium 会话连续达到错误上限并已重建 {exhausted_sessions} 次,任务终止。"
|
| 202 |
+
f"最后错误: {exc}"
|
| 203 |
+
)
|
| 204 |
+
self.logger("ERROR", message)
|
| 205 |
+
return TaskResult(status="failed", error=message)
|
| 206 |
+
|
| 207 |
+
self.logger(
|
| 208 |
+
"WARNING",
|
| 209 |
+
f"当前 Selenium 会话连续错误达到 {self.config.selenium_error_limit} 次,准备重建浏览器。"
|
| 210 |
+
f"已耗尽 {exhausted_sessions}/{self.config.selenium_restart_limit} 个会话。",
|
| 211 |
+
)
|
| 212 |
+
break
|
| 213 |
+
except Exception as exc: # pragma: no cover - defensive fallback
|
| 214 |
+
session_ready = False
|
| 215 |
+
session_error_count += 1
|
| 216 |
+
self.logger(
|
| 217 |
+
"WARNING",
|
| 218 |
+
f"当前 Selenium 会话第 {session_error_count}/{self.config.selenium_error_limit} 次未知错误: {exc}",
|
| 219 |
+
)
|
| 220 |
+
if session_error_count < self.config.selenium_error_limit:
|
| 221 |
+
self._sleep_with_cancel(
|
| 222 |
+
stop_event,
|
| 223 |
+
self.config.task_backoff_seconds,
|
| 224 |
+
"当前会话发生未知错误,稍后重试",
|
| 225 |
+
)
|
| 226 |
+
continue
|
| 227 |
+
|
| 228 |
+
exhausted_sessions += 1
|
| 229 |
+
if exhausted_sessions >= self.config.selenium_restart_limit:
|
| 230 |
+
message = (
|
| 231 |
+
f"Selenium 会话连续达到错误上限并已重建 {exhausted_sessions} 次,任务终止。"
|
| 232 |
+
f"最后错误: {exc}"
|
| 233 |
+
)
|
| 234 |
+
self.logger("ERROR", message)
|
| 235 |
+
return TaskResult(status="failed", error=message)
|
| 236 |
+
|
| 237 |
+
self.logger(
|
| 238 |
+
"WARNING",
|
| 239 |
+
f"未知错误累计达到上限,准备重建 Selenium 会话。"
|
| 240 |
+
f"已耗尽 {exhausted_sessions}/{self.config.selenium_restart_limit} 个会话。",
|
| 241 |
+
)
|
| 242 |
+
break
|
| 243 |
+
finally:
|
| 244 |
+
if driver is not None:
|
| 245 |
+
try:
|
| 246 |
+
driver.quit()
|
| 247 |
+
except Exception:
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
self.logger("INFO", "收到停止信号,任务已结束。")
|
| 251 |
+
return TaskResult(status="stopped")
|
| 252 |
+
|
| 253 |
+
def _login(self, driver: WebDriver, wait: WebDriverWait) -> None:
|
| 254 |
+
for attempt in range(1, self.config.login_retry_limit + 1):
|
| 255 |
+
driver.get(URL_LOGIN)
|
| 256 |
+
webdriver_utils.wait_for_ready(wait)
|
| 257 |
+
|
| 258 |
+
std_id_box = self._find_first_visible(driver, LOGIN_STUDENT_SELECTORS, "登录学号输入框", timeout=6)
|
| 259 |
+
password_box = self._find_first_visible(driver, LOGIN_PASSWORD_SELECTORS, "登录密码输入框", timeout=6)
|
| 260 |
+
captcha_box = self._find_first_visible(driver, LOGIN_CAPTCHA_INPUT_SELECTORS, "登录验证码输入框", timeout=6)
|
| 261 |
+
login_button = self._find_first_visible(driver, LOGIN_BUTTON_SELECTORS, "登录按钮", timeout=6)
|
| 262 |
+
captcha_image = self._find_first_visible(driver, LOGIN_CAPTCHA_IMAGE_SELECTORS, "登录验证码图片", timeout=6)
|
| 263 |
+
|
| 264 |
+
captcha_text = self.captcha_solver.classification(self._extract_image_bytes(captcha_image))
|
| 265 |
+
|
| 266 |
+
std_id_box.clear()
|
| 267 |
+
std_id_box.send_keys(self.user["student_id"])
|
| 268 |
+
password_box.clear()
|
| 269 |
+
password_box.send_keys(self.password)
|
| 270 |
+
captcha_box.clear()
|
| 271 |
+
captcha_box.send_keys(captcha_text)
|
| 272 |
+
login_button.click()
|
| 273 |
+
time.sleep(1.2)
|
| 274 |
+
|
| 275 |
+
if any(driver.current_url.startswith(prefix) for prefix in LOGIN_SUCCESS_PREFIXES):
|
| 276 |
+
self.logger("INFO", f"登录成功,耗费 {attempt} 次尝试。")
|
| 277 |
+
return
|
| 278 |
+
|
| 279 |
+
error_message = self._read_login_error(driver)
|
| 280 |
+
if any(token in error_message for token in ("用户名或密码错误", "密码错误", "账号或密码错误", "用户不存在")):
|
| 281 |
+
raise FatalCredentialsError("学号或密码错误,任务已停止,请在面板中更新后重新启动。")
|
| 282 |
+
if error_message:
|
| 283 |
+
self.logger("WARNING", f"登录失败,第 {attempt} 次尝试: {error_message}")
|
| 284 |
+
else:
|
| 285 |
+
self.logger("WARNING", f"登录失败,第 {attempt} 次尝试,未读取到明确错误提示。")
|
| 286 |
+
|
| 287 |
+
raise RecoverableAutomationError("连续多次登录失败,系统将稍后自动重试。")
|
| 288 |
+
|
| 289 |
+
def _goto_select_course(self, driver: WebDriver, wait: WebDriverWait) -> bool:
|
| 290 |
+
driver.get(URL_SELECT_COURSE)
|
| 291 |
+
webdriver_utils.wait_for_ready(wait)
|
| 292 |
+
body_text = self._find(driver, By.TAG_NAME, "body").text
|
| 293 |
+
if "非选课" in body_text or "未到选课时间" in body_text:
|
| 294 |
+
self.logger("INFO", body_text.strip() or "当前不是选课时段。")
|
| 295 |
+
return False
|
| 296 |
+
return True
|
| 297 |
+
|
| 298 |
+
def _attempt_single_course(self, driver: WebDriver, wait: WebDriverWait, course: dict) -> bool:
|
| 299 |
+
category_name = CATEGORY_META[course["category"]]["label"]
|
| 300 |
+
course_key = f'{course["course_id"]}_{course["course_index"]}'
|
| 301 |
+
self.logger("INFO", f"开始尝试 {category_name} {course_key}。")
|
| 302 |
+
|
| 303 |
+
if not self._goto_select_course(driver, wait):
|
| 304 |
+
self.logger("INFO", f"跳过 {course_key},当前系统暂时不在可选课页面。")
|
| 305 |
+
return False
|
| 306 |
+
self._open_category_tab(driver, wait, course["category"])
|
| 307 |
+
|
| 308 |
+
try:
|
| 309 |
+
wait.until(lambda current_driver: current_driver.find_element(By.ID, "ifra"))
|
| 310 |
+
driver.switch_to.frame("ifra")
|
| 311 |
+
course_id_box = self._find(driver, By.ID, "kch")
|
| 312 |
+
search_button = self._find(driver, By.ID, "queryButton")
|
| 313 |
+
course_id_box.clear()
|
| 314 |
+
course_id_box.send_keys(course["course_id"])
|
| 315 |
+
search_button.click()
|
| 316 |
+
wait.until(
|
| 317 |
+
lambda current_driver: current_driver.execute_script(
|
| 318 |
+
"return document.getElementById('queryButton').innerText.indexOf('正在') === -1"
|
| 319 |
+
)
|
| 320 |
+
)
|
| 321 |
+
except TimeoutException as exc:
|
| 322 |
+
raise RecoverableAutomationError("课程查询超时,页面可能暂时无响应。") from exc
|
| 323 |
+
finally:
|
| 324 |
+
driver.switch_to.default_content()
|
| 325 |
+
|
| 326 |
+
time.sleep(0.2)
|
| 327 |
+
found_target = driver.execute_script(self.select_course_js, course_key) == "yes"
|
| 328 |
+
if not found_target:
|
| 329 |
+
self.logger("INFO", f"本轮未找到目标课程 {course_key}。")
|
| 330 |
+
return False
|
| 331 |
+
|
| 332 |
+
self.logger("INFO", f"已勾选目标课程 {course_key},准备提交。")
|
| 333 |
+
results = self._submit_with_optional_captcha(driver, wait, course_key)
|
| 334 |
+
if not results:
|
| 335 |
+
self.logger("WARNING", f"提交 {course_key} 后没有读取到结果列表。")
|
| 336 |
+
return False
|
| 337 |
+
|
| 338 |
+
satisfied = False
|
| 339 |
+
for result in results:
|
| 340 |
+
detail = (result.get("detail") or "").strip()
|
| 341 |
+
subject = (result.get("subject") or course_key).strip()
|
| 342 |
+
if result.get("result"):
|
| 343 |
+
self.logger("SUCCESS", f"成功抢到课程: {subject}")
|
| 344 |
+
satisfied = True
|
| 345 |
+
elif any(token in detail for token in ("已选", "已选择", "已经选", "已在已选课程")):
|
| 346 |
+
self.logger("INFO", f"课程已在系统中存在,自动从队列移除: {subject}")
|
| 347 |
+
satisfied = True
|
| 348 |
+
else:
|
| 349 |
+
self.logger("WARNING", f"课程 {subject} 抢课失败: {detail or '未知原因'}")
|
| 350 |
+
|
| 351 |
+
if satisfied:
|
| 352 |
+
self.store.remove_course_by_identity(
|
| 353 |
+
self.user["id"],
|
| 354 |
+
course["category"],
|
| 355 |
+
course["course_id"],
|
| 356 |
+
course["course_index"],
|
| 357 |
+
)
|
| 358 |
+
return True
|
| 359 |
+
return False
|
| 360 |
+
|
| 361 |
+
def _submit_with_optional_captcha(self, driver: WebDriver, wait: WebDriverWait, course_key: str) -> list[dict]:
|
| 362 |
+
submit_button = self._find(driver, By.ID, "submitButton")
|
| 363 |
+
submit_button.click()
|
| 364 |
+
|
| 365 |
+
for attempt in range(1, self.config.submit_captcha_retry_limit + 1):
|
| 366 |
+
state = self._wait_for_submit_state(driver, wait)
|
| 367 |
+
if state == "result":
|
| 368 |
+
return self._read_result_page(driver, wait)
|
| 369 |
+
if state == "captcha":
|
| 370 |
+
self.logger("INFO", f"提交 {course_key} 时检测到验证码,第 {attempt} 次自动识别。")
|
| 371 |
+
if not self._solve_visible_submit_captcha(driver):
|
| 372 |
+
raise RecoverableAutomationError("提交选课时检测到验证码,但未能自动完成识别与提交。")
|
| 373 |
+
continue
|
| 374 |
+
self.logger("WARNING", f"提交 {course_key} 后页面未返回结果,也未检测到验证码。")
|
| 375 |
+
|
| 376 |
+
raise RecoverableAutomationError("提交选课后连续多次遇到验证码或未返回结果。")
|
| 377 |
+
|
| 378 |
+
def _wait_for_submit_state(self, driver: WebDriver, wait: WebDriverWait) -> str:
|
| 379 |
+
script = """
|
| 380 |
+
const visible = (el) => {
|
| 381 |
+
if (!el) return false;
|
| 382 |
+
const style = window.getComputedStyle(el);
|
| 383 |
+
const rect = el.getBoundingClientRect();
|
| 384 |
+
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
|
| 385 |
+
};
|
| 386 |
+
if (document.querySelector('#xkresult tbody tr')) return 'result';
|
| 387 |
+
const input = Array.from(document.querySelectorAll('input')).find((el) => {
|
| 388 |
+
const text = `${el.placeholder || ''} ${el.id || ''} ${el.name || ''} ${el.className || ''}`;
|
| 389 |
+
return visible(el) && /验证码|captcha/i.test(text);
|
| 390 |
+
});
|
| 391 |
+
const img = Array.from(document.querySelectorAll('img')).find((el) => {
|
| 392 |
+
const text = `${el.src || ''} ${el.id || ''} ${el.alt || ''} ${el.className || ''}`;
|
| 393 |
+
return visible(el) && (/captcha/i.test(text) || (el.src || '').includes('base64') || (el.naturalWidth >= 50 && el.naturalWidth <= 240 && el.naturalHeight >= 20 && el.naturalHeight <= 120));
|
| 394 |
+
});
|
| 395 |
+
const button = Array.from(document.querySelectorAll('button, input[type="button"], input[type="submit"]')).find((el) => {
|
| 396 |
+
const text = `${el.innerText || ''} ${el.value || ''}`;
|
| 397 |
+
return visible(el) && /确定|提交|确认|验证/.test(text);
|
| 398 |
+
});
|
| 399 |
+
if (input && img && button) return 'captcha';
|
| 400 |
+
return 'pending';
|
| 401 |
+
"""
|
| 402 |
+
try:
|
| 403 |
+
wait.until(lambda current_driver: current_driver.execute_script(script) != "pending")
|
| 404 |
+
except TimeoutException:
|
| 405 |
+
return "pending"
|
| 406 |
+
return str(driver.execute_script(script))
|
| 407 |
+
|
| 408 |
+
def _solve_visible_submit_captcha(self, driver: WebDriver) -> bool:
|
| 409 |
+
image = self._find_first_visible_optional(driver, SUBMIT_CAPTCHA_IMAGE_SELECTORS, timeout=3)
|
| 410 |
+
input_box = self._find_first_visible_optional(driver, SUBMIT_CAPTCHA_INPUT_SELECTORS, timeout=3)
|
| 411 |
+
button = self._find_first_visible_optional(driver, SUBMIT_CAPTCHA_BUTTON_SELECTORS, timeout=3)
|
| 412 |
+
if not image or not input_box or not button:
|
| 413 |
+
return False
|
| 414 |
+
|
| 415 |
+
captcha_text = self.captcha_solver.classification(self._extract_image_bytes(image))
|
| 416 |
+
self.logger("INFO", f"提交验证码 OCR 输出: {captcha_text}")
|
| 417 |
+
input_box.clear()
|
| 418 |
+
input_box.send_keys(captcha_text)
|
| 419 |
+
button.click()
|
| 420 |
+
time.sleep(1.0)
|
| 421 |
+
return True
|
| 422 |
+
|
| 423 |
+
def _open_category_tab(self, driver: WebDriver, wait: WebDriverWait, category: str) -> None:
|
| 424 |
+
tab_id = CATEGORY_META[category]["tab_id"]
|
| 425 |
+
tab = self._find(driver, By.ID, tab_id)
|
| 426 |
+
tab.click()
|
| 427 |
+
webdriver_utils.wait_for_ready(wait)
|
| 428 |
+
time.sleep(0.2)
|
| 429 |
+
|
| 430 |
+
def _read_result_page(self, driver: WebDriver, wait: WebDriverWait) -> list[dict]:
|
| 431 |
+
try:
|
| 432 |
+
webdriver_utils.wait_for_ready(wait)
|
| 433 |
+
wait.until(
|
| 434 |
+
lambda current_driver: current_driver.execute_script(
|
| 435 |
+
"""
|
| 436 |
+
const node = document.querySelector('#xkresult tbody tr');
|
| 437 |
+
return Boolean(node);
|
| 438 |
+
"""
|
| 439 |
+
)
|
| 440 |
+
)
|
| 441 |
+
return json.loads(driver.execute_script(self.check_result_js))
|
| 442 |
+
except Exception as exc:
|
| 443 |
+
raise RecoverableAutomationError("读取选课结果失败,页面结构可能发生变化。") from exc
|
| 444 |
+
|
| 445 |
+
def _read_login_error(self, driver: WebDriver) -> str:
|
| 446 |
+
script = """
|
| 447 |
+
const nodes = Array.from(document.querySelectorAll('body span, body div'));
|
| 448 |
+
for (const node of nodes) {
|
| 449 |
+
const text = (node.innerText || '').trim();
|
| 450 |
+
if (!text) continue;
|
| 451 |
+
if (/验证码|密码|用户|账号/.test(text)) return text;
|
| 452 |
+
}
|
| 453 |
+
return '';
|
| 454 |
+
"""
|
| 455 |
+
raw_message = driver.execute_script(script) or ""
|
| 456 |
+
message = re.sub(r"\s+", " ", str(raw_message)).strip()
|
| 457 |
+
return message
|
| 458 |
+
|
| 459 |
+
@staticmethod
|
| 460 |
+
def _extract_image_bytes(image_element) -> bytes:
|
| 461 |
+
source = image_element.get_attribute("src") or ""
|
| 462 |
+
if "base64," in source:
|
| 463 |
+
return base64.b64decode(source.split("base64,", 1)[1])
|
| 464 |
+
return image_element.screenshot_as_png
|
| 465 |
+
|
| 466 |
+
def _find_first_visible(self, driver: WebDriver, selectors: list[tuple[str, str]], label: str, timeout: int = 0):
|
| 467 |
+
element = self._find_first_visible_optional(driver, selectors, timeout=timeout)
|
| 468 |
+
if element is None:
|
| 469 |
+
raise RecoverableAutomationError(f"页面元素未找到: {label}")
|
| 470 |
+
return element
|
| 471 |
+
|
| 472 |
+
@staticmethod
|
| 473 |
+
def _find_first_visible_optional(driver: WebDriver, selectors: list[tuple[str, str]], timeout: int = 0):
|
| 474 |
+
deadline = time.monotonic() + max(0, timeout)
|
| 475 |
+
while True:
|
| 476 |
+
for by, value in selectors:
|
| 477 |
+
try:
|
| 478 |
+
elements = driver.find_elements(by, value)
|
| 479 |
+
except WebDriverException:
|
| 480 |
+
continue
|
| 481 |
+
for element in elements:
|
| 482 |
+
try:
|
| 483 |
+
if element.is_displayed():
|
| 484 |
+
return element
|
| 485 |
+
except WebDriverException:
|
| 486 |
+
continue
|
| 487 |
+
if timeout <= 0 or time.monotonic() >= deadline:
|
| 488 |
+
return None
|
| 489 |
+
time.sleep(0.2)
|
| 490 |
+
|
| 491 |
+
@staticmethod
|
| 492 |
+
def _find(driver: WebDriver, by: str, value: str):
|
| 493 |
+
try:
|
| 494 |
+
return driver.find_element(by, value)
|
| 495 |
+
except NoSuchElementException as exc:
|
| 496 |
+
raise RecoverableAutomationError(f"页面元素未找到: {value}") from exc
|
| 497 |
+
except WebDriverException as exc:
|
| 498 |
+
raise RecoverableAutomationError(f"浏览器操作失败: {value}") from exc
|
| 499 |
+
|
| 500 |
+
def _sleep_with_cancel(self, stop_event, seconds: int, reason: str) -> None:
|
| 501 |
+
if seconds <= 0:
|
| 502 |
+
return
|
| 503 |
+
self.logger("INFO", f"{reason} 大约 {seconds} 秒。")
|
| 504 |
+
for _ in range(seconds):
|
| 505 |
+
if stop_event.is_set():
|
| 506 |
+
return
|
| 507 |
+
time.sleep(1)
|
core/course_runner.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
|
| 9 |
+
from selenium.common.exceptions import NoSuchElementException, WebDriverException
|
| 10 |
+
from selenium.webdriver.common.by import By
|
| 11 |
+
from selenium.webdriver.support.wait import WebDriverWait
|
| 12 |
+
|
| 13 |
+
import onnx_inference
|
| 14 |
+
import webdriver_utils
|
| 15 |
+
from core.config import CAPTCHA_MODEL_PATH, CHECK_RESULT_JS_PATH, CONFIG, SELECT_COURSE_JS_PATH
|
| 16 |
+
from core.database import Database
|
| 17 |
+
from core.security import decrypt_secret
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
URL_LOGIN = 'http://id.scu.edu.cn/enduser/sp/sso/scdxplugin_jwt23?enterpriseId=scdx&target_url=index'
|
| 21 |
+
URL_SELECT_COURSE = 'http://zhjw.scu.edu.cn/student/courseSelect/courseSelect/index'
|
| 22 |
+
LOGIN_SUCCESS_PREFIXES = (
|
| 23 |
+
'http://zhjw.scu.edu.cn/index',
|
| 24 |
+
'http://zhjw.scu.edu.cn/',
|
| 25 |
+
'https://zhjw.scu.edu.cn/index',
|
| 26 |
+
'https://zhjw.scu.edu.cn/',
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TaskStoppedError(RuntimeError):
|
| 31 |
+
"""Raised when a running task is stopped by the user or the service."""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass(frozen=True)
|
| 35 |
+
class CourseTarget:
|
| 36 |
+
course_id: str
|
| 37 |
+
course_index: str
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CourseTaskRunner:
|
| 41 |
+
def __init__(self, database: Database, context):
|
| 42 |
+
self.database = database
|
| 43 |
+
self.context = context
|
| 44 |
+
self.driver = None
|
| 45 |
+
self.web_wait: WebDriverWait | None = None
|
| 46 |
+
self.select_course_js = SELECT_COURSE_JS_PATH.read_text(encoding='utf-8')
|
| 47 |
+
self.check_result_js = CHECK_RESULT_JS_PATH.read_text(encoding='utf-8')
|
| 48 |
+
self.captcha_solver = onnx_inference.CaptchaONNXInference(model_path=str(CAPTCHA_MODEL_PATH))
|
| 49 |
+
|
| 50 |
+
def run(self) -> None:
|
| 51 |
+
task = self.database.get_task(self.context.task_id)
|
| 52 |
+
if not task:
|
| 53 |
+
raise RuntimeError('任务不存在,无法启动。')
|
| 54 |
+
user = self.database.get_user_by_id(task['user_id'])
|
| 55 |
+
if not user:
|
| 56 |
+
raise RuntimeError('用户不存在,无法执行选课任务。')
|
| 57 |
+
|
| 58 |
+
payload = json.loads(task['task_payload'])
|
| 59 |
+
courses = [CourseTarget(**item) for item in payload.get('courses', [])]
|
| 60 |
+
if not courses:
|
| 61 |
+
self.database.set_task_status(self.context.task_id, 'failed', last_error='没有可执行的课程。')
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
plain_password = decrypt_secret(user['encrypted_password'])
|
| 65 |
+
self.context.log('info', f'任务启动,目标课程 {len(courses)} 门。')
|
| 66 |
+
self.context.log('info', '正在启动浏览器环境。')
|
| 67 |
+
self.driver = webdriver_utils.configure_browser()
|
| 68 |
+
self.web_wait = WebDriverWait(self.driver, CONFIG.page_ready_timeout, 0.4)
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
self._login(student_id=user['student_id'], password=plain_password)
|
| 72 |
+
self._catch_courses(courses)
|
| 73 |
+
finally:
|
| 74 |
+
if self.driver:
|
| 75 |
+
try:
|
| 76 |
+
self.driver.quit()
|
| 77 |
+
except WebDriverException:
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
def _login(self, *, student_id: str, password: str) -> None:
|
| 81 |
+
assert self.driver and self.web_wait
|
| 82 |
+
self.context.log('info', '正在登录川大统一认证。')
|
| 83 |
+
captcha_failures = 0
|
| 84 |
+
other_failures = 0
|
| 85 |
+
|
| 86 |
+
while True:
|
| 87 |
+
self._raise_if_stopped()
|
| 88 |
+
self.driver.get(URL_LOGIN)
|
| 89 |
+
webdriver_utils.wait_for_ready(self.web_wait)
|
| 90 |
+
std_box, password_box, captcha_box, login_button = self._get_login_fields()
|
| 91 |
+
std_box.clear()
|
| 92 |
+
std_box.send_keys(student_id)
|
| 93 |
+
password_box.clear()
|
| 94 |
+
password_box.send_keys(password)
|
| 95 |
+
|
| 96 |
+
captcha_raw, captcha_b64 = self._read_captcha_image()
|
| 97 |
+
if captcha_failures >= CONFIG.captcha_auto_attempts:
|
| 98 |
+
self.context.log('warning', '自动验证码识别已到阈值,等待人工输入。')
|
| 99 |
+
captcha_text = self.context.request_captcha(captcha_b64)
|
| 100 |
+
if not captcha_text:
|
| 101 |
+
raise RuntimeError('验证码等待超时,登录已终止。')
|
| 102 |
+
self.context.log('info', '收到人工验证码,继续登录。')
|
| 103 |
+
else:
|
| 104 |
+
captcha_text = self.captcha_solver.classification(captcha_raw)
|
| 105 |
+
self.context.log('debug', f'验证码模型输出:{captcha_text}')
|
| 106 |
+
|
| 107 |
+
captcha_box.clear()
|
| 108 |
+
captcha_box.send_keys(captcha_text)
|
| 109 |
+
login_button.click()
|
| 110 |
+
|
| 111 |
+
if self._wait_for_login_success():
|
| 112 |
+
self.context.log('info', '登录成功。')
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
error_text = self._read_login_error_text()
|
| 116 |
+
if error_text:
|
| 117 |
+
self.context.log('warning', f'登录返回:{error_text}')
|
| 118 |
+
else:
|
| 119 |
+
self.context.log('warning', '未捕获到明确登录错误,准备重试。')
|
| 120 |
+
|
| 121 |
+
if '密码错误' in error_text or '用户名或密码错误' in error_text or '用户不存在' in error_text:
|
| 122 |
+
raise RuntimeError('学号或密码错误,请先在后台或用户页更新账号信息。')
|
| 123 |
+
|
| 124 |
+
if '验证码' in error_text:
|
| 125 |
+
captcha_failures += 1
|
| 126 |
+
else:
|
| 127 |
+
other_failures += 1
|
| 128 |
+
|
| 129 |
+
if other_failures >= 8:
|
| 130 |
+
raise RuntimeError('登录多次失败,当前无法稳定进入教务系统。')
|
| 131 |
+
|
| 132 |
+
time.sleep(1.0)
|
| 133 |
+
|
| 134 |
+
def _get_login_fields(self):
|
| 135 |
+
assert self.driver
|
| 136 |
+
return (
|
| 137 |
+
self.driver.find_element(
|
| 138 |
+
By.XPATH,
|
| 139 |
+
'//*[@id="app"]/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[1]/div/div/div[2]/div/input',
|
| 140 |
+
),
|
| 141 |
+
self.driver.find_element(
|
| 142 |
+
By.XPATH,
|
| 143 |
+
'//*[@id="app"]/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[2]/div/div/div[2]/div/input',
|
| 144 |
+
),
|
| 145 |
+
self.driver.find_element(
|
| 146 |
+
By.XPATH,
|
| 147 |
+
'//*[@id="app"]/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[3]/div/div/div/div/input',
|
| 148 |
+
),
|
| 149 |
+
self.driver.find_element(
|
| 150 |
+
By.XPATH,
|
| 151 |
+
'//*[@id="app"]/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[4]/div/button',
|
| 152 |
+
),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def _read_captcha_image(self) -> tuple[bytes, str]:
|
| 156 |
+
assert self.driver
|
| 157 |
+
source = self.driver.find_element(
|
| 158 |
+
By.XPATH,
|
| 159 |
+
'//*[@id="app"]/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[3]/div/div/img',
|
| 160 |
+
).get_attribute('src')
|
| 161 |
+
if 'base64,' not in source:
|
| 162 |
+
raise RuntimeError('未能读取验证码图片。')
|
| 163 |
+
encoded = source.split('base64,', 1)[1]
|
| 164 |
+
return base64.b64decode(encoded), encoded
|
| 165 |
+
|
| 166 |
+
def _wait_for_login_success(self) -> bool:
|
| 167 |
+
assert self.driver
|
| 168 |
+
for _ in range(10):
|
| 169 |
+
current_url = self.driver.current_url
|
| 170 |
+
if any(current_url.startswith(prefix) for prefix in LOGIN_SUCCESS_PREFIXES):
|
| 171 |
+
return True
|
| 172 |
+
time.sleep(0.5)
|
| 173 |
+
return False
|
| 174 |
+
|
| 175 |
+
def _read_login_error_text(self) -> str:
|
| 176 |
+
assert self.driver
|
| 177 |
+
try:
|
| 178 |
+
error_box = self.driver.find_element(By.XPATH, '/html/body/div[2]')
|
| 179 |
+
return error_box.text.strip()
|
| 180 |
+
except NoSuchElementException:
|
| 181 |
+
return ''
|
| 182 |
+
|
| 183 |
+
def _goto_select_course(self) -> None:
|
| 184 |
+
assert self.driver and self.web_wait
|
| 185 |
+
self.driver.get(URL_SELECT_COURSE)
|
| 186 |
+
webdriver_utils.wait_for_ready(self.web_wait)
|
| 187 |
+
body_text = self.driver.find_element(By.TAG_NAME, 'body').text
|
| 188 |
+
if '非选课' in body_text:
|
| 189 |
+
raise RuntimeError('当前不在选课时间,教务系统返回了非选课页面。')
|
| 190 |
+
|
| 191 |
+
def _catch_courses(self, courses: list[CourseTarget]) -> None:
|
| 192 |
+
remaining = {(course.course_id, course.course_index) for course in courses}
|
| 193 |
+
round_index = 0
|
| 194 |
+
while remaining:
|
| 195 |
+
self._raise_if_stopped()
|
| 196 |
+
round_index += 1
|
| 197 |
+
self.context.log('info', f'开始第 {round_index} 轮检索,剩余 {len(remaining)} 门课程。')
|
| 198 |
+
round_successes = 0
|
| 199 |
+
for tab_name, tab_id in (('方案选课', 'faxk'), ('自由选课', 'zyxk')):
|
| 200 |
+
if not remaining:
|
| 201 |
+
break
|
| 202 |
+
round_successes += self._process_tab(tab_name, tab_id, remaining)
|
| 203 |
+
|
| 204 |
+
if not remaining:
|
| 205 |
+
self.context.log('info', '所有目标课程已完成。')
|
| 206 |
+
self.database.set_task_status(
|
| 207 |
+
self.context.task_id,
|
| 208 |
+
'success',
|
| 209 |
+
completed_count=len(courses),
|
| 210 |
+
last_error='',
|
| 211 |
+
)
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
if round_successes == 0:
|
| 215 |
+
self.context.log('debug', f'本轮未命中课程,{CONFIG.task_poll_interval:.1f}s 后继续。')
|
| 216 |
+
self._sleep_with_stop(CONFIG.task_poll_interval)
|
| 217 |
+
|
| 218 |
+
def _process_tab(self, tab_name: str, tab_id: str, remaining: set[tuple[str, str]]) -> int:
|
| 219 |
+
assert self.driver and self.web_wait
|
| 220 |
+
self._goto_select_course()
|
| 221 |
+
self.driver.find_element(By.XPATH, f'//*[@id="{tab_id}"]').click()
|
| 222 |
+
webdriver_utils.wait_for_ready(self.web_wait)
|
| 223 |
+
|
| 224 |
+
selected_targets: list[tuple[str, str]] = []
|
| 225 |
+
for course_id, course_index in list(remaining):
|
| 226 |
+
self._raise_if_stopped()
|
| 227 |
+
if self._search_and_mark_current_tab(course_id, course_index):
|
| 228 |
+
selected_targets.append((course_id, course_index))
|
| 229 |
+
self.context.log('info', f'{tab_name} 命中课程 {course_id}_{course_index},已勾选。')
|
| 230 |
+
|
| 231 |
+
if not selected_targets:
|
| 232 |
+
return 0
|
| 233 |
+
|
| 234 |
+
self.driver.find_element(By.XPATH, '//*[@id="submitButton"]').click()
|
| 235 |
+
results = self._read_submit_results()
|
| 236 |
+
successes = 0
|
| 237 |
+
for result in results:
|
| 238 |
+
course_key = self._extract_course_key(result['subject'])
|
| 239 |
+
if result['result'] and course_key in remaining:
|
| 240 |
+
remaining.remove(course_key)
|
| 241 |
+
successes += 1
|
| 242 |
+
completed = self._current_completed_count(remaining)
|
| 243 |
+
self.database.update_task_progress(self.context.task_id, completed)
|
| 244 |
+
self.context.log('info', f"选课成功:{result['subject']}")
|
| 245 |
+
elif result['result']:
|
| 246 |
+
self.context.log('info', f"选课成功,但未能精确匹配目标项:{result['subject']}")
|
| 247 |
+
else:
|
| 248 |
+
self.context.log('warning', f"选课失败:{result['subject']},原因:{result['detail']}")
|
| 249 |
+
return successes
|
| 250 |
+
|
| 251 |
+
def _search_and_mark_current_tab(self, course_id: str, course_index: str) -> bool:
|
| 252 |
+
assert self.driver and self.web_wait
|
| 253 |
+
self.driver.switch_to.frame('ifra')
|
| 254 |
+
try:
|
| 255 |
+
course_id_box = self.driver.find_element(By.XPATH, '//*[@id="kch"]')
|
| 256 |
+
query_button = self.driver.find_element(By.XPATH, '//*[@id="queryButton"]')
|
| 257 |
+
course_id_box.clear()
|
| 258 |
+
course_id_box.send_keys(course_id)
|
| 259 |
+
query_button.click()
|
| 260 |
+
self.web_wait.until(
|
| 261 |
+
lambda driver: driver.execute_script(
|
| 262 |
+
"return document.getElementById('queryButton').innerText.indexOf('正在') === -1"
|
| 263 |
+
)
|
| 264 |
+
)
|
| 265 |
+
finally:
|
| 266 |
+
self.driver.switch_to.default_content()
|
| 267 |
+
|
| 268 |
+
self.web_wait.until(lambda driver: driver.execute_script("return document.getElementById('ifra') != null"))
|
| 269 |
+
time.sleep(0.15)
|
| 270 |
+
return self.driver.execute_script(self.select_course_js, f'{course_id}_{course_index}') == 'yes'
|
| 271 |
+
|
| 272 |
+
def _read_submit_results(self) -> list[dict]:
|
| 273 |
+
assert self.driver and self.web_wait
|
| 274 |
+
self.web_wait.until(
|
| 275 |
+
lambda driver: driver.execute_script("return document.getElementById('xkresult') != null")
|
| 276 |
+
)
|
| 277 |
+
time.sleep(0.3)
|
| 278 |
+
raw = self.driver.execute_script(self.check_result_js)
|
| 279 |
+
return json.loads(raw)
|
| 280 |
+
|
| 281 |
+
def _extract_course_key(self, subject: str) -> tuple[str, str]:
|
| 282 |
+
match = re.search(r'(\d{5,})_(\d{2})', subject)
|
| 283 |
+
if match:
|
| 284 |
+
return (match.group(1), match.group(2))
|
| 285 |
+
numbers = re.findall(r'\d+', subject)
|
| 286 |
+
if len(numbers) >= 2:
|
| 287 |
+
return (numbers[-2], numbers[-1].zfill(2))
|
| 288 |
+
return ('', '')
|
| 289 |
+
|
| 290 |
+
def _current_completed_count(self, remaining: set[tuple[str, str]]) -> int:
|
| 291 |
+
task = self.database.get_task(self.context.task_id)
|
| 292 |
+
total = int(task['total_count']) if task else 0
|
| 293 |
+
return max(0, total - len(remaining))
|
| 294 |
+
|
| 295 |
+
def _sleep_with_stop(self, seconds: float) -> None:
|
| 296 |
+
deadline = time.monotonic() + seconds
|
| 297 |
+
while time.monotonic() < deadline:
|
| 298 |
+
self._raise_if_stopped()
|
| 299 |
+
time.sleep(0.2)
|
| 300 |
+
|
| 301 |
+
def _raise_if_stopped(self) -> None:
|
| 302 |
+
if self.context.should_stop():
|
| 303 |
+
raise TaskStoppedError()
|
core/database.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
import uuid
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
TERMINAL_TASK_STATUSES = {'success', 'failed', 'stopped', 'interrupted'}
|
| 12 |
+
ACTIVE_TASK_STATUSES = {'queued', 'running', 'waiting_captcha'}
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def utc_now() -> str:
|
| 16 |
+
return datetime.now(timezone.utc).isoformat(timespec='seconds')
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Database:
|
| 20 |
+
def __init__(self, db_path: Path):
|
| 21 |
+
self.db_path = Path(db_path)
|
| 22 |
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
def _connect(self) -> sqlite3.Connection:
|
| 25 |
+
connection = sqlite3.connect(self.db_path, check_same_thread=False)
|
| 26 |
+
connection.row_factory = sqlite3.Row
|
| 27 |
+
connection.execute('PRAGMA foreign_keys = ON')
|
| 28 |
+
return connection
|
| 29 |
+
|
| 30 |
+
def initialize(self) -> None:
|
| 31 |
+
with self._connect() as connection:
|
| 32 |
+
connection.execute('PRAGMA journal_mode = WAL')
|
| 33 |
+
connection.executescript(
|
| 34 |
+
"""
|
| 35 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 36 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 37 |
+
student_id TEXT NOT NULL UNIQUE,
|
| 38 |
+
display_name TEXT NOT NULL DEFAULT '',
|
| 39 |
+
encrypted_password TEXT NOT NULL,
|
| 40 |
+
created_at TEXT NOT NULL,
|
| 41 |
+
updated_at TEXT NOT NULL
|
| 42 |
+
);
|
| 43 |
+
|
| 44 |
+
CREATE TABLE IF NOT EXISTS admins (
|
| 45 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 46 |
+
username TEXT NOT NULL UNIQUE,
|
| 47 |
+
password_hash TEXT NOT NULL,
|
| 48 |
+
created_at TEXT NOT NULL,
|
| 49 |
+
updated_at TEXT NOT NULL
|
| 50 |
+
);
|
| 51 |
+
|
| 52 |
+
CREATE TABLE IF NOT EXISTS courses (
|
| 53 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 54 |
+
user_id INTEGER NOT NULL,
|
| 55 |
+
course_id TEXT NOT NULL,
|
| 56 |
+
course_index TEXT NOT NULL,
|
| 57 |
+
created_at TEXT NOT NULL,
|
| 58 |
+
UNIQUE(user_id, course_id, course_index),
|
| 59 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
CREATE TABLE IF NOT EXISTS tasks (
|
| 63 |
+
id TEXT PRIMARY KEY,
|
| 64 |
+
user_id INTEGER NOT NULL,
|
| 65 |
+
status TEXT NOT NULL,
|
| 66 |
+
created_at TEXT NOT NULL,
|
| 67 |
+
started_at TEXT,
|
| 68 |
+
finished_at TEXT,
|
| 69 |
+
requested_by_role TEXT NOT NULL,
|
| 70 |
+
requested_by_identity TEXT NOT NULL,
|
| 71 |
+
stop_requested INTEGER NOT NULL DEFAULT 0,
|
| 72 |
+
last_error TEXT NOT NULL DEFAULT '',
|
| 73 |
+
total_count INTEGER NOT NULL DEFAULT 0,
|
| 74 |
+
completed_count INTEGER NOT NULL DEFAULT 0,
|
| 75 |
+
task_payload TEXT NOT NULL,
|
| 76 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 77 |
+
);
|
| 78 |
+
|
| 79 |
+
CREATE TABLE IF NOT EXISTS task_logs (
|
| 80 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 81 |
+
task_id TEXT NOT NULL,
|
| 82 |
+
level TEXT NOT NULL,
|
| 83 |
+
message TEXT NOT NULL,
|
| 84 |
+
created_at TEXT NOT NULL,
|
| 85 |
+
FOREIGN KEY(task_id) REFERENCES tasks(id) ON DELETE CASCADE
|
| 86 |
+
);
|
| 87 |
+
|
| 88 |
+
CREATE TABLE IF NOT EXISTS settings (
|
| 89 |
+
key TEXT PRIMARY KEY,
|
| 90 |
+
value TEXT NOT NULL
|
| 91 |
+
);
|
| 92 |
+
|
| 93 |
+
CREATE INDEX IF NOT EXISTS idx_courses_user_id ON courses(user_id);
|
| 94 |
+
CREATE INDEX IF NOT EXISTS idx_tasks_user_id ON tasks(user_id);
|
| 95 |
+
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
|
| 96 |
+
CREATE INDEX IF NOT EXISTS idx_task_logs_task_id ON task_logs(task_id, id);
|
| 97 |
+
"""
|
| 98 |
+
)
|
| 99 |
+
connection.execute(
|
| 100 |
+
'INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)',
|
| 101 |
+
('max_parallel_tasks', '2'),
|
| 102 |
+
)
|
| 103 |
+
connection.execute(
|
| 104 |
+
"""
|
| 105 |
+
UPDATE tasks
|
| 106 |
+
SET status = 'interrupted',
|
| 107 |
+
finished_at = ?,
|
| 108 |
+
last_error = CASE
|
| 109 |
+
WHEN COALESCE(last_error, '') = '' THEN '应用重启,上一轮任务被中断。'
|
| 110 |
+
ELSE last_error
|
| 111 |
+
END
|
| 112 |
+
WHERE status IN ('queued', 'running', 'waiting_captcha')
|
| 113 |
+
""",
|
| 114 |
+
(utc_now(),),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def get_setting(self, key: str, default: str = '') -> str:
|
| 118 |
+
with self._connect() as connection:
|
| 119 |
+
row = connection.execute('SELECT value FROM settings WHERE key = ?', (key,)).fetchone()
|
| 120 |
+
return row['value'] if row else default
|
| 121 |
+
|
| 122 |
+
def set_setting(self, key: str, value: str) -> None:
|
| 123 |
+
with self._connect() as connection:
|
| 124 |
+
connection.execute(
|
| 125 |
+
"""
|
| 126 |
+
INSERT INTO settings(key, value) VALUES (?, ?)
|
| 127 |
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
| 128 |
+
""",
|
| 129 |
+
(key, value),
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def get_max_parallel_tasks(self) -> int:
|
| 133 |
+
raw = self.get_setting('max_parallel_tasks', '2')
|
| 134 |
+
try:
|
| 135 |
+
return max(1, min(8, int(raw)))
|
| 136 |
+
except ValueError:
|
| 137 |
+
return 2
|
| 138 |
+
|
| 139 |
+
def create_user(self, student_id: str, encrypted_password: str, display_name: str = '') -> int:
|
| 140 |
+
now = utc_now()
|
| 141 |
+
with self._connect() as connection:
|
| 142 |
+
cursor = connection.execute(
|
| 143 |
+
"""
|
| 144 |
+
INSERT INTO users(student_id, display_name, encrypted_password, created_at, updated_at)
|
| 145 |
+
VALUES (?, ?, ?, ?, ?)
|
| 146 |
+
""",
|
| 147 |
+
(student_id, display_name, encrypted_password, now, now),
|
| 148 |
+
)
|
| 149 |
+
return int(cursor.lastrowid)
|
| 150 |
+
|
| 151 |
+
def update_user(
|
| 152 |
+
self,
|
| 153 |
+
user_id: int,
|
| 154 |
+
*,
|
| 155 |
+
student_id: str | None = None,
|
| 156 |
+
encrypted_password: str | None = None,
|
| 157 |
+
display_name: str | None = None,
|
| 158 |
+
) -> None:
|
| 159 |
+
fields: list[str] = []
|
| 160 |
+
values: list[Any] = []
|
| 161 |
+
if student_id is not None:
|
| 162 |
+
fields.append('student_id = ?')
|
| 163 |
+
values.append(student_id)
|
| 164 |
+
if encrypted_password is not None:
|
| 165 |
+
fields.append('encrypted_password = ?')
|
| 166 |
+
values.append(encrypted_password)
|
| 167 |
+
if display_name is not None:
|
| 168 |
+
fields.append('display_name = ?')
|
| 169 |
+
values.append(display_name)
|
| 170 |
+
if not fields:
|
| 171 |
+
return
|
| 172 |
+
fields.append('updated_at = ?')
|
| 173 |
+
values.append(utc_now())
|
| 174 |
+
values.append(user_id)
|
| 175 |
+
with self._connect() as connection:
|
| 176 |
+
connection.execute(f"UPDATE users SET {', '.join(fields)} WHERE id = ?", values)
|
| 177 |
+
|
| 178 |
+
def delete_user(self, user_id: int) -> None:
|
| 179 |
+
with self._connect() as connection:
|
| 180 |
+
connection.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
| 181 |
+
|
| 182 |
+
def get_user_by_student_id(self, student_id: str) -> dict[str, Any] | None:
|
| 183 |
+
with self._connect() as connection:
|
| 184 |
+
row = connection.execute('SELECT * FROM users WHERE student_id = ?', (student_id,)).fetchone()
|
| 185 |
+
return dict(row) if row else None
|
| 186 |
+
|
| 187 |
+
def get_user_by_id(self, user_id: int) -> dict[str, Any] | None:
|
| 188 |
+
with self._connect() as connection:
|
| 189 |
+
row = connection.execute('SELECT * FROM users WHERE id = ?', (user_id,)).fetchone()
|
| 190 |
+
return dict(row) if row else None
|
| 191 |
+
|
| 192 |
+
def list_users(self) -> list[dict[str, Any]]:
|
| 193 |
+
with self._connect() as connection:
|
| 194 |
+
rows = connection.execute(
|
| 195 |
+
"""
|
| 196 |
+
SELECT
|
| 197 |
+
u.*,
|
| 198 |
+
COUNT(c.id) AS course_count,
|
| 199 |
+
(
|
| 200 |
+
SELECT t.status
|
| 201 |
+
FROM tasks t
|
| 202 |
+
WHERE t.user_id = u.id
|
| 203 |
+
ORDER BY t.created_at DESC
|
| 204 |
+
LIMIT 1
|
| 205 |
+
) AS latest_task_status
|
| 206 |
+
FROM users u
|
| 207 |
+
LEFT JOIN courses c ON c.user_id = u.id
|
| 208 |
+
GROUP BY u.id
|
| 209 |
+
ORDER BY u.created_at ASC
|
| 210 |
+
"""
|
| 211 |
+
).fetchall()
|
| 212 |
+
return [dict(row) for row in rows]
|
| 213 |
+
|
| 214 |
+
def list_courses_for_user(self, user_id: int) -> list[dict[str, Any]]:
|
| 215 |
+
with self._connect() as connection:
|
| 216 |
+
rows = connection.execute(
|
| 217 |
+
"""
|
| 218 |
+
SELECT id, course_id, course_index, created_at
|
| 219 |
+
FROM courses
|
| 220 |
+
WHERE user_id = ?
|
| 221 |
+
ORDER BY created_at ASC, id ASC
|
| 222 |
+
""",
|
| 223 |
+
(user_id,),
|
| 224 |
+
).fetchall()
|
| 225 |
+
return [dict(row) for row in rows]
|
| 226 |
+
|
| 227 |
+
def add_course(self, user_id: int, course_id: str, course_index: str) -> None:
|
| 228 |
+
with self._connect() as connection:
|
| 229 |
+
connection.execute(
|
| 230 |
+
"""
|
| 231 |
+
INSERT OR IGNORE INTO courses(user_id, course_id, course_index, created_at)
|
| 232 |
+
VALUES (?, ?, ?, ?)
|
| 233 |
+
""",
|
| 234 |
+
(user_id, course_id, course_index, utc_now()),
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def delete_course(self, course_row_id: int, user_id: int | None = None) -> None:
|
| 238 |
+
with self._connect() as connection:
|
| 239 |
+
if user_id is None:
|
| 240 |
+
connection.execute('DELETE FROM courses WHERE id = ?', (course_row_id,))
|
| 241 |
+
else:
|
| 242 |
+
connection.execute('DELETE FROM courses WHERE id = ? AND user_id = ?', (course_row_id, user_id))
|
| 243 |
+
|
| 244 |
+
def list_admins(self) -> list[dict[str, Any]]:
|
| 245 |
+
with self._connect() as connection:
|
| 246 |
+
rows = connection.execute('SELECT id, username, created_at, updated_at FROM admins ORDER BY created_at ASC').fetchall()
|
| 247 |
+
return [dict(row) for row in rows]
|
| 248 |
+
|
| 249 |
+
def get_admin_by_username(self, username: str) -> dict[str, Any] | None:
|
| 250 |
+
with self._connect() as connection:
|
| 251 |
+
row = connection.execute('SELECT * FROM admins WHERE username = ?', (username,)).fetchone()
|
| 252 |
+
return dict(row) if row else None
|
| 253 |
+
|
| 254 |
+
def create_admin(self, username: str, password_hash: str) -> int:
|
| 255 |
+
now = utc_now()
|
| 256 |
+
with self._connect() as connection:
|
| 257 |
+
cursor = connection.execute(
|
| 258 |
+
"""
|
| 259 |
+
INSERT INTO admins(username, password_hash, created_at, updated_at)
|
| 260 |
+
VALUES (?, ?, ?, ?)
|
| 261 |
+
""",
|
| 262 |
+
(username, password_hash, now, now),
|
| 263 |
+
)
|
| 264 |
+
return int(cursor.lastrowid)
|
| 265 |
+
|
| 266 |
+
def update_admin_password(self, admin_id: int, password_hash: str) -> None:
|
| 267 |
+
with self._connect() as connection:
|
| 268 |
+
connection.execute(
|
| 269 |
+
'UPDATE admins SET password_hash = ?, updated_at = ? WHERE id = ?',
|
| 270 |
+
(password_hash, utc_now(), admin_id),
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
def delete_admin(self, admin_id: int) -> None:
|
| 274 |
+
with self._connect() as connection:
|
| 275 |
+
connection.execute('DELETE FROM admins WHERE id = ?', (admin_id,))
|
| 276 |
+
|
| 277 |
+
def find_active_task_for_user(self, user_id: int) -> dict[str, Any] | None:
|
| 278 |
+
with self._connect() as connection:
|
| 279 |
+
row = connection.execute(
|
| 280 |
+
"""
|
| 281 |
+
SELECT * FROM tasks
|
| 282 |
+
WHERE user_id = ? AND status IN ('queued', 'running', 'waiting_captcha')
|
| 283 |
+
ORDER BY created_at DESC
|
| 284 |
+
LIMIT 1
|
| 285 |
+
""",
|
| 286 |
+
(user_id,),
|
| 287 |
+
).fetchone()
|
| 288 |
+
return dict(row) if row else None
|
| 289 |
+
|
| 290 |
+
def create_task(
|
| 291 |
+
self,
|
| 292 |
+
*,
|
| 293 |
+
user_id: int,
|
| 294 |
+
requested_by_role: str,
|
| 295 |
+
requested_by_identity: str,
|
| 296 |
+
payload: dict[str, Any],
|
| 297 |
+
) -> str:
|
| 298 |
+
task_id = str(uuid.uuid4())
|
| 299 |
+
now = utc_now()
|
| 300 |
+
with self._connect() as connection:
|
| 301 |
+
connection.execute(
|
| 302 |
+
"""
|
| 303 |
+
INSERT INTO tasks(
|
| 304 |
+
id,
|
| 305 |
+
user_id,
|
| 306 |
+
status,
|
| 307 |
+
created_at,
|
| 308 |
+
requested_by_role,
|
| 309 |
+
requested_by_identity,
|
| 310 |
+
total_count,
|
| 311 |
+
completed_count,
|
| 312 |
+
task_payload
|
| 313 |
+
)
|
| 314 |
+
VALUES (?, ?, 'queued', ?, ?, ?, ?, 0, ?)
|
| 315 |
+
""",
|
| 316 |
+
(
|
| 317 |
+
task_id,
|
| 318 |
+
user_id,
|
| 319 |
+
now,
|
| 320 |
+
requested_by_role,
|
| 321 |
+
requested_by_identity,
|
| 322 |
+
len(payload.get('courses', [])),
|
| 323 |
+
json.dumps(payload, ensure_ascii=False),
|
| 324 |
+
),
|
| 325 |
+
)
|
| 326 |
+
return task_id
|
| 327 |
+
|
| 328 |
+
def claim_next_queued_task(self) -> dict[str, Any] | None:
|
| 329 |
+
with self._connect() as connection:
|
| 330 |
+
row = connection.execute("SELECT id FROM tasks WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1").fetchone()
|
| 331 |
+
if not row:
|
| 332 |
+
return None
|
| 333 |
+
updated = connection.execute(
|
| 334 |
+
"""
|
| 335 |
+
UPDATE tasks
|
| 336 |
+
SET status = 'running', started_at = ?, last_error = ''
|
| 337 |
+
WHERE id = ? AND status = 'queued'
|
| 338 |
+
""",
|
| 339 |
+
(utc_now(), row['id']),
|
| 340 |
+
).rowcount
|
| 341 |
+
if not updated:
|
| 342 |
+
return None
|
| 343 |
+
claimed = connection.execute('SELECT * FROM tasks WHERE id = ?', (row['id'],)).fetchone()
|
| 344 |
+
return dict(claimed) if claimed else None
|
| 345 |
+
|
| 346 |
+
def get_task(self, task_id: str) -> dict[str, Any] | None:
|
| 347 |
+
with self._connect() as connection:
|
| 348 |
+
row = connection.execute('SELECT * FROM tasks WHERE id = ?', (task_id,)).fetchone()
|
| 349 |
+
return dict(row) if row else None
|
| 350 |
+
|
| 351 |
+
def get_task_with_user(self, task_id: str) -> dict[str, Any] | None:
|
| 352 |
+
with self._connect() as connection:
|
| 353 |
+
row = connection.execute(
|
| 354 |
+
"""
|
| 355 |
+
SELECT
|
| 356 |
+
t.*,
|
| 357 |
+
u.student_id,
|
| 358 |
+
u.display_name
|
| 359 |
+
FROM tasks t
|
| 360 |
+
JOIN users u ON u.id = t.user_id
|
| 361 |
+
WHERE t.id = ?
|
| 362 |
+
""",
|
| 363 |
+
(task_id,),
|
| 364 |
+
).fetchone()
|
| 365 |
+
return dict(row) if row else None
|
| 366 |
+
|
| 367 |
+
def list_recent_tasks_for_user(self, user_id: int, limit: int = 12) -> list[dict[str, Any]]:
|
| 368 |
+
with self._connect() as connection:
|
| 369 |
+
rows = connection.execute(
|
| 370 |
+
"""
|
| 371 |
+
SELECT id, user_id, status, created_at, started_at, finished_at, stop_requested,
|
| 372 |
+
last_error, total_count, completed_count
|
| 373 |
+
FROM tasks
|
| 374 |
+
WHERE user_id = ?
|
| 375 |
+
ORDER BY created_at DESC
|
| 376 |
+
LIMIT ?
|
| 377 |
+
""",
|
| 378 |
+
(user_id, limit),
|
| 379 |
+
).fetchall()
|
| 380 |
+
return [dict(row) for row in rows]
|
| 381 |
+
|
| 382 |
+
def list_recent_tasks(self, limit: int = 20) -> list[dict[str, Any]]:
|
| 383 |
+
with self._connect() as connection:
|
| 384 |
+
rows = connection.execute(
|
| 385 |
+
"""
|
| 386 |
+
SELECT
|
| 387 |
+
t.id,
|
| 388 |
+
t.user_id,
|
| 389 |
+
t.status,
|
| 390 |
+
t.created_at,
|
| 391 |
+
t.started_at,
|
| 392 |
+
t.finished_at,
|
| 393 |
+
t.stop_requested,
|
| 394 |
+
t.last_error,
|
| 395 |
+
t.total_count,
|
| 396 |
+
t.completed_count,
|
| 397 |
+
u.student_id,
|
| 398 |
+
u.display_name
|
| 399 |
+
FROM tasks t
|
| 400 |
+
JOIN users u ON u.id = t.user_id
|
| 401 |
+
ORDER BY t.created_at DESC
|
| 402 |
+
LIMIT ?
|
| 403 |
+
""",
|
| 404 |
+
(limit,),
|
| 405 |
+
).fetchall()
|
| 406 |
+
return [dict(row) for row in rows]
|
| 407 |
+
|
| 408 |
+
def set_task_status(
|
| 409 |
+
self,
|
| 410 |
+
task_id: str,
|
| 411 |
+
status: str,
|
| 412 |
+
*,
|
| 413 |
+
last_error: str | None = None,
|
| 414 |
+
completed_count: int | None = None,
|
| 415 |
+
) -> None:
|
| 416 |
+
assignments = ['status = ?']
|
| 417 |
+
values: list[Any] = [status]
|
| 418 |
+
if last_error is not None:
|
| 419 |
+
assignments.append('last_error = ?')
|
| 420 |
+
values.append(last_error)
|
| 421 |
+
if completed_count is not None:
|
| 422 |
+
assignments.append('completed_count = ?')
|
| 423 |
+
values.append(completed_count)
|
| 424 |
+
if status == 'running':
|
| 425 |
+
assignments.append('started_at = COALESCE(started_at, ?)')
|
| 426 |
+
values.append(utc_now())
|
| 427 |
+
if status in TERMINAL_TASK_STATUSES:
|
| 428 |
+
assignments.append('finished_at = ?')
|
| 429 |
+
values.append(utc_now())
|
| 430 |
+
values.append(task_id)
|
| 431 |
+
with self._connect() as connection:
|
| 432 |
+
connection.execute(f"UPDATE tasks SET {', '.join(assignments)} WHERE id = ?", values)
|
| 433 |
+
|
| 434 |
+
def update_task_progress(self, task_id: str, completed_count: int) -> None:
|
| 435 |
+
with self._connect() as connection:
|
| 436 |
+
connection.execute('UPDATE tasks SET completed_count = ? WHERE id = ?', (completed_count, task_id))
|
| 437 |
+
|
| 438 |
+
def request_task_stop(self, task_id: str) -> None:
|
| 439 |
+
with self._connect() as connection:
|
| 440 |
+
connection.execute('UPDATE tasks SET stop_requested = 1 WHERE id = ?', (task_id,))
|
| 441 |
+
|
| 442 |
+
def is_task_stop_requested(self, task_id: str) -> bool:
|
| 443 |
+
with self._connect() as connection:
|
| 444 |
+
row = connection.execute('SELECT stop_requested FROM tasks WHERE id = ?', (task_id,)).fetchone()
|
| 445 |
+
return bool(row and row['stop_requested'])
|
| 446 |
+
|
| 447 |
+
def append_task_log(self, task_id: str, level: str, message: str) -> int:
|
| 448 |
+
with self._connect() as connection:
|
| 449 |
+
cursor = connection.execute(
|
| 450 |
+
"""
|
| 451 |
+
INSERT INTO task_logs(task_id, level, message, created_at)
|
| 452 |
+
VALUES (?, ?, ?, ?)
|
| 453 |
+
""",
|
| 454 |
+
(task_id, level, message, utc_now()),
|
| 455 |
+
)
|
| 456 |
+
return int(cursor.lastrowid)
|
| 457 |
+
|
| 458 |
+
def list_task_logs(self, task_id: str, after_id: int = 0, limit: int = 200) -> list[dict[str, Any]]:
|
| 459 |
+
with self._connect() as connection:
|
| 460 |
+
rows = connection.execute(
|
| 461 |
+
"""
|
| 462 |
+
SELECT id, level, message, created_at
|
| 463 |
+
FROM task_logs
|
| 464 |
+
WHERE task_id = ? AND id > ?
|
| 465 |
+
ORDER BY id ASC
|
| 466 |
+
LIMIT ?
|
| 467 |
+
""",
|
| 468 |
+
(task_id, after_id, limit),
|
| 469 |
+
).fetchall()
|
| 470 |
+
return [dict(row) for row in rows]
|
| 471 |
+
|
| 472 |
+
def get_system_snapshot(self) -> dict[str, Any]:
|
| 473 |
+
with self._connect() as connection:
|
| 474 |
+
return {
|
| 475 |
+
'users': connection.execute('SELECT COUNT(*) FROM users').fetchone()[0],
|
| 476 |
+
'admins': connection.execute('SELECT COUNT(*) FROM admins').fetchone()[0],
|
| 477 |
+
'queued': connection.execute("SELECT COUNT(*) FROM tasks WHERE status = 'queued'").fetchone()[0],
|
| 478 |
+
'running': connection.execute(
|
| 479 |
+
"SELECT COUNT(*) FROM tasks WHERE status IN ('running', 'waiting_captcha')"
|
| 480 |
+
).fetchone()[0],
|
| 481 |
+
'max_parallel_tasks': self.get_max_parallel_tasks(),
|
| 482 |
+
}
|
core/db.py
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sqlite3
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Iterator
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
ACTIVE_TASK_STATUSES = {"pending", "running", "cancel_requested"}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def utc_now() -> str:
|
| 14 |
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Database:
|
| 18 |
+
def __init__(self, path: Path, default_parallel_limit: int = 2) -> None:
|
| 19 |
+
self.path = Path(path)
|
| 20 |
+
self.default_parallel_limit = default_parallel_limit
|
| 21 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
def _connect(self) -> sqlite3.Connection:
|
| 24 |
+
connection = sqlite3.connect(self.path, timeout=30)
|
| 25 |
+
connection.row_factory = sqlite3.Row
|
| 26 |
+
connection.execute("PRAGMA foreign_keys = ON")
|
| 27 |
+
connection.execute("PRAGMA journal_mode = WAL")
|
| 28 |
+
return connection
|
| 29 |
+
|
| 30 |
+
@contextmanager
|
| 31 |
+
def _cursor(self) -> Iterator[tuple[sqlite3.Connection, sqlite3.Cursor]]:
|
| 32 |
+
connection = self._connect()
|
| 33 |
+
try:
|
| 34 |
+
cursor = connection.cursor()
|
| 35 |
+
yield connection, cursor
|
| 36 |
+
connection.commit()
|
| 37 |
+
finally:
|
| 38 |
+
connection.close()
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def _rows_to_dicts(rows: list[sqlite3.Row]) -> list[dict[str, Any]]:
|
| 42 |
+
return [dict(row) for row in rows]
|
| 43 |
+
|
| 44 |
+
def init_db(self) -> None:
|
| 45 |
+
with self._cursor() as (_connection, cursor):
|
| 46 |
+
cursor.executescript(
|
| 47 |
+
"""
|
| 48 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 49 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 50 |
+
student_id TEXT NOT NULL UNIQUE,
|
| 51 |
+
password_encrypted TEXT NOT NULL,
|
| 52 |
+
display_name TEXT NOT NULL DEFAULT '',
|
| 53 |
+
is_active INTEGER NOT NULL DEFAULT 1,
|
| 54 |
+
created_at TEXT NOT NULL,
|
| 55 |
+
updated_at TEXT NOT NULL
|
| 56 |
+
);
|
| 57 |
+
|
| 58 |
+
CREATE TABLE IF NOT EXISTS course_targets (
|
| 59 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 60 |
+
user_id INTEGER NOT NULL,
|
| 61 |
+
category TEXT NOT NULL DEFAULT 'free',
|
| 62 |
+
course_id TEXT NOT NULL,
|
| 63 |
+
course_index TEXT NOT NULL,
|
| 64 |
+
created_at TEXT NOT NULL,
|
| 65 |
+
UNIQUE(user_id, category, course_id, course_index),
|
| 66 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 67 |
+
);
|
| 68 |
+
|
| 69 |
+
CREATE TABLE IF NOT EXISTS admins (
|
| 70 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 71 |
+
username TEXT NOT NULL UNIQUE,
|
| 72 |
+
password_hash TEXT NOT NULL,
|
| 73 |
+
created_at TEXT NOT NULL,
|
| 74 |
+
updated_at TEXT NOT NULL
|
| 75 |
+
);
|
| 76 |
+
|
| 77 |
+
CREATE TABLE IF NOT EXISTS app_settings (
|
| 78 |
+
key TEXT PRIMARY KEY,
|
| 79 |
+
value TEXT NOT NULL,
|
| 80 |
+
updated_at TEXT NOT NULL
|
| 81 |
+
);
|
| 82 |
+
|
| 83 |
+
CREATE TABLE IF NOT EXISTS tasks (
|
| 84 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 85 |
+
user_id INTEGER NOT NULL,
|
| 86 |
+
status TEXT NOT NULL,
|
| 87 |
+
requested_by TEXT NOT NULL,
|
| 88 |
+
requested_by_role TEXT NOT NULL,
|
| 89 |
+
last_error TEXT NOT NULL DEFAULT '',
|
| 90 |
+
created_at TEXT NOT NULL,
|
| 91 |
+
started_at TEXT,
|
| 92 |
+
finished_at TEXT,
|
| 93 |
+
updated_at TEXT NOT NULL,
|
| 94 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 95 |
+
);
|
| 96 |
+
|
| 97 |
+
CREATE TABLE IF NOT EXISTS logs (
|
| 98 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 99 |
+
task_id INTEGER,
|
| 100 |
+
user_id INTEGER,
|
| 101 |
+
scope TEXT NOT NULL,
|
| 102 |
+
level TEXT NOT NULL,
|
| 103 |
+
message TEXT NOT NULL,
|
| 104 |
+
created_at TEXT NOT NULL,
|
| 105 |
+
FOREIGN KEY(task_id) REFERENCES tasks(id) ON DELETE CASCADE,
|
| 106 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 107 |
+
);
|
| 108 |
+
"""
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if self.get_setting("parallel_limit") is None:
|
| 112 |
+
self.set_setting("parallel_limit", str(self.default_parallel_limit))
|
| 113 |
+
|
| 114 |
+
def get_setting(self, key: str) -> str | None:
|
| 115 |
+
with self._cursor() as (_connection, cursor):
|
| 116 |
+
row = cursor.execute("SELECT value FROM app_settings WHERE key = ?", (key,)).fetchone()
|
| 117 |
+
return None if row is None else str(row["value"])
|
| 118 |
+
|
| 119 |
+
def set_setting(self, key: str, value: str) -> None:
|
| 120 |
+
now = utc_now()
|
| 121 |
+
with self._cursor() as (_connection, cursor):
|
| 122 |
+
cursor.execute(
|
| 123 |
+
"""
|
| 124 |
+
INSERT INTO app_settings (key, value, updated_at)
|
| 125 |
+
VALUES (?, ?, ?)
|
| 126 |
+
ON CONFLICT(key) DO UPDATE SET
|
| 127 |
+
value = excluded.value,
|
| 128 |
+
updated_at = excluded.updated_at
|
| 129 |
+
""",
|
| 130 |
+
(key, value, now),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def get_parallel_limit(self) -> int:
|
| 134 |
+
raw_value = self.get_setting("parallel_limit")
|
| 135 |
+
if raw_value is None:
|
| 136 |
+
return self.default_parallel_limit
|
| 137 |
+
try:
|
| 138 |
+
return max(1, int(raw_value))
|
| 139 |
+
except ValueError:
|
| 140 |
+
return self.default_parallel_limit
|
| 141 |
+
|
| 142 |
+
def set_parallel_limit(self, limit: int) -> None:
|
| 143 |
+
self.set_setting("parallel_limit", str(max(1, limit)))
|
| 144 |
+
|
| 145 |
+
def create_user(self, student_id: str, password_encrypted: str, display_name: str = "") -> int:
|
| 146 |
+
now = utc_now()
|
| 147 |
+
with self._cursor() as (_connection, cursor):
|
| 148 |
+
cursor.execute(
|
| 149 |
+
"""
|
| 150 |
+
INSERT INTO users (student_id, password_encrypted, display_name, is_active, created_at, updated_at)
|
| 151 |
+
VALUES (?, ?, ?, 1, ?, ?)
|
| 152 |
+
""",
|
| 153 |
+
(student_id.strip(), password_encrypted, display_name.strip(), now, now),
|
| 154 |
+
)
|
| 155 |
+
return int(cursor.lastrowid)
|
| 156 |
+
|
| 157 |
+
def update_user(
|
| 158 |
+
self,
|
| 159 |
+
user_id: int,
|
| 160 |
+
*,
|
| 161 |
+
password_encrypted: str | None = None,
|
| 162 |
+
display_name: str | None = None,
|
| 163 |
+
is_active: bool | None = None,
|
| 164 |
+
) -> None:
|
| 165 |
+
assignments: list[str] = []
|
| 166 |
+
values: list[Any] = []
|
| 167 |
+
if password_encrypted is not None:
|
| 168 |
+
assignments.append("password_encrypted = ?")
|
| 169 |
+
values.append(password_encrypted)
|
| 170 |
+
if display_name is not None:
|
| 171 |
+
assignments.append("display_name = ?")
|
| 172 |
+
values.append(display_name.strip())
|
| 173 |
+
if is_active is not None:
|
| 174 |
+
assignments.append("is_active = ?")
|
| 175 |
+
values.append(1 if is_active else 0)
|
| 176 |
+
if not assignments:
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
assignments.append("updated_at = ?")
|
| 180 |
+
values.append(utc_now())
|
| 181 |
+
values.append(user_id)
|
| 182 |
+
|
| 183 |
+
with self._cursor() as (_connection, cursor):
|
| 184 |
+
cursor.execute(f"UPDATE users SET {', '.join(assignments)} WHERE id = ?", tuple(values))
|
| 185 |
+
|
| 186 |
+
def toggle_user_active(self, user_id: int) -> dict[str, Any] | None:
|
| 187 |
+
user = self.get_user(user_id)
|
| 188 |
+
if not user:
|
| 189 |
+
return None
|
| 190 |
+
self.update_user(user_id, is_active=not bool(user["is_active"]))
|
| 191 |
+
return self.get_user(user_id)
|
| 192 |
+
|
| 193 |
+
def get_user(self, user_id: int) -> dict[str, Any] | None:
|
| 194 |
+
with self._cursor() as (_connection, cursor):
|
| 195 |
+
row = cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
|
| 196 |
+
return None if row is None else dict(row)
|
| 197 |
+
|
| 198 |
+
def get_user_by_student_id(self, student_id: str) -> dict[str, Any] | None:
|
| 199 |
+
with self._cursor() as (_connection, cursor):
|
| 200 |
+
row = cursor.execute("SELECT * FROM users WHERE student_id = ?", (student_id.strip(),)).fetchone()
|
| 201 |
+
return None if row is None else dict(row)
|
| 202 |
+
|
| 203 |
+
def list_users(self) -> list[dict[str, Any]]:
|
| 204 |
+
with self._cursor() as (_connection, cursor):
|
| 205 |
+
rows = cursor.execute(
|
| 206 |
+
"""
|
| 207 |
+
SELECT
|
| 208 |
+
u.*,
|
| 209 |
+
COUNT(c.id) AS course_count,
|
| 210 |
+
(
|
| 211 |
+
SELECT t.status
|
| 212 |
+
FROM tasks t
|
| 213 |
+
WHERE t.user_id = u.id
|
| 214 |
+
ORDER BY t.created_at DESC
|
| 215 |
+
LIMIT 1
|
| 216 |
+
) AS latest_task_status,
|
| 217 |
+
(
|
| 218 |
+
SELECT t.updated_at
|
| 219 |
+
FROM tasks t
|
| 220 |
+
WHERE t.user_id = u.id
|
| 221 |
+
ORDER BY t.created_at DESC
|
| 222 |
+
LIMIT 1
|
| 223 |
+
) AS latest_task_updated_at
|
| 224 |
+
FROM users u
|
| 225 |
+
LEFT JOIN course_targets c ON c.user_id = u.id
|
| 226 |
+
GROUP BY u.id
|
| 227 |
+
ORDER BY u.student_id ASC
|
| 228 |
+
"""
|
| 229 |
+
).fetchall()
|
| 230 |
+
return self._rows_to_dicts(rows)
|
| 231 |
+
|
| 232 |
+
def add_course(self, user_id: int, category: str, course_id: str, course_index: str) -> int | None:
|
| 233 |
+
now = utc_now()
|
| 234 |
+
normalized_category = "plan" if category == "plan" else "free"
|
| 235 |
+
with self._cursor() as (_connection, cursor):
|
| 236 |
+
cursor.execute(
|
| 237 |
+
"""
|
| 238 |
+
INSERT OR IGNORE INTO course_targets (user_id, category, course_id, course_index, created_at)
|
| 239 |
+
VALUES (?, ?, ?, ?, ?)
|
| 240 |
+
""",
|
| 241 |
+
(user_id, normalized_category, course_id.strip(), course_index.strip(), now),
|
| 242 |
+
)
|
| 243 |
+
return int(cursor.lastrowid) if cursor.lastrowid else None
|
| 244 |
+
|
| 245 |
+
def delete_course(self, course_target_id: int) -> None:
|
| 246 |
+
with self._cursor() as (_connection, cursor):
|
| 247 |
+
cursor.execute("DELETE FROM course_targets WHERE id = ?", (course_target_id,))
|
| 248 |
+
|
| 249 |
+
def remove_course_by_identity(self, user_id: int, category: str, course_id: str, course_index: str) -> None:
|
| 250 |
+
with self._cursor() as (_connection, cursor):
|
| 251 |
+
cursor.execute(
|
| 252 |
+
"""
|
| 253 |
+
DELETE FROM course_targets
|
| 254 |
+
WHERE user_id = ? AND category = ? AND course_id = ? AND course_index = ?
|
| 255 |
+
""",
|
| 256 |
+
(user_id, category, course_id, course_index),
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
def list_courses_for_user(self, user_id: int) -> list[dict[str, Any]]:
|
| 260 |
+
with self._cursor() as (_connection, cursor):
|
| 261 |
+
rows = cursor.execute(
|
| 262 |
+
"""
|
| 263 |
+
SELECT *
|
| 264 |
+
FROM course_targets
|
| 265 |
+
WHERE user_id = ?
|
| 266 |
+
ORDER BY category ASC, course_id ASC, course_index ASC
|
| 267 |
+
""",
|
| 268 |
+
(user_id,),
|
| 269 |
+
).fetchall()
|
| 270 |
+
return self._rows_to_dicts(rows)
|
| 271 |
+
|
| 272 |
+
def create_admin(self, username: str, password_hash: str) -> int:
|
| 273 |
+
now = utc_now()
|
| 274 |
+
with self._cursor() as (_connection, cursor):
|
| 275 |
+
cursor.execute(
|
| 276 |
+
"""
|
| 277 |
+
INSERT INTO admins (username, password_hash, created_at, updated_at)
|
| 278 |
+
VALUES (?, ?, ?, ?)
|
| 279 |
+
""",
|
| 280 |
+
(username.strip(), password_hash, now, now),
|
| 281 |
+
)
|
| 282 |
+
return int(cursor.lastrowid)
|
| 283 |
+
|
| 284 |
+
def get_admin_by_username(self, username: str) -> dict[str, Any] | None:
|
| 285 |
+
with self._cursor() as (_connection, cursor):
|
| 286 |
+
row = cursor.execute("SELECT * FROM admins WHERE username = ?", (username.strip(),)).fetchone()
|
| 287 |
+
return None if row is None else dict(row)
|
| 288 |
+
|
| 289 |
+
def list_admins(self) -> list[dict[str, Any]]:
|
| 290 |
+
with self._cursor() as (_connection, cursor):
|
| 291 |
+
rows = cursor.execute(
|
| 292 |
+
"SELECT id, username, created_at, updated_at FROM admins ORDER BY username ASC"
|
| 293 |
+
).fetchall()
|
| 294 |
+
return self._rows_to_dicts(rows)
|
| 295 |
+
|
| 296 |
+
def find_active_task_for_user(self, user_id: int) -> dict[str, Any] | None:
|
| 297 |
+
with self._cursor() as (_connection, cursor):
|
| 298 |
+
row = cursor.execute(
|
| 299 |
+
"""
|
| 300 |
+
SELECT *
|
| 301 |
+
FROM tasks
|
| 302 |
+
WHERE user_id = ? AND status IN ('pending', 'running', 'cancel_requested')
|
| 303 |
+
ORDER BY created_at DESC
|
| 304 |
+
LIMIT 1
|
| 305 |
+
""",
|
| 306 |
+
(user_id,),
|
| 307 |
+
).fetchone()
|
| 308 |
+
return None if row is None else dict(row)
|
| 309 |
+
|
| 310 |
+
def create_task(self, user_id: int, requested_by: str, requested_by_role: str) -> int:
|
| 311 |
+
now = utc_now()
|
| 312 |
+
with self._cursor() as (_connection, cursor):
|
| 313 |
+
cursor.execute(
|
| 314 |
+
"""
|
| 315 |
+
INSERT INTO tasks (user_id, status, requested_by, requested_by_role, created_at, updated_at)
|
| 316 |
+
VALUES (?, 'pending', ?, ?, ?, ?)
|
| 317 |
+
""",
|
| 318 |
+
(user_id, requested_by, requested_by_role, now, now),
|
| 319 |
+
)
|
| 320 |
+
return int(cursor.lastrowid)
|
| 321 |
+
|
| 322 |
+
def get_task(self, task_id: int) -> dict[str, Any] | None:
|
| 323 |
+
with self._cursor() as (_connection, cursor):
|
| 324 |
+
row = cursor.execute(
|
| 325 |
+
"""
|
| 326 |
+
SELECT
|
| 327 |
+
t.*,
|
| 328 |
+
u.student_id,
|
| 329 |
+
u.display_name
|
| 330 |
+
FROM tasks t
|
| 331 |
+
JOIN users u ON u.id = t.user_id
|
| 332 |
+
WHERE t.id = ?
|
| 333 |
+
""",
|
| 334 |
+
(task_id,),
|
| 335 |
+
).fetchone()
|
| 336 |
+
return None if row is None else dict(row)
|
| 337 |
+
|
| 338 |
+
def get_latest_task_for_user(self, user_id: int) -> dict[str, Any] | None:
|
| 339 |
+
with self._cursor() as (_connection, cursor):
|
| 340 |
+
row = cursor.execute(
|
| 341 |
+
"""
|
| 342 |
+
SELECT
|
| 343 |
+
t.*,
|
| 344 |
+
u.student_id,
|
| 345 |
+
u.display_name
|
| 346 |
+
FROM tasks t
|
| 347 |
+
JOIN users u ON u.id = t.user_id
|
| 348 |
+
WHERE t.user_id = ?
|
| 349 |
+
ORDER BY t.created_at DESC
|
| 350 |
+
LIMIT 1
|
| 351 |
+
""",
|
| 352 |
+
(user_id,),
|
| 353 |
+
).fetchone()
|
| 354 |
+
return None if row is None else dict(row)
|
| 355 |
+
|
| 356 |
+
def list_pending_tasks(self, limit: int) -> list[dict[str, Any]]:
|
| 357 |
+
with self._cursor() as (_connection, cursor):
|
| 358 |
+
rows = cursor.execute(
|
| 359 |
+
"""
|
| 360 |
+
SELECT
|
| 361 |
+
t.*,
|
| 362 |
+
u.student_id,
|
| 363 |
+
u.display_name,
|
| 364 |
+
u.password_encrypted,
|
| 365 |
+
u.is_active
|
| 366 |
+
FROM tasks t
|
| 367 |
+
JOIN users u ON u.id = t.user_id
|
| 368 |
+
WHERE t.status = 'pending'
|
| 369 |
+
ORDER BY t.created_at ASC
|
| 370 |
+
LIMIT ?
|
| 371 |
+
""",
|
| 372 |
+
(limit,),
|
| 373 |
+
).fetchall()
|
| 374 |
+
return self._rows_to_dicts(rows)
|
| 375 |
+
|
| 376 |
+
def list_recent_tasks(self, limit: int = 20) -> list[dict[str, Any]]:
|
| 377 |
+
with self._cursor() as (_connection, cursor):
|
| 378 |
+
rows = cursor.execute(
|
| 379 |
+
"""
|
| 380 |
+
SELECT
|
| 381 |
+
t.*,
|
| 382 |
+
u.student_id,
|
| 383 |
+
u.display_name
|
| 384 |
+
FROM tasks t
|
| 385 |
+
JOIN users u ON u.id = t.user_id
|
| 386 |
+
ORDER BY t.created_at DESC
|
| 387 |
+
LIMIT ?
|
| 388 |
+
""",
|
| 389 |
+
(limit,),
|
| 390 |
+
).fetchall()
|
| 391 |
+
return self._rows_to_dicts(rows)
|
| 392 |
+
|
| 393 |
+
def mark_task_running(self, task_id: int) -> None:
|
| 394 |
+
now = utc_now()
|
| 395 |
+
with self._cursor() as (_connection, cursor):
|
| 396 |
+
cursor.execute(
|
| 397 |
+
"""
|
| 398 |
+
UPDATE tasks
|
| 399 |
+
SET status = 'running',
|
| 400 |
+
started_at = COALESCE(started_at, ?),
|
| 401 |
+
updated_at = ?,
|
| 402 |
+
last_error = ''
|
| 403 |
+
WHERE id = ?
|
| 404 |
+
""",
|
| 405 |
+
(now, now, task_id),
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
def finish_task(self, task_id: int, status: str, last_error: str = "") -> None:
|
| 409 |
+
now = utc_now()
|
| 410 |
+
with self._cursor() as (_connection, cursor):
|
| 411 |
+
cursor.execute(
|
| 412 |
+
"""
|
| 413 |
+
UPDATE tasks
|
| 414 |
+
SET status = ?,
|
| 415 |
+
finished_at = ?,
|
| 416 |
+
updated_at = ?,
|
| 417 |
+
last_error = ?
|
| 418 |
+
WHERE id = ?
|
| 419 |
+
""",
|
| 420 |
+
(status, now, now, last_error, task_id),
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
def update_task_status(self, task_id: int, status: str, last_error: str = "") -> None:
|
| 424 |
+
with self._cursor() as (_connection, cursor):
|
| 425 |
+
cursor.execute(
|
| 426 |
+
"""
|
| 427 |
+
UPDATE tasks
|
| 428 |
+
SET status = ?, updated_at = ?, last_error = ?
|
| 429 |
+
WHERE id = ?
|
| 430 |
+
""",
|
| 431 |
+
(status, utc_now(), last_error, task_id),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
def request_task_stop(self, task_id: int) -> bool:
|
| 435 |
+
task = self.get_task(task_id)
|
| 436 |
+
if not task or task["status"] not in ACTIVE_TASK_STATUSES:
|
| 437 |
+
return False
|
| 438 |
+
with self._cursor() as (_connection, cursor):
|
| 439 |
+
cursor.execute(
|
| 440 |
+
"""
|
| 441 |
+
UPDATE tasks
|
| 442 |
+
SET status = 'cancel_requested', updated_at = ?
|
| 443 |
+
WHERE id = ?
|
| 444 |
+
""",
|
| 445 |
+
(utc_now(), task_id),
|
| 446 |
+
)
|
| 447 |
+
return True
|
| 448 |
+
|
| 449 |
+
def reset_inflight_tasks(self) -> None:
|
| 450 |
+
now = utc_now()
|
| 451 |
+
with self._cursor() as (_connection, cursor):
|
| 452 |
+
cursor.execute(
|
| 453 |
+
"""
|
| 454 |
+
UPDATE tasks
|
| 455 |
+
SET status = 'stopped',
|
| 456 |
+
finished_at = COALESCE(finished_at, ?),
|
| 457 |
+
updated_at = ?
|
| 458 |
+
WHERE status IN ('pending', 'running', 'cancel_requested')
|
| 459 |
+
""",
|
| 460 |
+
(now, now),
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
def add_log(self, task_id: int | None, user_id: int | None, scope: str, level: str, message: str) -> int:
|
| 464 |
+
now = utc_now()
|
| 465 |
+
with self._cursor() as (_connection, cursor):
|
| 466 |
+
cursor.execute(
|
| 467 |
+
"""
|
| 468 |
+
INSERT INTO logs (task_id, user_id, scope, level, message, created_at)
|
| 469 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 470 |
+
""",
|
| 471 |
+
(task_id, user_id, scope, level.upper(), message, now),
|
| 472 |
+
)
|
| 473 |
+
return int(cursor.lastrowid)
|
| 474 |
+
|
| 475 |
+
def list_recent_logs(self, *, user_id: int | None = None, limit: int = 120) -> list[dict[str, Any]]:
|
| 476 |
+
if user_id is None:
|
| 477 |
+
query = """
|
| 478 |
+
SELECT
|
| 479 |
+
l.*,
|
| 480 |
+
u.student_id,
|
| 481 |
+
u.display_name
|
| 482 |
+
FROM logs l
|
| 483 |
+
LEFT JOIN users u ON u.id = l.user_id
|
| 484 |
+
ORDER BY l.id DESC
|
| 485 |
+
LIMIT ?
|
| 486 |
+
"""
|
| 487 |
+
params = (limit,)
|
| 488 |
+
else:
|
| 489 |
+
query = """
|
| 490 |
+
SELECT
|
| 491 |
+
l.*,
|
| 492 |
+
u.student_id,
|
| 493 |
+
u.display_name
|
| 494 |
+
FROM logs l
|
| 495 |
+
LEFT JOIN users u ON u.id = l.user_id
|
| 496 |
+
WHERE l.user_id = ?
|
| 497 |
+
ORDER BY l.id DESC
|
| 498 |
+
LIMIT ?
|
| 499 |
+
"""
|
| 500 |
+
params = (user_id, limit)
|
| 501 |
+
|
| 502 |
+
with self._cursor() as (_connection, cursor):
|
| 503 |
+
rows = cursor.execute(query, params).fetchall()
|
| 504 |
+
return list(reversed(self._rows_to_dicts(rows)))
|
| 505 |
+
|
| 506 |
+
def list_logs_after(self, after_id: int, *, user_id: int | None = None, limit: int = 100) -> list[dict[str, Any]]:
|
| 507 |
+
if user_id is None:
|
| 508 |
+
query = """
|
| 509 |
+
SELECT
|
| 510 |
+
l.*,
|
| 511 |
+
u.student_id,
|
| 512 |
+
u.display_name
|
| 513 |
+
FROM logs l
|
| 514 |
+
LEFT JOIN users u ON u.id = l.user_id
|
| 515 |
+
WHERE l.id > ?
|
| 516 |
+
ORDER BY l.id ASC
|
| 517 |
+
LIMIT ?
|
| 518 |
+
"""
|
| 519 |
+
params = (after_id, limit)
|
| 520 |
+
else:
|
| 521 |
+
query = """
|
| 522 |
+
SELECT
|
| 523 |
+
l.*,
|
| 524 |
+
u.student_id,
|
| 525 |
+
u.display_name
|
| 526 |
+
FROM logs l
|
| 527 |
+
LEFT JOIN users u ON u.id = l.user_id
|
| 528 |
+
WHERE l.id > ? AND l.user_id = ?
|
| 529 |
+
ORDER BY l.id ASC
|
| 530 |
+
LIMIT ?
|
| 531 |
+
"""
|
| 532 |
+
params = (after_id, user_id, limit)
|
| 533 |
+
|
| 534 |
+
with self._cursor() as (_connection, cursor):
|
| 535 |
+
rows = cursor.execute(query, params).fetchall()
|
| 536 |
+
return self._rows_to_dicts(rows)
|
| 537 |
+
|
| 538 |
+
def get_admin_stats(self) -> dict[str, int]:
|
| 539 |
+
with self._cursor() as (_connection, cursor):
|
| 540 |
+
users_count = cursor.execute("SELECT COUNT(*) AS total FROM users").fetchone()["total"]
|
| 541 |
+
courses_count = cursor.execute("SELECT COUNT(*) AS total FROM course_targets").fetchone()["total"]
|
| 542 |
+
admins_count = cursor.execute("SELECT COUNT(*) AS total FROM admins").fetchone()["total"]
|
| 543 |
+
running_count = cursor.execute("SELECT COUNT(*) AS total FROM tasks WHERE status = 'running'").fetchone()["total"]
|
| 544 |
+
pending_count = cursor.execute("SELECT COUNT(*) AS total FROM tasks WHERE status = 'pending'").fetchone()["total"]
|
| 545 |
+
return {
|
| 546 |
+
"users_count": int(users_count),
|
| 547 |
+
"courses_count": int(courses_count),
|
| 548 |
+
"admins_count": int(admins_count) + 1,
|
| 549 |
+
"running_count": int(running_count),
|
| 550 |
+
"pending_count": int(pending_count),
|
| 551 |
+
}
|
core/security.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from cryptography.fernet import Fernet
|
| 4 |
+
from werkzeug.security import check_password_hash, generate_password_hash
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SecretBox:
|
| 8 |
+
def __init__(self, encryption_key: str) -> None:
|
| 9 |
+
self._fernet = Fernet(encryption_key.encode("utf-8"))
|
| 10 |
+
|
| 11 |
+
def encrypt(self, value: str) -> str:
|
| 12 |
+
return self._fernet.encrypt(value.encode("utf-8")).decode("utf-8")
|
| 13 |
+
|
| 14 |
+
def decrypt(self, value: str) -> str:
|
| 15 |
+
return self._fernet.decrypt(value.encode("utf-8")).decode("utf-8")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def hash_password(password: str) -> str:
|
| 19 |
+
return generate_password_hash(password)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def verify_password(password_hash: str, password: str) -> bool:
|
| 23 |
+
return check_password_hash(password_hash, password)
|
core/task_manager.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
import time
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
from core.course_bot import CourseBot, TaskResult
|
| 8 |
+
from core.db import Database
|
| 9 |
+
from core.security import SecretBox
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(slots=True)
|
| 13 |
+
class RunningTask:
|
| 14 |
+
task_id: int
|
| 15 |
+
thread: threading.Thread
|
| 16 |
+
stop_event: threading.Event
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TaskManager:
|
| 20 |
+
def __init__(self, *, config, store: Database, secret_box: SecretBox) -> None:
|
| 21 |
+
self.config = config
|
| 22 |
+
self.store = store
|
| 23 |
+
self.secret_box = secret_box
|
| 24 |
+
self._started = False
|
| 25 |
+
self._startup_lock = threading.Lock()
|
| 26 |
+
self._running_lock = threading.Lock()
|
| 27 |
+
self._shutdown_event = threading.Event()
|
| 28 |
+
self._dispatcher_thread: threading.Thread | None = None
|
| 29 |
+
self._running: dict[int, RunningTask] = {}
|
| 30 |
+
|
| 31 |
+
def start(self) -> None:
|
| 32 |
+
with self._startup_lock:
|
| 33 |
+
if self._started:
|
| 34 |
+
return
|
| 35 |
+
self.store.reset_inflight_tasks()
|
| 36 |
+
self._dispatcher_thread = threading.Thread(target=self._dispatch_loop, name="task-dispatcher", daemon=True)
|
| 37 |
+
self._dispatcher_thread.start()
|
| 38 |
+
self._started = True
|
| 39 |
+
|
| 40 |
+
def shutdown(self) -> None:
|
| 41 |
+
self._shutdown_event.set()
|
| 42 |
+
with self._running_lock:
|
| 43 |
+
for running_task in self._running.values():
|
| 44 |
+
running_task.stop_event.set()
|
| 45 |
+
|
| 46 |
+
def queue_task(self, user_id: int, requested_by: str, requested_by_role: str) -> tuple[dict, bool]:
|
| 47 |
+
active_task = self.store.find_active_task_for_user(user_id)
|
| 48 |
+
if active_task is not None:
|
| 49 |
+
return self.store.get_task(active_task["id"]) or active_task, False
|
| 50 |
+
|
| 51 |
+
task_id = self.store.create_task(user_id, requested_by, requested_by_role)
|
| 52 |
+
self._log(task_id, user_id, "SYSTEM", "INFO", f"任务已进入队列,触发者: {requested_by_role}:{requested_by}")
|
| 53 |
+
return self.store.get_task(task_id), True
|
| 54 |
+
|
| 55 |
+
def stop_task(self, task_id: int) -> bool:
|
| 56 |
+
requested = self.store.request_task_stop(task_id)
|
| 57 |
+
if not requested:
|
| 58 |
+
return False
|
| 59 |
+
self._log(task_id, None, "SYSTEM", "INFO", "收到停止请求,任务会在安全节点退出。")
|
| 60 |
+
with self._running_lock:
|
| 61 |
+
running_task = self._running.get(task_id)
|
| 62 |
+
if running_task is not None:
|
| 63 |
+
running_task.stop_event.set()
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
def _dispatch_loop(self) -> None:
|
| 67 |
+
while not self._shutdown_event.is_set():
|
| 68 |
+
self._cleanup_running_registry()
|
| 69 |
+
parallel_limit = self.store.get_parallel_limit()
|
| 70 |
+
running_count = self._running_count()
|
| 71 |
+
available_slots = max(0, parallel_limit - running_count)
|
| 72 |
+
if available_slots > 0:
|
| 73 |
+
pending_tasks = self.store.list_pending_tasks(available_slots)
|
| 74 |
+
for task in pending_tasks:
|
| 75 |
+
if self._shutdown_event.is_set():
|
| 76 |
+
break
|
| 77 |
+
if not task["is_active"]:
|
| 78 |
+
self.store.finish_task(task["id"], "failed", "该用户已被禁用,任务未执行。")
|
| 79 |
+
self._log(task["id"], task["user_id"], "SYSTEM", "WARNING", "用户已禁用,队列中的任务被取消。")
|
| 80 |
+
continue
|
| 81 |
+
self._launch_task(task["id"])
|
| 82 |
+
time.sleep(1)
|
| 83 |
+
|
| 84 |
+
def _launch_task(self, task_id: int) -> None:
|
| 85 |
+
with self._running_lock:
|
| 86 |
+
if task_id in self._running:
|
| 87 |
+
return
|
| 88 |
+
stop_event = threading.Event()
|
| 89 |
+
thread = threading.Thread(target=self._run_task, args=(task_id, stop_event), name=f"task-{task_id}", daemon=True)
|
| 90 |
+
self._running[task_id] = RunningTask(task_id=task_id, thread=thread, stop_event=stop_event)
|
| 91 |
+
thread.start()
|
| 92 |
+
|
| 93 |
+
def _run_task(self, task_id: int, stop_event: threading.Event) -> None:
|
| 94 |
+
task = self.store.get_task(task_id)
|
| 95 |
+
if task is None:
|
| 96 |
+
self._remove_running(task_id)
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
user = self.store.get_user(task["user_id"])
|
| 100 |
+
if user is None:
|
| 101 |
+
self.store.finish_task(task_id, "failed", "用户不存在。")
|
| 102 |
+
self._remove_running(task_id)
|
| 103 |
+
return
|
| 104 |
+
|
| 105 |
+
self.store.mark_task_running(task_id)
|
| 106 |
+
self._log(task_id, user["id"], "SYSTEM", "INFO", "任务开始执行。")
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
password = self.secret_box.decrypt(user["password_encrypted"])
|
| 110 |
+
bot = CourseBot(
|
| 111 |
+
config=self.config,
|
| 112 |
+
store=self.store,
|
| 113 |
+
task_id=task_id,
|
| 114 |
+
user=user,
|
| 115 |
+
password=password,
|
| 116 |
+
logger=lambda level, message: self._log(task_id, user["id"], "RUNNER", level, message),
|
| 117 |
+
)
|
| 118 |
+
result = bot.run(stop_event)
|
| 119 |
+
except Exception as exc: # pragma: no cover - defensive fallback
|
| 120 |
+
result = TaskResult(status="failed", error=str(exc))
|
| 121 |
+
self._log(task_id, user["id"], "SYSTEM", "ERROR", f"任务初始化失败: {exc}")
|
| 122 |
+
|
| 123 |
+
current_task = self.store.get_task(task_id)
|
| 124 |
+
final_status = result.status
|
| 125 |
+
if current_task and current_task["status"] == "cancel_requested" and result.status != "completed":
|
| 126 |
+
final_status = "stopped"
|
| 127 |
+
elif stop_event.is_set() and result.status != "completed":
|
| 128 |
+
final_status = "stopped"
|
| 129 |
+
|
| 130 |
+
self.store.finish_task(task_id, final_status, result.error)
|
| 131 |
+
final_text = result.error or f"任务已结束,状态: {final_status}"
|
| 132 |
+
level = "ERROR" if final_status == "failed" else "INFO"
|
| 133 |
+
self._log(task_id, user["id"], "SYSTEM", level, final_text)
|
| 134 |
+
self._remove_running(task_id)
|
| 135 |
+
|
| 136 |
+
def _log(self, task_id: int | None, user_id: int | None, scope: str, level: str, message: str) -> None:
|
| 137 |
+
self.store.add_log(task_id, user_id, scope, level, message)
|
| 138 |
+
|
| 139 |
+
def _running_count(self) -> int:
|
| 140 |
+
with self._running_lock:
|
| 141 |
+
return len(self._running)
|
| 142 |
+
|
| 143 |
+
def _cleanup_running_registry(self) -> None:
|
| 144 |
+
finished_ids: list[int] = []
|
| 145 |
+
with self._running_lock:
|
| 146 |
+
for task_id, running_task in self._running.items():
|
| 147 |
+
if not running_task.thread.is_alive():
|
| 148 |
+
finished_ids.append(task_id)
|
| 149 |
+
for task_id in finished_ids:
|
| 150 |
+
self._running.pop(task_id, None)
|
| 151 |
+
|
| 152 |
+
def _remove_running(self, task_id: int) -> None:
|
| 153 |
+
with self._running_lock:
|
| 154 |
+
self._running.pop(task_id, None)
|
course_catcher/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from course_catcher.web import create_app
|
| 2 |
+
|
| 3 |
+
app = create_app()
|
| 4 |
+
|
| 5 |
+
__all__ = ["app", "create_app"]
|
course_catcher/automation.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Callable
|
| 9 |
+
|
| 10 |
+
import onnx_inference
|
| 11 |
+
from selenium import webdriver
|
| 12 |
+
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException
|
| 13 |
+
from selenium.webdriver.chrome.service import Service
|
| 14 |
+
from selenium.webdriver.common.by import By
|
| 15 |
+
from selenium.webdriver.remote.webdriver import WebDriver
|
| 16 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 17 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 18 |
+
|
| 19 |
+
from course_catcher.config import AppConfig
|
| 20 |
+
|
| 21 |
+
SCU_LOGIN_URL = (
|
| 22 |
+
"http://id.scu.edu.cn/enduser/sp/sso/scdxplugin_jwt23?enterpriseId=scdx&target_url=index"
|
| 23 |
+
)
|
| 24 |
+
SCU_SELECT_URL = "http://zhjw.scu.edu.cn/student/courseSelect/courseSelect/index"
|
| 25 |
+
TAB_IDS = {"plan": "faxk", "free": "zyxk"}
|
| 26 |
+
ALREADY_SELECTED_KEYWORDS = ("已选", "已选择", "已修读")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class AutomationError(Exception):
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CredentialsError(AutomationError):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SessionExpiredError(AutomationError):
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TemporaryAutomationError(AutomationError):
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class CourseAutomation:
|
| 46 |
+
def __init__(self, config: AppConfig) -> None:
|
| 47 |
+
self.config = config
|
| 48 |
+
self.select_course_js = Path("javascript/select_course.js").read_text(encoding="utf-8")
|
| 49 |
+
self.check_result_js = Path("javascript/check_result.js").read_text(encoding="utf-8")
|
| 50 |
+
self.captcha_solver = onnx_inference.CaptchaONNXInference(
|
| 51 |
+
model_path=str(Path("ocr_provider") / "captcha_model.onnx")
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def run_until_stopped(
|
| 55 |
+
self,
|
| 56 |
+
task_id: int,
|
| 57 |
+
user_credentials: dict,
|
| 58 |
+
db,
|
| 59 |
+
should_stop: Callable[[], bool],
|
| 60 |
+
log: Callable[[str, str], None],
|
| 61 |
+
) -> tuple[str, str]:
|
| 62 |
+
driver: WebDriver | None = None
|
| 63 |
+
last_error = ""
|
| 64 |
+
try:
|
| 65 |
+
while True:
|
| 66 |
+
if should_stop():
|
| 67 |
+
log("INFO", "收到停止请求,准备安全退出任务。")
|
| 68 |
+
return "stopped", ""
|
| 69 |
+
|
| 70 |
+
pending_courses = db.list_pending_courses(user_credentials["id"])
|
| 71 |
+
if not pending_courses:
|
| 72 |
+
log("SUCCESS", "所有待抢课程都已完成,本轮任务结束。")
|
| 73 |
+
return "completed", ""
|
| 74 |
+
|
| 75 |
+
db.increment_task_attempt(task_id)
|
| 76 |
+
if driver is None:
|
| 77 |
+
log("INFO", "正在启动浏览器会话并登录教务系统。")
|
| 78 |
+
driver = self._build_driver()
|
| 79 |
+
self._login(driver, user_credentials["student_id"], user_credentials["password"], log)
|
| 80 |
+
self._goto_select_course(driver, log)
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
self._run_single_cycle(driver, user_credentials["id"], pending_courses, db, log)
|
| 84 |
+
last_error = ""
|
| 85 |
+
except SessionExpiredError as exc:
|
| 86 |
+
last_error = str(exc)
|
| 87 |
+
log("WARNING", f"{exc},将重新建立会话。")
|
| 88 |
+
self._safe_quit(driver)
|
| 89 |
+
driver = None
|
| 90 |
+
time.sleep(2)
|
| 91 |
+
continue
|
| 92 |
+
except TemporaryAutomationError as exc:
|
| 93 |
+
last_error = str(exc)
|
| 94 |
+
log("WARNING", f"{exc},稍后重试。")
|
| 95 |
+
self._safe_quit(driver)
|
| 96 |
+
driver = None
|
| 97 |
+
except CredentialsError:
|
| 98 |
+
raise
|
| 99 |
+
except Exception as exc: # pragma: no cover - defensive path
|
| 100 |
+
last_error = str(exc)
|
| 101 |
+
log("ERROR", f"本轮执行发生异常:{exc}")
|
| 102 |
+
self._safe_quit(driver)
|
| 103 |
+
driver = None
|
| 104 |
+
|
| 105 |
+
if should_stop():
|
| 106 |
+
log("INFO", "收到停止请求,准备安全退出任务。")
|
| 107 |
+
return "stopped", ""
|
| 108 |
+
|
| 109 |
+
time.sleep(db.get_setting_float("loop_interval_seconds", self.config.loop_interval_seconds))
|
| 110 |
+
except CredentialsError as exc:
|
| 111 |
+
return "failed", str(exc)
|
| 112 |
+
finally:
|
| 113 |
+
self._safe_quit(driver)
|
| 114 |
+
|
| 115 |
+
def _build_driver(self) -> WebDriver:
|
| 116 |
+
options = webdriver.ChromeOptions()
|
| 117 |
+
options.add_argument("--headless=new")
|
| 118 |
+
options.add_argument("--no-sandbox")
|
| 119 |
+
options.add_argument("--disable-dev-shm-usage")
|
| 120 |
+
options.add_argument("--disable-gpu")
|
| 121 |
+
options.add_argument("--disable-blink-features=AutomationControlled")
|
| 122 |
+
options.add_argument("--window-size=1440,1600")
|
| 123 |
+
options.add_argument("--lang=zh-CN")
|
| 124 |
+
options.add_argument(
|
| 125 |
+
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 126 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
chrome_binary = Path(self.config.chrome_binary)
|
| 130 |
+
if chrome_binary.exists():
|
| 131 |
+
options.binary_location = str(chrome_binary)
|
| 132 |
+
|
| 133 |
+
service = None
|
| 134 |
+
chromedriver_binary = Path(self.config.chromedriver_binary)
|
| 135 |
+
if chromedriver_binary.exists():
|
| 136 |
+
service = Service(executable_path=str(chromedriver_binary))
|
| 137 |
+
|
| 138 |
+
driver = webdriver.Chrome(service=service, options=options) if service else webdriver.Chrome(options=options)
|
| 139 |
+
driver.set_page_load_timeout(self.config.request_timeout_seconds)
|
| 140 |
+
driver.implicitly_wait(5)
|
| 141 |
+
return driver
|
| 142 |
+
|
| 143 |
+
def _login(self, driver: WebDriver, student_id: str, password: str, log: Callable[[str, str], None]) -> None:
|
| 144 |
+
for attempt in range(1, self.config.login_retry_limit + 1):
|
| 145 |
+
driver.get(SCU_LOGIN_URL)
|
| 146 |
+
self._wait_ready(driver)
|
| 147 |
+
|
| 148 |
+
student_box = self._find_first(
|
| 149 |
+
driver,
|
| 150 |
+
[
|
| 151 |
+
(By.XPATH, "//*[@id='app']//form//input[@type='text']"),
|
| 152 |
+
(
|
| 153 |
+
By.XPATH,
|
| 154 |
+
"//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[1]/div/div/div[2]/div/input",
|
| 155 |
+
),
|
| 156 |
+
],
|
| 157 |
+
)
|
| 158 |
+
password_box = self._find_first(
|
| 159 |
+
driver,
|
| 160 |
+
[
|
| 161 |
+
(By.XPATH, "//*[@id='app']//form//input[@type='password']"),
|
| 162 |
+
(
|
| 163 |
+
By.XPATH,
|
| 164 |
+
"//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[2]/div/div/div[2]/div/input",
|
| 165 |
+
),
|
| 166 |
+
],
|
| 167 |
+
)
|
| 168 |
+
captcha_box = self._find_first(
|
| 169 |
+
driver,
|
| 170 |
+
[
|
| 171 |
+
(
|
| 172 |
+
By.XPATH,
|
| 173 |
+
"//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[3]//input",
|
| 174 |
+
),
|
| 175 |
+
(By.XPATH, "//*[@id='app']//form//input[contains(@placeholder, '验证码')]"),
|
| 176 |
+
],
|
| 177 |
+
)
|
| 178 |
+
login_button = self._find_first(
|
| 179 |
+
driver,
|
| 180 |
+
[
|
| 181 |
+
(By.XPATH, "//*[@id='app']//form//button"),
|
| 182 |
+
(
|
| 183 |
+
By.XPATH,
|
| 184 |
+
"//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[4]/div/button",
|
| 185 |
+
),
|
| 186 |
+
],
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
student_box.clear()
|
| 190 |
+
student_box.send_keys(student_id)
|
| 191 |
+
password_box.clear()
|
| 192 |
+
password_box.send_keys(password)
|
| 193 |
+
captcha_box.clear()
|
| 194 |
+
captcha_box.send_keys(self._solve_captcha(driver))
|
| 195 |
+
login_button.click()
|
| 196 |
+
|
| 197 |
+
if self._wait_for_login_success(driver):
|
| 198 |
+
log("SUCCESS", "教务系统登录成功。")
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
error_message = self._read_login_error(driver)
|
| 202 |
+
if error_message:
|
| 203 |
+
log("WARNING", f"第 {attempt} 次登录失败:{error_message}")
|
| 204 |
+
if "用户名或密码错误" in error_message or "密码错误" in error_message:
|
| 205 |
+
raise CredentialsError("学生账号或密码错误,请在用户面板更新后重新启动任务。")
|
| 206 |
+
if "验证码" not in error_message and attempt >= 2:
|
| 207 |
+
raise TemporaryAutomationError(error_message)
|
| 208 |
+
else:
|
| 209 |
+
log("WARNING", f"第 {attempt} 次登录失败,未捕获到明确错误提示。")
|
| 210 |
+
|
| 211 |
+
raise TemporaryAutomationError("连续多次登录失败,可能是验证码识别失败或当前系统不可用。")
|
| 212 |
+
|
| 213 |
+
def _wait_for_login_success(self, driver: WebDriver) -> bool:
|
| 214 |
+
try:
|
| 215 |
+
WebDriverWait(driver, 8, 0.5).until(
|
| 216 |
+
lambda current: current.current_url in {"http://zhjw.scu.edu.cn/index", "http://zhjw.scu.edu.cn/"}
|
| 217 |
+
or current.current_url.startswith("http://zhjw.scu.edu.cn/index")
|
| 218 |
+
)
|
| 219 |
+
return True
|
| 220 |
+
except TimeoutException:
|
| 221 |
+
return False
|
| 222 |
+
|
| 223 |
+
def _read_login_error(self, driver: WebDriver) -> str:
|
| 224 |
+
candidates = [
|
| 225 |
+
"/html/body/div[2]",
|
| 226 |
+
"//div[contains(@class, 'el-message') or contains(@class, 'message')]",
|
| 227 |
+
]
|
| 228 |
+
for xpath in candidates:
|
| 229 |
+
try:
|
| 230 |
+
element = driver.find_element(By.XPATH, xpath)
|
| 231 |
+
text = element.text.strip()
|
| 232 |
+
if text:
|
| 233 |
+
return text
|
| 234 |
+
except NoSuchElementException:
|
| 235 |
+
continue
|
| 236 |
+
return ""
|
| 237 |
+
|
| 238 |
+
def _solve_captcha(self, driver: WebDriver) -> str:
|
| 239 |
+
captcha_img = self._find_first(
|
| 240 |
+
driver,
|
| 241 |
+
[
|
| 242 |
+
(
|
| 243 |
+
By.XPATH,
|
| 244 |
+
"//*[@id='app']/div[1]/div/div[2]/div/div[1]/div[2]/div[2]/div/form/div[3]/div/div/img",
|
| 245 |
+
),
|
| 246 |
+
(By.XPATH, "//*[@id='app']//form//img"),
|
| 247 |
+
],
|
| 248 |
+
)
|
| 249 |
+
src = captcha_img.get_attribute("src") or ""
|
| 250 |
+
if "base64," in src:
|
| 251 |
+
image_bytes = base64.b64decode(src.split("base64,", 1)[1])
|
| 252 |
+
else:
|
| 253 |
+
image_bytes = captcha_img.screenshot_as_png
|
| 254 |
+
return self.captcha_solver.classification(image_bytes)
|
| 255 |
+
|
| 256 |
+
def _goto_select_course(self, driver: WebDriver, log: Callable[[str, str], None]) -> None:
|
| 257 |
+
driver.get(SCU_SELECT_URL)
|
| 258 |
+
self._wait_ready(driver)
|
| 259 |
+
body_text = driver.find_element(By.TAG_NAME, "body").text
|
| 260 |
+
if "非选课" in body_text:
|
| 261 |
+
raise TemporaryAutomationError("当前不是可选课时段,教务系统已返回非选课提示")
|
| 262 |
+
if "登录" in body_text and "学号" in body_text:
|
| 263 |
+
raise SessionExpiredError("当前会话已失效,需要重新登录")
|
| 264 |
+
log("INFO", "已进入选课页面。")
|
| 265 |
+
|
| 266 |
+
def _run_single_cycle(
|
| 267 |
+
self,
|
| 268 |
+
driver: WebDriver,
|
| 269 |
+
user_id: int,
|
| 270 |
+
pending_courses: list[dict],
|
| 271 |
+
db,
|
| 272 |
+
log: Callable[[str, str], None],
|
| 273 |
+
) -> None:
|
| 274 |
+
self._goto_select_course(driver, log)
|
| 275 |
+
for tab_name in ("plan", "free"):
|
| 276 |
+
current_pending = db.list_pending_courses(user_id)
|
| 277 |
+
if not current_pending:
|
| 278 |
+
return
|
| 279 |
+
results = self._attempt_tab(driver, tab_name, current_pending, log)
|
| 280 |
+
for result in results:
|
| 281 |
+
parsed = self._extract_course_pair(result["subject"])
|
| 282 |
+
if not parsed:
|
| 283 |
+
log("WARNING", f"无法从结果文本中解析课程号:{result['subject']}")
|
| 284 |
+
continue
|
| 285 |
+
course_id, course_index = parsed
|
| 286 |
+
status = "selected" if self._is_selected_result(result) else "pending"
|
| 287 |
+
db.mark_course_result(user_id, course_id, course_index, status, result["detail"])
|
| 288 |
+
level = "SUCCESS" if status == "selected" else "INFO"
|
| 289 |
+
log(level, f"{course_id}_{course_index}: {result['detail']}")
|
| 290 |
+
if results:
|
| 291 |
+
self._goto_select_course(driver, log)
|
| 292 |
+
|
| 293 |
+
def _attempt_tab(
|
| 294 |
+
self,
|
| 295 |
+
driver: WebDriver,
|
| 296 |
+
tab_name: str,
|
| 297 |
+
courses: list[dict],
|
| 298 |
+
log: Callable[[str, str], None],
|
| 299 |
+
) -> list[dict]:
|
| 300 |
+
tab_id = TAB_IDS[tab_name]
|
| 301 |
+
self._find_first(driver, [(By.ID, tab_id)]).click()
|
| 302 |
+
self._wait_ready(driver)
|
| 303 |
+
selected_any = False
|
| 304 |
+
|
| 305 |
+
for course in courses:
|
| 306 |
+
self._wait_for_iframe(driver)
|
| 307 |
+
driver.switch_to.frame("ifra")
|
| 308 |
+
try:
|
| 309 |
+
course_input = self._find_first(driver, [(By.ID, "kch")], timeout=10)
|
| 310 |
+
query_button = self._find_first(driver, [(By.ID, "queryButton")], timeout=10)
|
| 311 |
+
course_input.clear()
|
| 312 |
+
course_input.send_keys(course["course_id"])
|
| 313 |
+
query_button.click()
|
| 314 |
+
WebDriverWait(driver, 20, 0.3).until(
|
| 315 |
+
lambda current: "正在" not in current.find_element(By.ID, "queryButton").text
|
| 316 |
+
)
|
| 317 |
+
finally:
|
| 318 |
+
driver.switch_to.default_content()
|
| 319 |
+
|
| 320 |
+
self._wait_for_iframe(driver)
|
| 321 |
+
found = (
|
| 322 |
+
driver.execute_script(
|
| 323 |
+
self.select_course_js,
|
| 324 |
+
f"{course['course_id']}_{course['course_index']}",
|
| 325 |
+
)
|
| 326 |
+
== "yes"
|
| 327 |
+
)
|
| 328 |
+
if found:
|
| 329 |
+
selected_any = True
|
| 330 |
+
log("INFO", f"[{tab_name}] 已勾选课程 {course['course_id']}_{course['course_index']}。")
|
| 331 |
+
else:
|
| 332 |
+
log("INFO", f"[{tab_name}] 未找到课程 {course['course_id']}_{course['course_index']}。")
|
| 333 |
+
|
| 334 |
+
if not selected_any:
|
| 335 |
+
return []
|
| 336 |
+
|
| 337 |
+
submit_button = self._find_first(driver, [(By.ID, "submitButton")], timeout=10)
|
| 338 |
+
submit_button.click()
|
| 339 |
+
return self._collect_results(driver)
|
| 340 |
+
|
| 341 |
+
def _collect_results(self, driver: WebDriver) -> list[dict]:
|
| 342 |
+
WebDriverWait(driver, 20, 0.5).until(
|
| 343 |
+
lambda current: current.execute_script("return document.getElementById('xkresult') !== null")
|
| 344 |
+
)
|
| 345 |
+
raw_result = driver.execute_script(self.check_result_js)
|
| 346 |
+
if isinstance(raw_result, str):
|
| 347 |
+
return json.loads(raw_result)
|
| 348 |
+
return raw_result
|
| 349 |
+
|
| 350 |
+
def _is_selected_result(self, result: dict) -> bool:
|
| 351 |
+
detail = result.get("detail", "")
|
| 352 |
+
return bool(result.get("result")) or any(keyword in detail for keyword in ALREADY_SELECTED_KEYWORDS)
|
| 353 |
+
|
| 354 |
+
def _extract_course_pair(self, subject: str) -> tuple[str, str] | None:
|
| 355 |
+
strict_match = re.findall(r"(\d{5,})_(\d{2})", subject)
|
| 356 |
+
if strict_match:
|
| 357 |
+
return strict_match[-1]
|
| 358 |
+
loose_match = re.findall(r"(\d+)", subject)
|
| 359 |
+
if len(loose_match) >= 2:
|
| 360 |
+
return loose_match[-2], loose_match[-1].zfill(2)[-2:]
|
| 361 |
+
return None
|
| 362 |
+
|
| 363 |
+
def _wait_for_iframe(self, driver: WebDriver) -> None:
|
| 364 |
+
try:
|
| 365 |
+
WebDriverWait(driver, 15, 0.5).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "ifra")))
|
| 366 |
+
except TimeoutException as exc:
|
| 367 |
+
raise SessionExpiredError("选课 iframe 未能正常加载") from exc
|
| 368 |
+
finally:
|
| 369 |
+
driver.switch_to.default_content()
|
| 370 |
+
|
| 371 |
+
def _wait_ready(self, driver: WebDriver) -> None:
|
| 372 |
+
WebDriverWait(driver, self.config.request_timeout_seconds, 0.5).until(
|
| 373 |
+
lambda current: current.execute_script("return document.readyState") == "complete"
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
def _find_first(self, driver: WebDriver, selectors: list[tuple[str, str]], timeout: int | None = None):
|
| 377 |
+
timeout = timeout or self.config.request_timeout_seconds
|
| 378 |
+
|
| 379 |
+
def locate(current: WebDriver):
|
| 380 |
+
for by, value in selectors:
|
| 381 |
+
try:
|
| 382 |
+
return current.find_element(by, value)
|
| 383 |
+
except NoSuchElementException:
|
| 384 |
+
continue
|
| 385 |
+
return False
|
| 386 |
+
|
| 387 |
+
try:
|
| 388 |
+
return WebDriverWait(driver, timeout, 0.5).until(locate)
|
| 389 |
+
except TimeoutException as exc:
|
| 390 |
+
selectors_text = ", ".join(f"{by}:{value}" for by, value in selectors)
|
| 391 |
+
raise TemporaryAutomationError(f"未找到页面元素:{selectors_text}") from exc
|
| 392 |
+
|
| 393 |
+
def _safe_quit(self, driver: WebDriver | None) -> None:
|
| 394 |
+
if not driver:
|
| 395 |
+
return
|
| 396 |
+
try:
|
| 397 |
+
driver.quit()
|
| 398 |
+
except WebDriverException:
|
| 399 |
+
pass
|
course_catcher/config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import os
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _default_data_dir() -> Path:
|
| 10 |
+
persistent_root = Path("/data")
|
| 11 |
+
if persistent_root.exists():
|
| 12 |
+
return persistent_root / "scu-course-catcher"
|
| 13 |
+
return Path("runtime")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass(frozen=True)
|
| 17 |
+
class AppConfig:
|
| 18 |
+
admin_username: str
|
| 19 |
+
admin_password: str
|
| 20 |
+
secret_key: str
|
| 21 |
+
data_dir: Path
|
| 22 |
+
database_path: Path
|
| 23 |
+
chrome_binary: str
|
| 24 |
+
chromedriver_binary: str
|
| 25 |
+
default_parallelism: int
|
| 26 |
+
loop_interval_seconds: float
|
| 27 |
+
login_retry_limit: int
|
| 28 |
+
request_timeout_seconds: int
|
| 29 |
+
debug: bool
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_config() -> AppConfig:
|
| 33 |
+
admin_username = os.getenv("ADMIN", "admin")
|
| 34 |
+
admin_password = os.getenv("PASSWORD", "change-me-now")
|
| 35 |
+
|
| 36 |
+
derived_secret = hashlib.sha256(
|
| 37 |
+
f"{admin_username}:{admin_password}:scu-course-catcher".encode("utf-8")
|
| 38 |
+
).hexdigest()
|
| 39 |
+
secret_key = os.getenv("APP_SECRET", derived_secret)
|
| 40 |
+
|
| 41 |
+
data_dir = Path(os.getenv("APP_DATA_DIR", str(_default_data_dir()))).resolve()
|
| 42 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
|
| 44 |
+
return AppConfig(
|
| 45 |
+
admin_username=admin_username,
|
| 46 |
+
admin_password=admin_password,
|
| 47 |
+
secret_key=secret_key,
|
| 48 |
+
data_dir=data_dir,
|
| 49 |
+
database_path=data_dir / "app.db",
|
| 50 |
+
chrome_binary=os.getenv("CHROME_BIN", "/usr/bin/chromium"),
|
| 51 |
+
chromedriver_binary=os.getenv("CHROMEDRIVER_BIN", "/usr/bin/chromedriver"),
|
| 52 |
+
default_parallelism=max(1, int(os.getenv("DEFAULT_PARALLELISM", "1"))),
|
| 53 |
+
loop_interval_seconds=max(1.0, float(os.getenv("LOOP_INTERVAL_SECONDS", "3"))),
|
| 54 |
+
login_retry_limit=max(1, int(os.getenv("LOGIN_RETRY_LIMIT", "6"))),
|
| 55 |
+
request_timeout_seconds=max(15, int(os.getenv("REQUEST_TIMEOUT_SECONDS", "30"))),
|
| 56 |
+
debug=os.getenv("DEBUG", "").lower() in {"1", "true", "yes", "on"},
|
| 57 |
+
)
|
course_catcher/db.py
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sqlite3
|
| 4 |
+
import threading
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from course_catcher.security import CredentialCipher, hash_password, verify_password
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def utc_now() -> str:
|
| 14 |
+
return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Database:
|
| 18 |
+
def __init__(self, db_path: Path, cipher: CredentialCipher, default_parallelism: int) -> None:
|
| 19 |
+
self.db_path = Path(db_path)
|
| 20 |
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 21 |
+
self.cipher = cipher
|
| 22 |
+
self.default_parallelism = default_parallelism
|
| 23 |
+
self._write_lock = threading.RLock()
|
| 24 |
+
self._initialize()
|
| 25 |
+
|
| 26 |
+
@contextmanager
|
| 27 |
+
def connect(self) -> sqlite3.Connection:
|
| 28 |
+
connection = sqlite3.connect(self.db_path, timeout=30, check_same_thread=False)
|
| 29 |
+
connection.row_factory = sqlite3.Row
|
| 30 |
+
connection.execute("PRAGMA foreign_keys = ON")
|
| 31 |
+
connection.execute("PRAGMA busy_timeout = 30000")
|
| 32 |
+
try:
|
| 33 |
+
yield connection
|
| 34 |
+
connection.commit()
|
| 35 |
+
finally:
|
| 36 |
+
connection.close()
|
| 37 |
+
|
| 38 |
+
def _initialize(self) -> None:
|
| 39 |
+
with self._write_lock, self.connect() as connection:
|
| 40 |
+
connection.executescript(
|
| 41 |
+
"""
|
| 42 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 43 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 44 |
+
student_id TEXT NOT NULL UNIQUE,
|
| 45 |
+
password_hash TEXT NOT NULL,
|
| 46 |
+
password_encrypted TEXT NOT NULL,
|
| 47 |
+
created_at TEXT NOT NULL,
|
| 48 |
+
updated_at TEXT NOT NULL,
|
| 49 |
+
last_login_at TEXT
|
| 50 |
+
);
|
| 51 |
+
|
| 52 |
+
CREATE TABLE IF NOT EXISTS admins (
|
| 53 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 54 |
+
username TEXT NOT NULL UNIQUE,
|
| 55 |
+
password_hash TEXT NOT NULL,
|
| 56 |
+
role TEXT NOT NULL CHECK(role IN ('admin', 'superadmin')),
|
| 57 |
+
created_at TEXT NOT NULL,
|
| 58 |
+
updated_at TEXT NOT NULL,
|
| 59 |
+
last_login_at TEXT
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
CREATE TABLE IF NOT EXISTS courses (
|
| 63 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 64 |
+
user_id INTEGER NOT NULL,
|
| 65 |
+
course_id TEXT NOT NULL,
|
| 66 |
+
course_index TEXT NOT NULL,
|
| 67 |
+
status TEXT NOT NULL DEFAULT 'pending',
|
| 68 |
+
last_result TEXT NOT NULL DEFAULT '',
|
| 69 |
+
created_at TEXT NOT NULL,
|
| 70 |
+
updated_at TEXT NOT NULL,
|
| 71 |
+
UNIQUE(user_id, course_id, course_index),
|
| 72 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 73 |
+
);
|
| 74 |
+
|
| 75 |
+
CREATE TABLE IF NOT EXISTS tasks (
|
| 76 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 77 |
+
user_id INTEGER NOT NULL,
|
| 78 |
+
status TEXT NOT NULL CHECK(status IN ('queued', 'running', 'completed', 'failed', 'stopped')),
|
| 79 |
+
requested_by_type TEXT NOT NULL,
|
| 80 |
+
requested_by_name TEXT NOT NULL,
|
| 81 |
+
stop_requested INTEGER NOT NULL DEFAULT 0,
|
| 82 |
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
| 83 |
+
last_error TEXT NOT NULL DEFAULT '',
|
| 84 |
+
created_at TEXT NOT NULL,
|
| 85 |
+
updated_at TEXT NOT NULL,
|
| 86 |
+
started_at TEXT,
|
| 87 |
+
finished_at TEXT,
|
| 88 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 89 |
+
);
|
| 90 |
+
|
| 91 |
+
CREATE TABLE IF NOT EXISTS settings (
|
| 92 |
+
key TEXT PRIMARY KEY,
|
| 93 |
+
value TEXT NOT NULL
|
| 94 |
+
);
|
| 95 |
+
|
| 96 |
+
CREATE TABLE IF NOT EXISTS logs (
|
| 97 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 98 |
+
task_id INTEGER,
|
| 99 |
+
user_id INTEGER,
|
| 100 |
+
created_at TEXT NOT NULL,
|
| 101 |
+
level TEXT NOT NULL,
|
| 102 |
+
actor TEXT NOT NULL,
|
| 103 |
+
message TEXT NOT NULL,
|
| 104 |
+
FOREIGN KEY(task_id) REFERENCES tasks(id) ON DELETE SET NULL,
|
| 105 |
+
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
| 106 |
+
);
|
| 107 |
+
"""
|
| 108 |
+
)
|
| 109 |
+
connection.execute(
|
| 110 |
+
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
|
| 111 |
+
("max_parallel_tasks", str(self.default_parallelism)),
|
| 112 |
+
)
|
| 113 |
+
connection.execute(
|
| 114 |
+
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
|
| 115 |
+
("loop_interval_seconds", "3"),
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
def ensure_superadmin(self, username: str, password: str) -> None:
|
| 119 |
+
now = utc_now()
|
| 120 |
+
password_hash = hash_password(password)
|
| 121 |
+
with self._write_lock, self.connect() as connection:
|
| 122 |
+
row = connection.execute(
|
| 123 |
+
"SELECT id FROM admins WHERE role = 'superadmin' ORDER BY id LIMIT 1"
|
| 124 |
+
).fetchone()
|
| 125 |
+
if row:
|
| 126 |
+
connection.execute(
|
| 127 |
+
"""
|
| 128 |
+
UPDATE admins
|
| 129 |
+
SET username = ?, password_hash = ?, updated_at = ?
|
| 130 |
+
WHERE id = ?
|
| 131 |
+
""",
|
| 132 |
+
(username, password_hash, now, row["id"]),
|
| 133 |
+
)
|
| 134 |
+
else:
|
| 135 |
+
connection.execute(
|
| 136 |
+
"""
|
| 137 |
+
INSERT INTO admins(username, password_hash, role, created_at, updated_at)
|
| 138 |
+
VALUES (?, ?, 'superadmin', ?, ?)
|
| 139 |
+
""",
|
| 140 |
+
(username, password_hash, now, now),
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
def get_setting_int(self, key: str, fallback: int) -> int:
|
| 144 |
+
with self.connect() as connection:
|
| 145 |
+
row = connection.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
|
| 146 |
+
if not row:
|
| 147 |
+
return fallback
|
| 148 |
+
try:
|
| 149 |
+
return int(row["value"])
|
| 150 |
+
except (TypeError, ValueError):
|
| 151 |
+
return fallback
|
| 152 |
+
|
| 153 |
+
def get_setting_float(self, key: str, fallback: float) -> float:
|
| 154 |
+
with self.connect() as connection:
|
| 155 |
+
row = connection.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
|
| 156 |
+
if not row:
|
| 157 |
+
return fallback
|
| 158 |
+
try:
|
| 159 |
+
return float(row["value"])
|
| 160 |
+
except (TypeError, ValueError):
|
| 161 |
+
return fallback
|
| 162 |
+
|
| 163 |
+
def set_setting(self, key: str, value: str) -> None:
|
| 164 |
+
with self._write_lock, self.connect() as connection:
|
| 165 |
+
connection.execute(
|
| 166 |
+
"""
|
| 167 |
+
INSERT INTO settings(key, value) VALUES (?, ?)
|
| 168 |
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
| 169 |
+
""",
|
| 170 |
+
(key, value),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def list_admins(self) -> list[dict[str, Any]]:
|
| 174 |
+
with self.connect() as connection:
|
| 175 |
+
rows = connection.execute(
|
| 176 |
+
"SELECT id, username, role, created_at, updated_at, last_login_at FROM admins ORDER BY role DESC, username ASC"
|
| 177 |
+
).fetchall()
|
| 178 |
+
return [dict(row) for row in rows]
|
| 179 |
+
|
| 180 |
+
def create_admin(self, username: str, password: str) -> dict[str, Any]:
|
| 181 |
+
now = utc_now()
|
| 182 |
+
with self._write_lock, self.connect() as connection:
|
| 183 |
+
connection.execute(
|
| 184 |
+
"""
|
| 185 |
+
INSERT INTO admins(username, password_hash, role, created_at, updated_at)
|
| 186 |
+
VALUES (?, ?, 'admin', ?, ?)
|
| 187 |
+
""",
|
| 188 |
+
(username, hash_password(password), now, now),
|
| 189 |
+
)
|
| 190 |
+
row = connection.execute(
|
| 191 |
+
"SELECT id, username, role, created_at, updated_at, last_login_at FROM admins WHERE username = ?",
|
| 192 |
+
(username,),
|
| 193 |
+
).fetchone()
|
| 194 |
+
return dict(row)
|
| 195 |
+
|
| 196 |
+
def verify_admin_login(self, username: str, password: str) -> dict[str, Any] | None:
|
| 197 |
+
with self.connect() as connection:
|
| 198 |
+
row = connection.execute("SELECT * FROM admins WHERE username = ?", (username,)).fetchone()
|
| 199 |
+
if not row or not verify_password(row["password_hash"], password):
|
| 200 |
+
return None
|
| 201 |
+
connection.execute(
|
| 202 |
+
"UPDATE admins SET last_login_at = ?, updated_at = ? WHERE id = ?",
|
| 203 |
+
(utc_now(), utc_now(), row["id"]),
|
| 204 |
+
)
|
| 205 |
+
refreshed = connection.execute(
|
| 206 |
+
"SELECT id, username, role, created_at, updated_at, last_login_at FROM admins WHERE id = ?",
|
| 207 |
+
(row["id"],),
|
| 208 |
+
).fetchone()
|
| 209 |
+
return dict(refreshed)
|
| 210 |
+
|
| 211 |
+
def get_admin_by_id(self, admin_id: int) -> dict[str, Any] | None:
|
| 212 |
+
with self.connect() as connection:
|
| 213 |
+
row = connection.execute(
|
| 214 |
+
"SELECT id, username, role, created_at, updated_at, last_login_at FROM admins WHERE id = ?",
|
| 215 |
+
(admin_id,),
|
| 216 |
+
).fetchone()
|
| 217 |
+
return dict(row) if row else None
|
| 218 |
+
|
| 219 |
+
def get_user_by_id(self, user_id: int, include_password: bool = False) -> dict[str, Any] | None:
|
| 220 |
+
fields = "id, student_id, created_at, updated_at, last_login_at"
|
| 221 |
+
if include_password:
|
| 222 |
+
fields += ", password_hash, password_encrypted"
|
| 223 |
+
with self.connect() as connection:
|
| 224 |
+
row = connection.execute(f"SELECT {fields} FROM users WHERE id = ?", (user_id,)).fetchone()
|
| 225 |
+
return dict(row) if row else None
|
| 226 |
+
|
| 227 |
+
def get_user_by_student_id(self, student_id: str, include_password: bool = False) -> dict[str, Any] | None:
|
| 228 |
+
fields = "id, student_id, created_at, updated_at, last_login_at"
|
| 229 |
+
if include_password:
|
| 230 |
+
fields += ", password_hash, password_encrypted"
|
| 231 |
+
with self.connect() as connection:
|
| 232 |
+
row = connection.execute(
|
| 233 |
+
f"SELECT {fields} FROM users WHERE student_id = ?",
|
| 234 |
+
(student_id,),
|
| 235 |
+
).fetchone()
|
| 236 |
+
return dict(row) if row else None
|
| 237 |
+
|
| 238 |
+
def create_user(self, student_id: str, password: str) -> dict[str, Any]:
|
| 239 |
+
now = utc_now()
|
| 240 |
+
encrypted = self.cipher.encrypt(password)
|
| 241 |
+
with self._write_lock, self.connect() as connection:
|
| 242 |
+
connection.execute(
|
| 243 |
+
"""
|
| 244 |
+
INSERT INTO users(student_id, password_hash, password_encrypted, created_at, updated_at)
|
| 245 |
+
VALUES (?, ?, ?, ?, ?)
|
| 246 |
+
""",
|
| 247 |
+
(student_id, hash_password(password), encrypted, now, now),
|
| 248 |
+
)
|
| 249 |
+
row = connection.execute(
|
| 250 |
+
"SELECT id, student_id, created_at, updated_at, last_login_at FROM users WHERE student_id = ?",
|
| 251 |
+
(student_id,),
|
| 252 |
+
).fetchone()
|
| 253 |
+
return dict(row)
|
| 254 |
+
|
| 255 |
+
def create_or_update_user(self, student_id: str, password: str) -> dict[str, Any]:
|
| 256 |
+
existing = self.get_user_by_student_id(student_id)
|
| 257 |
+
if existing:
|
| 258 |
+
self.update_user_password(existing["id"], password)
|
| 259 |
+
return self.get_user_by_id(existing["id"]) or existing
|
| 260 |
+
return self.create_user(student_id, password)
|
| 261 |
+
|
| 262 |
+
def verify_or_create_user_login(self, student_id: str, password: str) -> tuple[dict[str, Any] | None, bool]:
|
| 263 |
+
user = self.get_user_by_student_id(student_id, include_password=True)
|
| 264 |
+
if not user:
|
| 265 |
+
created = self.create_user(student_id, password)
|
| 266 |
+
return created, True
|
| 267 |
+
if not verify_password(user["password_hash"], password):
|
| 268 |
+
return None, False
|
| 269 |
+
now = utc_now()
|
| 270 |
+
with self._write_lock, self.connect() as connection:
|
| 271 |
+
connection.execute(
|
| 272 |
+
"UPDATE users SET last_login_at = ?, updated_at = ? WHERE id = ?",
|
| 273 |
+
(now, now, user["id"]),
|
| 274 |
+
)
|
| 275 |
+
refreshed = connection.execute(
|
| 276 |
+
"SELECT id, student_id, created_at, updated_at, last_login_at FROM users WHERE id = ?",
|
| 277 |
+
(user["id"],),
|
| 278 |
+
).fetchone()
|
| 279 |
+
return dict(refreshed), False
|
| 280 |
+
|
| 281 |
+
def update_user_password(self, user_id: int, password: str) -> None:
|
| 282 |
+
now = utc_now()
|
| 283 |
+
with self._write_lock, self.connect() as connection:
|
| 284 |
+
connection.execute(
|
| 285 |
+
"""
|
| 286 |
+
UPDATE users
|
| 287 |
+
SET password_hash = ?, password_encrypted = ?, updated_at = ?
|
| 288 |
+
WHERE id = ?
|
| 289 |
+
""",
|
| 290 |
+
(hash_password(password), self.cipher.encrypt(password), now, user_id),
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
def get_user_runtime_credentials(self, user_id: int) -> dict[str, Any] | None:
|
| 294 |
+
with self.connect() as connection:
|
| 295 |
+
row = connection.execute(
|
| 296 |
+
"SELECT id, student_id, password_encrypted FROM users WHERE id = ?",
|
| 297 |
+
(user_id,),
|
| 298 |
+
).fetchone()
|
| 299 |
+
if not row:
|
| 300 |
+
return None
|
| 301 |
+
data = dict(row)
|
| 302 |
+
data["password"] = self.cipher.decrypt(data["password_encrypted"])
|
| 303 |
+
return data
|
| 304 |
+
|
| 305 |
+
def list_courses(self, user_id: int) -> list[dict[str, Any]]:
|
| 306 |
+
with self.connect() as connection:
|
| 307 |
+
rows = connection.execute(
|
| 308 |
+
"""
|
| 309 |
+
SELECT id, user_id, course_id, course_index, status, last_result, created_at, updated_at
|
| 310 |
+
FROM courses
|
| 311 |
+
WHERE user_id = ?
|
| 312 |
+
ORDER BY status DESC, course_id ASC, course_index ASC
|
| 313 |
+
""",
|
| 314 |
+
(user_id,),
|
| 315 |
+
).fetchall()
|
| 316 |
+
return [dict(row) for row in rows]
|
| 317 |
+
|
| 318 |
+
def list_pending_courses(self, user_id: int) -> list[dict[str, Any]]:
|
| 319 |
+
with self.connect() as connection:
|
| 320 |
+
rows = connection.execute(
|
| 321 |
+
"""
|
| 322 |
+
SELECT id, user_id, course_id, course_index, status, last_result, created_at, updated_at
|
| 323 |
+
FROM courses
|
| 324 |
+
WHERE user_id = ? AND status != 'selected'
|
| 325 |
+
ORDER BY course_id ASC, course_index ASC
|
| 326 |
+
""",
|
| 327 |
+
(user_id,),
|
| 328 |
+
).fetchall()
|
| 329 |
+
return [dict(row) for row in rows]
|
| 330 |
+
|
| 331 |
+
def add_course(self, user_id: int, course_id: str, course_index: str) -> None:
|
| 332 |
+
now = utc_now()
|
| 333 |
+
with self._write_lock, self.connect() as connection:
|
| 334 |
+
connection.execute(
|
| 335 |
+
"""
|
| 336 |
+
INSERT INTO courses(user_id, course_id, course_index, status, last_result, created_at, updated_at)
|
| 337 |
+
VALUES (?, ?, ?, 'pending', '', ?, ?)
|
| 338 |
+
ON CONFLICT(user_id, course_id, course_index)
|
| 339 |
+
DO UPDATE SET status = 'pending', updated_at = excluded.updated_at
|
| 340 |
+
""",
|
| 341 |
+
(user_id, course_id, course_index, now, now),
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
def delete_course(self, course_id: int, user_id: int) -> None:
|
| 345 |
+
with self._write_lock, self.connect() as connection:
|
| 346 |
+
connection.execute("DELETE FROM courses WHERE id = ? AND user_id = ?", (course_id, user_id))
|
| 347 |
+
|
| 348 |
+
def mark_course_result(
|
| 349 |
+
self,
|
| 350 |
+
user_id: int,
|
| 351 |
+
course_id: str,
|
| 352 |
+
course_index: str,
|
| 353 |
+
status: str,
|
| 354 |
+
detail: str,
|
| 355 |
+
) -> None:
|
| 356 |
+
with self._write_lock, self.connect() as connection:
|
| 357 |
+
connection.execute(
|
| 358 |
+
"""
|
| 359 |
+
UPDATE courses
|
| 360 |
+
SET status = ?, last_result = ?, updated_at = ?
|
| 361 |
+
WHERE user_id = ? AND course_id = ? AND course_index = ?
|
| 362 |
+
""",
|
| 363 |
+
(status, detail, utc_now(), user_id, course_id, course_index),
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def list_users_with_summary(self) -> list[dict[str, Any]]:
|
| 367 |
+
with self.connect() as connection:
|
| 368 |
+
rows = connection.execute(
|
| 369 |
+
"""
|
| 370 |
+
SELECT
|
| 371 |
+
u.id,
|
| 372 |
+
u.student_id,
|
| 373 |
+
u.created_at,
|
| 374 |
+
u.updated_at,
|
| 375 |
+
u.last_login_at,
|
| 376 |
+
COALESCE(course_stats.course_count, 0) AS course_count,
|
| 377 |
+
COALESCE(course_stats.selected_count, 0) AS selected_count,
|
| 378 |
+
active_task.id AS active_task_id,
|
| 379 |
+
active_task.status AS active_task_status
|
| 380 |
+
FROM users u
|
| 381 |
+
LEFT JOIN (
|
| 382 |
+
SELECT
|
| 383 |
+
user_id,
|
| 384 |
+
COUNT(*) AS course_count,
|
| 385 |
+
SUM(CASE WHEN status = 'selected' THEN 1 ELSE 0 END) AS selected_count
|
| 386 |
+
FROM courses
|
| 387 |
+
GROUP BY user_id
|
| 388 |
+
) AS course_stats ON course_stats.user_id = u.id
|
| 389 |
+
LEFT JOIN (
|
| 390 |
+
SELECT t1.*
|
| 391 |
+
FROM tasks t1
|
| 392 |
+
JOIN (
|
| 393 |
+
SELECT user_id, MAX(id) AS id
|
| 394 |
+
FROM tasks
|
| 395 |
+
WHERE status IN ('queued', 'running')
|
| 396 |
+
GROUP BY user_id
|
| 397 |
+
) latest ON latest.id = t1.id
|
| 398 |
+
) AS active_task ON active_task.user_id = u.id
|
| 399 |
+
ORDER BY u.updated_at DESC, u.student_id ASC
|
| 400 |
+
"""
|
| 401 |
+
).fetchall()
|
| 402 |
+
return [dict(row) for row in rows]
|
| 403 |
+
|
| 404 |
+
def get_user_dashboard_state(self, user_id: int) -> dict[str, Any]:
|
| 405 |
+
with self.connect() as connection:
|
| 406 |
+
counts = connection.execute(
|
| 407 |
+
"""
|
| 408 |
+
SELECT
|
| 409 |
+
COUNT(*) AS total_courses,
|
| 410 |
+
SUM(CASE WHEN status = 'selected' THEN 1 ELSE 0 END) AS selected_courses,
|
| 411 |
+
SUM(CASE WHEN status != 'selected' THEN 1 ELSE 0 END) AS pending_courses
|
| 412 |
+
FROM courses
|
| 413 |
+
WHERE user_id = ?
|
| 414 |
+
""",
|
| 415 |
+
(user_id,),
|
| 416 |
+
).fetchone()
|
| 417 |
+
task = connection.execute(
|
| 418 |
+
"""
|
| 419 |
+
SELECT id, status, attempt_count, updated_at, started_at, finished_at
|
| 420 |
+
FROM tasks
|
| 421 |
+
WHERE user_id = ?
|
| 422 |
+
ORDER BY id DESC
|
| 423 |
+
LIMIT 1
|
| 424 |
+
""",
|
| 425 |
+
(user_id,),
|
| 426 |
+
).fetchone()
|
| 427 |
+
return {
|
| 428 |
+
"total_courses": counts["total_courses"] or 0,
|
| 429 |
+
"selected_courses": counts["selected_courses"] or 0,
|
| 430 |
+
"pending_courses": counts["pending_courses"] or 0,
|
| 431 |
+
"task": dict(task) if task else None,
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
def get_admin_summary(self) -> dict[str, Any]:
|
| 435 |
+
with self.connect() as connection:
|
| 436 |
+
users = connection.execute("SELECT COUNT(*) AS total FROM users").fetchone()["total"]
|
| 437 |
+
running_tasks = connection.execute(
|
| 438 |
+
"SELECT COUNT(*) AS total FROM tasks WHERE status = 'running'"
|
| 439 |
+
).fetchone()["total"]
|
| 440 |
+
queued_tasks = connection.execute(
|
| 441 |
+
"SELECT COUNT(*) AS total FROM tasks WHERE status = 'queued'"
|
| 442 |
+
).fetchone()["total"]
|
| 443 |
+
pending_courses = connection.execute(
|
| 444 |
+
"SELECT COUNT(*) AS total FROM courses WHERE status != 'selected'"
|
| 445 |
+
).fetchone()["total"]
|
| 446 |
+
return {
|
| 447 |
+
"users": users,
|
| 448 |
+
"running_tasks": running_tasks,
|
| 449 |
+
"queued_tasks": queued_tasks,
|
| 450 |
+
"pending_courses": pending_courses,
|
| 451 |
+
"parallelism": self.get_setting_int("max_parallel_tasks", self.default_parallelism),
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
def create_task(self, user_id: int, requested_by_type: str, requested_by_name: str) -> dict[str, Any]:
|
| 455 |
+
with self._write_lock, self.connect() as connection:
|
| 456 |
+
existing = connection.execute(
|
| 457 |
+
"""
|
| 458 |
+
SELECT *
|
| 459 |
+
FROM tasks
|
| 460 |
+
WHERE user_id = ? AND status IN ('queued', 'running')
|
| 461 |
+
ORDER BY id DESC
|
| 462 |
+
LIMIT 1
|
| 463 |
+
""",
|
| 464 |
+
(user_id,),
|
| 465 |
+
).fetchone()
|
| 466 |
+
if existing:
|
| 467 |
+
return dict(existing)
|
| 468 |
+
now = utc_now()
|
| 469 |
+
connection.execute(
|
| 470 |
+
"""
|
| 471 |
+
INSERT INTO tasks(
|
| 472 |
+
user_id, status, requested_by_type, requested_by_name, stop_requested,
|
| 473 |
+
attempt_count, last_error, created_at, updated_at
|
| 474 |
+
)
|
| 475 |
+
VALUES (?, 'queued', ?, ?, 0, 0, '', ?, ?)
|
| 476 |
+
""",
|
| 477 |
+
(user_id, requested_by_type, requested_by_name, now, now),
|
| 478 |
+
)
|
| 479 |
+
created = connection.execute(
|
| 480 |
+
"SELECT * FROM tasks WHERE id = last_insert_rowid()"
|
| 481 |
+
).fetchone()
|
| 482 |
+
return dict(created)
|
| 483 |
+
|
| 484 |
+
def get_task(self, task_id: int) -> dict[str, Any] | None:
|
| 485 |
+
with self.connect() as connection:
|
| 486 |
+
row = connection.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
|
| 487 |
+
return dict(row) if row else None
|
| 488 |
+
|
| 489 |
+
def fetch_queued_tasks(self, limit: int) -> list[dict[str, Any]]:
|
| 490 |
+
with self.connect() as connection:
|
| 491 |
+
rows = connection.execute(
|
| 492 |
+
"""
|
| 493 |
+
SELECT *
|
| 494 |
+
FROM tasks
|
| 495 |
+
WHERE status = 'queued'
|
| 496 |
+
ORDER BY created_at ASC, id ASC
|
| 497 |
+
LIMIT ?
|
| 498 |
+
""",
|
| 499 |
+
(limit,),
|
| 500 |
+
).fetchall()
|
| 501 |
+
return [dict(row) for row in rows]
|
| 502 |
+
|
| 503 |
+
def mark_task_running(self, task_id: int) -> None:
|
| 504 |
+
now = utc_now()
|
| 505 |
+
with self._write_lock, self.connect() as connection:
|
| 506 |
+
connection.execute(
|
| 507 |
+
"""
|
| 508 |
+
UPDATE tasks
|
| 509 |
+
SET status = 'running', updated_at = ?, started_at = COALESCE(started_at, ?)
|
| 510 |
+
WHERE id = ?
|
| 511 |
+
""",
|
| 512 |
+
(now, now, task_id),
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
def increment_task_attempt(self, task_id: int) -> None:
|
| 516 |
+
with self._write_lock, self.connect() as connection:
|
| 517 |
+
connection.execute(
|
| 518 |
+
"""
|
| 519 |
+
UPDATE tasks
|
| 520 |
+
SET attempt_count = attempt_count + 1, updated_at = ?
|
| 521 |
+
WHERE id = ?
|
| 522 |
+
""",
|
| 523 |
+
(utc_now(), task_id),
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
def request_stop_task(self, user_id: int) -> None:
|
| 527 |
+
now = utc_now()
|
| 528 |
+
with self._write_lock, self.connect() as connection:
|
| 529 |
+
connection.execute(
|
| 530 |
+
"""
|
| 531 |
+
UPDATE tasks
|
| 532 |
+
SET stop_requested = 1, updated_at = ?
|
| 533 |
+
WHERE user_id = ? AND status = 'running'
|
| 534 |
+
""",
|
| 535 |
+
(now, user_id),
|
| 536 |
+
)
|
| 537 |
+
connection.execute(
|
| 538 |
+
"""
|
| 539 |
+
UPDATE tasks
|
| 540 |
+
SET status = 'stopped', stop_requested = 1, updated_at = ?, finished_at = ?
|
| 541 |
+
WHERE user_id = ? AND status = 'queued'
|
| 542 |
+
""",
|
| 543 |
+
(now, now, user_id),
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
def is_stop_requested(self, task_id: int) -> bool:
|
| 547 |
+
with self.connect() as connection:
|
| 548 |
+
row = connection.execute(
|
| 549 |
+
"SELECT stop_requested FROM tasks WHERE id = ?",
|
| 550 |
+
(task_id,),
|
| 551 |
+
).fetchone()
|
| 552 |
+
return bool(row and row["stop_requested"])
|
| 553 |
+
|
| 554 |
+
def finish_task(self, task_id: int, status: str, last_error: str = "") -> None:
|
| 555 |
+
now = utc_now()
|
| 556 |
+
with self._write_lock, self.connect() as connection:
|
| 557 |
+
connection.execute(
|
| 558 |
+
"""
|
| 559 |
+
UPDATE tasks
|
| 560 |
+
SET status = ?, last_error = ?, updated_at = ?, finished_at = ?
|
| 561 |
+
WHERE id = ?
|
| 562 |
+
""",
|
| 563 |
+
(status, last_error, now, now, task_id),
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
def add_log(self, task_id: int | None, user_id: int | None, actor: str, level: str, message: str) -> None:
|
| 567 |
+
with self._write_lock, self.connect() as connection:
|
| 568 |
+
connection.execute(
|
| 569 |
+
"""
|
| 570 |
+
INSERT INTO logs(task_id, user_id, created_at, level, actor, message)
|
| 571 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 572 |
+
""",
|
| 573 |
+
(task_id, user_id, utc_now(), level.upper(), actor, message),
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
def get_logs_after(self, last_id: int, user_id: int | None = None, limit: int = 200) -> list[dict[str, Any]]:
|
| 577 |
+
query = """
|
| 578 |
+
SELECT
|
| 579 |
+
logs.id,
|
| 580 |
+
logs.task_id,
|
| 581 |
+
logs.user_id,
|
| 582 |
+
logs.created_at,
|
| 583 |
+
logs.level,
|
| 584 |
+
logs.actor,
|
| 585 |
+
logs.message,
|
| 586 |
+
users.student_id
|
| 587 |
+
FROM logs
|
| 588 |
+
LEFT JOIN users ON users.id = logs.user_id
|
| 589 |
+
WHERE logs.id > ?
|
| 590 |
+
"""
|
| 591 |
+
params: list[Any] = [last_id]
|
| 592 |
+
if user_id is not None:
|
| 593 |
+
query += " AND logs.user_id = ?"
|
| 594 |
+
params.append(user_id)
|
| 595 |
+
query += " ORDER BY logs.id ASC LIMIT ?"
|
| 596 |
+
params.append(limit)
|
| 597 |
+
with self.connect() as connection:
|
| 598 |
+
rows = connection.execute(query, params).fetchall()
|
| 599 |
+
return [dict(row) for row in rows]
|
| 600 |
+
|
| 601 |
+
def get_recent_logs(self, user_id: int | None = None, limit: int = 120) -> list[dict[str, Any]]:
|
| 602 |
+
query = """
|
| 603 |
+
SELECT
|
| 604 |
+
logs.id,
|
| 605 |
+
logs.task_id,
|
| 606 |
+
logs.user_id,
|
| 607 |
+
logs.created_at,
|
| 608 |
+
logs.level,
|
| 609 |
+
logs.actor,
|
| 610 |
+
logs.message,
|
| 611 |
+
users.student_id
|
| 612 |
+
FROM logs
|
| 613 |
+
LEFT JOIN users ON users.id = logs.user_id
|
| 614 |
+
"""
|
| 615 |
+
params: list[Any] = []
|
| 616 |
+
if user_id is not None:
|
| 617 |
+
query += " WHERE logs.user_id = ?"
|
| 618 |
+
params.append(user_id)
|
| 619 |
+
query += " ORDER BY logs.id DESC LIMIT ?"
|
| 620 |
+
params.append(limit)
|
| 621 |
+
with self.connect() as connection:
|
| 622 |
+
rows = connection.execute(query, params).fetchall()
|
| 623 |
+
items = [dict(row) for row in rows]
|
| 624 |
+
items.reverse()
|
| 625 |
+
return items
|
course_catcher/security.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import hashlib
|
| 5 |
+
|
| 6 |
+
from cryptography.fernet import Fernet
|
| 7 |
+
from werkzeug.security import check_password_hash, generate_password_hash
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CredentialCipher:
|
| 11 |
+
def __init__(self, secret_key: str) -> None:
|
| 12 |
+
digest = hashlib.sha256(secret_key.encode("utf-8")).digest()
|
| 13 |
+
self._fernet = Fernet(base64.urlsafe_b64encode(digest))
|
| 14 |
+
|
| 15 |
+
def encrypt(self, value: str) -> str:
|
| 16 |
+
return self._fernet.encrypt(value.encode("utf-8")).decode("utf-8")
|
| 17 |
+
|
| 18 |
+
def decrypt(self, value: str) -> str:
|
| 19 |
+
return self._fernet.decrypt(value.encode("utf-8")).decode("utf-8")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def hash_password(password: str) -> str:
|
| 23 |
+
return generate_password_hash(password)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def verify_password(password_hash: str, password: str) -> bool:
|
| 27 |
+
return check_password_hash(password_hash, password)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def mask_secret(secret: str) -> str:
|
| 31 |
+
if len(secret) <= 4:
|
| 32 |
+
return "*" * len(secret)
|
| 33 |
+
return f"{secret[:2]}{'*' * (len(secret) - 4)}{secret[-2:]}"
|
course_catcher/task_manager.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
from typing import Callable
|
| 5 |
+
|
| 6 |
+
from course_catcher.automation import CourseAutomation
|
| 7 |
+
from course_catcher.config import AppConfig
|
| 8 |
+
from course_catcher.db import Database
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TaskManager:
|
| 12 |
+
def __init__(self, db: Database, config: AppConfig) -> None:
|
| 13 |
+
self.db = db
|
| 14 |
+
self.config = config
|
| 15 |
+
self.automation = CourseAutomation(config)
|
| 16 |
+
self._workers: dict[int, threading.Thread] = {}
|
| 17 |
+
self._lock = threading.RLock()
|
| 18 |
+
self._stop_event = threading.Event()
|
| 19 |
+
self._scheduler_thread: threading.Thread | None = None
|
| 20 |
+
|
| 21 |
+
def start(self) -> None:
|
| 22 |
+
with self._lock:
|
| 23 |
+
if self._scheduler_thread and self._scheduler_thread.is_alive():
|
| 24 |
+
return
|
| 25 |
+
self._scheduler_thread = threading.Thread(
|
| 26 |
+
target=self._scheduler_loop,
|
| 27 |
+
name="task-scheduler",
|
| 28 |
+
daemon=True,
|
| 29 |
+
)
|
| 30 |
+
self._scheduler_thread.start()
|
| 31 |
+
|
| 32 |
+
def stop(self) -> None:
|
| 33 |
+
self._stop_event.set()
|
| 34 |
+
|
| 35 |
+
def _scheduler_loop(self) -> None:
|
| 36 |
+
while not self._stop_event.is_set():
|
| 37 |
+
self._reap_workers()
|
| 38 |
+
parallelism = self.db.get_setting_int("max_parallel_tasks", self.config.default_parallelism)
|
| 39 |
+
available_slots = max(0, parallelism - len(self._workers))
|
| 40 |
+
if available_slots > 0:
|
| 41 |
+
queued_tasks = self.db.fetch_queued_tasks(available_slots)
|
| 42 |
+
for task in queued_tasks:
|
| 43 |
+
task_id = task["id"]
|
| 44 |
+
with self._lock:
|
| 45 |
+
if task_id in self._workers:
|
| 46 |
+
continue
|
| 47 |
+
self.db.mark_task_running(task_id)
|
| 48 |
+
worker = threading.Thread(
|
| 49 |
+
target=self._run_task,
|
| 50 |
+
args=(task_id,),
|
| 51 |
+
name=f"task-{task_id}",
|
| 52 |
+
daemon=True,
|
| 53 |
+
)
|
| 54 |
+
self._workers[task_id] = worker
|
| 55 |
+
worker.start()
|
| 56 |
+
self._stop_event.wait(1)
|
| 57 |
+
|
| 58 |
+
def _reap_workers(self) -> None:
|
| 59 |
+
with self._lock:
|
| 60 |
+
finished = [task_id for task_id, worker in self._workers.items() if not worker.is_alive()]
|
| 61 |
+
for task_id in finished:
|
| 62 |
+
self._workers.pop(task_id, None)
|
| 63 |
+
|
| 64 |
+
def _run_task(self, task_id: int) -> None:
|
| 65 |
+
task = self.db.get_task(task_id)
|
| 66 |
+
if not task:
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
user_id = task["user_id"]
|
| 70 |
+
|
| 71 |
+
def log(level: str, message: str) -> None:
|
| 72 |
+
self.db.add_log(task_id=task_id, user_id=user_id, actor="runner", level=level, message=message)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
credentials = self.db.get_user_runtime_credentials(user_id)
|
| 76 |
+
if not credentials:
|
| 77 |
+
self.db.finish_task(task_id, "failed", "关联用户不存在")
|
| 78 |
+
log("ERROR", "任务关联的用户记录不存在。")
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
log("INFO", f"任务已启动,当前用户 {credentials['student_id']}。")
|
| 82 |
+
final_status, last_error = self.automation.run_until_stopped(
|
| 83 |
+
task_id=task_id,
|
| 84 |
+
user_credentials=credentials,
|
| 85 |
+
db=self.db,
|
| 86 |
+
should_stop=lambda: self.db.is_stop_requested(task_id) or self._stop_event.is_set(),
|
| 87 |
+
log=log,
|
| 88 |
+
)
|
| 89 |
+
self.db.finish_task(task_id, final_status, last_error)
|
| 90 |
+
if final_status == "completed":
|
| 91 |
+
log("SUCCESS", "任务完成,所有待抢课程均已处理。")
|
| 92 |
+
elif final_status == "stopped":
|
| 93 |
+
log("INFO", "任务已停止。")
|
| 94 |
+
else:
|
| 95 |
+
log("ERROR", f"任务失败:{last_error}")
|
| 96 |
+
except Exception as exc: # pragma: no cover - defensive path
|
| 97 |
+
self.db.finish_task(task_id, "failed", str(exc))
|
| 98 |
+
log("ERROR", f"任务崩溃:{exc}")
|
course_catcher/web.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from functools import wraps
|
| 6 |
+
from typing import Any, Callable
|
| 7 |
+
|
| 8 |
+
from flask import (
|
| 9 |
+
Flask,
|
| 10 |
+
Response,
|
| 11 |
+
flash,
|
| 12 |
+
jsonify,
|
| 13 |
+
redirect,
|
| 14 |
+
render_template,
|
| 15 |
+
request,
|
| 16 |
+
session,
|
| 17 |
+
stream_with_context,
|
| 18 |
+
url_for,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
from course_catcher.config import AppConfig, load_config
|
| 22 |
+
from course_catcher.db import Database
|
| 23 |
+
from course_catcher.security import CredentialCipher, mask_secret
|
| 24 |
+
from course_catcher.task_manager import TaskManager
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def create_app() -> Flask:
|
| 28 |
+
config = load_config()
|
| 29 |
+
cipher = CredentialCipher(config.secret_key)
|
| 30 |
+
db = Database(config.database_path, cipher, config.default_parallelism)
|
| 31 |
+
db.ensure_superadmin(config.admin_username, config.admin_password)
|
| 32 |
+
task_manager = TaskManager(db, config)
|
| 33 |
+
task_manager.start()
|
| 34 |
+
|
| 35 |
+
app = Flask(
|
| 36 |
+
__name__,
|
| 37 |
+
template_folder="../templates",
|
| 38 |
+
static_folder="../static",
|
| 39 |
+
)
|
| 40 |
+
app.config["SECRET_KEY"] = config.secret_key
|
| 41 |
+
app.extensions["app_config"] = config
|
| 42 |
+
app.extensions["db"] = db
|
| 43 |
+
app.extensions["task_manager"] = task_manager
|
| 44 |
+
|
| 45 |
+
def current_user() -> dict[str, Any] | None:
|
| 46 |
+
user_id = session.get("user_id")
|
| 47 |
+
if not user_id:
|
| 48 |
+
return None
|
| 49 |
+
return db.get_user_by_id(int(user_id))
|
| 50 |
+
|
| 51 |
+
def current_admin() -> dict[str, Any] | None:
|
| 52 |
+
admin_id = session.get("admin_id")
|
| 53 |
+
if not admin_id:
|
| 54 |
+
return None
|
| 55 |
+
return db.get_admin_by_id(int(admin_id))
|
| 56 |
+
|
| 57 |
+
def require_user(view: Callable):
|
| 58 |
+
@wraps(view)
|
| 59 |
+
def wrapped(*args, **kwargs):
|
| 60 |
+
user = current_user()
|
| 61 |
+
if not user:
|
| 62 |
+
return redirect(url_for("login"))
|
| 63 |
+
return view(user, *args, **kwargs)
|
| 64 |
+
|
| 65 |
+
return wrapped
|
| 66 |
+
|
| 67 |
+
def require_admin(view: Callable):
|
| 68 |
+
@wraps(view)
|
| 69 |
+
def wrapped(*args, **kwargs):
|
| 70 |
+
admin = current_admin()
|
| 71 |
+
if not admin:
|
| 72 |
+
return redirect(url_for("admin_login"))
|
| 73 |
+
return view(admin, *args, **kwargs)
|
| 74 |
+
|
| 75 |
+
return wrapped
|
| 76 |
+
|
| 77 |
+
def require_superadmin(view: Callable):
|
| 78 |
+
@wraps(view)
|
| 79 |
+
def wrapped(*args, **kwargs):
|
| 80 |
+
admin = current_admin()
|
| 81 |
+
if not admin or admin["role"] != "superadmin":
|
| 82 |
+
flash("只有超级管理员可以执行该操作。", "error")
|
| 83 |
+
return redirect(url_for("admin_panel"))
|
| 84 |
+
return view(admin, *args, **kwargs)
|
| 85 |
+
|
| 86 |
+
return wrapped
|
| 87 |
+
|
| 88 |
+
def normalize_student_id(student_id: str) -> str:
|
| 89 |
+
return (student_id or "").strip()
|
| 90 |
+
|
| 91 |
+
def normalize_course_pair(course_id: str, course_index: str) -> tuple[str, str]:
|
| 92 |
+
return (course_id or "").strip(), (course_index or "").strip().zfill(2)
|
| 93 |
+
|
| 94 |
+
def validate_student_login_form(student_id: str, password: str) -> str | None:
|
| 95 |
+
if not student_id.isdigit():
|
| 96 |
+
return "学号必须为纯数字。"
|
| 97 |
+
if len(student_id) < 8:
|
| 98 |
+
return "学号长度看起来不正确。"
|
| 99 |
+
if not password:
|
| 100 |
+
return "密码不能为空。"
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
def validate_course_form(course_id: str, course_index: str) -> str | None:
|
| 104 |
+
if not course_id.isdigit():
|
| 105 |
+
return "课程号必须为纯数字。"
|
| 106 |
+
if not course_index.isdigit():
|
| 107 |
+
return "课序号必须为纯数字。"
|
| 108 |
+
if len(course_index) != 2:
|
| 109 |
+
return "课序号必须是两位数字。"
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
def build_user_view_model(user: dict[str, Any]) -> dict[str, Any]:
|
| 113 |
+
dashboard_state = db.get_user_dashboard_state(user["id"])
|
| 114 |
+
courses = db.list_courses(user["id"])
|
| 115 |
+
logs = db.get_recent_logs(user_id=user["id"])
|
| 116 |
+
return {
|
| 117 |
+
"user": user,
|
| 118 |
+
"dashboard_state": dashboard_state,
|
| 119 |
+
"courses": courses,
|
| 120 |
+
"logs": logs,
|
| 121 |
+
"masked_password": mask_secret("******"),
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
def build_admin_view_model(admin: dict[str, Any]) -> dict[str, Any]:
|
| 125 |
+
summary = db.get_admin_summary()
|
| 126 |
+
users = db.list_users_with_summary()
|
| 127 |
+
users_with_courses: list[dict[str, Any]] = []
|
| 128 |
+
for user in users:
|
| 129 |
+
entry = dict(user)
|
| 130 |
+
entry["courses"] = db.list_courses(user["id"])
|
| 131 |
+
entry["dashboard_state"] = db.get_user_dashboard_state(user["id"])
|
| 132 |
+
users_with_courses.append(entry)
|
| 133 |
+
return {
|
| 134 |
+
"admin": admin,
|
| 135 |
+
"summary": summary,
|
| 136 |
+
"users": users_with_courses,
|
| 137 |
+
"admins": db.list_admins(),
|
| 138 |
+
"logs": db.get_recent_logs(),
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
def event_stream(log_scope_user_id: int | None = None):
|
| 142 |
+
last_id = int(request.args.get("last_id", "0") or 0)
|
| 143 |
+
while True:
|
| 144 |
+
items = db.get_logs_after(last_id=last_id, user_id=log_scope_user_id)
|
| 145 |
+
if items:
|
| 146 |
+
for item in items:
|
| 147 |
+
last_id = item["id"]
|
| 148 |
+
yield f"id: {item['id']}\n"
|
| 149 |
+
yield "event: log\n"
|
| 150 |
+
yield f"data: {json.dumps(item, ensure_ascii=False)}\n\n"
|
| 151 |
+
else:
|
| 152 |
+
yield ": keepalive\n\n"
|
| 153 |
+
time.sleep(1)
|
| 154 |
+
|
| 155 |
+
@app.context_processor
|
| 156 |
+
def inject_session_context():
|
| 157 |
+
return {
|
| 158 |
+
"session_user": current_user(),
|
| 159 |
+
"session_admin": current_admin(),
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
@app.get("/")
|
| 163 |
+
def index():
|
| 164 |
+
if current_user():
|
| 165 |
+
return redirect(url_for("dashboard"))
|
| 166 |
+
if current_admin():
|
| 167 |
+
return redirect(url_for("admin_panel"))
|
| 168 |
+
return redirect(url_for("login"))
|
| 169 |
+
|
| 170 |
+
@app.route("/login", methods=["GET", "POST"])
|
| 171 |
+
def login():
|
| 172 |
+
if current_user():
|
| 173 |
+
return redirect(url_for("dashboard"))
|
| 174 |
+
if request.method == "POST":
|
| 175 |
+
student_id = normalize_student_id(request.form.get("student_id", ""))
|
| 176 |
+
password = request.form.get("password", "")
|
| 177 |
+
error = validate_student_login_form(student_id, password)
|
| 178 |
+
if error:
|
| 179 |
+
flash(error, "error")
|
| 180 |
+
return render_template("login.html")
|
| 181 |
+
|
| 182 |
+
user, created = db.verify_or_create_user_login(student_id, password)
|
| 183 |
+
if not user:
|
| 184 |
+
flash("学号或密码错误。", "error")
|
| 185 |
+
return render_template("login.html")
|
| 186 |
+
|
| 187 |
+
session.clear()
|
| 188 |
+
session["user_id"] = user["id"]
|
| 189 |
+
flash("首次登录已自动创建账户。" if created else "登录成功。", "success")
|
| 190 |
+
return redirect(url_for("dashboard"))
|
| 191 |
+
return render_template("login.html")
|
| 192 |
+
|
| 193 |
+
@app.post("/logout")
|
| 194 |
+
def logout():
|
| 195 |
+
session.clear()
|
| 196 |
+
flash("已退出登录。", "success")
|
| 197 |
+
return redirect(url_for("login"))
|
| 198 |
+
|
| 199 |
+
@app.route("/admin", methods=["GET", "POST"])
|
| 200 |
+
def admin_login():
|
| 201 |
+
if current_admin():
|
| 202 |
+
return redirect(url_for("admin_panel"))
|
| 203 |
+
if request.method == "POST":
|
| 204 |
+
username = (request.form.get("username") or "").strip()
|
| 205 |
+
password = request.form.get("password") or ""
|
| 206 |
+
if not username or not password:
|
| 207 |
+
flash("管理员账号和密码不能为空。", "error")
|
| 208 |
+
return render_template("admin_login.html")
|
| 209 |
+
|
| 210 |
+
admin = db.verify_admin_login(username, password)
|
| 211 |
+
if not admin:
|
| 212 |
+
flash("管理员账号或密码错误。", "error")
|
| 213 |
+
return render_template("admin_login.html")
|
| 214 |
+
|
| 215 |
+
session.clear()
|
| 216 |
+
session["admin_id"] = admin["id"]
|
| 217 |
+
flash("管理员登录成功。", "success")
|
| 218 |
+
return redirect(url_for("admin_panel"))
|
| 219 |
+
return render_template("admin_login.html")
|
| 220 |
+
|
| 221 |
+
@app.post("/admin/logout")
|
| 222 |
+
def admin_logout():
|
| 223 |
+
session.clear()
|
| 224 |
+
flash("管理员已退出登录。", "success")
|
| 225 |
+
return redirect(url_for("admin_login"))
|
| 226 |
+
|
| 227 |
+
@app.get("/dashboard")
|
| 228 |
+
@require_user
|
| 229 |
+
def dashboard(user: dict[str, Any]):
|
| 230 |
+
return render_template("dashboard.html", **build_user_view_model(user))
|
| 231 |
+
|
| 232 |
+
@app.post("/dashboard/password")
|
| 233 |
+
@require_user
|
| 234 |
+
def update_user_password(user: dict[str, Any]):
|
| 235 |
+
password = request.form.get("password", "")
|
| 236 |
+
if not password:
|
| 237 |
+
flash("密码不能为空。", "error")
|
| 238 |
+
return redirect(url_for("dashboard"))
|
| 239 |
+
db.update_user_password(user["id"], password)
|
| 240 |
+
db.add_log(None, user["id"], "user", "INFO", "用户已更新自己的登录密码。")
|
| 241 |
+
flash("密码已更新。", "success")
|
| 242 |
+
return redirect(url_for("dashboard"))
|
| 243 |
+
|
| 244 |
+
@app.post("/dashboard/courses")
|
| 245 |
+
@require_user
|
| 246 |
+
def add_user_course(user: dict[str, Any]):
|
| 247 |
+
course_id, course_index = normalize_course_pair(
|
| 248 |
+
request.form.get("course_id", ""),
|
| 249 |
+
request.form.get("course_index", ""),
|
| 250 |
+
)
|
| 251 |
+
error = validate_course_form(course_id, course_index)
|
| 252 |
+
if error:
|
| 253 |
+
flash(error, "error")
|
| 254 |
+
return redirect(url_for("dashboard"))
|
| 255 |
+
|
| 256 |
+
db.add_course(user["id"], course_id, course_index)
|
| 257 |
+
db.add_log(None, user["id"], "user", "INFO", f"新增课程 {course_id}_{course_index}。")
|
| 258 |
+
flash("课程已添加。", "success")
|
| 259 |
+
return redirect(url_for("dashboard"))
|
| 260 |
+
|
| 261 |
+
@app.post("/dashboard/courses/<int:course_record_id>/delete")
|
| 262 |
+
@require_user
|
| 263 |
+
def delete_user_course(user: dict[str, Any], course_record_id: int):
|
| 264 |
+
db.delete_course(course_record_id, user["id"])
|
| 265 |
+
db.add_log(None, user["id"], "user", "INFO", f"删除课程记录 #{course_record_id}。")
|
| 266 |
+
flash("课程已删除。", "success")
|
| 267 |
+
return redirect(url_for("dashboard"))
|
| 268 |
+
|
| 269 |
+
@app.post("/dashboard/tasks/start")
|
| 270 |
+
@require_user
|
| 271 |
+
def start_user_task(user: dict[str, Any]):
|
| 272 |
+
task = db.create_task(user["id"], "user", user["student_id"])
|
| 273 |
+
db.add_log(task["id"], user["id"], "user", "INFO", "用户发起了新的选课任务。")
|
| 274 |
+
flash("任务已加入队列。", "success")
|
| 275 |
+
return redirect(url_for("dashboard"))
|
| 276 |
+
|
| 277 |
+
@app.post("/dashboard/tasks/stop")
|
| 278 |
+
@require_user
|
| 279 |
+
def stop_user_task(user: dict[str, Any]):
|
| 280 |
+
db.request_stop_task(user["id"])
|
| 281 |
+
db.add_log(None, user["id"], "user", "INFO", "用户请求停止当前任务。")
|
| 282 |
+
flash("停止请求已提交。", "success")
|
| 283 |
+
return redirect(url_for("dashboard"))
|
| 284 |
+
|
| 285 |
+
@app.get("/api/dashboard/status")
|
| 286 |
+
@require_user
|
| 287 |
+
def dashboard_status(user: dict[str, Any]):
|
| 288 |
+
return jsonify(db.get_user_dashboard_state(user["id"]))
|
| 289 |
+
|
| 290 |
+
@app.get("/events/logs/user")
|
| 291 |
+
@require_user
|
| 292 |
+
def user_log_stream(user: dict[str, Any]):
|
| 293 |
+
response = Response(stream_with_context(event_stream(log_scope_user_id=user["id"])))
|
| 294 |
+
response.headers["Content-Type"] = "text/event-stream"
|
| 295 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 296 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 297 |
+
return response
|
| 298 |
+
|
| 299 |
+
@app.get("/admin/panel")
|
| 300 |
+
@require_admin
|
| 301 |
+
def admin_panel(admin: dict[str, Any]):
|
| 302 |
+
return render_template("admin.html", **build_admin_view_model(admin))
|
| 303 |
+
|
| 304 |
+
@app.post("/admin/panel/settings/parallelism")
|
| 305 |
+
@require_admin
|
| 306 |
+
def update_parallelism(admin: dict[str, Any]):
|
| 307 |
+
raw_value = request.form.get("parallelism", "1")
|
| 308 |
+
try:
|
| 309 |
+
parallelism = max(1, min(8, int(raw_value)))
|
| 310 |
+
except ValueError:
|
| 311 |
+
flash("并行数必须是数字。", "error")
|
| 312 |
+
return redirect(url_for("admin_panel"))
|
| 313 |
+
|
| 314 |
+
db.set_setting("max_parallel_tasks", str(parallelism))
|
| 315 |
+
db.add_log(None, None, "admin", "INFO", f"管理员 {admin['username']} 将并行数设置为 {parallelism}。")
|
| 316 |
+
flash("并行数已更新。", "success")
|
| 317 |
+
return redirect(url_for("admin_panel"))
|
| 318 |
+
|
| 319 |
+
@app.post("/admin/panel/users")
|
| 320 |
+
@require_admin
|
| 321 |
+
def create_or_update_user_from_admin(admin: dict[str, Any]):
|
| 322 |
+
student_id = normalize_student_id(request.form.get("student_id", ""))
|
| 323 |
+
password = request.form.get("password", "")
|
| 324 |
+
error = validate_student_login_form(student_id, password)
|
| 325 |
+
if error:
|
| 326 |
+
flash(error, "error")
|
| 327 |
+
return redirect(url_for("admin_panel"))
|
| 328 |
+
|
| 329 |
+
user = db.create_or_update_user(student_id, password)
|
| 330 |
+
db.add_log(None, user["id"], "admin", "INFO", f"管理员 {admin['username']} 录入或更新了用户账号。")
|
| 331 |
+
|
| 332 |
+
initial_course_id, initial_course_index = normalize_course_pair(
|
| 333 |
+
request.form.get("course_id", ""),
|
| 334 |
+
request.form.get("course_index", ""),
|
| 335 |
+
)
|
| 336 |
+
if initial_course_id or initial_course_index:
|
| 337 |
+
course_error = validate_course_form(initial_course_id, initial_course_index)
|
| 338 |
+
if course_error:
|
| 339 |
+
flash(course_error, "error")
|
| 340 |
+
return redirect(url_for("admin_panel"))
|
| 341 |
+
db.add_course(user["id"], initial_course_id, initial_course_index)
|
| 342 |
+
db.add_log(
|
| 343 |
+
None,
|
| 344 |
+
user["id"],
|
| 345 |
+
"admin",
|
| 346 |
+
"INFO",
|
| 347 |
+
f"管理员 {admin['username']} 为用户新增课程 {initial_course_id}_{initial_course_index}。",
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
flash("用户信息已保存。", "success")
|
| 351 |
+
return redirect(url_for("admin_panel"))
|
| 352 |
+
|
| 353 |
+
@app.post("/admin/panel/users/<int:user_id>/password")
|
| 354 |
+
@require_admin
|
| 355 |
+
def update_user_password_from_admin(admin: dict[str, Any], user_id: int):
|
| 356 |
+
password = request.form.get("password", "")
|
| 357 |
+
if not password:
|
| 358 |
+
flash("密码不能为空。", "error")
|
| 359 |
+
return redirect(url_for("admin_panel"))
|
| 360 |
+
db.update_user_password(user_id, password)
|
| 361 |
+
db.add_log(None, user_id, "admin", "INFO", f"管理员 {admin['username']} 更新了用户密码。")
|
| 362 |
+
flash("用户密码已更新。", "success")
|
| 363 |
+
return redirect(url_for("admin_panel"))
|
| 364 |
+
|
| 365 |
+
@app.post("/admin/panel/users/<int:user_id>/courses")
|
| 366 |
+
@require_admin
|
| 367 |
+
def add_user_course_from_admin(admin: dict[str, Any], user_id: int):
|
| 368 |
+
course_id, course_index = normalize_course_pair(
|
| 369 |
+
request.form.get("course_id", ""),
|
| 370 |
+
request.form.get("course_index", ""),
|
| 371 |
+
)
|
| 372 |
+
error = validate_course_form(course_id, course_index)
|
| 373 |
+
if error:
|
| 374 |
+
flash(error, "error")
|
| 375 |
+
return redirect(url_for("admin_panel"))
|
| 376 |
+
db.add_course(user_id, course_id, course_index)
|
| 377 |
+
db.add_log(
|
| 378 |
+
None,
|
| 379 |
+
user_id,
|
| 380 |
+
"admin",
|
| 381 |
+
"INFO",
|
| 382 |
+
f"管理员 {admin['username']} 为用户新增课程 {course_id}_{course_index}。",
|
| 383 |
+
)
|
| 384 |
+
flash("课程已添加到目标用户。", "success")
|
| 385 |
+
return redirect(url_for("admin_panel"))
|
| 386 |
+
|
| 387 |
+
@app.post("/admin/panel/users/<int:user_id>/courses/<int:course_record_id>/delete")
|
| 388 |
+
@require_admin
|
| 389 |
+
def delete_user_course_from_admin(admin: dict[str, Any], user_id: int, course_record_id: int):
|
| 390 |
+
db.delete_course(course_record_id, user_id)
|
| 391 |
+
db.add_log(
|
| 392 |
+
None,
|
| 393 |
+
user_id,
|
| 394 |
+
"admin",
|
| 395 |
+
"INFO",
|
| 396 |
+
f"管理员 {admin['username']} 删除了课程记录 #{course_record_id}。",
|
| 397 |
+
)
|
| 398 |
+
flash("课程已删除。", "success")
|
| 399 |
+
return redirect(url_for("admin_panel"))
|
| 400 |
+
|
| 401 |
+
@app.post("/admin/panel/users/<int:user_id>/tasks/start")
|
| 402 |
+
@require_admin
|
| 403 |
+
def start_user_task_from_admin(admin: dict[str, Any], user_id: int):
|
| 404 |
+
user = db.get_user_by_id(user_id)
|
| 405 |
+
if not user:
|
| 406 |
+
flash("用户不存在。", "error")
|
| 407 |
+
return redirect(url_for("admin_panel"))
|
| 408 |
+
task = db.create_task(user_id, "admin", admin["username"])
|
| 409 |
+
db.add_log(
|
| 410 |
+
task["id"],
|
| 411 |
+
user_id,
|
| 412 |
+
"admin",
|
| 413 |
+
"INFO",
|
| 414 |
+
f"管理员 {admin['username']} 启动了用户 {user['student_id']} 的任务。",
|
| 415 |
+
)
|
| 416 |
+
flash("任务已加入队列。", "success")
|
| 417 |
+
return redirect(url_for("admin_panel"))
|
| 418 |
+
|
| 419 |
+
@app.post("/admin/panel/users/<int:user_id>/tasks/stop")
|
| 420 |
+
@require_admin
|
| 421 |
+
def stop_user_task_from_admin(admin: dict[str, Any], user_id: int):
|
| 422 |
+
db.request_stop_task(user_id)
|
| 423 |
+
db.add_log(None, user_id, "admin", "INFO", f"管理员 {admin['username']} 请求停止用户任务。")
|
| 424 |
+
flash("停止请求已提交。", "success")
|
| 425 |
+
return redirect(url_for("admin_panel"))
|
| 426 |
+
|
| 427 |
+
@app.post("/admin/panel/admins")
|
| 428 |
+
@require_superadmin
|
| 429 |
+
def create_admin_account(admin: dict[str, Any]):
|
| 430 |
+
username = (request.form.get("username") or "").strip()
|
| 431 |
+
password = request.form.get("password") or ""
|
| 432 |
+
if not username or not password:
|
| 433 |
+
flash("管理员账号和密码不能为空。", "error")
|
| 434 |
+
return redirect(url_for("admin_panel"))
|
| 435 |
+
try:
|
| 436 |
+
db.create_admin(username, password)
|
| 437 |
+
db.add_log(None, None, "admin", "INFO", f"超级管理员 {admin['username']} 创建了管理员 {username}。")
|
| 438 |
+
flash("管理员已创建。", "success")
|
| 439 |
+
except Exception as exc:
|
| 440 |
+
flash(f"管理员创建失败:{exc}", "error")
|
| 441 |
+
return redirect(url_for("admin_panel"))
|
| 442 |
+
|
| 443 |
+
@app.get("/api/admin/status")
|
| 444 |
+
@require_admin
|
| 445 |
+
def admin_status(admin: dict[str, Any]):
|
| 446 |
+
return jsonify(db.get_admin_summary())
|
| 447 |
+
|
| 448 |
+
@app.get("/events/logs/admin")
|
| 449 |
+
@require_admin
|
| 450 |
+
def admin_log_stream(admin: dict[str, Any]):
|
| 451 |
+
response = Response(stream_with_context(event_stream(log_scope_user_id=None)))
|
| 452 |
+
response.headers["Content-Type"] = "text/event-stream"
|
| 453 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 454 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 455 |
+
return response
|
| 456 |
+
|
| 457 |
+
return app
|
ensure_package_exist.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
确保所有依赖项都已安装
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def ensure_package_exist():
|
| 8 |
+
"""
|
| 9 |
+
确保所有依赖项都已安装
|
| 10 |
+
"""
|
| 11 |
+
try:
|
| 12 |
+
import initialize
|
| 13 |
+
from selenium import webdriver
|
| 14 |
+
import type_defs as types
|
| 15 |
+
from fake_useragent import UserAgent
|
| 16 |
+
except:
|
| 17 |
+
print("警告:你似乎还没有安装完全这些依赖项")
|
| 18 |
+
op=input("输入y以自动安装,或者输入uv使用uv pip:")
|
| 19 |
+
if op == "y":
|
| 20 |
+
os.system("pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt")
|
| 21 |
+
print("安装完成!")
|
| 22 |
+
elif op == "uv":
|
| 23 |
+
os.system("uv pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt")
|
| 24 |
+
print("安装完成!")
|
| 25 |
+
else:
|
| 26 |
+
print("缺少必要依赖项")
|
| 27 |
+
print("程序无法运行,即将退出")
|
| 28 |
+
input("Press Enter to Continue...")
|
| 29 |
+
exit()
|
favicon.ico
ADDED
|
|
Git LFS Details
|
initialize.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#This program will save your information for quicker catching
|
| 2 |
+
#The data will only save locally.
|
| 3 |
+
import ensure_package_exist
|
| 4 |
+
ensure_package_exist.ensure_package_exist()
|
| 5 |
+
import json,re
|
| 6 |
+
from type_defs import Course, CourseData, UserData
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def save_user_date(user_data:UserData):
|
| 10 |
+
with open("user_data.json",mode="w",encoding="utf-8") as file:
|
| 11 |
+
json.dump(user_data.to_dict(),file,indent=2)
|
| 12 |
+
|
| 13 |
+
def main()->UserData:
|
| 14 |
+
user_data = UserData(
|
| 15 |
+
std_id=input("Input your Student ID: "),
|
| 16 |
+
password=input("Input your password: ")
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
while True:
|
| 20 |
+
source=""
|
| 21 |
+
while source not in ["a","b","q"]:
|
| 22 |
+
source = input("输入课程来源(a.方案选课/b.自由选课/q.停止添加)(输入a或b即可): ")
|
| 23 |
+
if(source == "q"):
|
| 24 |
+
break
|
| 25 |
+
course_id = input("输入课程号: ")
|
| 26 |
+
course_index = input("输入课序号(必须为两位数,如:01、33): ")
|
| 27 |
+
try:
|
| 28 |
+
int(course_id),int(course_index)
|
| 29 |
+
if len(course_index) != 2:
|
| 30 |
+
raise Exception
|
| 31 |
+
new_course = Course(course_id=course_id, course_index=course_index)
|
| 32 |
+
if source == "a":
|
| 33 |
+
user_data.course.a.append(new_course)
|
| 34 |
+
else:
|
| 35 |
+
user_data.course.b.append(new_course)
|
| 36 |
+
except:
|
| 37 |
+
print("Invaild course!Failed to add the course!")
|
| 38 |
+
continue
|
| 39 |
+
|
| 40 |
+
save_user_date(user_data)
|
| 41 |
+
print("Done!")
|
| 42 |
+
return user_data
|
| 43 |
+
|
| 44 |
+
def show_user_data(user_data:UserData) -> None:
|
| 45 |
+
print("User information:")
|
| 46 |
+
print("Student ID:%s"%(user_data.std_id),"Password:%s"%(user_data.password),sep="\n")
|
| 47 |
+
print("Your courses:")
|
| 48 |
+
print("-"*20)
|
| 49 |
+
print("Plan courses:")
|
| 50 |
+
print("\n".join(map(lambda x:"Course %s_%s"%(x.course_id,x.course_index),user_data.course.a)))
|
| 51 |
+
print("-"*20)
|
| 52 |
+
print("Free courses:")
|
| 53 |
+
print("\n".join(map(lambda x:"Course %s_%s"%(x.course_id,x.course_index),user_data.course.b)))
|
| 54 |
+
print("-"*20)
|
| 55 |
+
|
| 56 |
+
def update(user_data:UserData) -> UserData:
|
| 57 |
+
show_user_data(user_data)
|
| 58 |
+
|
| 59 |
+
operate = ""
|
| 60 |
+
while True:
|
| 61 |
+
while operate not in ["i","p","a","b","q"]:
|
| 62 |
+
operate = input("请输入更新指令(i.更改学号/p.更改密码/a.更改方案选课/b.更改自由选课/s.展示当前信息/q.保存并退出)(输入前面的字母即可):")
|
| 63 |
+
if operate == "q":
|
| 64 |
+
return user_data
|
| 65 |
+
elif operate == "i":
|
| 66 |
+
user_data.std_id = input("Input the new std_id:")
|
| 67 |
+
print("Student ID has been updated!")
|
| 68 |
+
elif operate == "p":
|
| 69 |
+
new_passwd = input("Input the new password:")
|
| 70 |
+
if new_passwd == input("Input the new password again:"):
|
| 71 |
+
user_data.password = new_passwd
|
| 72 |
+
print("Password has been updated!")
|
| 73 |
+
else:
|
| 74 |
+
print("The passwords entered did not match.Failed to update the password!")
|
| 75 |
+
elif operate in ["a","b"]:
|
| 76 |
+
order,args = "",[]
|
| 77 |
+
name = "方案选课" if operate == "a" else "自由选课"
|
| 78 |
+
en_name = "Plan courses" if operate == "a" else "Free courses"
|
| 79 |
+
course_list = user_data.course.a if operate == "a" else user_data.course.b
|
| 80 |
+
while True:
|
| 81 |
+
print("%s:"%(en_name))
|
| 82 |
+
print("\n".join(map(lambda x:"%d.%s"%(x[0],x[1]),enumerate(map(lambda x:"Course %s_%s"%(x.course_id,x.course_index),course_list),1))))
|
| 83 |
+
while order not in ["a","d","q"]:
|
| 84 |
+
manage = input("请输入更改%s的指令(a [课程号] [课序号].添加新的课程/d [序号].删除第[序号]条课程/q.退出方案选课更新)(输入指令并带上参数):"%(name))
|
| 85 |
+
order = manage.split(" ")[0]
|
| 86 |
+
args = re.findall(r"\d+",manage)
|
| 87 |
+
if order == "q":
|
| 88 |
+
break
|
| 89 |
+
elif order == "a":
|
| 90 |
+
if len(args) == 2:
|
| 91 |
+
try:
|
| 92 |
+
numbers = [int(i) for i in args]
|
| 93 |
+
if len(args[1]) != 2:
|
| 94 |
+
raise Exception
|
| 95 |
+
new_course = Course(course_id=args[0], course_index=args[1])
|
| 96 |
+
if not new_course in course_list:
|
| 97 |
+
course_list.append(new_course)
|
| 98 |
+
print("Successfully added Course %s_%s!"%(args[0],args[1]))
|
| 99 |
+
else:
|
| 100 |
+
print("Course %s_%s has already existed!"%(args[0],args[1]))
|
| 101 |
+
except:
|
| 102 |
+
print("Invaild arguments type!Failed to add the course!")
|
| 103 |
+
else:
|
| 104 |
+
print("Invaild number of arguments!Failed to add the course!")
|
| 105 |
+
elif order == "d":
|
| 106 |
+
if len(args) == 1:
|
| 107 |
+
try:
|
| 108 |
+
pos = int(args[0])
|
| 109 |
+
try:
|
| 110 |
+
if pos <= 0:
|
| 111 |
+
raise Exception
|
| 112 |
+
target = course_list[pos-1]
|
| 113 |
+
del course_list[pos-1]
|
| 114 |
+
print("Successfully deleted the Course %s_%s!"%(target.course_id,target.course_index))
|
| 115 |
+
except:
|
| 116 |
+
print("Invaild position!Failed to delete the course!")
|
| 117 |
+
except:
|
| 118 |
+
print("Invaild argument type!Failed to delete the course!")
|
| 119 |
+
else:
|
| 120 |
+
print("Invaild number of arguments!Failed to add the course!")
|
| 121 |
+
order,args = "",[]
|
| 122 |
+
elif operate == "s":
|
| 123 |
+
show_user_data(user_data)
|
| 124 |
+
operate = ""
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
try:
|
| 128 |
+
with open("user_data.json",mode="r") as file:
|
| 129 |
+
new_json = update(UserData.from_dict(json.load(file)))
|
| 130 |
+
save_user_date(new_json)
|
| 131 |
+
print("Update finished!")
|
| 132 |
+
except:
|
| 133 |
+
main()
|
| 134 |
+
|
| 135 |
+
|
initialize_plus.pyw
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json,copy
|
| 2 |
+
from tkinter import *
|
| 3 |
+
from tkinter import messagebox
|
| 4 |
+
from type_defs import UserData, Setting, Course, CourseData
|
| 5 |
+
import ensure_package_exist
|
| 6 |
+
ensure_package_exist.ensure_package_exist()
|
| 7 |
+
|
| 8 |
+
def save(user_data:UserData,setting:Setting):
|
| 9 |
+
with open("user_data.json",mode="w") as file:
|
| 10 |
+
json.dump(user_data.to_dict(),file,indent=2)
|
| 11 |
+
with open("setting.json",mode="w") as file:
|
| 12 |
+
json.dump(setting.to_dict(),file,indent=2)
|
| 13 |
+
|
| 14 |
+
def window_quit():
|
| 15 |
+
if old_user_data != new_user_data or old_setting_data != new_setting_data:
|
| 16 |
+
if messagebox.askyesno("Exit","Do you want to save your data?"):
|
| 17 |
+
save(new_user_data,new_setting_data)
|
| 18 |
+
window.destroy()
|
| 19 |
+
|
| 20 |
+
def click_save_button():
|
| 21 |
+
global old_user_data,old_setting_data
|
| 22 |
+
try:
|
| 23 |
+
save(new_user_data,new_setting_data)
|
| 24 |
+
old_user_data = copy.deepcopy(new_user_data)
|
| 25 |
+
old_setting_data = copy.deepcopy(new_setting_data)
|
| 26 |
+
messagebox.showinfo("Message","Save data successfully")
|
| 27 |
+
except:
|
| 28 |
+
messagebox.showerror("Error","Failed to save data,please check your json files!")
|
| 29 |
+
|
| 30 |
+
def show_passwd():
|
| 31 |
+
global passwd_show
|
| 32 |
+
passwd_show = not passwd_show
|
| 33 |
+
if passwd_show:
|
| 34 |
+
passwd_entry_box.configure(show="")
|
| 35 |
+
passwd_show_button.configure(text="Hide")
|
| 36 |
+
else:
|
| 37 |
+
passwd_entry_box.configure(show="*")
|
| 38 |
+
passwd_show_button.configure(text="Show")
|
| 39 |
+
|
| 40 |
+
def user_ok():
|
| 41 |
+
std_id,passwd = id_entry_box.get(),passwd_entry_box.get()
|
| 42 |
+
if not std_id.isdigit() or len(id_entry_box.get()) != 13:
|
| 43 |
+
messagebox.showerror("Invalid student ID","Your student ID should only consist of 13 numbers!")
|
| 44 |
+
id_entry_box.delete(0,END)
|
| 45 |
+
id_entry_box.insert(0,new_user_data.std_id)
|
| 46 |
+
else:
|
| 47 |
+
new_user_data.std_id = std_id
|
| 48 |
+
new_user_data.password = passwd
|
| 49 |
+
messagebox.showinfo("Message","Enter your user information successfully")
|
| 50 |
+
|
| 51 |
+
def plan_course():
|
| 52 |
+
main_interface()
|
| 53 |
+
course_name_label.configure(text="Plan courses")
|
| 54 |
+
course_list_box.delete(0,END)
|
| 55 |
+
for course in new_user_data.course.a:
|
| 56 |
+
course_list_box.insert(END,"%s_%s"%(course.course_id,course.course_index))
|
| 57 |
+
no_select()
|
| 58 |
+
|
| 59 |
+
def free_course():
|
| 60 |
+
main_interface()
|
| 61 |
+
course_name_label.configure(text="Free courses")
|
| 62 |
+
course_list_box.delete(0,END)
|
| 63 |
+
for course in new_user_data.course.b:
|
| 64 |
+
course_list_box.insert(END,"%s_%s"%(course.course_id,course.course_index))
|
| 65 |
+
no_select()
|
| 66 |
+
|
| 67 |
+
def course_select(event):
|
| 68 |
+
course_id,course_index = event.widget.get(event.widget.curselection()).split("_")
|
| 69 |
+
course_id_entry_box.delete(0,END)
|
| 70 |
+
course_index_entry_box.delete(0,END)
|
| 71 |
+
course_id_entry_box.insert(0,course_id)
|
| 72 |
+
course_index_entry_box.insert(0,course_index)
|
| 73 |
+
cancel_button.configure(state=NORMAL)
|
| 74 |
+
delete_button.configure(state=NORMAL)
|
| 75 |
+
manage_button.configure(text="Update",command=update_course)
|
| 76 |
+
|
| 77 |
+
def no_select(event=None):
|
| 78 |
+
course_list_box.selection_clear(0, END)
|
| 79 |
+
course_id_entry_box.delete(0,END)
|
| 80 |
+
course_index_entry_box.delete(0,END)
|
| 81 |
+
cancel_button.configure(state=DISABLED)
|
| 82 |
+
delete_button.configure(state=DISABLED)
|
| 83 |
+
manage_button.configure(text="Add",command=add_course)
|
| 84 |
+
|
| 85 |
+
def listbox_locate(listbox:Listbox,scrollbar:Scrollbar,index:int):
|
| 86 |
+
height,size = listbox.cget("height"),listbox.size()
|
| 87 |
+
first = index if index + height <= size else size - height
|
| 88 |
+
last = first + height
|
| 89 |
+
listbox.yview_moveto(first/size)
|
| 90 |
+
scrollbar.set(first=first/size,last=last/size)
|
| 91 |
+
|
| 92 |
+
def add_course():
|
| 93 |
+
course_id,course_index = course_id_entry_box.get(),course_index_entry_box.get()
|
| 94 |
+
course_list = new_user_data.course.a if course_name_label.cget("text") == "Plan courses" else new_user_data.course.b
|
| 95 |
+
index = -1
|
| 96 |
+
for i in range(len(course_list)):
|
| 97 |
+
if course_list[i].course_id == course_id:
|
| 98 |
+
index = i
|
| 99 |
+
break
|
| 100 |
+
if not course_id or not course_index:
|
| 101 |
+
messagebox.showerror("Empty course","Please input the course information first!")
|
| 102 |
+
elif not course_id.isdigit() or not course_index.isdigit():
|
| 103 |
+
messagebox.showerror("Invalid course","Please enter the right course data that consists of only numbers!")
|
| 104 |
+
if not course_id.isdigit():
|
| 105 |
+
course_id_entry_box.delete(0,END)
|
| 106 |
+
if not course_index.isdigit():
|
| 107 |
+
course_index_entry_box.delete(0,END)
|
| 108 |
+
elif len(course_index) != 2:
|
| 109 |
+
messagebox.showerror("Invalid index","Please enter the right index that consists of only 2 numbers!")
|
| 110 |
+
course_index_entry_box.delete(0,END)
|
| 111 |
+
elif index != -1:
|
| 112 |
+
course_list_box.select_set(index)
|
| 113 |
+
listbox_locate(course_list_box,course_list_box_scroll,index)
|
| 114 |
+
old_course = course_list_box.get(index)
|
| 115 |
+
if course_list[index].course_index != course_index and messagebox.askyesno("Update a already existing course","You already have the course %s\nWould you want to update it?(New:%s_%s)"%(old_course,course_id,course_index)):
|
| 116 |
+
course_list_box.delete(index)
|
| 117 |
+
course_list_box.insert(index,"%s_%s"%(course_id,course_index))
|
| 118 |
+
course_list_box.select_set(index)
|
| 119 |
+
course_list[index].course_index = course_index
|
| 120 |
+
course_index_entry_box.delete(0,END)
|
| 121 |
+
course_index_entry_box.insert(0,course_index)
|
| 122 |
+
cancel_button.configure(state=NORMAL)
|
| 123 |
+
delete_button.configure(state=NORMAL)
|
| 124 |
+
manage_button.configure(text="Update",command=update_course)
|
| 125 |
+
else:
|
| 126 |
+
course_list_box.insert(END,"%s_%s"%(course_id,course_index))
|
| 127 |
+
course_list.append(Course(course_id=course_id,course_index=course_index))
|
| 128 |
+
course_id_entry_box.delete(0,END)
|
| 129 |
+
course_index_entry_box.delete(0,END)
|
| 130 |
+
|
| 131 |
+
def update_course():
|
| 132 |
+
index = course_list_box.curselection()[0]
|
| 133 |
+
old_id,old_index = course_list_box.get(index).split("_")
|
| 134 |
+
new_id,new_index = course_id_entry_box.get(),course_index_entry_box.get()
|
| 135 |
+
course_list = new_user_data.course.a if course_name_label.cget("text") == "Plan courses" else new_user_data.course.b
|
| 136 |
+
if not new_id or not new_index:
|
| 137 |
+
messagebox.showerror("Empty course","Please input the course information first!")
|
| 138 |
+
if not new_id:
|
| 139 |
+
course_id_entry_box.insert(0,old_id)
|
| 140 |
+
if not new_index:
|
| 141 |
+
course_index_entry_box.insert(0,old_index)
|
| 142 |
+
elif not new_id.isdigit() or not new_index.isdigit():
|
| 143 |
+
messagebox.showerror("Invalid course","Please enter the right course data that consists of only numbers!")
|
| 144 |
+
if not new_id.isdigit():
|
| 145 |
+
course_id_entry_box.delete(0,END)
|
| 146 |
+
course_id_entry_box.insert(0,old_id)
|
| 147 |
+
if not new_index.isdigit():
|
| 148 |
+
course_index_entry_box.delete(0,END)
|
| 149 |
+
course_index_entry_box.insert(0,old_index)
|
| 150 |
+
elif len(new_index) != 2:
|
| 151 |
+
messagebox.showerror("Invalid index","Please enter the right index that consists of only 2 numbers!")
|
| 152 |
+
course_index_entry_box.delete(0,END)
|
| 153 |
+
course_index_entry_box.insert(0,old_index)
|
| 154 |
+
else:
|
| 155 |
+
course_list_box.delete(index)
|
| 156 |
+
course_list_box.insert(index,"%s_%s"%(new_id,new_index))
|
| 157 |
+
course = course_list[index]
|
| 158 |
+
course.course_id,course.course_index = new_id,new_index
|
| 159 |
+
|
| 160 |
+
def delete_course():
|
| 161 |
+
index = course_list_box.curselection()[0]
|
| 162 |
+
course_id,course_index = course_list_box.get(index).split("_")
|
| 163 |
+
if messagebox.askyesno("Confirm","Are you sure you want to delete the course %s_%s?"%(course_id,course_index)):
|
| 164 |
+
course_list_box.delete(index)
|
| 165 |
+
course_id_entry_box.delete(0,END)
|
| 166 |
+
course_index_entry_box.delete(0,END)
|
| 167 |
+
course_list = new_user_data.course.a if course_name_label.cget("text") == "Plan courses" else new_user_data.course.b
|
| 168 |
+
course_list.remove(Course(course_id=course_id,course_index=course_index))
|
| 169 |
+
|
| 170 |
+
def manual_login_click():
|
| 171 |
+
if manual_login_button.cget("text") == "Disable":
|
| 172 |
+
if messagebox.askyesno("Disable manual login","It\'ll significantly accelerate the login, but it also usually leads to the incapability of the login when the server is busy (especially during peak course selection periods).\nAre you sure to disable?"):
|
| 173 |
+
try:
|
| 174 |
+
new_setting_data.manual_login = False
|
| 175 |
+
manual_login_button.configure(text="Enable")
|
| 176 |
+
manual_login_state.configure(text="Disabled",fg="red")
|
| 177 |
+
messagebox.showinfo("Message","Disable manual login successfully")
|
| 178 |
+
except:
|
| 179 |
+
messagebox.showwarning("Error","Failed to disable manual login!")
|
| 180 |
+
else:
|
| 181 |
+
if messagebox.askyesno("Enable manual login","It\'ll significantly stabilize the login (especially during peak course selection periods), but it\'ll also significantly slow the login down.\nAre you sure to enable?"):
|
| 182 |
+
try:
|
| 183 |
+
new_setting_data.manual_login = True
|
| 184 |
+
manual_login_button.configure(text="Disable")
|
| 185 |
+
manual_login_state.configure(text="Enabled",fg="green")
|
| 186 |
+
messagebox.showinfo("Message","Enable manual login successfully")
|
| 187 |
+
except:
|
| 188 |
+
messagebox.showwarning("Error","Failed to enable manual login!")
|
| 189 |
+
|
| 190 |
+
def browser_click():
|
| 191 |
+
if new_setting_data.browser == "edge":
|
| 192 |
+
new_setting_data.browser = "chrome"
|
| 193 |
+
browser_state.configure(text="Chrome",fg="blue")
|
| 194 |
+
browser_button.configure(text="Switch to Edge")
|
| 195 |
+
else:
|
| 196 |
+
new_setting_data.browser = "edge"
|
| 197 |
+
browser_state.configure(text="Edge",fg="green")
|
| 198 |
+
browser_button.configure(text="Switch to Chrome")
|
| 199 |
+
|
| 200 |
+
def main_interface():
|
| 201 |
+
for widget in window.winfo_children():
|
| 202 |
+
widget.place_forget()
|
| 203 |
+
|
| 204 |
+
id_label.place(x=size[0]-290,y=50)
|
| 205 |
+
id_entry_box.place(x=size[0]-220,y=50)
|
| 206 |
+
passwd_label.place(x=size[0]-285,y=85)
|
| 207 |
+
passwd_entry_box.place(x=size[0]-220,y=85)
|
| 208 |
+
passwd_show_button.place(x=size[0]-70,y=80)
|
| 209 |
+
user_ok_button.place(x=size[0]-175,y=125)
|
| 210 |
+
save_button.place(x=size[0]-225,y=size[1]-110)
|
| 211 |
+
course_name_label.place(x=50,y=5)
|
| 212 |
+
course_list_box.place(x=50,y=30)
|
| 213 |
+
course_list_box_scroll.place(x=295,y=30,height=380)
|
| 214 |
+
course_id_label.place(x=size[0]-290,y=200)
|
| 215 |
+
course_index_label.place(x=size[0]-310,y=235)
|
| 216 |
+
course_id_entry_box.place(x=size[0]-220,y=200)
|
| 217 |
+
course_index_entry_box.place(x=size[0]-220,y=235)
|
| 218 |
+
cancel_button.place(x=size[0]-230,y=280)
|
| 219 |
+
manage_button.place(x=size[0]-180,y=325)
|
| 220 |
+
delete_button.place(x=size[0]-130,y=280)
|
| 221 |
+
|
| 222 |
+
def setting_interface():
|
| 223 |
+
for widget in window.winfo_children():
|
| 224 |
+
widget.place_forget()
|
| 225 |
+
|
| 226 |
+
save_button.place(x=size[0]-225,y=size[1]-110)
|
| 227 |
+
manual_login_label.place(x=50,y=20)
|
| 228 |
+
manual_login_state.place(x=280,y=23)
|
| 229 |
+
manual_login_button.place(x=500,y=20)
|
| 230 |
+
browser_label.place(x=50,y=60)
|
| 231 |
+
browser_state.place(x=280,y=63)
|
| 232 |
+
browser_button.place(x=500,y=60)
|
| 233 |
+
|
| 234 |
+
#load the data,if it exists
|
| 235 |
+
try:
|
| 236 |
+
old_user_data = UserData.from_file("user_data.json")
|
| 237 |
+
old_setting_data = Setting.from_file("setting.json")
|
| 238 |
+
except Exception as e:
|
| 239 |
+
print(e)
|
| 240 |
+
old_user_data = UserData(std_id="", password="", course=CourseData())
|
| 241 |
+
old_setting_data = Setting(manual_login=False)
|
| 242 |
+
|
| 243 |
+
new_user_data = copy.deepcopy(old_user_data)
|
| 244 |
+
new_setting_data = copy.deepcopy(old_setting_data)
|
| 245 |
+
passwd_show = False
|
| 246 |
+
size = [640,480]
|
| 247 |
+
|
| 248 |
+
#Create a gui
|
| 249 |
+
window = Tk()
|
| 250 |
+
window.title("Initialize")
|
| 251 |
+
window.iconbitmap("favicon.ico")
|
| 252 |
+
window.geometry("%dx%d"%(size[0],size[1]))
|
| 253 |
+
window.protocol("WM_DELETE_WINDOW",window_quit)
|
| 254 |
+
|
| 255 |
+
#Labels
|
| 256 |
+
id_label = Label(window,text="Student ID")
|
| 257 |
+
passwd_label = Label(window,text="Password")
|
| 258 |
+
course_id_label = Label(window,text="Course ID")
|
| 259 |
+
course_index_label = Label(window,text="Course Index")
|
| 260 |
+
course_name_label = Label(window,font=("consolas",15))
|
| 261 |
+
|
| 262 |
+
manual_login_label = Label(window,text="Manual login")
|
| 263 |
+
manual_login_state = Label(window)
|
| 264 |
+
|
| 265 |
+
browser_label = Label(window,text="Browser")
|
| 266 |
+
browser_state = Label(window)
|
| 267 |
+
|
| 268 |
+
#initialize the state
|
| 269 |
+
if new_setting_data.manual_login:
|
| 270 |
+
manual_login_state.configure(text="Enabled",fg="green")
|
| 271 |
+
else:
|
| 272 |
+
manual_login_state.configure(text="Disabled",fg="red")
|
| 273 |
+
|
| 274 |
+
#Entries
|
| 275 |
+
id_entry_box = Entry(window,width=20)
|
| 276 |
+
passwd_entry_box = Entry(window,width=20,show="*")
|
| 277 |
+
course_id_entry_box = Entry(window,width=20)
|
| 278 |
+
course_index_entry_box = Entry(window,width=20)
|
| 279 |
+
|
| 280 |
+
#Buttons
|
| 281 |
+
passwd_show_button = Button(window,text="Show",command=show_passwd)
|
| 282 |
+
save_button = Button(window,text="Save",width=20,height=2,command=click_save_button)
|
| 283 |
+
user_ok_button = Button(window,text="OK",width=7,height=1,command=user_ok)
|
| 284 |
+
cancel_button = Button(window,text="Cancel",width=7,height=1,state=DISABLED,command=no_select)
|
| 285 |
+
manage_button = Button(window,text="Add",width=7,height=1,command=add_course)
|
| 286 |
+
delete_button = Button(window,text="Delete",width=7,height=1,state=DISABLED,command=delete_course)
|
| 287 |
+
|
| 288 |
+
manual_login_button = Button(window,width=7,height=1,command=manual_login_click)
|
| 289 |
+
|
| 290 |
+
browser_button = Button(window,width=15,height=1,command=browser_click)
|
| 291 |
+
|
| 292 |
+
#initialize the setting button
|
| 293 |
+
if new_setting_data.manual_login:
|
| 294 |
+
manual_login_button.configure(text="Disable")
|
| 295 |
+
else:
|
| 296 |
+
manual_login_button.configure(text="Enable")
|
| 297 |
+
|
| 298 |
+
#initialize the browser state
|
| 299 |
+
if new_setting_data.browser == "edge":
|
| 300 |
+
browser_state.configure(text="Edge",fg="green")
|
| 301 |
+
browser_button.configure(text="Switch to Chrome")
|
| 302 |
+
else:
|
| 303 |
+
browser_state.configure(text="Chrome",fg="blue")
|
| 304 |
+
browser_button.configure(text="Switch to Edge")
|
| 305 |
+
|
| 306 |
+
#Listbox
|
| 307 |
+
course_list_box_scroll = Scrollbar(window,width=20)
|
| 308 |
+
course_list_box = Listbox(window,height=15,font=("consolas",16),yscrollcommand=course_list_box_scroll.set,exportselection=False)
|
| 309 |
+
course_list_box.bind("<Button-3>",no_select)
|
| 310 |
+
course_list_box.bind("<<ListboxSelect>>",course_select)
|
| 311 |
+
course_list_box_scroll.config(command=course_list_box.yview)
|
| 312 |
+
|
| 313 |
+
#Menus
|
| 314 |
+
window_menu = Menu(window)
|
| 315 |
+
window_menu_list = Menu(window_menu,tearoff=False)
|
| 316 |
+
window_menu.add_cascade(label="Course type",menu=window_menu_list)
|
| 317 |
+
window_menu_list.add_command(label="Plan course",command=plan_course)
|
| 318 |
+
window_menu_list.add_command(label="Free course",command=free_course)
|
| 319 |
+
window_menu.add_command(label="Settings",command=setting_interface)
|
| 320 |
+
|
| 321 |
+
#Insert
|
| 322 |
+
id_entry_box.insert(0,new_user_data.std_id)
|
| 323 |
+
passwd_entry_box.insert(0,new_user_data.password)
|
| 324 |
+
|
| 325 |
+
"""
|
| 326 |
+
#Place
|
| 327 |
+
id_label.place(x=size[0]-290,y=50)
|
| 328 |
+
id_entry_box.place(x=size[0]-220,y=50)
|
| 329 |
+
passwd_label.place(x=size[0]-285,y=85)
|
| 330 |
+
passwd_entry_box.place(x=size[0]-220,y=85)
|
| 331 |
+
passwd_show_button.place(x=size[0]-70,y=80)
|
| 332 |
+
user_ok_button.place(x=size[0]-175,y=125)
|
| 333 |
+
save_button.place(x=size[0]-225,y=size[1]-110)
|
| 334 |
+
course_name_label.place(x=50,y=5)
|
| 335 |
+
course_list_box.place(x=50,y=30)
|
| 336 |
+
course_list_box_scroll.place(x=295,y=30,height=380)
|
| 337 |
+
course_id_label.place(x=size[0]-290,y=200)
|
| 338 |
+
course_index_label.place(x=size[0]-310,y=235)
|
| 339 |
+
course_id_entry_box.place(x=size[0]-220,y=200)
|
| 340 |
+
course_index_entry_box.place(x=size[0]-220,y=235)
|
| 341 |
+
cancel_button.place(x=size[0]-230,y=280)
|
| 342 |
+
manage_button.place(x=size[0]-180,y=325)
|
| 343 |
+
delete_button.place(x=size[0]-130,y=280)
|
| 344 |
+
"""
|
| 345 |
+
window.config(menu=window_menu)
|
| 346 |
+
plan_course()
|
| 347 |
+
|
| 348 |
+
#keep the gui active
|
| 349 |
+
window.mainloop()
|
javascript/check_result.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const rows = Array.from(document.querySelectorAll("#xkresult tbody tr"));
|
| 2 |
+
const items = rows.map((row) => {
|
| 3 |
+
const subjectCell = row.querySelector("td");
|
| 4 |
+
const statusNode = row.querySelector("span");
|
| 5 |
+
const detailText = statusNode ? statusNode.innerText.trim() : "";
|
| 6 |
+
return {
|
| 7 |
+
subject: subjectCell ? subjectCell.innerText.trim() : "",
|
| 8 |
+
result: statusNode ? !statusNode.className.includes("danger") : false,
|
| 9 |
+
detail: detailText,
|
| 10 |
+
};
|
| 11 |
+
});
|
| 12 |
+
|
| 13 |
+
return JSON.stringify(items);
|
javascript/select_course.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const target = arguments[0];
|
| 2 |
+
const iframe = document.getElementById("ifra");
|
| 3 |
+
|
| 4 |
+
if (!iframe) {
|
| 5 |
+
return "no";
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
|
| 9 |
+
if (!iframeDoc) {
|
| 10 |
+
return "no";
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
const rows = iframeDoc.querySelectorAll("#xirxkxkbody tr");
|
| 14 |
+
for (const row of rows) {
|
| 15 |
+
const cells = row.querySelectorAll("td");
|
| 16 |
+
if (cells.length < 3) {
|
| 17 |
+
continue;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
const rowText = cells[2].innerText.trim();
|
| 21 |
+
if (!rowText.includes(target)) {
|
| 22 |
+
continue;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
const picker = cells[0].querySelector("input");
|
| 26 |
+
if (picker) {
|
| 27 |
+
picker.click();
|
| 28 |
+
return "yes";
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
return "no";
|
main.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from app import app
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main() -> None:
|
| 9 |
+
host = os.getenv("HOST", "0.0.0.0")
|
| 10 |
+
port = int(os.getenv("PORT", "7860"))
|
| 11 |
+
app.run(host=host, port=port, debug=False, threaded=True, use_reloader=False)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if __name__ == "__main__":
|
| 15 |
+
main()
|
ocr_provider/captcha_model.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7db2b56ef35d351f97fb2dbf2ffef63426d1d17dbe7bb227582bc7e175f2312d
|
| 3 |
+
size 4450
|
ocr_provider/captcha_model.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ae70953fc6ca2f39ed9b2fccb221a4371aa9b6b34a0a0bd2819d0ca558ebdea2
|
| 3 |
+
size 452696
|
onnx_inference.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import onnxruntime as ort
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
|
| 6 |
+
num2char = {
|
| 7 |
+
k:v for k,v in enumerate("0123456789abcdefghijklmnopqrstuvwxyz")
|
| 8 |
+
}
|
| 9 |
+
char_length = len(num2char)
|
| 10 |
+
|
| 11 |
+
class CaptchaONNXInference:
|
| 12 |
+
def __init__(self, model_path, providers=None):
|
| 13 |
+
if providers is None:
|
| 14 |
+
providers = ['CPUExecutionProvider']
|
| 15 |
+
self.session = ort.InferenceSession(model_path, providers=providers)
|
| 16 |
+
self.input_name = self.session.get_inputs()[0].name
|
| 17 |
+
self.output_name = self.session.get_outputs()[0].name
|
| 18 |
+
|
| 19 |
+
def preprocess_array(self, img_array):
|
| 20 |
+
if img_array.max() > 1:
|
| 21 |
+
img_array = img_array.astype(np.float32) / 255.0
|
| 22 |
+
if len(img_array.shape) == 3:
|
| 23 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 24 |
+
return img_array
|
| 25 |
+
|
| 26 |
+
def predict(self, input_data):
|
| 27 |
+
outputs = self.session.run([self.output_name], {self.input_name: input_data})
|
| 28 |
+
output = outputs[0]
|
| 29 |
+
result = []
|
| 30 |
+
for i in range(4):
|
| 31 |
+
char_logits = output[0, i * char_length:(i + 1) * char_length]
|
| 32 |
+
char_index = np.argmax(char_logits)
|
| 33 |
+
result.append(num2char[char_index])
|
| 34 |
+
return "".join(result)
|
| 35 |
+
|
| 36 |
+
def classification(self,img_bytes):
|
| 37 |
+
img = Image.open(BytesIO(img_bytes)).convert('RGB')
|
| 38 |
+
img = img.resize((80, 26))
|
| 39 |
+
img_array = np.array(img).astype(np.float32) / 255.0
|
| 40 |
+
img_array = np.transpose(img_array, (2, 0, 1))
|
| 41 |
+
img_array = np.transpose(img_array, (1, 2, 0))
|
| 42 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 43 |
+
return self.predict(img_array)
|
| 44 |
+
|
| 45 |
+
def predict_batch(self, input_data):
|
| 46 |
+
outputs = self.session.run([self.output_name], {self.input_name: input_data})
|
| 47 |
+
output = outputs[0]
|
| 48 |
+
batch_size = output.shape[0]
|
| 49 |
+
results = []
|
| 50 |
+
for b in range(batch_size):
|
| 51 |
+
result = []
|
| 52 |
+
for i in range(4):
|
| 53 |
+
char_logits = output[b, i * char_length:(i + 1) * char_length]
|
| 54 |
+
char_index = np.argmax(char_logits)
|
| 55 |
+
result.append(num2char[char_index])
|
| 56 |
+
results.append("".join(result))
|
| 57 |
+
return results
|
pyproject.toml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "advanced-scu-course-catcher"
|
| 3 |
+
version = "2.0.0"
|
| 4 |
+
description = "SCU course catcher web app for Hugging Face Spaces"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.11"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"Flask>=3.0.0",
|
| 9 |
+
"gunicorn>=23.0.0",
|
| 10 |
+
"selenium>=4.35.0",
|
| 11 |
+
"onnxruntime>=1.18.0",
|
| 12 |
+
"numpy>=1.24.0",
|
| 13 |
+
"Pillow>=10.0.0",
|
| 14 |
+
"cryptography>=43.0.0",
|
| 15 |
+
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Flask>=3.0.0
|
| 2 |
+
gunicorn>=23.0.0
|
| 3 |
+
selenium>=4.35.0
|
| 4 |
+
onnxruntime>=1.18.0
|
| 5 |
+
numpy>=1.24.0
|
| 6 |
+
Pillow>=10.0.0
|
| 7 |
+
cryptography>=43.0.0
|
space_app.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import atexit
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
from functools import wraps
|
| 7 |
+
from typing import Callable
|
| 8 |
+
|
| 9 |
+
from flask import Flask, Response, flash, jsonify, redirect, render_template, request, session, stream_with_context, url_for
|
| 10 |
+
|
| 11 |
+
from core.config import AppConfig
|
| 12 |
+
from core.db import Database
|
| 13 |
+
from core.security import SecretBox, hash_password, verify_password
|
| 14 |
+
from core.task_manager import TaskManager
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
config = AppConfig.load()
|
| 18 |
+
store = Database(config.db_path, default_parallel_limit=config.default_parallel_limit)
|
| 19 |
+
store.init_db()
|
| 20 |
+
secret_box = SecretBox(config.encryption_key)
|
| 21 |
+
task_manager = TaskManager(config=config, store=store, secret_box=secret_box)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _seed_legacy_user() -> None:
|
| 25 |
+
if store.list_users():
|
| 26 |
+
return
|
| 27 |
+
|
| 28 |
+
legacy_path = config.root_dir / "user_data.json"
|
| 29 |
+
if not legacy_path.exists():
|
| 30 |
+
return
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
payload = json.loads(legacy_path.read_text(encoding="utf-8"))
|
| 34 |
+
except (OSError, json.JSONDecodeError):
|
| 35 |
+
return
|
| 36 |
+
|
| 37 |
+
student_id = str(payload.get("std_id", "")).strip()
|
| 38 |
+
password = str(payload.get("password", "")).strip()
|
| 39 |
+
if not student_id or not password:
|
| 40 |
+
return
|
| 41 |
+
|
| 42 |
+
user_id = store.create_user(student_id, secret_box.encrypt(password), "Legacy User")
|
| 43 |
+
for source_key, category in (("a", "plan"), ("b", "free")):
|
| 44 |
+
for course in payload.get("course", {}).get(source_key, []):
|
| 45 |
+
course_id = str(course.get("course_id", "")).strip()
|
| 46 |
+
course_index = str(course.get("course_index", "")).strip()
|
| 47 |
+
if course_id and course_index:
|
| 48 |
+
store.add_course(user_id, category, course_id, course_index)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_seed_legacy_user()
|
| 52 |
+
task_manager.start()
|
| 53 |
+
atexit.register(task_manager.shutdown)
|
| 54 |
+
|
| 55 |
+
app = Flask(__name__, template_folder="templates", static_folder="static")
|
| 56 |
+
app.secret_key = config.session_secret
|
| 57 |
+
app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax")
|
| 58 |
+
|
| 59 |
+
CATEGORY_LABELS = {
|
| 60 |
+
"plan": "方案选课",
|
| 61 |
+
"free": "自由选课",
|
| 62 |
+
}
|
| 63 |
+
TASK_LABELS = {
|
| 64 |
+
"pending": "排队中",
|
| 65 |
+
"running": "执行中",
|
| 66 |
+
"cancel_requested": "停止中",
|
| 67 |
+
"completed": "已完成",
|
| 68 |
+
"stopped": "已停止",
|
| 69 |
+
"failed": "失败",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@app.context_processor
|
| 74 |
+
def inject_globals() -> dict:
|
| 75 |
+
return {
|
| 76 |
+
"category_labels": CATEGORY_LABELS,
|
| 77 |
+
"task_labels": TASK_LABELS,
|
| 78 |
+
"session_role": session.get("role", "guest"),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _login_required(role: str) -> Callable:
|
| 83 |
+
def decorator(view: Callable) -> Callable:
|
| 84 |
+
@wraps(view)
|
| 85 |
+
def wrapped(*args, **kwargs):
|
| 86 |
+
current_role = session.get("role")
|
| 87 |
+
if role == "user" and current_role != "user":
|
| 88 |
+
flash("请先登录学生账号。", "warning")
|
| 89 |
+
return redirect(url_for("login"))
|
| 90 |
+
if role == "admin" and current_role != "admin":
|
| 91 |
+
flash("请先登录管理员账号。", "warning")
|
| 92 |
+
return redirect(url_for("admin_login"))
|
| 93 |
+
return view(*args, **kwargs)
|
| 94 |
+
|
| 95 |
+
return wrapped
|
| 96 |
+
|
| 97 |
+
return decorator
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _get_current_user() -> dict | None:
|
| 101 |
+
user_id = session.get("user_id")
|
| 102 |
+
if not user_id:
|
| 103 |
+
return None
|
| 104 |
+
return store.get_user(int(user_id))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _get_admin_identity() -> dict:
|
| 108 |
+
return {
|
| 109 |
+
"username": session.get("admin_username", ""),
|
| 110 |
+
"is_super_admin": bool(session.get("is_super_admin", False)),
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _user_owns_course(user_id: int, course_target_id: int) -> bool:
|
| 115 |
+
return any(course["id"] == course_target_id for course in store.list_courses_for_user(user_id))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _build_user_dashboard_context(user: dict) -> dict:
|
| 119 |
+
return {
|
| 120 |
+
"current_user": user,
|
| 121 |
+
"courses": store.list_courses_for_user(user["id"]),
|
| 122 |
+
"task": store.get_latest_task_for_user(user["id"]),
|
| 123 |
+
"recent_logs": store.list_recent_logs(user_id=user["id"], limit=config.logs_page_size),
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _build_admin_dashboard_context() -> dict:
|
| 128 |
+
users = store.list_users()
|
| 129 |
+
for user in users:
|
| 130 |
+
user["courses"] = store.list_courses_for_user(user["id"])
|
| 131 |
+
user["latest_task"] = store.get_latest_task_for_user(user["id"])
|
| 132 |
+
admin_identity = _get_admin_identity()
|
| 133 |
+
return {
|
| 134 |
+
"users": users,
|
| 135 |
+
"admins": store.list_admins(),
|
| 136 |
+
"stats": store.get_admin_stats(),
|
| 137 |
+
"recent_tasks": store.list_recent_tasks(limit=18),
|
| 138 |
+
"recent_logs": store.list_recent_logs(limit=config.logs_page_size),
|
| 139 |
+
"parallel_limit": store.get_parallel_limit(),
|
| 140 |
+
"is_super_admin": admin_identity["is_super_admin"],
|
| 141 |
+
"admin_identity": admin_identity,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _queue_task_for_user(user: dict, *, requested_by: str, requested_by_role: str) -> tuple[dict, bool]:
|
| 146 |
+
return task_manager.queue_task(user["id"], requested_by=requested_by, requested_by_role=requested_by_role)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _latest_log_id(logs: list[dict]) -> int:
|
| 150 |
+
if not logs:
|
| 151 |
+
return 0
|
| 152 |
+
return int(logs[-1]["id"])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@app.get("/")
|
| 156 |
+
def index():
|
| 157 |
+
if session.get("role") == "user":
|
| 158 |
+
return redirect(url_for("dashboard"))
|
| 159 |
+
if session.get("role") == "admin":
|
| 160 |
+
return redirect(url_for("admin_dashboard"))
|
| 161 |
+
return redirect(url_for("login"))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@app.route("/login", methods=["GET", "POST"])
|
| 165 |
+
def login():
|
| 166 |
+
if request.method == "POST":
|
| 167 |
+
student_id = request.form.get("student_id", "").strip()
|
| 168 |
+
password = request.form.get("password", "")
|
| 169 |
+
user = store.get_user_by_student_id(student_id)
|
| 170 |
+
if user is None:
|
| 171 |
+
flash("没有找到该学号对应的账号,请联系管理员录入。", "danger")
|
| 172 |
+
return render_template("login.html")
|
| 173 |
+
if not user["is_active"]:
|
| 174 |
+
flash("该账号已被管理员禁用。", "danger")
|
| 175 |
+
return render_template("login.html")
|
| 176 |
+
try:
|
| 177 |
+
stored_password = secret_box.decrypt(user["password_encrypted"])
|
| 178 |
+
except Exception:
|
| 179 |
+
flash("账号数据损坏,请联系管理员重置密码。", "danger")
|
| 180 |
+
return render_template("login.html")
|
| 181 |
+
if stored_password != password:
|
| 182 |
+
flash("学号或密码不正确。", "danger")
|
| 183 |
+
return render_template("login.html")
|
| 184 |
+
|
| 185 |
+
session.clear()
|
| 186 |
+
session["role"] = "user"
|
| 187 |
+
session["user_id"] = user["id"]
|
| 188 |
+
return redirect(url_for("dashboard"))
|
| 189 |
+
|
| 190 |
+
return render_template("login.html")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@app.post("/logout")
|
| 194 |
+
def logout():
|
| 195 |
+
session.clear()
|
| 196 |
+
return redirect(url_for("login"))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@app.route("/admin", methods=["GET", "POST"])
|
| 200 |
+
def admin_login():
|
| 201 |
+
if request.method == "POST":
|
| 202 |
+
username = request.form.get("username", "").strip()
|
| 203 |
+
password = request.form.get("password", "")
|
| 204 |
+
is_super_admin = username == config.super_admin_username and password == config.super_admin_password
|
| 205 |
+
admin_row = store.get_admin_by_username(username)
|
| 206 |
+
is_regular_admin = bool(admin_row and verify_password(admin_row["password_hash"], password))
|
| 207 |
+
if not is_super_admin and not is_regular_admin:
|
| 208 |
+
flash("管理员账号或密码错误。", "danger")
|
| 209 |
+
return render_template("admin_login.html")
|
| 210 |
+
|
| 211 |
+
session.clear()
|
| 212 |
+
session["role"] = "admin"
|
| 213 |
+
session["admin_username"] = username
|
| 214 |
+
session["is_super_admin"] = is_super_admin
|
| 215 |
+
return redirect(url_for("admin_dashboard"))
|
| 216 |
+
|
| 217 |
+
return render_template("admin_login.html")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@app.post("/admin/logout")
|
| 221 |
+
def admin_logout():
|
| 222 |
+
session.clear()
|
| 223 |
+
return redirect(url_for("admin_login"))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@app.get("/dashboard")
|
| 227 |
+
@_login_required("user")
|
| 228 |
+
def dashboard():
|
| 229 |
+
user = _get_current_user()
|
| 230 |
+
if user is None:
|
| 231 |
+
session.clear()
|
| 232 |
+
return redirect(url_for("login"))
|
| 233 |
+
return render_template("dashboard.html", **_build_user_dashboard_context(user))
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@app.post("/dashboard/profile")
|
| 237 |
+
@_login_required("user")
|
| 238 |
+
def update_profile():
|
| 239 |
+
user = _get_current_user()
|
| 240 |
+
if user is None:
|
| 241 |
+
session.clear()
|
| 242 |
+
return redirect(url_for("login"))
|
| 243 |
+
|
| 244 |
+
password = request.form.get("password", "").strip()
|
| 245 |
+
display_name = request.form.get("display_name", "").strip()
|
| 246 |
+
if not password:
|
| 247 |
+
flash("密码不能为空。", "danger")
|
| 248 |
+
return redirect(url_for("dashboard"))
|
| 249 |
+
|
| 250 |
+
store.update_user(user["id"], password_encrypted=secret_box.encrypt(password), display_name=display_name)
|
| 251 |
+
flash("账号信息已更新。", "success")
|
| 252 |
+
return redirect(url_for("dashboard"))
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@app.post("/dashboard/courses")
|
| 256 |
+
@_login_required("user")
|
| 257 |
+
def add_course():
|
| 258 |
+
user = _get_current_user()
|
| 259 |
+
if user is None:
|
| 260 |
+
session.clear()
|
| 261 |
+
return redirect(url_for("login"))
|
| 262 |
+
|
| 263 |
+
category = request.form.get("category", "free")
|
| 264 |
+
course_id = request.form.get("course_id", "").strip()
|
| 265 |
+
course_index = request.form.get("course_index", "").strip()
|
| 266 |
+
if not course_id.isdigit() or not course_index.isdigit() or len(course_index) != 2:
|
| 267 |
+
flash("课程号必须为数字,课序号必须是 2 位数字。", "danger")
|
| 268 |
+
return redirect(url_for("dashboard"))
|
| 269 |
+
|
| 270 |
+
store.add_course(user["id"], category, course_id, course_index)
|
| 271 |
+
flash("课程已加入任务列表。", "success")
|
| 272 |
+
return redirect(url_for("dashboard"))
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@app.post("/dashboard/courses/<int:course_target_id>/delete")
|
| 276 |
+
@_login_required("user")
|
| 277 |
+
def delete_course(course_target_id: int):
|
| 278 |
+
user = _get_current_user()
|
| 279 |
+
if user is None:
|
| 280 |
+
session.clear()
|
| 281 |
+
return redirect(url_for("login"))
|
| 282 |
+
if not _user_owns_course(user["id"], course_target_id):
|
| 283 |
+
flash("不能删除不属于当前账号的课程。", "danger")
|
| 284 |
+
return redirect(url_for("dashboard"))
|
| 285 |
+
store.delete_course(course_target_id)
|
| 286 |
+
flash("课程已移除。", "success")
|
| 287 |
+
return redirect(url_for("dashboard"))
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@app.post("/dashboard/task/start")
|
| 291 |
+
@_login_required("user")
|
| 292 |
+
def start_task():
|
| 293 |
+
user = _get_current_user()
|
| 294 |
+
if user is None:
|
| 295 |
+
session.clear()
|
| 296 |
+
return redirect(url_for("login"))
|
| 297 |
+
task, created = _queue_task_for_user(user, requested_by=user["student_id"], requested_by_role="user")
|
| 298 |
+
flash("任务已启动。" if created else f"已有任务处于 {TASK_LABELS.get(task['status'], task['status'])} 状态。", "success" if created else "warning")
|
| 299 |
+
return redirect(url_for("dashboard"))
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@app.post("/dashboard/task/stop")
|
| 303 |
+
@_login_required("user")
|
| 304 |
+
def stop_task():
|
| 305 |
+
user = _get_current_user()
|
| 306 |
+
if user is None:
|
| 307 |
+
session.clear()
|
| 308 |
+
return redirect(url_for("login"))
|
| 309 |
+
active_task = store.find_active_task_for_user(user["id"])
|
| 310 |
+
if active_task and task_manager.stop_task(active_task["id"]):
|
| 311 |
+
flash("停止请求已发送。", "success")
|
| 312 |
+
else:
|
| 313 |
+
flash("当前没有可停止的任务。", "warning")
|
| 314 |
+
return redirect(url_for("dashboard"))
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@app.get("/admin/dashboard")
|
| 318 |
+
@_login_required("admin")
|
| 319 |
+
def admin_dashboard():
|
| 320 |
+
return render_template("admin_dashboard.html", **_build_admin_dashboard_context())
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@app.post("/admin/settings/parallel-limit")
|
| 324 |
+
@_login_required("admin")
|
| 325 |
+
def update_parallel_limit():
|
| 326 |
+
try:
|
| 327 |
+
parallel_limit = max(1, min(8, int(request.form.get("parallel_limit", "2"))))
|
| 328 |
+
except ValueError:
|
| 329 |
+
flash("并行数必须是 1 到 8 的整数。", "danger")
|
| 330 |
+
return redirect(url_for("admin_dashboard"))
|
| 331 |
+
store.set_parallel_limit(parallel_limit)
|
| 332 |
+
flash(f"并行数已更新为 {parallel_limit}。", "success")
|
| 333 |
+
return redirect(url_for("admin_dashboard"))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@app.post("/admin/users")
|
| 337 |
+
@_login_required("admin")
|
| 338 |
+
def create_user():
|
| 339 |
+
student_id = request.form.get("student_id", "").strip()
|
| 340 |
+
password = request.form.get("password", "").strip()
|
| 341 |
+
display_name = request.form.get("display_name", "").strip()
|
| 342 |
+
if not student_id.isdigit() or not password:
|
| 343 |
+
flash("请填写有效的学号和密码。", "danger")
|
| 344 |
+
return redirect(url_for("admin_dashboard"))
|
| 345 |
+
if store.get_user_by_student_id(student_id):
|
| 346 |
+
flash("该学号已经存在。", "warning")
|
| 347 |
+
return redirect(url_for("admin_dashboard"))
|
| 348 |
+
store.create_user(student_id, secret_box.encrypt(password), display_name)
|
| 349 |
+
flash("用户已创建。", "success")
|
| 350 |
+
return redirect(url_for("admin_dashboard"))
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@app.post("/admin/users/<int:user_id>/update")
|
| 354 |
+
@_login_required("admin")
|
| 355 |
+
def update_user(user_id: int):
|
| 356 |
+
user = store.get_user(user_id)
|
| 357 |
+
if user is None:
|
| 358 |
+
flash("用户不存在。", "danger")
|
| 359 |
+
return redirect(url_for("admin_dashboard"))
|
| 360 |
+
display_name = request.form.get("display_name", user["display_name"]).strip()
|
| 361 |
+
password = request.form.get("password", "").strip()
|
| 362 |
+
if password:
|
| 363 |
+
store.update_user(user_id, display_name=display_name, password_encrypted=secret_box.encrypt(password))
|
| 364 |
+
else:
|
| 365 |
+
store.update_user(user_id, display_name=display_name)
|
| 366 |
+
flash("用户信息已更新。", "success")
|
| 367 |
+
return redirect(url_for("admin_dashboard"))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
@app.post("/admin/users/<int:user_id>/toggle")
|
| 371 |
+
@_login_required("admin")
|
| 372 |
+
def toggle_user(user_id: int):
|
| 373 |
+
updated = store.toggle_user_active(user_id)
|
| 374 |
+
if updated is None:
|
| 375 |
+
flash("用户不存在。", "danger")
|
| 376 |
+
else:
|
| 377 |
+
flash("用户状态已切换。", "success")
|
| 378 |
+
return redirect(url_for("admin_dashboard"))
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@app.post("/admin/users/<int:user_id>/courses")
|
| 382 |
+
@_login_required("admin")
|
| 383 |
+
def admin_add_course(user_id: int):
|
| 384 |
+
if store.get_user(user_id) is None:
|
| 385 |
+
flash("用户不存在。", "danger")
|
| 386 |
+
return redirect(url_for("admin_dashboard"))
|
| 387 |
+
category = request.form.get("category", "free")
|
| 388 |
+
course_id = request.form.get("course_id", "").strip()
|
| 389 |
+
course_index = request.form.get("course_index", "").strip()
|
| 390 |
+
if not course_id.isdigit() or not course_index.isdigit() or len(course_index) != 2:
|
| 391 |
+
flash("课程号必须为数字,课序号必须是 2 位数字。", "danger")
|
| 392 |
+
return redirect(url_for("admin_dashboard"))
|
| 393 |
+
store.add_course(user_id, category, course_id, course_index)
|
| 394 |
+
flash("课程已添加到对应用户。", "success")
|
| 395 |
+
return redirect(url_for("admin_dashboard"))
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
@app.post("/admin/courses/<int:course_target_id>/delete")
|
| 399 |
+
@_login_required("admin")
|
| 400 |
+
def admin_delete_course(course_target_id: int):
|
| 401 |
+
store.delete_course(course_target_id)
|
| 402 |
+
flash("课程已删除。", "success")
|
| 403 |
+
return redirect(url_for("admin_dashboard"))
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@app.post("/admin/users/<int:user_id>/task/start")
|
| 407 |
+
@_login_required("admin")
|
| 408 |
+
def admin_start_user_task(user_id: int):
|
| 409 |
+
user = store.get_user(user_id)
|
| 410 |
+
if user is None:
|
| 411 |
+
flash("用户不存在。", "danger")
|
| 412 |
+
return redirect(url_for("admin_dashboard"))
|
| 413 |
+
admin_identity = _get_admin_identity()
|
| 414 |
+
task, created = _queue_task_for_user(user, requested_by=admin_identity["username"], requested_by_role="admin")
|
| 415 |
+
flash("任务已加入队列。" if created else f"该用户已有任务处于 {TASK_LABELS.get(task['status'], task['status'])} 状态。", "success" if created else "warning")
|
| 416 |
+
return redirect(url_for("admin_dashboard"))
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@app.post("/admin/users/<int:user_id>/task/stop")
|
| 420 |
+
@_login_required("admin")
|
| 421 |
+
def admin_stop_user_task(user_id: int):
|
| 422 |
+
active_task = store.find_active_task_for_user(user_id)
|
| 423 |
+
if active_task and task_manager.stop_task(active_task["id"]):
|
| 424 |
+
flash("已发送停止请求。", "success")
|
| 425 |
+
else:
|
| 426 |
+
flash("当前没有可停止任务。", "warning")
|
| 427 |
+
return redirect(url_for("admin_dashboard"))
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
@app.post("/admin/admins")
|
| 431 |
+
@_login_required("admin")
|
| 432 |
+
def create_admin():
|
| 433 |
+
if not session.get("is_super_admin", False):
|
| 434 |
+
flash("只有超级管理员可以新增管理员。", "danger")
|
| 435 |
+
return redirect(url_for("admin_dashboard"))
|
| 436 |
+
username = request.form.get("username", "").strip()
|
| 437 |
+
password = request.form.get("password", "").strip()
|
| 438 |
+
if not username or not password:
|
| 439 |
+
flash("请填写管理员账号和密码。", "danger")
|
| 440 |
+
return redirect(url_for("admin_dashboard"))
|
| 441 |
+
if username == config.super_admin_username or store.get_admin_by_username(username):
|
| 442 |
+
flash("该管理员账号已存在。", "warning")
|
| 443 |
+
return redirect(url_for("admin_dashboard"))
|
| 444 |
+
store.create_admin(username, hash_password(password))
|
| 445 |
+
flash("管理员已创建。", "success")
|
| 446 |
+
return redirect(url_for("admin_dashboard"))
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@app.get("/api/user/status")
|
| 450 |
+
@_login_required("user")
|
| 451 |
+
def user_status():
|
| 452 |
+
user = _get_current_user()
|
| 453 |
+
if user is None:
|
| 454 |
+
return jsonify({"ok": False}), 401
|
| 455 |
+
task = store.get_latest_task_for_user(user["id"])
|
| 456 |
+
return jsonify({"ok": True, "task": task, "courses": store.list_courses_for_user(user["id"])})
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
@app.get("/api/admin/status")
|
| 460 |
+
@_login_required("admin")
|
| 461 |
+
def admin_status():
|
| 462 |
+
return jsonify(
|
| 463 |
+
{
|
| 464 |
+
"ok": True,
|
| 465 |
+
"stats": store.get_admin_stats(),
|
| 466 |
+
"parallel_limit": store.get_parallel_limit(),
|
| 467 |
+
"recent_tasks": store.list_recent_tasks(limit=12),
|
| 468 |
+
}
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
@app.get("/api/user/logs/stream")
|
| 473 |
+
@_login_required("user")
|
| 474 |
+
def stream_user_logs():
|
| 475 |
+
user = _get_current_user()
|
| 476 |
+
if user is None:
|
| 477 |
+
return jsonify({"ok": False}), 401
|
| 478 |
+
last_id = int(request.args.get("last_id", _latest_log_id(store.list_recent_logs(user_id=user["id"], limit=1))))
|
| 479 |
+
|
| 480 |
+
@stream_with_context
|
| 481 |
+
def generate():
|
| 482 |
+
current_last_id = last_id
|
| 483 |
+
while True:
|
| 484 |
+
logs = store.list_logs_after(current_last_id, user_id=user["id"], limit=60)
|
| 485 |
+
if logs:
|
| 486 |
+
for log in logs:
|
| 487 |
+
current_last_id = int(log["id"])
|
| 488 |
+
yield f"id: {log['id']}\ndata: {json.dumps(log, ensure_ascii=False)}\n\n"
|
| 489 |
+
else:
|
| 490 |
+
yield ": keep-alive\n\n"
|
| 491 |
+
time.sleep(1)
|
| 492 |
+
|
| 493 |
+
response = Response(generate(), mimetype="text/event-stream")
|
| 494 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 495 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 496 |
+
return response
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
@app.get("/api/admin/logs/stream")
|
| 500 |
+
@_login_required("admin")
|
| 501 |
+
def stream_admin_logs():
|
| 502 |
+
last_id = int(request.args.get("last_id", _latest_log_id(store.list_recent_logs(limit=1))))
|
| 503 |
+
|
| 504 |
+
@stream_with_context
|
| 505 |
+
def generate():
|
| 506 |
+
current_last_id = last_id
|
| 507 |
+
while True:
|
| 508 |
+
logs = store.list_logs_after(current_last_id, limit=80)
|
| 509 |
+
if logs:
|
| 510 |
+
for log in logs:
|
| 511 |
+
current_last_id = int(log["id"])
|
| 512 |
+
yield f"id: {log['id']}\ndata: {json.dumps(log, ensure_ascii=False)}\n\n"
|
| 513 |
+
else:
|
| 514 |
+
yield ": keep-alive\n\n"
|
| 515 |
+
time.sleep(1)
|
| 516 |
+
|
| 517 |
+
response = Response(generate(), mimetype="text/event-stream")
|
| 518 |
+
response.headers["Cache-Control"] = "no-cache"
|
| 519 |
+
response.headers["X-Accel-Buffering"] = "no"
|
| 520 |
+
return response
|
static/app.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
(function () {
|
| 2 |
+
const statusLabels = {
|
| 3 |
+
pending: "排队中",
|
| 4 |
+
running: "执行中",
|
| 5 |
+
cancel_requested: "停止中",
|
| 6 |
+
completed: "已完成",
|
| 7 |
+
stopped: "已停止",
|
| 8 |
+
failed: "失败",
|
| 9 |
+
idle: "未启动"
|
| 10 |
+
};
|
| 11 |
+
|
| 12 |
+
function renderLogLine(log) {
|
| 13 |
+
const line = document.createElement("div");
|
| 14 |
+
const level = (log.level || "INFO").toLowerCase();
|
| 15 |
+
line.className = `log-line level-${level}`;
|
| 16 |
+
|
| 17 |
+
const meta = document.createElement("span");
|
| 18 |
+
meta.className = "log-meta";
|
| 19 |
+
const owner = log.student_id || "system";
|
| 20 |
+
meta.textContent = `${log.created_at} · ${owner} · ${log.scope} · ${log.level}`;
|
| 21 |
+
|
| 22 |
+
const message = document.createElement("span");
|
| 23 |
+
message.textContent = log.message || "";
|
| 24 |
+
|
| 25 |
+
line.append(meta, message);
|
| 26 |
+
return line;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
function bindLogStream() {
|
| 30 |
+
const shell = document.querySelector("[data-log-stream-url]");
|
| 31 |
+
const consoleNode = document.getElementById("log-console");
|
| 32 |
+
if (!shell || !consoleNode || !window.EventSource) {
|
| 33 |
+
return;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const streamUrl = shell.getAttribute("data-log-stream-url");
|
| 37 |
+
const eventSource = new EventSource(streamUrl);
|
| 38 |
+
|
| 39 |
+
eventSource.onmessage = function (event) {
|
| 40 |
+
try {
|
| 41 |
+
const payload = JSON.parse(event.data);
|
| 42 |
+
if (consoleNode.querySelector(".muted")) {
|
| 43 |
+
consoleNode.innerHTML = "";
|
| 44 |
+
}
|
| 45 |
+
consoleNode.appendChild(renderLogLine(payload));
|
| 46 |
+
while (consoleNode.children.length > 360) {
|
| 47 |
+
consoleNode.removeChild(consoleNode.firstChild);
|
| 48 |
+
}
|
| 49 |
+
consoleNode.scrollTop = consoleNode.scrollHeight;
|
| 50 |
+
} catch (_error) {
|
| 51 |
+
// Ignore malformed frames and keep the stream alive.
|
| 52 |
+
}
|
| 53 |
+
};
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
function updateUserStatus(data) {
|
| 57 |
+
const taskText = document.getElementById("task-status-text");
|
| 58 |
+
const taskPill = document.getElementById("task-status-pill");
|
| 59 |
+
const courseCount = document.getElementById("course-count");
|
| 60 |
+
const status = (data.task && data.task.status) || "idle";
|
| 61 |
+
if (taskText) {
|
| 62 |
+
taskText.textContent = statusLabels[status] || status;
|
| 63 |
+
}
|
| 64 |
+
if (taskPill) {
|
| 65 |
+
taskPill.className = `status-pill status-${status}`;
|
| 66 |
+
taskPill.textContent = statusLabels[status] || status;
|
| 67 |
+
}
|
| 68 |
+
if (courseCount && Array.isArray(data.courses)) {
|
| 69 |
+
courseCount.textContent = String(data.courses.length);
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
function updateAdminStatus(data) {
|
| 74 |
+
const users = document.getElementById("stat-users");
|
| 75 |
+
const running = document.getElementById("stat-running");
|
| 76 |
+
const pending = document.getElementById("stat-pending");
|
| 77 |
+
const parallel = document.getElementById("parallel-limit-input");
|
| 78 |
+
if (users) {
|
| 79 |
+
users.textContent = String(data.stats.users_count || 0);
|
| 80 |
+
}
|
| 81 |
+
if (running) {
|
| 82 |
+
running.textContent = String(data.stats.running_count || 0);
|
| 83 |
+
}
|
| 84 |
+
if (pending) {
|
| 85 |
+
pending.textContent = String(data.stats.pending_count || 0);
|
| 86 |
+
}
|
| 87 |
+
if (parallel) {
|
| 88 |
+
parallel.value = String(data.parallel_limit || parallel.value);
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
function bindStatusPolling() {
|
| 93 |
+
const shell = document.querySelector("[data-status-url]");
|
| 94 |
+
if (!shell) {
|
| 95 |
+
return;
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
const statusUrl = shell.getAttribute("data-status-url");
|
| 99 |
+
const isAdmin = shell.classList.contains("admin-dashboard");
|
| 100 |
+
|
| 101 |
+
async function refresh() {
|
| 102 |
+
try {
|
| 103 |
+
const response = await fetch(statusUrl, { headers: { "X-Requested-With": "fetch" } });
|
| 104 |
+
if (!response.ok) {
|
| 105 |
+
return;
|
| 106 |
+
}
|
| 107 |
+
const payload = await response.json();
|
| 108 |
+
if (!payload.ok) {
|
| 109 |
+
return;
|
| 110 |
+
}
|
| 111 |
+
if (isAdmin) {
|
| 112 |
+
updateAdminStatus(payload);
|
| 113 |
+
} else {
|
| 114 |
+
updateUserStatus(payload);
|
| 115 |
+
}
|
| 116 |
+
} catch (_error) {
|
| 117 |
+
// Leave the current UI state as-is if polling fails.
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
refresh();
|
| 122 |
+
window.setInterval(refresh, 7000);
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
bindLogStream();
|
| 126 |
+
bindStatusPolling();
|
| 127 |
+
})();
|
static/style.css
ADDED
|
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
--bg: #07131d;
|
| 3 |
+
--bg-2: #0d2030;
|
| 4 |
+
--panel: rgba(10, 24, 36, 0.82);
|
| 5 |
+
--panel-strong: rgba(8, 18, 28, 0.94);
|
| 6 |
+
--line: rgba(151, 204, 213, 0.18);
|
| 7 |
+
--text: #eef6f6;
|
| 8 |
+
--muted: #9ab7bd;
|
| 9 |
+
--primary: #2ed3ad;
|
| 10 |
+
--primary-deep: #109a88;
|
| 11 |
+
--secondary: #ffb648;
|
| 12 |
+
--danger: #ff6f61;
|
| 13 |
+
--shadow: 0 24px 70px rgba(0, 0, 0, 0.36);
|
| 14 |
+
--radius-lg: 28px;
|
| 15 |
+
--radius-md: 20px;
|
| 16 |
+
--radius-sm: 14px;
|
| 17 |
+
--font-display: "Space Grotesk", sans-serif;
|
| 18 |
+
--font-body: "Noto Sans SC", sans-serif;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
* {
|
| 22 |
+
box-sizing: border-box;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
html {
|
| 26 |
+
scroll-behavior: smooth;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
body {
|
| 30 |
+
margin: 0;
|
| 31 |
+
min-height: 100vh;
|
| 32 |
+
font-family: var(--font-body);
|
| 33 |
+
color: var(--text);
|
| 34 |
+
background:
|
| 35 |
+
radial-gradient(circle at top left, rgba(20, 110, 116, 0.34), transparent 34%),
|
| 36 |
+
radial-gradient(circle at top right, rgba(255, 182, 72, 0.16), transparent 28%),
|
| 37 |
+
linear-gradient(135deg, #041019 0%, #07131d 36%, #0d2030 100%);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
button,
|
| 41 |
+
input,
|
| 42 |
+
select {
|
| 43 |
+
font: inherit;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
code {
|
| 47 |
+
padding: 0.15rem 0.45rem;
|
| 48 |
+
border-radius: 999px;
|
| 49 |
+
background: rgba(255, 255, 255, 0.08);
|
| 50 |
+
color: #fff5dd;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
.app-body {
|
| 54 |
+
position: relative;
|
| 55 |
+
overflow-x: hidden;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
.bg-orb {
|
| 59 |
+
position: fixed;
|
| 60 |
+
width: 28rem;
|
| 61 |
+
height: 28rem;
|
| 62 |
+
border-radius: 50%;
|
| 63 |
+
filter: blur(20px);
|
| 64 |
+
opacity: 0.42;
|
| 65 |
+
pointer-events: none;
|
| 66 |
+
animation: drift 14s ease-in-out infinite;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
.bg-orb-a {
|
| 70 |
+
top: -10rem;
|
| 71 |
+
left: -6rem;
|
| 72 |
+
background: radial-gradient(circle, rgba(46, 211, 173, 0.48), transparent 68%);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
.bg-orb-b {
|
| 76 |
+
right: -8rem;
|
| 77 |
+
bottom: -10rem;
|
| 78 |
+
background: radial-gradient(circle, rgba(255, 182, 72, 0.32), transparent 68%);
|
| 79 |
+
animation-delay: -6s;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
.bg-grid {
|
| 83 |
+
position: fixed;
|
| 84 |
+
inset: 0;
|
| 85 |
+
background-image:
|
| 86 |
+
linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
|
| 87 |
+
linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
|
| 88 |
+
background-size: 42px 42px;
|
| 89 |
+
mask-image: radial-gradient(circle at center, black 42%, transparent 100%);
|
| 90 |
+
pointer-events: none;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
.page-shell {
|
| 94 |
+
position: relative;
|
| 95 |
+
z-index: 1;
|
| 96 |
+
width: min(1240px, calc(100% - 2rem));
|
| 97 |
+
margin: 0 auto;
|
| 98 |
+
padding: 2rem 0 3rem;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
.flash-stack {
|
| 102 |
+
display: grid;
|
| 103 |
+
gap: 0.75rem;
|
| 104 |
+
margin-bottom: 1rem;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
.flash {
|
| 108 |
+
border: 1px solid rgba(255, 255, 255, 0.12);
|
| 109 |
+
border-radius: var(--radius-sm);
|
| 110 |
+
padding: 0.9rem 1rem;
|
| 111 |
+
backdrop-filter: blur(10px);
|
| 112 |
+
box-shadow: 0 14px 30px rgba(0, 0, 0, 0.18);
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
.flash-success {
|
| 116 |
+
background: rgba(46, 211, 173, 0.16);
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
.flash-warning {
|
| 120 |
+
background: rgba(255, 182, 72, 0.16);
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
.flash-danger {
|
| 124 |
+
background: rgba(255, 111, 97, 0.16);
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
.auth-layout,
|
| 128 |
+
.dashboard-shell {
|
| 129 |
+
display: grid;
|
| 130 |
+
gap: 1.4rem;
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
.auth-layout {
|
| 134 |
+
min-height: calc(100vh - 7rem);
|
| 135 |
+
align-items: center;
|
| 136 |
+
grid-template-columns: 1.15fr 0.9fr;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
.hero-panel,
|
| 140 |
+
.auth-card,
|
| 141 |
+
.card,
|
| 142 |
+
.metric-card,
|
| 143 |
+
.user-card,
|
| 144 |
+
.empty-state-card {
|
| 145 |
+
position: relative;
|
| 146 |
+
border: 1px solid var(--line);
|
| 147 |
+
border-radius: var(--radius-lg);
|
| 148 |
+
background: var(--panel);
|
| 149 |
+
backdrop-filter: blur(18px);
|
| 150 |
+
box-shadow: var(--shadow);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
.hero-panel,
|
| 154 |
+
.auth-card,
|
| 155 |
+
.card,
|
| 156 |
+
.empty-state-card {
|
| 157 |
+
padding: 1.7rem;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
.hero-panel {
|
| 161 |
+
overflow: hidden;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
.hero-panel::after,
|
| 165 |
+
.card::after,
|
| 166 |
+
.auth-card::after {
|
| 167 |
+
content: "";
|
| 168 |
+
position: absolute;
|
| 169 |
+
inset: 0;
|
| 170 |
+
border-radius: inherit;
|
| 171 |
+
background: linear-gradient(120deg, rgba(255, 255, 255, 0.12), transparent 22%, transparent 78%, rgba(255, 255, 255, 0.05));
|
| 172 |
+
pointer-events: none;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
.eyebrow,
|
| 176 |
+
.kicker {
|
| 177 |
+
display: inline-flex;
|
| 178 |
+
align-items: center;
|
| 179 |
+
gap: 0.5rem;
|
| 180 |
+
font-family: var(--font-display);
|
| 181 |
+
letter-spacing: 0.12em;
|
| 182 |
+
text-transform: uppercase;
|
| 183 |
+
font-size: 0.75rem;
|
| 184 |
+
color: #9fe8da;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
.hero-panel h1,
|
| 188 |
+
.topbar h1,
|
| 189 |
+
.card-head h2,
|
| 190 |
+
.auth-card h2 {
|
| 191 |
+
margin: 0.5rem 0 0;
|
| 192 |
+
font-family: var(--font-display);
|
| 193 |
+
line-height: 1.05;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
.hero-panel h1 {
|
| 197 |
+
max-width: 13ch;
|
| 198 |
+
font-size: clamp(2.8rem, 6vw, 5rem);
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
.hero-panel p,
|
| 202 |
+
.card-head p,
|
| 203 |
+
.topbar p,
|
| 204 |
+
.auth-card p,
|
| 205 |
+
.metric-card small,
|
| 206 |
+
.auth-footnote {
|
| 207 |
+
color: var(--muted);
|
| 208 |
+
line-height: 1.7;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
.hero-metrics {
|
| 212 |
+
display: grid;
|
| 213 |
+
grid-template-columns: repeat(3, minmax(0, 1fr));
|
| 214 |
+
gap: 1rem;
|
| 215 |
+
margin-top: 2rem;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
.hero-metrics article {
|
| 219 |
+
padding: 1rem;
|
| 220 |
+
border-radius: var(--radius-md);
|
| 221 |
+
background: rgba(255, 255, 255, 0.05);
|
| 222 |
+
border: 1px solid rgba(255, 255, 255, 0.08);
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
.hero-metrics strong,
|
| 226 |
+
.metric-card strong {
|
| 227 |
+
display: block;
|
| 228 |
+
font-family: var(--font-display);
|
| 229 |
+
font-size: 1.2rem;
|
| 230 |
+
margin-bottom: 0.25rem;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
.auth-card {
|
| 234 |
+
max-width: 520px;
|
| 235 |
+
justify-self: end;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
.card-head {
|
| 239 |
+
display: grid;
|
| 240 |
+
gap: 0.35rem;
|
| 241 |
+
margin-bottom: 1.2rem;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
.card-head.compact {
|
| 245 |
+
margin-bottom: 1rem;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
.card-head.split,
|
| 249 |
+
.topbar {
|
| 250 |
+
display: flex;
|
| 251 |
+
align-items: flex-start;
|
| 252 |
+
justify-content: space-between;
|
| 253 |
+
gap: 1rem;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
.form-grid {
|
| 257 |
+
display: grid;
|
| 258 |
+
gap: 1rem;
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
.form-grid-compact {
|
| 262 |
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
.slim-form {
|
| 266 |
+
margin-top: 1rem;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
.field {
|
| 270 |
+
display: grid;
|
| 271 |
+
gap: 0.45rem;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
.field span {
|
| 275 |
+
color: #d4ece6;
|
| 276 |
+
font-size: 0.92rem;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
.field input,
|
| 280 |
+
.field select {
|
| 281 |
+
width: 100%;
|
| 282 |
+
border: 1px solid rgba(255, 255, 255, 0.08);
|
| 283 |
+
border-radius: 16px;
|
| 284 |
+
padding: 0.95rem 1rem;
|
| 285 |
+
background: rgba(5, 14, 22, 0.66);
|
| 286 |
+
color: var(--text);
|
| 287 |
+
outline: none;
|
| 288 |
+
transition: border-color 180ms ease, transform 180ms ease, box-shadow 180ms ease;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
.field input:focus,
|
| 292 |
+
.field select:focus {
|
| 293 |
+
border-color: rgba(46, 211, 173, 0.85);
|
| 294 |
+
box-shadow: 0 0 0 4px rgba(46, 211, 173, 0.12);
|
| 295 |
+
transform: translateY(-1px);
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
.span-2 {
|
| 299 |
+
grid-column: span 2;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
.btn {
|
| 303 |
+
display: inline-flex;
|
| 304 |
+
align-items: center;
|
| 305 |
+
justify-content: center;
|
| 306 |
+
gap: 0.55rem;
|
| 307 |
+
min-height: 48px;
|
| 308 |
+
border: 0;
|
| 309 |
+
border-radius: 999px;
|
| 310 |
+
padding: 0 1.2rem;
|
| 311 |
+
cursor: pointer;
|
| 312 |
+
transition: transform 180ms ease, box-shadow 180ms ease, opacity 180ms ease;
|
| 313 |
+
text-decoration: none;
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
.btn:hover {
|
| 317 |
+
transform: translateY(-2px);
|
| 318 |
+
box-shadow: 0 14px 30px rgba(0, 0, 0, 0.24);
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
.btn-primary {
|
| 322 |
+
background: linear-gradient(135deg, var(--primary) 0%, #4be9c3 100%);
|
| 323 |
+
color: #052119;
|
| 324 |
+
font-weight: 800;
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
.btn-secondary {
|
| 328 |
+
background: linear-gradient(135deg, var(--secondary) 0%, #ffd07a 100%);
|
| 329 |
+
color: #24160a;
|
| 330 |
+
font-weight: 800;
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
.btn-ghost {
|
| 334 |
+
background: rgba(255, 255, 255, 0.06);
|
| 335 |
+
color: var(--text);
|
| 336 |
+
border: 1px solid rgba(255, 255, 255, 0.09);
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
.btn-ghost.danger {
|
| 340 |
+
color: #ffd0ca;
|
| 341 |
+
border-color: rgba(255, 111, 97, 0.34);
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
.btn-lg {
|
| 345 |
+
min-height: 54px;
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
.auth-footnote {
|
| 349 |
+
margin-top: 1rem;
|
| 350 |
+
padding-top: 1rem;
|
| 351 |
+
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
.topbar {
|
| 355 |
+
padding: 1rem 0 0.3rem;
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
.metric-grid {
|
| 359 |
+
display: grid;
|
| 360 |
+
grid-template-columns: repeat(4, minmax(0, 1fr));
|
| 361 |
+
gap: 1rem;
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
.metric-card {
|
| 365 |
+
padding: 1.25rem;
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
.metric-card span {
|
| 369 |
+
color: var(--muted);
|
| 370 |
+
font-size: 0.92rem;
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
.metric-card strong {
|
| 374 |
+
font-size: clamp(1.4rem, 4vw, 2.2rem);
|
| 375 |
+
margin: 0.35rem 0;
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
.content-grid {
|
| 379 |
+
display: grid;
|
| 380 |
+
gap: 1rem;
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
.dashboard-grid {
|
| 384 |
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
.admin-grid {
|
| 388 |
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
.status-strip,
|
| 392 |
+
.button-row,
|
| 393 |
+
.chip-row,
|
| 394 |
+
.course-chip-row {
|
| 395 |
+
display: flex;
|
| 396 |
+
align-items: center;
|
| 397 |
+
gap: 0.7rem;
|
| 398 |
+
flex-wrap: wrap;
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
.wrap-row {
|
| 402 |
+
margin-top: 1rem;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
.status-strip {
|
| 406 |
+
margin-bottom: 1rem;
|
| 407 |
+
color: var(--muted);
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
.status-pill,
|
| 411 |
+
.chip,
|
| 412 |
+
.live-dot {
|
| 413 |
+
display: inline-flex;
|
| 414 |
+
align-items: center;
|
| 415 |
+
justify-content: center;
|
| 416 |
+
border-radius: 999px;
|
| 417 |
+
padding: 0.45rem 0.9rem;
|
| 418 |
+
font-size: 0.84rem;
|
| 419 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
.status-idle,
|
| 423 |
+
.chip {
|
| 424 |
+
background: rgba(255, 255, 255, 0.05);
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
.status-running,
|
| 428 |
+
.status-completed,
|
| 429 |
+
.highlight,
|
| 430 |
+
.live-dot {
|
| 431 |
+
background: rgba(46, 211, 173, 0.14);
|
| 432 |
+
color: #96f2dd;
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
.status-pending,
|
| 436 |
+
.status-cancel_requested {
|
| 437 |
+
background: rgba(255, 182, 72, 0.14);
|
| 438 |
+
color: #ffd48d;
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
.status-stopped,
|
| 442 |
+
.status-failed,
|
| 443 |
+
.danger {
|
| 444 |
+
background: rgba(255, 111, 97, 0.14);
|
| 445 |
+
color: #ffcec7;
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
.live-dot {
|
| 449 |
+
position: relative;
|
| 450 |
+
gap: 0.4rem;
|
| 451 |
+
font-family: var(--font-display);
|
| 452 |
+
letter-spacing: 0.08em;
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
.live-dot::before {
|
| 456 |
+
content: "";
|
| 457 |
+
width: 8px;
|
| 458 |
+
height: 8px;
|
| 459 |
+
border-radius: 50%;
|
| 460 |
+
background: currentColor;
|
| 461 |
+
box-shadow: 0 0 0 0 rgba(150, 242, 221, 0.65);
|
| 462 |
+
animation: pulse 2.1s infinite;
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
.course-table-wrap {
|
| 466 |
+
overflow-x: auto;
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
.data-table {
|
| 470 |
+
width: 100%;
|
| 471 |
+
border-collapse: collapse;
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
.data-table th,
|
| 475 |
+
.data-table td {
|
| 476 |
+
text-align: left;
|
| 477 |
+
padding: 0.95rem 0.85rem;
|
| 478 |
+
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
.data-table th {
|
| 482 |
+
color: #b8d4d4;
|
| 483 |
+
font-size: 0.9rem;
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
.inline-action {
|
| 487 |
+
border: 0;
|
| 488 |
+
background: transparent;
|
| 489 |
+
color: #ffd0ca;
|
| 490 |
+
cursor: pointer;
|
| 491 |
+
padding: 0;
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
.empty-cell,
|
| 495 |
+
.empty-mini,
|
| 496 |
+
.empty-state-card {
|
| 497 |
+
color: var(--muted);
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
.log-console {
|
| 501 |
+
min-height: 360px;
|
| 502 |
+
max-height: 540px;
|
| 503 |
+
overflow: auto;
|
| 504 |
+
padding: 1rem;
|
| 505 |
+
border-radius: 22px;
|
| 506 |
+
background: rgba(4, 10, 16, 0.92);
|
| 507 |
+
border: 1px solid rgba(255, 255, 255, 0.06);
|
| 508 |
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
.log-line {
|
| 512 |
+
display: grid;
|
| 513 |
+
gap: 0.25rem;
|
| 514 |
+
padding: 0.8rem 0;
|
| 515 |
+
border-bottom: 1px dashed rgba(255, 255, 255, 0.08);
|
| 516 |
+
font-size: 0.92rem;
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
.log-line:last-child {
|
| 520 |
+
border-bottom: 0;
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
.log-meta {
|
| 524 |
+
color: #7ea4aa;
|
| 525 |
+
font-size: 0.78rem;
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
.level-error {
|
| 529 |
+
color: #ffb5ac;
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
.level-warning {
|
| 533 |
+
color: #ffd59a;
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
.level-info {
|
| 537 |
+
color: #d8ece9;
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
.level-success {
|
| 541 |
+
color: #97f4dd;
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
.muted {
|
| 545 |
+
color: var(--muted);
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
.user-card-grid {
|
| 549 |
+
display: grid;
|
| 550 |
+
gap: 1rem;
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
.user-card {
|
| 554 |
+
padding: 1.25rem;
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
.user-card-head {
|
| 558 |
+
display: flex;
|
| 559 |
+
align-items: flex-start;
|
| 560 |
+
justify-content: space-between;
|
| 561 |
+
gap: 1rem;
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
.user-card h3 {
|
| 565 |
+
margin: 0;
|
| 566 |
+
font-family: var(--font-display);
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
.user-card p {
|
| 570 |
+
margin: 0.35rem 0 0;
|
| 571 |
+
color: var(--muted);
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
.course-list {
|
| 575 |
+
display: grid;
|
| 576 |
+
gap: 0.65rem;
|
| 577 |
+
margin-top: 1rem;
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
.course-chip-row {
|
| 581 |
+
justify-content: space-between;
|
| 582 |
+
padding: 0.8rem 0.95rem;
|
| 583 |
+
border-radius: 16px;
|
| 584 |
+
background: rgba(255, 255, 255, 0.05);
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
.chip-row.tight {
|
| 588 |
+
margin-top: 0.85rem;
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
.accent-amber {
|
| 592 |
+
box-shadow: 0 24px 70px rgba(255, 182, 72, 0.16);
|
| 593 |
+
}
|
| 594 |
+
|
| 595 |
+
.reveal-up {
|
| 596 |
+
opacity: 0;
|
| 597 |
+
transform: translateY(22px);
|
| 598 |
+
animation: revealUp 0.7s cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
.delay-1 {
|
| 602 |
+
animation-delay: 0.08s;
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
.delay-2 {
|
| 606 |
+
animation-delay: 0.16s;
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
.delay-3 {
|
| 610 |
+
animation-delay: 0.24s;
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
.delay-4 {
|
| 614 |
+
animation-delay: 0.32s;
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
@keyframes revealUp {
|
| 618 |
+
to {
|
| 619 |
+
opacity: 1;
|
| 620 |
+
transform: translateY(0);
|
| 621 |
+
}
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
@keyframes drift {
|
| 625 |
+
0%,
|
| 626 |
+
100% {
|
| 627 |
+
transform: translate3d(0, 0, 0) scale(1);
|
| 628 |
+
}
|
| 629 |
+
50% {
|
| 630 |
+
transform: translate3d(16px, -18px, 0) scale(1.05);
|
| 631 |
+
}
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
@keyframes pulse {
|
| 635 |
+
0% {
|
| 636 |
+
box-shadow: 0 0 0 0 rgba(150, 242, 221, 0.65);
|
| 637 |
+
}
|
| 638 |
+
70% {
|
| 639 |
+
box-shadow: 0 0 0 14px rgba(150, 242, 221, 0);
|
| 640 |
+
}
|
| 641 |
+
100% {
|
| 642 |
+
box-shadow: 0 0 0 0 rgba(150, 242, 221, 0);
|
| 643 |
+
}
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
@media (max-width: 1100px) {
|
| 647 |
+
.auth-layout,
|
| 648 |
+
.dashboard-grid,
|
| 649 |
+
.admin-grid,
|
| 650 |
+
.metric-grid,
|
| 651 |
+
.hero-metrics {
|
| 652 |
+
grid-template-columns: 1fr;
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
.auth-card {
|
| 656 |
+
justify-self: stretch;
|
| 657 |
+
max-width: none;
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
.span-2 {
|
| 661 |
+
grid-column: auto;
|
| 662 |
+
}
|
| 663 |
+
}
|
| 664 |
+
|
| 665 |
+
@media (max-width: 760px) {
|
| 666 |
+
.page-shell {
|
| 667 |
+
width: min(100% - 1rem, 100%);
|
| 668 |
+
padding-top: 1rem;
|
| 669 |
+
padding-bottom: 2rem;
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
.hero-panel,
|
| 673 |
+
.auth-card,
|
| 674 |
+
.card,
|
| 675 |
+
.user-card,
|
| 676 |
+
.empty-state-card {
|
| 677 |
+
padding: 1.2rem;
|
| 678 |
+
border-radius: 22px;
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
.card-head.split,
|
| 682 |
+
.topbar,
|
| 683 |
+
.user-card-head {
|
| 684 |
+
flex-direction: column;
|
| 685 |
+
}
|
| 686 |
+
|
| 687 |
+
.form-grid-compact {
|
| 688 |
+
grid-template-columns: 1fr;
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
.button-row form,
|
| 692 |
+
.button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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
|
| 3 |
+
{% block title %}管理员后台{% endblock %}
|
| 4 |
+
|
| 5 |
+
{% block header_actions %}
|
| 6 |
+
<span class="status-pill status-live">{{ admin.role }} · {{ admin.username }}</span>
|
| 7 |
+
<form method="post" action="{{ url_for('admin_logout') }}">
|
| 8 |
+
<button type="submit" class="button button-ghost">退出后台</button>
|
| 9 |
+
</form>
|
| 10 |
+
{% endblock %}
|
| 11 |
+
|
| 12 |
+
{% block content %}
|
| 13 |
+
<section class="hero-card">
|
| 14 |
+
<div class="hero-copy-block">
|
| 15 |
+
<div class="eyebrow">管理员后台</div>
|
| 16 |
+
<h1>统一管理用户、并发调度与全局实时日志。</h1>
|
| 17 |
+
<p class="hero-copy">
|
| 18 |
+
用户提交的课程配置会集中展示在这里。管理员可以手动录入用户信息、代为启动任务,并根据 Hugging Face Space 资源调整并行数。
|
| 19 |
+
</p>
|
| 20 |
+
</div>
|
| 21 |
+
<div class="stat-grid admin-stat-grid">
|
| 22 |
+
<div class="stat-card">
|
| 23 |
+
<span>用户数</span>
|
| 24 |
+
<strong id="admin-users">{{ summary.users }}</strong>
|
| 25 |
+
</div>
|
| 26 |
+
<div class="stat-card">
|
| 27 |
+
<span>运行中任务</span>
|
| 28 |
+
<strong id="admin-running">{{ summary.running_tasks }}</strong>
|
| 29 |
+
</div>
|
| 30 |
+
<div class="stat-card">
|
| 31 |
+
<span>排队任务</span>
|
| 32 |
+
<strong id="admin-queued">{{ summary.queued_tasks }}</strong>
|
| 33 |
+
</div>
|
| 34 |
+
<div class="stat-card">
|
| 35 |
+
<span>并行数</span>
|
| 36 |
+
<strong id="admin-parallelism">{{ summary.parallelism }}</strong>
|
| 37 |
+
</div>
|
| 38 |
+
</div>
|
| 39 |
+
</section>
|
| 40 |
+
|
| 41 |
+
<section class="content-grid content-grid-admin">
|
| 42 |
+
<article class="panel">
|
| 43 |
+
<div class="panel-head">
|
| 44 |
+
<div>
|
| 45 |
+
<div class="section-kicker">系统设置</div>
|
| 46 |
+
<h2>并行调度</h2>
|
| 47 |
+
</div>
|
| 48 |
+
<span class="status-pill status-pending">资源敏感</span>
|
| 49 |
+
</div>
|
| 50 |
+
<form method="post" action="{{ url_for('update_parallelism') }}" class="form-grid form-grid-inline">
|
| 51 |
+
<label class="field">
|
| 52 |
+
<span>最大并行任务数</span>
|
| 53 |
+
<input type="number" name="parallelism" min="1" max="8" value="{{ summary.parallelism }}" required>
|
| 54 |
+
</label>
|
| 55 |
+
<button type="submit" class="button button-primary">保存并行数</button>
|
| 56 |
+
</form>
|
| 57 |
+
<p class="muted-note">建议根据 Space 资源从 1 开始逐步增加。每个任务都会独立启动一个无头浏览器实例。</p>
|
| 58 |
+
</article>
|
| 59 |
+
|
| 60 |
+
<article class="panel">
|
| 61 |
+
<div class="panel-head">
|
| 62 |
+
<div>
|
| 63 |
+
<div class="section-kicker">用户录入</div>
|
| 64 |
+
<h2>手动添加或更新用户</h2>
|
| 65 |
+
</div>
|
| 66 |
+
<span class="status-pill status-live">管理员可写</span>
|
| 67 |
+
</div>
|
| 68 |
+
<form method="post" action="{{ url_for('create_or_update_user_from_admin') }}" class="form-grid">
|
| 69 |
+
<label class="field">
|
| 70 |
+
<span>学号</span>
|
| 71 |
+
<input type="text" name="student_id" inputmode="numeric" placeholder="学生学号" required>
|
| 72 |
+
</label>
|
| 73 |
+
<label class="field">
|
| 74 |
+
<span>密码</span>
|
| 75 |
+
<input type="password" name="password" placeholder="学生密码" required>
|
| 76 |
+
</label>
|
| 77 |
+
<label class="field">
|
| 78 |
+
<span>初始课程号</span>
|
| 79 |
+
<input type="text" name="course_id" inputmode="numeric" placeholder="可选">
|
| 80 |
+
</label>
|
| 81 |
+
<label class="field">
|
| 82 |
+
<span>初始课序号</span>
|
| 83 |
+
<input type="text" name="course_index" inputmode="numeric" maxlength="2" placeholder="可选">
|
| 84 |
+
</label>
|
| 85 |
+
<button type="submit" class="button button-primary">保存用户</button>
|
| 86 |
+
</form>
|
| 87 |
+
</article>
|
| 88 |
+
|
| 89 |
+
{% if admin.role == "superadmin" %}
|
| 90 |
+
<article class="panel">
|
| 91 |
+
<div class="panel-head">
|
| 92 |
+
<div>
|
| 93 |
+
<div class="section-kicker">权限管理</div>
|
| 94 |
+
<h2>创建普通管理员</h2>
|
| 95 |
+
</div>
|
| 96 |
+
<span class="status-pill status-live">仅超级管理员</span>
|
| 97 |
+
</div>
|
| 98 |
+
<form method="post" action="{{ url_for('create_admin_account') }}" class="form-grid form-grid-inline">
|
| 99 |
+
<label class="field">
|
| 100 |
+
<span>管理员账号</span>
|
| 101 |
+
<input type="text" name="username" placeholder="admin-ops" required>
|
| 102 |
+
</label>
|
| 103 |
+
<label class="field">
|
| 104 |
+
<span>管理员密码</span>
|
| 105 |
+
<input type="password" name="password" placeholder="管理员密码" required>
|
| 106 |
+
</label>
|
| 107 |
+
<button type="submit" class="button button-ghost">创建管理员</button>
|
| 108 |
+
</form>
|
| 109 |
+
<div class="chip-wrap">
|
| 110 |
+
{% for item in admins %}
|
| 111 |
+
<span class="feature-pill">{{ item.username }} · {{ item.role }}</span>
|
| 112 |
+
{% endfor %}
|
| 113 |
+
</div>
|
| 114 |
+
</article>
|
| 115 |
+
{% endif %}
|
| 116 |
+
</section>
|
| 117 |
+
|
| 118 |
+
<section class="panel">
|
| 119 |
+
<div class="panel-head">
|
| 120 |
+
<div>
|
| 121 |
+
<div class="section-kicker">用户列表</div>
|
| 122 |
+
<h2>多用户管理</h2>
|
| 123 |
+
</div>
|
| 124 |
+
<span class="status-pill status-live">管理员全量可见</span>
|
| 125 |
+
</div>
|
| 126 |
+
|
| 127 |
+
<div class="user-grid">
|
| 128 |
+
{% if users %}
|
| 129 |
+
{% for item in users %}
|
| 130 |
+
<article class="user-card">
|
| 131 |
+
<div class="user-card-head">
|
| 132 |
+
<div>
|
| 133 |
+
<div class="user-code">{{ item.student_id }}</div>
|
| 134 |
+
<div class="user-meta-text">已选 {{ item.selected_count }}/{{ item.course_count }} · 最近登录 {{ item.last_login_at or "尚未登录" }}</div>
|
| 135 |
+
</div>
|
| 136 |
+
<span class="status-pill status-{{ item.active_task_status or 'idle' }}">{{ item.active_task_status or "idle" }}</span>
|
| 137 |
+
</div>
|
| 138 |
+
|
| 139 |
+
<div class="button-row compact">
|
| 140 |
+
<form method="post" action="{{ url_for('start_user_task_from_admin', user_id=item.id) }}">
|
| 141 |
+
<button type="submit" class="button button-primary button-small">启动</button>
|
| 142 |
+
</form>
|
| 143 |
+
<form method="post" action="{{ url_for('stop_user_task_from_admin', user_id=item.id) }}">
|
| 144 |
+
<button type="submit" class="button button-secondary button-small">停止</button>
|
| 145 |
+
</form>
|
| 146 |
+
</div>
|
| 147 |
+
|
| 148 |
+
<form method="post" action="{{ url_for('update_user_password_from_admin', user_id=item.id) }}" class="form-grid">
|
| 149 |
+
<label class="field">
|
| 150 |
+
<span>重置密码</span>
|
| 151 |
+
<input type="password" name="password" placeholder="输入新密码" required>
|
| 152 |
+
</label>
|
| 153 |
+
<button type="submit" class="button button-ghost button-small">更新</button>
|
| 154 |
+
</form>
|
| 155 |
+
|
| 156 |
+
<form method="post" action="{{ url_for('add_user_course_from_admin', user_id=item.id) }}" class="form-grid form-grid-inline">
|
| 157 |
+
<label class="field">
|
| 158 |
+
<span>课程号</span>
|
| 159 |
+
<input type="text" name="course_id" inputmode="numeric" placeholder="课程号" required>
|
| 160 |
+
</label>
|
| 161 |
+
<label class="field">
|
| 162 |
+
<span>课序号</span>
|
| 163 |
+
<input type="text" name="course_index" inputmode="numeric" maxlength="2" placeholder="01" required>
|
| 164 |
+
</label>
|
| 165 |
+
<button type="submit" class="button button-primary button-small">新增课程</button>
|
| 166 |
+
</form>
|
| 167 |
+
|
| 168 |
+
<div class="course-chip-grid">
|
| 169 |
+
{% if item.courses %}
|
| 170 |
+
{% for course in item.courses %}
|
| 171 |
+
<div class="course-chip course-chip-{{ course.status }}">
|
| 172 |
+
<div>
|
| 173 |
+
<strong>{{ course.course_id }}_{{ course.course_index }}</strong>
|
| 174 |
+
<p>{{ course.last_result or "等待执行" }}</p>
|
| 175 |
+
</div>
|
| 176 |
+
<form method="post" action="{{ url_for('delete_user_course_from_admin', user_id=item.id, course_record_id=course.id) }}">
|
| 177 |
+
<button type="submit" class="button button-danger button-small">删</button>
|
| 178 |
+
</form>
|
| 179 |
+
</div>
|
| 180 |
+
{% endfor %}
|
| 181 |
+
{% else %}
|
| 182 |
+
<div class="empty-state small">这个用户还没有课程记录。</div>
|
| 183 |
+
{% endif %}
|
| 184 |
+
</div>
|
| 185 |
+
</article>
|
| 186 |
+
{% endfor %}
|
| 187 |
+
{% else %}
|
| 188 |
+
<div class="empty-state">当前还没有任何用户,先在上方录入用户信息。</div>
|
| 189 |
+
{% endif %}
|
| 190 |
+
</div>
|
| 191 |
+
</section>
|
| 192 |
+
|
| 193 |
+
<section class="panel console-panel">
|
| 194 |
+
<div class="panel-head">
|
| 195 |
+
<div>
|
| 196 |
+
<div class="section-kicker">全局日志</div>
|
| 197 |
+
<h2>管理员实时控制台</h2>
|
| 198 |
+
</div>
|
| 199 |
+
<span class="status-pill status-live">Live</span>
|
| 200 |
+
</div>
|
| 201 |
+
<div
|
| 202 |
+
class="log-console"
|
| 203 |
+
id="admin-log-stream"
|
| 204 |
+
data-last-id="{{ logs[-1].id if logs else 0 }}"
|
| 205 |
+
data-empty="当前还没有系统日志。"
|
| 206 |
+
>
|
| 207 |
+
{% if logs %}
|
| 208 |
+
{% for log in logs %}
|
| 209 |
+
<div class="log-line log-{{ log.level|lower }}">
|
| 210 |
+
<span class="log-time">{{ log.created_at }}</span>
|
| 211 |
+
<span class="log-actor">{{ log.student_id or log.actor }}</span>
|
| 212 |
+
<span class="log-message">{{ log.message }}</span>
|
| 213 |
+
</div>
|
| 214 |
+
{% endfor %}
|
| 215 |
+
{% else %}
|
| 216 |
+
<div class="log-placeholder">当前还没有系统日志。</div>
|
| 217 |
+
{% endif %}
|
| 218 |
+
</div>
|
| 219 |
+
</section>
|
| 220 |
+
|
| 221 |
+
<script>
|
| 222 |
+
window.addEventListener("DOMContentLoaded", () => {
|
| 223 |
+
SCUApp.initLogStream("admin-log-stream", "{{ url_for('admin_log_stream') }}");
|
| 224 |
+
SCUApp.initAdminStatus("{{ url_for('admin_status') }}");
|
| 225 |
+
});
|
| 226 |
+
</script>
|
| 227 |
+
{% endblock %}
|
templates/admin_dashboard.html
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
{% block title %}管理后台 | SCU 选课控制台{% endblock %}
|
| 3 |
+
{% block body_class %}admin-theme{% endblock %}
|
| 4 |
+
{% block content %}
|
| 5 |
+
<section class="dashboard-shell admin-dashboard" data-log-stream-url="{{ url_for('stream_admin_logs', last_id=recent_logs[-1].id if recent_logs else 0) }}" data-status-url="{{ url_for('admin_status') }}">
|
| 6 |
+
<header class="topbar reveal-up">
|
| 7 |
+
<div>
|
| 8 |
+
<span class="eyebrow">Admin Console</span>
|
| 9 |
+
<h1>管理员后台</h1>
|
| 10 |
+
<p>当前管理员:{{ admin_identity.username }}{% if is_super_admin %} · 超级管理员{% endif %}</p>
|
| 11 |
+
</div>
|
| 12 |
+
<form method="post" action="{{ url_for('admin_logout') }}">
|
| 13 |
+
<button type="submit" class="btn btn-ghost">退出后台</button>
|
| 14 |
+
</form>
|
| 15 |
+
</header>
|
| 16 |
+
|
| 17 |
+
<section class="metric-grid reveal-up delay-1">
|
| 18 |
+
<article class="metric-card">
|
| 19 |
+
<span>用户数</span>
|
| 20 |
+
<strong id="stat-users">{{ stats.users_count }}</strong>
|
| 21 |
+
<small>已录入的学生账号</small>
|
| 22 |
+
</article>
|
| 23 |
+
<article class="metric-card">
|
| 24 |
+
<span>运行中任务</span>
|
| 25 |
+
<strong id="stat-running">{{ stats.running_count }}</strong>
|
| 26 |
+
<small>排队中:<span id="stat-pending">{{ stats.pending_count }}</span></small>
|
| 27 |
+
</article>
|
| 28 |
+
<article class="metric-card">
|
| 29 |
+
<span>总课程目标</span>
|
| 30 |
+
<strong>{{ stats.courses_count }}</strong>
|
| 31 |
+
<small>管理员可见全部课程号与课序号</small>
|
| 32 |
+
</article>
|
| 33 |
+
<article class="metric-card">
|
| 34 |
+
<span>管理员总数</span>
|
| 35 |
+
<strong>{{ stats.admins_count }}</strong>
|
| 36 |
+
<small>包含 1 位超级管理员</small>
|
| 37 |
+
</article>
|
| 38 |
+
</section>
|
| 39 |
+
|
| 40 |
+
<section class="content-grid admin-grid">
|
| 41 |
+
<article class="card reveal-up delay-2">
|
| 42 |
+
<div class="card-head">
|
| 43 |
+
<span class="kicker">调度设置</span>
|
| 44 |
+
<h2>并行数</h2>
|
| 45 |
+
<p>建议根据 Hugging Face Space 的 CPU 与内存情况控制在较低范围。</p>
|
| 46 |
+
</div>
|
| 47 |
+
<form method="post" action="{{ url_for('update_parallel_limit') }}" class="form-grid form-grid-compact">
|
| 48 |
+
<label class="field">
|
| 49 |
+
<span>当前并行数</span>
|
| 50 |
+
<input type="number" id="parallel-limit-input" name="parallel_limit" min="1" max="8" value="{{ parallel_limit }}" required>
|
| 51 |
+
</label>
|
| 52 |
+
<button type="submit" class="btn btn-primary">更新并行数</button>
|
| 53 |
+
</form>
|
| 54 |
+
</article>
|
| 55 |
+
|
| 56 |
+
<article class="card reveal-up delay-2">
|
| 57 |
+
<div class="card-head">
|
| 58 |
+
<span class="kicker">新增用户</span>
|
| 59 |
+
<h2>手动录入用户信息</h2>
|
| 60 |
+
<p>管理员可以直接创建学生账号,普通用户随后即可用学号和密码登录。</p>
|
| 61 |
+
</div>
|
| 62 |
+
<form method="post" action="{{ url_for('create_user') }}" class="form-grid form-grid-compact">
|
| 63 |
+
<label class="field">
|
| 64 |
+
<span>学号</span>
|
| 65 |
+
<input type="text" name="student_id" inputmode="numeric" placeholder="13 位学号" required>
|
| 66 |
+
</label>
|
| 67 |
+
<label class="field">
|
| 68 |
+
<span>显示名称</span>
|
| 69 |
+
<input type="text" name="display_name" placeholder="可选备注">
|
| 70 |
+
</label>
|
| 71 |
+
<label class="field span-2">
|
| 72 |
+
<span>密码</span>
|
| 73 |
+
<input type="password" name="password" placeholder="教务系统密码" required>
|
| 74 |
+
</label>
|
| 75 |
+
<button type="submit" class="btn btn-secondary">创建用户</button>
|
| 76 |
+
</form>
|
| 77 |
+
</article>
|
| 78 |
+
|
| 79 |
+
{% if is_super_admin %}
|
| 80 |
+
<article class="card reveal-up delay-2">
|
| 81 |
+
<div class="card-head">
|
| 82 |
+
<span class="kicker">管理员管理</span>
|
| 83 |
+
<h2>新增管理员</h2>
|
| 84 |
+
<p>只有超级管理员可以继续创建普通管理员。</p>
|
| 85 |
+
</div>
|
| 86 |
+
<form method="post" action="{{ url_for('create_admin') }}" class="form-grid form-grid-compact">
|
| 87 |
+
<label class="field">
|
| 88 |
+
<span>管理员账号</span>
|
| 89 |
+
<input type="text" name="username" placeholder="输入管理员账号" required>
|
| 90 |
+
</label>
|
| 91 |
+
<label class="field">
|
| 92 |
+
<span>管理员密码</span>
|
| 93 |
+
<input type="password" name="password" placeholder="输入管理员密码" required>
|
| 94 |
+
</label>
|
| 95 |
+
<button type="submit" class="btn btn-ghost">创建管理员</button>
|
| 96 |
+
</form>
|
| 97 |
+
<div class="chip-row">
|
| 98 |
+
<span class="chip highlight">超级管理员:{{ admin_identity.username }}</span>
|
| 99 |
+
{% for admin in admins %}
|
| 100 |
+
<span class="chip">{{ admin.username }}</span>
|
| 101 |
+
{% endfor %}
|
| 102 |
+
</div>
|
| 103 |
+
</article>
|
| 104 |
+
{% endif %}
|
| 105 |
+
|
| 106 |
+
<article class="card reveal-up delay-3 span-2">
|
| 107 |
+
<div class="card-head split">
|
| 108 |
+
<div>
|
| 109 |
+
<span class="kicker">任务总览</span>
|
| 110 |
+
<h2>最近任务</h2>
|
| 111 |
+
<p>用于快速确认任务是否正在排队、执行、停止或失败。</p>
|
| 112 |
+
</div>
|
| 113 |
+
<span class="status-pill status-running">实时刷新</span>
|
| 114 |
+
</div>
|
| 115 |
+
<div class="course-table-wrap">
|
| 116 |
+
<table class="data-table">
|
| 117 |
+
<thead>
|
| 118 |
+
<tr>
|
| 119 |
+
<th>任务</th>
|
| 120 |
+
<th>学号</th>
|
| 121 |
+
<th>状态</th>
|
| 122 |
+
<th>触发者</th>
|
| 123 |
+
<th>更新时间</th>
|
| 124 |
+
</tr>
|
| 125 |
+
</thead>
|
| 126 |
+
<tbody>
|
| 127 |
+
{% if recent_tasks %}
|
| 128 |
+
{% for task in recent_tasks %}
|
| 129 |
+
<tr>
|
| 130 |
+
<td>#{{ task.id }}</td>
|
| 131 |
+
<td>{{ task.student_id }}</td>
|
| 132 |
+
<td><span class="status-pill status-{{ task.status }}">{{ task_labels.get(task.status, task.status) }}</span></td>
|
| 133 |
+
<td>{{ task.requested_by_role }}:{{ task.requested_by }}</td>
|
| 134 |
+
<td>{{ task.updated_at }}</td>
|
| 135 |
+
</tr>
|
| 136 |
+
{% endfor %}
|
| 137 |
+
{% else %}
|
| 138 |
+
<tr>
|
| 139 |
+
<td colspan="5" class="empty-cell">还没有任务记录。</td>
|
| 140 |
+
</tr>
|
| 141 |
+
{% endif %}
|
| 142 |
+
</tbody>
|
| 143 |
+
</table>
|
| 144 |
+
</div>
|
| 145 |
+
</article>
|
| 146 |
+
|
| 147 |
+
<article class="card reveal-up delay-3 span-2">
|
| 148 |
+
<div class="card-head split">
|
| 149 |
+
<div>
|
| 150 |
+
<span class="kicker">全局日志</span>
|
| 151 |
+
<h2>所有用户的运行日志</h2>
|
| 152 |
+
<p>日志会持续流入,便于管理员确认浏览器登录、查课、提交结果与错误信息。</p>
|
| 153 |
+
</div>
|
| 154 |
+
<span class="live-dot">LIVE</span>
|
| 155 |
+
</div>
|
| 156 |
+
<div class="log-console" id="log-console">
|
| 157 |
+
{% if recent_logs %}
|
| 158 |
+
{% for log in recent_logs %}
|
| 159 |
+
<div class="log-line level-{{ log.level|lower }}">
|
| 160 |
+
<span class="log-meta">{{ log.created_at }} · {{ log.student_id or 'system' }} · {{ log.scope }} · {{ log.level }}</span>
|
| 161 |
+
<span>{{ log.message }}</span>
|
| 162 |
+
</div>
|
| 163 |
+
{% endfor %}
|
| 164 |
+
{% else %}
|
| 165 |
+
<div class="log-line level-info muted">暂无日志,用户启动任务后这里会自动刷新。</div>
|
| 166 |
+
{% endif %}
|
| 167 |
+
</div>
|
| 168 |
+
</article>
|
| 169 |
+
|
| 170 |
+
<article class="card reveal-up delay-4 span-2">
|
| 171 |
+
<div class="card-head">
|
| 172 |
+
<span class="kicker">用户清单</span>
|
| 173 |
+
<h2>所有用户与课程详情</h2>
|
| 174 |
+
<p>可以直接修改用户信息、增减课程,或代替用户启动和停止任务。</p>
|
| 175 |
+
</div>
|
| 176 |
+
<div class="user-card-grid">
|
| 177 |
+
{% for user in users %}
|
| 178 |
+
<section class="user-card">
|
| 179 |
+
<div class="user-card-head">
|
| 180 |
+
<div>
|
| 181 |
+
<h3>{{ user.display_name or user.student_id }}</h3>
|
| 182 |
+
<p>{{ user.student_id }}</p>
|
| 183 |
+
</div>
|
| 184 |
+
<span class="status-pill status-{{ user.latest_task.status if user.latest_task else 'idle' }}">
|
| 185 |
+
{{ task_labels.get(user.latest_task.status, '未启动') if user.latest_task else '未启动' }}
|
| 186 |
+
</span>
|
| 187 |
+
</div>
|
| 188 |
+
|
| 189 |
+
<div class="chip-row tight">
|
| 190 |
+
<span class="chip {% if user.is_active %}highlight{% endif %}">{{ '启用中' if user.is_active else '已禁用' }}</span>
|
| 191 |
+
<span class="chip">课程 {{ user.course_count }}</span>
|
| 192 |
+
<span class="chip">最近任务 {{ user.latest_task.id if user.latest_task else '--' }}</span>
|
| 193 |
+
</div>
|
| 194 |
+
|
| 195 |
+
<form method="post" action="{{ url_for('update_user', user_id=user.id) }}" class="form-grid form-grid-compact slim-form">
|
| 196 |
+
<label class="field span-2">
|
| 197 |
+
<span>显示名称</span>
|
| 198 |
+
<input type="text" name="display_name" value="{{ user.display_name }}" placeholder="备注名称">
|
| 199 |
+
</label>
|
| 200 |
+
<label class="field span-2">
|
| 201 |
+
<span>重置密码</span>
|
| 202 |
+
<input type="password" name="password" placeholder="留空表示不修改">
|
| 203 |
+
</label>
|
| 204 |
+
<button type="submit" class="btn btn-ghost">保存用户</button>
|
| 205 |
+
</form>
|
| 206 |
+
|
| 207 |
+
<div class="button-row wrap-row">
|
| 208 |
+
<form method="post" action="{{ url_for('toggle_user', user_id=user.id) }}">
|
| 209 |
+
<button type="submit" class="btn btn-ghost {% if not user.is_active %}danger{% endif %}">{{ '禁用' if user.is_active else '启用' }}</button>
|
| 210 |
+
</form>
|
| 211 |
+
<form method="post" action="{{ url_for('admin_start_user_task', user_id=user.id) }}">
|
| 212 |
+
<button type="submit" class="btn btn-primary">代启动任务</button>
|
| 213 |
+
</form>
|
| 214 |
+
<form method="post" action="{{ url_for('admin_stop_user_task', user_id=user.id) }}">
|
| 215 |
+
<button type="submit" class="btn btn-ghost danger">代停止任务</button>
|
| 216 |
+
</form>
|
| 217 |
+
</div>
|
| 218 |
+
|
| 219 |
+
<form method="post" action="{{ url_for('admin_add_course', user_id=user.id) }}" class="form-grid form-grid-compact slim-form">
|
| 220 |
+
<label class="field">
|
| 221 |
+
<span>类型</span>
|
| 222 |
+
<select name="category">
|
| 223 |
+
<option value="free">自由选课</option>
|
| 224 |
+
<option value="plan">方案选课</option>
|
| 225 |
+
</select>
|
| 226 |
+
</label>
|
| 227 |
+
<label class="field">
|
| 228 |
+
<span>课程号</span>
|
| 229 |
+
<input type="text" name="course_id" placeholder="课程号" required>
|
| 230 |
+
</label>
|
| 231 |
+
<label class="field">
|
| 232 |
+
<span>课序号</span>
|
| 233 |
+
<input type="text" name="course_index" placeholder="01" maxlength="2" required>
|
| 234 |
+
</label>
|
| 235 |
+
<button type="submit" class="btn btn-secondary">为该用户加课</button>
|
| 236 |
+
</form>
|
| 237 |
+
|
| 238 |
+
<div class="course-list">
|
| 239 |
+
{% if user.courses %}
|
| 240 |
+
{% for course in user.courses %}
|
| 241 |
+
<div class="course-chip-row">
|
| 242 |
+
<span>{{ category_labels.get(course.category, course.category) }} · {{ course.course_id }}_{{ course.course_index }}</span>
|
| 243 |
+
<form method="post" action="{{ url_for('admin_delete_course', course_target_id=course.id) }}">
|
| 244 |
+
<button type="submit" class="inline-action">删除</button>
|
| 245 |
+
</form>
|
| 246 |
+
</div>
|
| 247 |
+
{% endfor %}
|
| 248 |
+
{% else %}
|
| 249 |
+
<div class="empty-mini">当前没有课程目标。</div>
|
| 250 |
+
{% endif %}
|
| 251 |
+
</div>
|
| 252 |
+
</section>
|
| 253 |
+
{% else %}
|
| 254 |
+
<div class="empty-state-card">
|
| 255 |
+
还没有录入任何用户,请先通过上方表单创建。
|
| 256 |
+
</div>
|
| 257 |
+
{% endfor %}
|
| 258 |
+
</div>
|
| 259 |
+
</article>
|
| 260 |
+
</section>
|
| 261 |
+
</section>
|
| 262 |
+
{% endblock %}
|
templates/admin_login.html
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
{% block title %}管理员登录 | SCU 选课控制台{% endblock %}
|
| 3 |
+
{% block body_class %}auth-body admin-theme{% endblock %}
|
| 4 |
+
{% block content %}
|
| 5 |
+
<section class="auth-layout admin-layout">
|
| 6 |
+
<div class="hero-panel reveal-up">
|
| 7 |
+
<span class="eyebrow">Admin Console</span>
|
| 8 |
+
<h1>统一查看所有用户、任务队列、并行数和实时日志。</h1>
|
| 9 |
+
<p>
|
| 10 |
+
管理员可以手动录入用户账号、查看全部课程目标、控制任务启停,并根据 Hugging Face Space 的资源情况调整并行数。
|
| 11 |
+
</p>
|
| 12 |
+
<div class="hero-metrics">
|
| 13 |
+
<article>
|
| 14 |
+
<strong>多位管理员</strong>
|
| 15 |
+
<span>超级管理员可继续创建普通管理员</span>
|
| 16 |
+
</article>
|
| 17 |
+
<article>
|
| 18 |
+
<strong>并发可控</strong>
|
| 19 |
+
<span>任务并行度支持后台动态调整</span>
|
| 20 |
+
</article>
|
| 21 |
+
<article>
|
| 22 |
+
<strong>全量透视</strong>
|
| 23 |
+
<span>用户数据、任务结果和日志全部可见</span>
|
| 24 |
+
</article>
|
| 25 |
+
</div>
|
| 26 |
+
</div>
|
| 27 |
+
|
| 28 |
+
<div class="auth-card reveal-up delay-1 accent-amber">
|
| 29 |
+
<div class="card-head compact">
|
| 30 |
+
<span class="kicker">管理入口</span>
|
| 31 |
+
<h2>管理员登录</h2>
|
| 32 |
+
<p>超级管理员账号密码来自环境变量 <code>ADMIN</code> 与 <code>PASSWORD</code>。</p>
|
| 33 |
+
</div>
|
| 34 |
+
<form method="post" class="form-grid">
|
| 35 |
+
<label class="field">
|
| 36 |
+
<span>管理员账号</span>
|
| 37 |
+
<input type="text" name="username" autocomplete="username" placeholder="输入管理员账号" required>
|
| 38 |
+
</label>
|
| 39 |
+
<label class="field">
|
| 40 |
+
<span>管理员密码</span>
|
| 41 |
+
<input type="password" name="password" autocomplete="current-password" placeholder="输入管理员密码" required>
|
| 42 |
+
</label>
|
| 43 |
+
<button type="submit" class="btn btn-secondary btn-lg">进入管理后台</button>
|
| 44 |
+
</form>
|
| 45 |
+
<div class="auth-footnote">
|
| 46 |
+
普通学生无法从用户登录页看到此入口,管理员地址需单独访问。
|
| 47 |
+
</div>
|
| 48 |
+
</div>
|
| 49 |
+
</section>
|
| 50 |
+
{% endblock %}
|
templates/base.html
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="zh-CN">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>{% block title %}SCU 选课控制台{% endblock %}</title>
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700;800&family=Space+Grotesk:wght@500;700&display=swap" rel="stylesheet">
|
| 10 |
+
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
| 11 |
+
</head>
|
| 12 |
+
<body class="app-body {% block body_class %}{% endblock %}">
|
| 13 |
+
<div class="bg-orb bg-orb-a"></div>
|
| 14 |
+
<div class="bg-orb bg-orb-b"></div>
|
| 15 |
+
<div class="bg-grid"></div>
|
| 16 |
+
|
| 17 |
+
<main class="page-shell">
|
| 18 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 19 |
+
{% if messages %}
|
| 20 |
+
<section class="flash-stack">
|
| 21 |
+
{% for category, message in messages %}
|
| 22 |
+
<article class="flash flash-{{ category }}">{{ message }}</article>
|
| 23 |
+
{% endfor %}
|
| 24 |
+
</section>
|
| 25 |
+
{% endif %}
|
| 26 |
+
{% endwith %}
|
| 27 |
+
|
| 28 |
+
{% block content %}{% endblock %}
|
| 29 |
+
</main>
|
| 30 |
+
|
| 31 |
+
<script src="{{ url_for('static', filename='app.js') }}"></script>
|
| 32 |
+
{% block scripts %}{% endblock %}
|
| 33 |
+
</body>
|
| 34 |
+
</html>
|
templates/dashboard.html
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
{% block title %}用户控制台 | SCU 选课控制台{% endblock %}
|
| 3 |
+
{% block content %}
|
| 4 |
+
<section class="dashboard-shell" data-log-stream-url="{{ url_for('stream_user_logs', last_id=recent_logs[-1].id if recent_logs else 0) }}" data-status-url="{{ url_for('user_status') }}">
|
| 5 |
+
<header class="topbar reveal-up">
|
| 6 |
+
<div>
|
| 7 |
+
<span class="eyebrow">User Console</span>
|
| 8 |
+
<h1>{{ current_user.display_name or current_user.student_id }} 的选课面板</h1>
|
| 9 |
+
<p>登录账号:{{ current_user.student_id }},你的课程目标与运行日志会实时同步到这里。</p>
|
| 10 |
+
</div>
|
| 11 |
+
<form method="post" action="{{ url_for('logout') }}">
|
| 12 |
+
<button type="submit" class="btn btn-ghost">退出登录</button>
|
| 13 |
+
</form>
|
| 14 |
+
</header>
|
| 15 |
+
|
| 16 |
+
<section class="metric-grid reveal-up delay-1">
|
| 17 |
+
<article class="metric-card">
|
| 18 |
+
<span>当前任务</span>
|
| 19 |
+
<strong id="task-status-text">{{ task_labels.get(task.status, '未启动') if task else '未启动' }}</strong>
|
| 20 |
+
<small>最近更新时间:{{ task.updated_at if task else '暂无' }}</small>
|
| 21 |
+
</article>
|
| 22 |
+
<article class="metric-card">
|
| 23 |
+
<span>待选课程</span>
|
| 24 |
+
<strong id="course-count">{{ courses|length }}</strong>
|
| 25 |
+
<small>管理员可看到全部课程内容</small>
|
| 26 |
+
</article>
|
| 27 |
+
<article class="metric-card">
|
| 28 |
+
<span>最近任务编号</span>
|
| 29 |
+
<strong>{{ task.id if task else '--' }}</strong>
|
| 30 |
+
<small>{{ task.last_error if task and task.last_error else '当前没有错误提示' }}</small>
|
| 31 |
+
</article>
|
| 32 |
+
</section>
|
| 33 |
+
|
| 34 |
+
<section class="content-grid dashboard-grid">
|
| 35 |
+
<article class="card reveal-up delay-2">
|
| 36 |
+
<div class="card-head">
|
| 37 |
+
<span class="kicker">个人信息</span>
|
| 38 |
+
<h2>更新登录信息</h2>
|
| 39 |
+
<p>密码会用于后台登录教务系统,请保持为最新有效密码。</p>
|
| 40 |
+
</div>
|
| 41 |
+
<form method="post" action="{{ url_for('update_profile') }}" class="form-grid">
|
| 42 |
+
<label class="field">
|
| 43 |
+
<span>显示名称</span>
|
| 44 |
+
<input type="text" name="display_name" value="{{ current_user.display_name }}" placeholder="可选昵称">
|
| 45 |
+
</label>
|
| 46 |
+
<label class="field">
|
| 47 |
+
<span>教务密码</span>
|
| 48 |
+
<input type="password" name="password" value="" placeholder="重新输入当前有效密码" required>
|
| 49 |
+
</label>
|
| 50 |
+
<button type="submit" class="btn btn-primary">保存账号信息</button>
|
| 51 |
+
</form>
|
| 52 |
+
</article>
|
| 53 |
+
|
| 54 |
+
<article class="card reveal-up delay-2">
|
| 55 |
+
<div class="card-head">
|
| 56 |
+
<span class="kicker">课程目标</span>
|
| 57 |
+
<h2>添加课程号与课序号</h2>
|
| 58 |
+
<p>支持方案选课与自由选课,管理员会看到你录入的全部内容。</p>
|
| 59 |
+
</div>
|
| 60 |
+
<form method="post" action="{{ url_for('add_course') }}" class="form-grid form-grid-compact">
|
| 61 |
+
<label class="field">
|
| 62 |
+
<span>选课类型</span>
|
| 63 |
+
<select name="category">
|
| 64 |
+
<option value="free">自由选课</option>
|
| 65 |
+
<option value="plan">方案选课</option>
|
| 66 |
+
</select>
|
| 67 |
+
</label>
|
| 68 |
+
<label class="field">
|
| 69 |
+
<span>课程号</span>
|
| 70 |
+
<input type="text" name="course_id" inputmode="numeric" placeholder="课程号" required>
|
| 71 |
+
</label>
|
| 72 |
+
<label class="field">
|
| 73 |
+
<span>课序号</span>
|
| 74 |
+
<input type="text" name="course_index" inputmode="numeric" placeholder="例如 01" maxlength="2" required>
|
| 75 |
+
</label>
|
| 76 |
+
<button type="submit" class="btn btn-secondary">加入抢课队列</button>
|
| 77 |
+
</form>
|
| 78 |
+
</article>
|
| 79 |
+
|
| 80 |
+
<article class="card reveal-up delay-3 span-2">
|
| 81 |
+
<div class="card-head split">
|
| 82 |
+
<div>
|
| 83 |
+
<span class="kicker">执行控制</span>
|
| 84 |
+
<h2>启动与停止任务</h2>
|
| 85 |
+
<p>后台会按照管理员设置的并行数进行排队和执行。</p>
|
| 86 |
+
</div>
|
| 87 |
+
<div class="button-row">
|
| 88 |
+
<form method="post" action="{{ url_for('start_task') }}">
|
| 89 |
+
<button type="submit" class="btn btn-primary">启动任务</button>
|
| 90 |
+
</form>
|
| 91 |
+
<form method="post" action="{{ url_for('stop_task') }}">
|
| 92 |
+
<button type="submit" class="btn btn-ghost danger">停止任务</button>
|
| 93 |
+
</form>
|
| 94 |
+
</div>
|
| 95 |
+
</div>
|
| 96 |
+
<div class="status-strip">
|
| 97 |
+
<span class="status-pill status-{{ task.status if task else 'idle' }}" id="task-status-pill">{{ task_labels.get(task.status, '未启动') if task else '未启动' }}</span>
|
| 98 |
+
<span>创建时间:{{ task.created_at if task else '暂无任务' }}</span>
|
| 99 |
+
<span>触发者:{{ task.requested_by if task else '暂无' }}</span>
|
| 100 |
+
</div>
|
| 101 |
+
<div class="course-table-wrap">
|
| 102 |
+
<table class="data-table">
|
| 103 |
+
<thead>
|
| 104 |
+
<tr>
|
| 105 |
+
<th>类型</th>
|
| 106 |
+
<th>课程号</th>
|
| 107 |
+
<th>课序号</th>
|
| 108 |
+
<th>操作</th>
|
| 109 |
+
</tr>
|
| 110 |
+
</thead>
|
| 111 |
+
<tbody>
|
| 112 |
+
{% if courses %}
|
| 113 |
+
{% for course in courses %}
|
| 114 |
+
<tr>
|
| 115 |
+
<td>{{ category_labels.get(course.category, course.category) }}</td>
|
| 116 |
+
<td>{{ course.course_id }}</td>
|
| 117 |
+
<td>{{ course.course_index }}</td>
|
| 118 |
+
<td>
|
| 119 |
+
<form method="post" action="{{ url_for('delete_course', course_target_id=course.id) }}">
|
| 120 |
+
<button type="submit" class="inline-action">移除</button>
|
| 121 |
+
</form>
|
| 122 |
+
</td>
|
| 123 |
+
</tr>
|
| 124 |
+
{% endfor %}
|
| 125 |
+
{% else %}
|
| 126 |
+
<tr>
|
| 127 |
+
<td colspan="4" class="empty-cell">还没有课程目标,先添加课程号和课序号吧。</td>
|
| 128 |
+
</tr>
|
| 129 |
+
{% endif %}
|
| 130 |
+
</tbody>
|
| 131 |
+
</table>
|
| 132 |
+
</div>
|
| 133 |
+
</article>
|
| 134 |
+
|
| 135 |
+
<article class="card reveal-up delay-3 span-2">
|
| 136 |
+
<div class="card-head split">
|
| 137 |
+
<div>
|
| 138 |
+
<span class="kicker">实时日志</span>
|
| 139 |
+
<h2>后台运行日志</h2>
|
| 140 |
+
<p>这里会持续显示程序执行时的关键步骤、错误与结果。</p>
|
| 141 |
+
</div>
|
| 142 |
+
<span class="live-dot">LIVE</span>
|
| 143 |
+
</div>
|
| 144 |
+
<div class="log-console" id="log-console">
|
| 145 |
+
{% if recent_logs %}
|
| 146 |
+
{% for log in recent_logs %}
|
| 147 |
+
<div class="log-line level-{{ log.level|lower }}">
|
| 148 |
+
<span class="log-meta">{{ log.created_at }} · {{ log.scope }} · {{ log.level }}</span>
|
| 149 |
+
<span>{{ log.message }}</span>
|
| 150 |
+
</div>
|
| 151 |
+
{% endfor %}
|
| 152 |
+
{% else %}
|
| 153 |
+
<div class="log-line level-info muted">暂无日志,启动任务后这里会自动刷新。</div>
|
| 154 |
+
{% endif %}
|
| 155 |
+
</div>
|
| 156 |
+
</article>
|
| 157 |
+
</section>
|
| 158 |
+
</section>
|
| 159 |
+
{% endblock %}
|
templates/login.html
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
{% block title %}用户登录 | SCU 选课控制台{% endblock %}
|
| 3 |
+
{% block body_class %}auth-body{% endblock %}
|
| 4 |
+
{% block content %}
|
| 5 |
+
<section class="auth-layout">
|
| 6 |
+
<div class="hero-panel reveal-up">
|
| 7 |
+
<span class="eyebrow">Advanced SCU Course Catcher</span>
|
| 8 |
+
<h1>把抢课任务变成一个稳定、可并行、可追踪的个人控制台。</h1>
|
| 9 |
+
<p>
|
| 10 |
+
使用学号与教务密码登录后,你可以自行维护课程号与课序号,查看后台运行状态,并实时看到程序日志。
|
| 11 |
+
</p>
|
| 12 |
+
<div class="hero-metrics">
|
| 13 |
+
<article>
|
| 14 |
+
<strong>多用户隔离</strong>
|
| 15 |
+
<span>每位用户独立队列与日志流</span>
|
| 16 |
+
</article>
|
| 17 |
+
<article>
|
| 18 |
+
<strong>实时可见</strong>
|
| 19 |
+
<span>浏览器执行日志会持续推送</span>
|
| 20 |
+
</article>
|
| 21 |
+
<article>
|
| 22 |
+
<strong>HF Space 友好</strong>
|
| 23 |
+
<span>无头浏览器任务可直接部署</span>
|
| 24 |
+
</article>
|
| 25 |
+
</div>
|
| 26 |
+
</div>
|
| 27 |
+
|
| 28 |
+
<div class="auth-card reveal-up delay-1">
|
| 29 |
+
<div class="card-head compact">
|
| 30 |
+
<span class="kicker">学生入口</span>
|
| 31 |
+
<h2>用户登录</h2>
|
| 32 |
+
<p>此页面不展示管理员入口,管理员请直接访问 <code>/admin</code>。</p>
|
| 33 |
+
</div>
|
| 34 |
+
<form method="post" class="form-grid">
|
| 35 |
+
<label class="field">
|
| 36 |
+
<span>学号</span>
|
| 37 |
+
<input type="text" name="student_id" inputmode="numeric" autocomplete="username" placeholder="例如 2023XXXXXXXXX" required>
|
| 38 |
+
</label>
|
| 39 |
+
<label class="field">
|
| 40 |
+
<span>密码</span>
|
| 41 |
+
<input type="password" name="password" autocomplete="current-password" placeholder="输入教务系统密码" required>
|
| 42 |
+
</label>
|
| 43 |
+
<button type="submit" class="btn btn-primary btn-lg">进入用户控制台</button>
|
| 44 |
+
</form>
|
| 45 |
+
<div class="auth-footnote">
|
| 46 |
+
管理员可以在后台手动录入用户信息,普通用户登录后只会看到自己的课程数据与日志。
|
| 47 |
+
</div>
|
| 48 |
+
</div>
|
| 49 |
+
</section>
|
| 50 |
+
{% endblock %}
|
tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
tests/helpers.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import shutil
|
| 4 |
+
import uuid
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Iterator
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@contextmanager
|
| 11 |
+
def workspace_tempdir(prefix: str) -> Iterator[Path]:
|
| 12 |
+
base_dir = Path(__file__).resolve().parent.parent / "data" / "test-artifacts"
|
| 13 |
+
base_dir.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
temp_dir = base_dir / f"{prefix}{uuid.uuid4().hex}"
|
| 15 |
+
temp_dir.mkdir(parents=True, exist_ok=True)
|
| 16 |
+
try:
|
| 17 |
+
yield temp_dir
|
| 18 |
+
finally:
|
| 19 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
tests/test_config.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import unittest
|
| 5 |
+
from unittest.mock import patch
|
| 6 |
+
|
| 7 |
+
from core.config import AppConfig
|
| 8 |
+
from tests.helpers import workspace_tempdir
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class AppConfigTests(unittest.TestCase):
|
| 12 |
+
def test_internal_secrets_persist_when_admin_credentials_change(self) -> None:
|
| 13 |
+
with workspace_tempdir("config-") as temp_dir:
|
| 14 |
+
base_env = {
|
| 15 |
+
"DATA_DIR": str(temp_dir),
|
| 16 |
+
"ADMIN": "root-one",
|
| 17 |
+
"PASSWORD": "pass-one",
|
| 18 |
+
}
|
| 19 |
+
with patch.dict(os.environ, base_env, clear=False):
|
| 20 |
+
first = AppConfig.load()
|
| 21 |
+
|
| 22 |
+
changed_env = {
|
| 23 |
+
"DATA_DIR": str(temp_dir),
|
| 24 |
+
"ADMIN": "root-two",
|
| 25 |
+
"PASSWORD": "pass-two",
|
| 26 |
+
}
|
| 27 |
+
with patch.dict(os.environ, changed_env, clear=False):
|
| 28 |
+
second = AppConfig.load()
|
| 29 |
+
|
| 30 |
+
self.assertEqual(first.session_secret, second.session_secret)
|
| 31 |
+
self.assertEqual(first.encryption_key, second.encryption_key)
|
| 32 |
+
self.assertEqual(second.super_admin_username, "root-two")
|
| 33 |
+
self.assertEqual(second.super_admin_password, "pass-two")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if __name__ == "__main__":
|
| 37 |
+
unittest.main()
|
tests/test_course_bot.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
import unittest
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
from unittest.mock import patch
|
| 8 |
+
|
| 9 |
+
from core.course_bot import CourseBot, RecoverableAutomationError
|
| 10 |
+
from core.db import Database
|
| 11 |
+
from tests.helpers import workspace_tempdir
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class FakeDriver:
|
| 15 |
+
def __init__(self) -> None:
|
| 16 |
+
self.quit_called = False
|
| 17 |
+
|
| 18 |
+
def quit(self) -> None:
|
| 19 |
+
self.quit_called = True
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FakeButton:
|
| 23 |
+
def __init__(self) -> None:
|
| 24 |
+
self.click_count = 0
|
| 25 |
+
|
| 26 |
+
def click(self) -> None:
|
| 27 |
+
self.click_count += 1
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CourseBotTests(unittest.TestCase):
|
| 31 |
+
def _make_store(self, temp_dir: Path) -> tuple[Database, dict]:
|
| 32 |
+
store = Database(temp_dir / "test.db", default_parallel_limit=2)
|
| 33 |
+
store.init_db()
|
| 34 |
+
user_id = store.create_user("2023000000001", "encrypted", "Test User")
|
| 35 |
+
store.add_course(user_id, "free", "1001001", "01")
|
| 36 |
+
user = store.get_user(user_id)
|
| 37 |
+
self.assertIsNotNone(user)
|
| 38 |
+
return store, user
|
| 39 |
+
|
| 40 |
+
def _make_config(self) -> SimpleNamespace:
|
| 41 |
+
return SimpleNamespace(
|
| 42 |
+
login_retry_limit=2,
|
| 43 |
+
poll_interval_seconds=0,
|
| 44 |
+
task_backoff_seconds=0,
|
| 45 |
+
browser_page_timeout=1,
|
| 46 |
+
selenium_error_limit=2,
|
| 47 |
+
selenium_restart_limit=3,
|
| 48 |
+
submit_captcha_retry_limit=3,
|
| 49 |
+
chrome_binary="/usr/bin/chromium",
|
| 50 |
+
chromedriver_path="/usr/bin/chromedriver",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def _make_bot(self, store: Database, user: dict, config: SimpleNamespace, logs: list[tuple[str, str]]) -> CourseBot:
|
| 54 |
+
with patch("core.course_bot.onnx_inference.CaptchaONNXInference") as solver_cls:
|
| 55 |
+
solver_cls.return_value = SimpleNamespace(classification=lambda _image: "1234")
|
| 56 |
+
return CourseBot(
|
| 57 |
+
config=config,
|
| 58 |
+
store=store,
|
| 59 |
+
task_id=1,
|
| 60 |
+
user=user,
|
| 61 |
+
password="pw",
|
| 62 |
+
logger=lambda level, message: logs.append((level, message)),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def test_restart_browser_after_repeated_session_errors(self) -> None:
|
| 66 |
+
with workspace_tempdir("course-bot-") as temp_dir:
|
| 67 |
+
store, user = self._make_store(temp_dir)
|
| 68 |
+
config = self._make_config()
|
| 69 |
+
logs: list[tuple[str, str]] = []
|
| 70 |
+
drivers: list[FakeDriver] = []
|
| 71 |
+
|
| 72 |
+
def fake_configure_browser(**_kwargs):
|
| 73 |
+
driver = FakeDriver()
|
| 74 |
+
drivers.append(driver)
|
| 75 |
+
return driver
|
| 76 |
+
|
| 77 |
+
bot = self._make_bot(store, user, config, logs)
|
| 78 |
+
stop_event = threading.Event()
|
| 79 |
+
|
| 80 |
+
with patch("core.course_bot.webdriver_utils.configure_browser", side_effect=fake_configure_browser), patch.object(
|
| 81 |
+
CourseBot,
|
| 82 |
+
"_login",
|
| 83 |
+
return_value=None,
|
| 84 |
+
), patch.object(
|
| 85 |
+
CourseBot,
|
| 86 |
+
"_goto_select_course",
|
| 87 |
+
side_effect=RecoverableAutomationError("page unavailable"),
|
| 88 |
+
):
|
| 89 |
+
result = bot.run(stop_event)
|
| 90 |
+
|
| 91 |
+
self.assertEqual(result.status, "failed")
|
| 92 |
+
self.assertIn("任务终止", result.error)
|
| 93 |
+
self.assertEqual(len(drivers), config.selenium_restart_limit)
|
| 94 |
+
self.assertTrue(all(driver.quit_called for driver in drivers))
|
| 95 |
+
self.assertTrue(any("重建浏览器" in message or "重建 Selenium 会话" in message for _level, message in logs))
|
| 96 |
+
|
| 97 |
+
def test_submit_captcha_flow_uses_ocr_branch(self) -> None:
|
| 98 |
+
with workspace_tempdir("submit-captcha-") as temp_dir:
|
| 99 |
+
store, user = self._make_store(temp_dir)
|
| 100 |
+
config = self._make_config()
|
| 101 |
+
logs: list[tuple[str, str]] = []
|
| 102 |
+
bot = self._make_bot(store, user, config, logs)
|
| 103 |
+
fake_button = FakeButton()
|
| 104 |
+
fake_results = [{"result": True, "subject": "1001001_01", "detail": ""}]
|
| 105 |
+
|
| 106 |
+
with patch.object(bot, "_find", return_value=fake_button), patch.object(
|
| 107 |
+
bot,
|
| 108 |
+
"_wait_for_submit_state",
|
| 109 |
+
side_effect=["captcha", "result"],
|
| 110 |
+
), patch.object(
|
| 111 |
+
bot,
|
| 112 |
+
"_solve_visible_submit_captcha",
|
| 113 |
+
return_value=True,
|
| 114 |
+
) as solve_mock, patch.object(
|
| 115 |
+
bot,
|
| 116 |
+
"_read_result_page",
|
| 117 |
+
return_value=fake_results,
|
| 118 |
+
):
|
| 119 |
+
results = bot._submit_with_optional_captcha(object(), object(), "1001001_01")
|
| 120 |
+
|
| 121 |
+
self.assertEqual(results, fake_results)
|
| 122 |
+
self.assertEqual(fake_button.click_count, 1)
|
| 123 |
+
solve_mock.assert_called_once()
|
| 124 |
+
self.assertTrue(any("检测到验证码" in message for _level, message in logs))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
unittest.main()
|