├── .cims-conf
└── .gitignore
├── .gitattributes
├── .github
└── workflows
│ └── nuitka.yml
├── .gitignore
├── .idea
├── .gitignore
├── ClassIslandManagementServer.py.iml
├── dictionaries
│ ├── 34876.xml
│ └── project.xml
├── inspectionProfiles
│ ├── Project_Default.xml
│ └── profiles_settings.xml
├── jsLibraryMappings.xml
├── misc.xml
├── modules.xml
├── runConfigurations
│ ├── .xml
│ ├── 2.xml
│ ├── 3.xml
│ ├── 4.xml
│ └── _CIMS_py.xml
└── vcs.xml
├── .spacecompiler
├── APIDocument.md
├── BuildInClasses.py
├── CIMS.py
├── CIMS.spacescript
├── Datas
├── .gitignore
├── ClassPlan
│ └── default.json
├── DefaultSettings
│ └── default.json
├── Policy
│ └── default.json
├── Subjects
│ └── default.json
├── TimeLayout
│ └── default.json
├── __init__.py
├── client_status.json
├── clients.json
├── pre_register.json
└── profile_config.json
├── LICENSE
├── ManagementServer.vercel
├── __init__.py
├── api.py
├── command.py
└── gRPC.py
├── ManagementServer
├── __init__.py
├── api.py
├── command.py
└── gRPC.py
├── Protobuf
├── .gitignore
├── Client
│ ├── ClientCommandDeliverScReq.proto
│ ├── ClientRegisterCsReq.proto
│ └── __init__.py
├── Command
│ ├── HeartBeat.proto
│ ├── SendNotification.proto
│ └── __init__.py
├── Enum
│ ├── CommandTypes.proto
│ ├── Retcode.proto
│ └── __init__.py
├── Server
│ ├── ClientCommandDeliverScRsp.proto
│ ├── ClientRegisterScRsp.proto
│ └── __init__.py
├── Service
│ ├── ClientCommandDeliver.proto
│ ├── ClientRegister.proto
│ └── __init__.py
└── __init__.py
├── QuickValues.py
├── README.md
├── Shell.py
├── abstract.py
├── change-visble.txt
├── changelog.txt
├── i18n
└── __init__.py
├── install.sh
├── logger
└── __init__.py
├── logs
└── .gitignore
├── nuitka-build.bat
├── nuitka-ubuntu.sh
├── project.json
├── project_info.json
├── requirements.txt
├── updater.py
└── vercel.json
/.cims-conf/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/.cims-conf/.gitignore
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.github/workflows/nuitka.yml:
--------------------------------------------------------------------------------
1 | name: 构建二进制文件
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | branches:
8 | - main
9 | workflow_dispatch:
10 |
11 | jobs:
12 | builder_matrix:
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | os: [ ubuntu-latest, windows-latest]
17 | runs-on: ${{ matrix.os }}
18 | steps:
19 | - name: Checkout repository
20 | uses: actions/checkout@v4.2.2
21 | - name: Setup Python
22 | uses: actions/setup-python@v5.3.0
23 | with:
24 | python-version: '3.13'
25 | cache: 'pip'
26 | cache-dependency-path: |
27 | **/requirements*.txt
28 | - name: Setup toolkits
29 | run: pip install grpcio-tools
30 | - name: Build protobuf (Windows)
31 | if: ${{ startsWith(matrix.os, 'windows') }}
32 | run: |
33 | $protoFiles = Get-ChildItem Protobuf -Recurse -Filter *.proto -File `
34 | | ForEach-Object { $_.FullName }
35 | python -m grpc_tools.protoc --proto_path=D:\a\CIMS-backend\CIMS-backend\ --python_out=. --grpc_python_out=. $protoFiles
36 | - name: Build protobuf (Linux)
37 | if: ${{ startsWith(matrix.os, 'ubuntu') }}
38 | run: |
39 | find Protobuf/ -type f -name "*.proto" \
40 | | xargs python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=.
41 | - name: Install Linux-specific Dependencies
42 | if: ${{ startsWith(matrix.os, 'ubuntu') }}
43 | run: |
44 | sudo apt-get update
45 | sudo apt-get install -y mold clang
46 |
47 | - name: Install Dependencies
48 | run: pip install -r requirements.txt
49 |
50 | - name: Build (Windows)
51 | if: ${{ startsWith(matrix.os, 'windows') }}
52 | uses: Nuitka/Nuitka-Action@main
53 | with:
54 | mode: standalone
55 | script-name: CIMS.py
56 | output-file: CIMS-backend
57 | include-data-files: LICENSE=LICENSE
58 | disable-console: false
59 | file-version: 1.0.0.0
60 | product-name: CIMS-backend
61 | - name: Build (Linux)
62 | if: ${{ startsWith(matrix.os, 'ubuntu') }}
63 | uses: Nuitka/Nuitka-Action@main
64 | env:
65 | CC: clang
66 | CXX: clang++
67 | LDFLAGS: "-fuse-ld=mold"
68 | with:
69 | mode: standalone
70 | script-name: CIMS.py
71 | output-file: CIMS-backend
72 |
73 | - name: Upload unsigned application
74 | uses: actions/upload-artifact@v4.4.2
75 | with:
76 | name: ${{ matrix.os }}
77 | path: build/CIMS.dist
78 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *$py.class
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | build/
11 | develop-eggs/
12 | dist/
13 | downloads/
14 | eggs/
15 | .eggs/
16 | lib/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | wheels/
22 | share/python-wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .nox/
42 | .coverage
43 | .coverage.*
44 | .cache
45 | nosetests.xml
46 | coverage.xml
47 | *.cover
48 | *.py,cover
49 | .hypothesis/
50 | .pytest_cache/
51 | cover/
52 |
53 | # Translations
54 | *.mo
55 | *.pot
56 |
57 | # Django stuff:
58 | *.log
59 | local_settings.py
60 | db.sqlite3
61 | db.sqlite3-journal
62 |
63 | # Flask stuff:
64 | instance/
65 | .webassets-cache
66 |
67 | # Scrapy stuff:
68 | .scrapy
69 |
70 | # Sphinx documentation
71 | docs/_build/
72 |
73 | # PyBuilder
74 | .pybuilder/
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | # For a library or package, you might want to ignore these files since the code is
86 | # intended to run in multiple environments; otherwise, check them in:
87 | .python-version
88 |
89 | # pipenv
90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
93 | # install all needed dependencies.
94 | #Pipfile.lock
95 |
96 | # poetry
97 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
98 | # This is especially recommended for binary packages to ensure reproducibility, and is more
99 | # commonly ignored for libraries.
100 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
101 | #poetry.lock
102 |
103 | # pdm
104 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
105 | #pdm.lock
106 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
107 | # in version control.
108 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
109 | .pdm.toml
110 | .pdm-python
111 | .pdm-build/
112 |
113 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114 | __pypackages__/
115 |
116 | # Celery stuff
117 | celerybeat-schedule
118 | celerybeat.pid
119 |
120 | # SageMath parsed files
121 | *.sage.py
122 |
123 | # Environments
124 | .env
125 | .venv
126 | env/
127 | venv/
128 | ENV/
129 | env.bak/
130 | venv.bak/
131 |
132 | # Spyder project settings
133 | .spyderproject
134 | .spyproject
135 |
136 | # Rope project settings
137 | .ropeproject
138 |
139 | # mkdocs documentation
140 | /site
141 |
142 | # mypy
143 | .mypy_cache/
144 | .dmypy.json
145 | dmypy.json
146 |
147 | # Pyre type checker
148 | .pyre/
149 |
150 | # pytype static type analyzer
151 | .pytype/
152 |
153 | # Cython debug symbols
154 | cython_debug/
155 |
156 | # Visual Studio
157 | .vs/
158 | *.pyproj
159 | *.sln
160 |
161 | # Github Release
162 | release/
163 |
164 | # Generated Resources
165 | .installed
166 | ManagementPreset.json
167 | ManagementPreset.json.bak
168 | settings.json
169 |
170 | # Protocol Buffer
171 | Protobuf/
172 |
173 | # PyCharm
174 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
175 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
176 | # and can be added to the global gitignore or merged into this file. For a more nuclear
177 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
178 | #.idea/
179 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # 默认忽略的文件
2 | /shelf/
3 | /workspace.xml
4 | # 基于编辑器的 HTTP 客户端请求
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/ClassIslandManagementServer.py.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/dictionaries/34876.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | retcode
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/dictionaries/project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | cims
5 | classisland
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/jsLibraryMappings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/3.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/4.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/_CIMS_py.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.spacecompiler:
--------------------------------------------------------------------------------
1 | .compiler.ext:py312
2 | .compiler.ext.py312.requirements:1
--------------------------------------------------------------------------------
/APIDocument.md:
--------------------------------------------------------------------------------
1 | # ClassIsland 集控与客户端 API 及配置文件文档
2 |
3 | 本文档旨在说明 ClassIsland 客户端与其集控后端(CIMS-backend)之间的 API 交互,以及相关的配置文件结构。
4 |
5 | ## 概述
6 |
7 | ClassIsland 客户端通过 HTTP API 从集控后端获取配置清单(Manifest)和具体的配置文件。集控后端同时提供 gRPC 服务用于客户端注册和实时指令下发。此外,集控后端还有一个内部 HTTP API 用于管理服务器本身。
8 |
9 | ## 1. 客户端 API (供 ClassIsland 客户端实例使用)
10 |
11 | 这些 API 由 `ManagementServer/api.py` (或 `ManagementServer.vercel/api.py`) 提供。
12 |
13 | ### 1.1 获取客户端配置清单 (Manifest)
14 |
15 | 客户端首先请求此接口以获取其专属的配置资源清单。
16 |
17 | * **Endpoint**: `GET /api/v1/client/{client_uid}/manifest`
18 | * **Path Parameters**:
19 | * `client_uid` (string, 必选): 客户端的唯一标识符 (UUID)。
20 | * **Query Parameters**:
21 | * `version` (integer, 可选): 客户端当前配置的版本号(通常是时间戳)。服务器用此判断是否需要更新。如果未提供,服务器通常会返回最新的配置。
22 | * **请求示例**:
23 | `GET /api/v1/client/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/manifest?version=1678886400`
24 | * **响应格式**: `application/json`
25 | * **响应成功 (200 OK)**:
26 | ```json
27 | {
28 | "ClassPlanSource": { // 课表源信息
29 | "Value": "/api/v1/client/ClassPlan?name=default_classplan", // 获取课表的URL路径
30 | "Version": 1678886401 // 课表版本
31 | },
32 | "TimeLayoutSource": { // 时间表源信息
33 | "Value": "/api/v1/client/TimeLayout?name=default_timelayout",
34 | "Version": 1678886402
35 | },
36 | "SubjectsSource": { // 科目源信息
37 | "Value": "/api/v1/client/Subjects?name=default_subjects",
38 | "Version": 1678886403
39 | },
40 | "DefaultSettingsSource": { // 默认客户端设置源信息
41 | "Value": "/api/v1/client/DefaultSettings?name=default_settings",
42 | "Version": 1678886404
43 | },
44 | "PolicySource": { // 策略源信息
45 | "Value": "/api/v1/client/Policy?name=default_policy",
46 | "Version": 1678886405
47 | },
48 | "ServerKind": 0, // 服务器类型 (0: Serverless, 1: ManagementServer)
49 | "OrganizationName": "我的学校" // 组织名称
50 | }
51 | ```
52 | * `Value` 字段中的 URL 是相对于服务器 API Host 的路径。客户端需要将服务器的 Host 和 Port (以及可能的 http/https 前缀)与此路径拼接。
53 | * 如果 `profile_config` 中未找到 `client_uid` 对应的配置,则会使用默认的资源名称(如 `default_classplan`)。
54 |
55 | ### 1.2 获取具体配置文件
56 |
57 | 客户端根据 Manifest 中获取到的 URL 来请求具体的配置文件。
58 |
59 | * **Endpoint**: `GET /api/v1/client/{resource_type}`
60 | * **Path Parameters**:
61 | * `resource_type` (string, 必选): 资源类型,例如 `ClassPlan`, `TimeLayout`, `Subjects`, `DefaultSettings`, `Policy`。
62 | * **Query Parameters**:
63 | * `name` (string, 必选): 资源文件的名称 (不含扩展名),例如 `default_classplan`。
64 | * **请求示例**:
65 | `GET /api/v1/client/ClassPlan?name=default_classplan`
66 | * **响应格式**: `application/json`
67 | * **响应成功 (200 OK)**:
68 | 响应体是对应资源类型的 JSON 内容。具体结构见下文“配置文件结构说明”。
69 | 例如,请求 `/api/v1/client/Policy?name=default_policy` 会返回 `ManagementPolicy` 结构的 JSON。
70 | * **响应失败**:
71 | * `404 Not Found`: 如果请求的资源不存在。
72 |
73 | ## 2. 命令 API (供服务器管理使用)
74 |
75 | 这些 API 由 `ManagementServer/command.py` 提供,用于服务器的内部管理和维护。
76 |
77 | ### 2.1 配置文件管理 (`/command/datas/{resource_type}/...`)
78 |
79 | * `resource_type` 可以是: `ClassPlan`, `DefaultSettings`, `Policy`, `Subjects`, `TimeLayout`, `ProfileConfig`, `Clients`, `ClientStatus`。
80 |
81 | * **创建配置文件**: `GET /command/datas/{resource_type}/create?name=`
82 | * 创建一个新的空配置文件。
83 | * 响应: JSON `{"status": "success/error", "message": "..."}`
84 |
85 | * **删除配置文件**: `DELETE /command/datas/{resource_type}/delete?name=` (也支持GET)
86 | * 删除指定的配置文件。
87 | * 响应: JSON `{"status": "success/error", "message": "..."}`
88 |
89 | * **列出配置文件**: `GET /command/datas/{resource_type}/list`
90 | * 列出指定资源类型下的所有配置文件名。
91 | * 响应: JSON `["filename1", "filename2", ...]`
92 |
93 | * **重命名配置文件**: `PUT /command/datas/{resource_type}/rename?name=&target=`
94 | * 重命名配置文件。
95 | * 响应: JSON `{"status": "success/error", "message": "..."}`
96 |
97 | * **写入配置文件**: `PUT /command/datas/{resource_type}/write?name=` (也支持POST, GET)
98 | * **Request Body**: 对应资源类型的 JSON 内容。
99 | * 响应: JSON `{"status": "success/error", "message": "..."}`
100 |
101 | ### 2.2 服务器管理 (`/command/server/...`)
102 |
103 | * **获取服务器配置**: `GET /command/server/settings`
104 | * 响应: 服务器 `settings.json` 的内容。
105 |
106 | * **更新服务器配置**: `PUT /command/server/settings` (也支持POST)
107 | * **Request Body**: 新的服务器 `settings.json` 内容。
108 | * 响应: JSON `{"status": "success"}`
109 |
110 | * **获取服务器信息**: `GET /command/server/info` (旧版本为 `/command/server/version`)
111 | * 响应: JSON `{"version": "backend_version_string"}`
112 |
113 | * **下载集控预设配置**: `GET /command/download/preset` (旧版本为 `/command/server/ManagementPreset.json`)
114 | * 下载一个包含默认配置的 `cims_preset_config.zip` 文件。
115 | * 响应: `application/zip`
116 |
117 | * **导出服务器数据**: `GET /command/export/data` (旧版本为 `/command/server/export`)
118 | * 下载包含所有服务器数据的 `cims_export_YYYYMMDD_HHMMSS.zip` 文件。
119 | * 响应: `application/zip`
120 |
121 | ### 2.3 客户端管理 (`/command/clients/...`)
122 |
123 | * **列出已注册客户端**: `GET /command/clients/list`
124 | * 响应: JSON `["client_uid_1", "client_uid_2", ...]` (从 `Datas/Clients.json` 读取)
125 |
126 | * **获取客户端状态**: `GET /command/clients/status`
127 | * 响应: JSON 列表,每个对象包含:
128 | ```json
129 | [
130 | {
131 | "uid": "client_uid_1",
132 | "name": "client_id_from_registration_or_Clients.json",
133 | "status": "online/offline/unknown", // "unknown"表示仅在Clients.json中存在
134 | "lastHeartbeat": "YYYY-MM-DDTHH:MM:SS.ffffffZ", // ISO 8601 格式, UTC
135 | "ip": "client_ip_address" // 从gRPC元数据中获取
136 | }
137 | ]
138 | ```
139 |
140 | * **获取单个客户端详情**: `GET /command/client/{client_uid}/details`
141 | * 响应: JSON 对象,合并 `/status` 的信息与 `Datas/ProfileConfig.json` 中对应客户端的配置。
142 | ```json
143 | {
144 | "uid": "client_uid_1",
145 | "name": "client_id_1",
146 | "status": "online",
147 | "lastHeartbeat": "...",
148 | "ip": "...",
149 | "profileConfig": { // 来自 ProfileConfig.json
150 | "ClassPlan": "plan_name_for_client_1",
151 | "TimeLayout": "layout_name_for_client_1",
152 | // ... 其他资源类型
153 | },
154 | "isPreRegistered": true/false // 如果在 pre_registers 中找到
155 | }
156 | ```
157 |
158 | * **预注册客户端**: `POST /command/clients/pre_register` (也支持PUT, GET)
159 | * **Request Body**:
160 | ```json
161 | {
162 | "id": "client_uid_to_pre_register",
163 | "config": {
164 | "ClassPlan": "plan_name",
165 | "TimeLayout": "layout_name",
166 | // ...
167 | }
168 | }
169 | ```
170 | * 响应: JSON `{"status": "success"}`
171 |
172 | * **列出预注册客户端**: `GET /command/clients/pre_registered/list`
173 | * 响应: JSON `[{"id": "client_uid", "config": {...}}, ...]`
174 |
175 | * **删除预注册客户端**: `DELETE /command/clients/pre_registered/delete?client_id=`
176 | * 响应: JSON `{"status": "success/error", "message": "..."}`
177 |
178 | * **更新预注册客户端配置**: `PUT /command/clients/pre_registered/update`
179 | * **Request Body**: 同预注册。
180 | * 响应: JSON `{"status": "success/error", "message": "..."}`
181 |
182 | ### 2.4 指令下发 (`/command/client/{client_uid}/...`)
183 |
184 | * **重启客户端应用**: `GET /command/client/{client_uid}/restart`
185 | * 通过 gRPC 向客户端发送 `RestartApp` 指令。
186 | * 响应: JSON `{"status": "success/error", "message": "..."}`
187 |
188 | * **通知客户端更新数据**: `GET /command/client/{client_uid}/update_data`
189 | * 通过 gRPC 向客户端发送 `DataUpdated` 指令。
190 | * 响应: JSON `{"status": "success/error", "message": "..."}`
191 |
192 | * **发送通知到客户端**: `POST /command/client/{client_uid}/send_notification`
193 | * **Request Body** (SendNotification protobuf 消息的 JSON 表示):
194 | ```json
195 | {
196 | "message_mask": "遮罩文本",
197 | "message_content": "通知正文内容",
198 | "overlay_icon_left": 0, // 通常不用
199 | "overlay_icon_right": 0, // 通常不用
200 | "is_emergency": false, // 是否紧急
201 | "is_speech_enabled": true,
202 | "is_effect_enabled": true,
203 | "is_sound_enabled": true,
204 | "is_topmost": true,
205 | "duration_seconds": 10.0, // 单次显示时长(秒)
206 | "repeat_counts": 1 // 重复次数
207 | }
208 | ```
209 | * 通过 gRPC 向客户端发送 `SendNotification` 指令。
210 | * 响应: JSON `{"status": "success/error", "message": "..."}`
211 |
212 | * **批量操作**: `POST /command/client/batch_action`
213 | * **Request Body**:
214 | ```json
215 | {
216 | "action": "restartApp" | "updateData" | "sendNotification",
217 | "clients": ["client_uid_1", "client_uid_2"],
218 | "payload": { /* 如果 action 是 sendNotification,则这里是 SendNotification 的 JSON */ }
219 | }
220 | ```
221 | * 响应: JSON 数组,每个元素对应一个客户端的操作结果 `[{"uid": "...", "status": "success/error", "message": "..."}, ...]`
222 |
223 | ### 2.5 其他
224 |
225 | * **刷新服务器配置**: `GET /api/refresh`
226 | * 重新加载服务器的 `settings.json`。
227 | * 响应: 无内容 (200 OK)
228 |
229 | ## 3. gRPC API
230 |
231 | 由 `ManagementServer/gRPC.py` 和 `Protobuf/` 目录下的 `.proto` 文件定义。
232 |
233 | ### 3.1 Service: `ClientRegister`
234 |
235 | * **RPC: `Register`**
236 | * **Request**: `ClientRegisterCsReq`
237 | ```protobuf
238 | message ClientRegisterCsReq {
239 | string clientUid = 1; // 客户端唯一ID (UUID)
240 | string clientId = 2; // 用户定义的客户端ID (可选)
241 | }
242 | ```
243 | * **Response**: `ClientRegisterScRsp`
244 | ```protobuf
245 | message ClientRegisterScRsp {
246 | Enum.Retcode retcode = 1; // 返回码
247 | string message = 2; // 消息
248 | }
249 | ```
250 | * **逻辑**:
251 | 1. 检查 `clients.json` 中是否存在该 `clientUid`。
252 | 2. 如果不存在,则将其添加到 `clients.json`,并使用 `client_id` (如果提供) 或 `client_uid` 的前8位作为名称。
253 | 3. 如果客户端在 `pre_registers.json` 中,则将其配置应用到 `profile_config.json` 并从 `pre_registers.json` 中移除。
254 | 4. 返回 `Registered` (首次) 或 `Success` (已存在)。
255 |
256 | * **RPC: `UnRegister`**
257 | * **Request**: `ClientRegisterCsReq` (同上)
258 | * **Response**: `ClientRegisterScRsp` (同上)
259 | * **逻辑**:
260 | 1. 从 `clients.json` 和 `profile_config.json` 中移除该客户端信息。
261 | 2. 返回 `Success`。
262 |
263 | ### 3.2 Service: `ClientCommandDeliver`
264 |
265 | * **RPC: `ListenCommand`** (双向流)
266 | * 客户端通过 gRPC Metadata 发送 `cuid` (客户端UID)。
267 | * **Client -> Server**: `stream ClientCommandDeliverScReq`
268 | ```protobuf
269 | message ClientCommandDeliverScReq {
270 | Enum.CommandTypes Type = 2; // 通常是 Ping
271 | bytes Payload = 3; // 通常是 HeartBeat 消息序列化后的字节
272 | }
273 | ```
274 | * `HeartBeat.proto`:
275 | ```protobuf
276 | message HeartBeat {
277 | bool isOnline = 1; // 通常为 true
278 | }
279 | ```
280 | * **Server -> Client**: `stream ClientCommandDeliverScRsp`
281 | ```protobuf
282 | message ClientCommandDeliverScRsp {
283 | Enum.Retcode RetCode = 1;
284 | Enum.CommandTypes Type = 2; // 例如 Pong, RestartApp, SendNotification, DataUpdated
285 | bytes Payload = 3; // 如果 Type 是 SendNotification,则是 SendNotification 消息序列化后的字节
286 | }
287 | ```
288 | * `SendNotification.proto`:
289 | ```protobuf
290 | message SendNotification {
291 | string MessageMask=1;
292 | string MessageContent=2;
293 | int32 OverlayIconLeft=3;
294 | int32 OverlayIconRight=4;
295 | bool IsEmergency=5;
296 | bool IsSpeechEnabled=6;
297 | bool IsEffectEnabled=7;
298 | bool IsSoundEnabled=8;
299 | bool IsTopmost=9;
300 | double DurationSeconds=10;
301 | int32 RepeatCounts=11;
302 | }
303 | ```
304 | * **逻辑**:
305 | 1. 服务器维护一个活动客户端连接的字典。
306 | 2. 客户端连接后,定期发送 `Ping` + `HeartBeat`。
307 | 3. 服务器收到 `Ping` 后,更新客户端状态 (最后心跳时间、IP),并回复 `Pong`。
308 | 4. 当有指令 (如通过 Command API 发送的) 需要下发给特定客户端时,服务器通过此流将指令发送给对应的客户端。
309 | 5. 如果连接断开或超时,服务器将客户端标记为离线。
310 |
311 | ### 3.3 枚举 (Enums)
312 |
313 | * **`CommandTypes.proto`**:
314 | * `DefaultCommand` (0)
315 | * `ServerConnected` (1): 服务器连接成功 (客户端可能未使用)
316 | * `Ping` (2): 客户端心跳请求
317 | * `Pong` (3): 服务器心跳响应
318 | * `RestartApp` (4): 指令客户端重启
319 | * `SendNotification` (5): 指令客户端发送通知
320 | * `DataUpdated` (6): 指令客户端其配置数据已更新
321 |
322 | * **`Retcode.proto`**:
323 | * `None` (0)
324 | * `Success` (200): 操作成功
325 | * `ServerInternalError` (500): 服务器内部错误
326 | * `InvalidRequest` (404): 无效请求 (gRPC 中通常用作资源未找到等)
327 | * `Registered` (10001): (ClientRegister) 客户端首次注册成功
328 | * `ClientNotFound` (10002): (ClientRegister) 客户端未找到 (例如在 UnRegister 时)
329 |
330 | ## 4. 配置文件结构说明
331 |
332 | 所有配置文件均存储在服务器的 `Datas/` 目录下,并按资源类型分子目录。
333 |
334 | ### 4.1 服务器设置 (`settings.json`)
335 |
336 | 位于服务器根目录。
337 |
338 | ```json
339 | {
340 | "api": {
341 | "host": "0.0.0.0", // API 服务监听的主机
342 | "port": 50050, // API 服务监听的端口
343 | "prefix": "http" // API 服务URL前缀 (http 或 https)
344 | },
345 | "gRPC": {
346 | "host": "0.0.0.0", // gRPC 服务监听的主机
347 | "port": 50051 // gRPC 服务监听的端口
348 | },
349 | "command": {
350 | "host": "0.0.0.0", // Command API 服务监听的主机
351 | "port": 50052 // Command API 服务监听的端口
352 | },
353 | "organization_name": "我的学校" // 组织名称,会显示在客户端
354 | }
355 | ```
356 |
357 | ### 4.2 客户端注册信息 (`Datas/Clients.json`)
358 |
359 | 存储已注册的客户端信息。
360 |
361 | ```json
362 | {
363 | "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": { // Client UID
364 | "name": "Client-001" // 用户定义的客户端ID或UID前8位
365 | },
366 | // ... 更多客户端
367 | }
368 | ```
369 |
370 | ### 4.3 客户端状态 (`Datas/ClientStatus.json`)
371 |
372 | 存储客户端的在线状态和心跳信息。
373 |
374 | ```json
375 | {
376 | "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": { // Client UID
377 | "lastHeartbeat": "YYYY-MM-DDTHH:MM:SS.ffffffZ", // ISO 8601 UTC
378 | "ip": "192.168.1.100",
379 | "isOnline": true/false // 根据心跳判断
380 | },
381 | // ... 更多客户端
382 | }
383 | ```
384 |
385 | ### 4.4 客户端配置文件映射 (`Datas/ProfileConfig.json`)
386 |
387 | 定义每个客户端使用哪些具体的配置文件。
388 |
389 | ```json
390 | {
391 | "profile_config": {
392 | "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": { // Client UID
393 | "ClassPlan": "plan_name_1", // 使用名为 plan_name_1.json 的课表
394 | "TimeLayout": "layout_name_1", // 使用名为 layout_name_1.json 的时间表
395 | "Subjects": "subjects_name_1", // ...
396 | "DefaultSettings": "settings_name_1",
397 | "Policy": "policy_name_1"
398 | }
399 | // ... 更多客户端的配置映射
400 | },
401 | "pre_registers": { // 预注册的客户端
402 | "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy": { // Client UID
403 | "id": "Optional-Client-ID-Name", // 可选的客户端易记名称
404 | "config": { // 该客户端注册时自动应用的配置
405 | "ClassPlan": "plan_name_for_pre_reg",
406 | // ...
407 | }
408 | }
409 | }
410 | }
411 | ```
412 |
413 | ### 4.5 课表 (`Datas/ClassPlan/.json`)
414 |
415 | 结构与 ClassIsland 客户端的 `Profile.ClassPlans` 中的单个 `ClassPlan` 对象类似。
416 |
417 | ```json
418 | {
419 | "TimeLayoutId": "guid_of_timelayout",
420 | "TimeRule": { // 触发规则
421 | "WeekDay": 1, // 0=周日, 1=周一, ...
422 | "WeekCountDiv": 0, // 0=不分单双周, 1=第一周/单周, 2=第二周/双周 ...
423 | "WeekCountDivTotal": 0 // 0 或 2=双周轮换, 3=三周轮换, 4=四周轮换
424 | },
425 | "Classes": [ // 课程列表,顺序对应时间表中上课类型的时间点
426 | {
427 | "SubjectId": "guid_of_subject",
428 | "IsChangedClass": false, // 是否为临时换课标记
429 | "AttachedObjects": { /* ... */ } // 附加设置
430 | }
431 | // ... 更多课程
432 | ],
433 | "Name": "高一(1)班课表",
434 | "IsOverlay": false,
435 | "OverlaySourceId": null,
436 | "OverlaySetupTime": "YYYY-MM-DDTHH:MM:SSZ",
437 | "IsEnabled": true,
438 | "AssociatedGroup": "guid_of_classplan_group", // 课表组ID
439 | "AttachedObjects": { /* ... */ } // 附加设置
440 | }
441 | ```
442 |
443 | ### 4.6 时间表 (`Datas/TimeLayout/.json`)
444 |
445 | 结构与 ClassIsland 客户端的 `Profile.TimeLayouts` 中的单个 `TimeLayout` 对象类似。
446 |
447 | ```json
448 | {
449 | "Name": "夏季作息时间",
450 | "Layouts": [
451 | {
452 | "StartSecond": "YYYY-MM-DDT08:00:00Z", // 时间的日期部分不重要,主要用时间部分
453 | "EndSecond": "YYYY-MM-DDT08:45:00Z",
454 | "TimeType": 0, // 0=上课, 1=课间, 2=分割线, 3=行动
455 | "IsHideDefault": false,
456 | "DefaultClassId": "guid_of_default_subject_for_this_slot",
457 | "BreakName": "课间休息", // 仅当 TimeType=1 时有效
458 | "ActionSet": { // 仅当 TimeType=3 时有效 (见 ActionSet 结构)
459 | /* ... */
460 | },
461 | "AttachedObjects": { /* ... */ }
462 | }
463 | // ... 更多时间点
464 | ],
465 | "AttachedObjects": { /* ... */ }
466 | }
467 | ```
468 |
469 | ### 4.7 科目 (`Datas/Subjects/.json`)
470 |
471 | 结构与 ClassIsland 客户端的 `Profile.Subjects` 对象类似(是一个以科目GUID为键,科目对象为值的字典)。
472 |
473 | ```json
474 | {
475 | "guid_of_subject_1": {
476 | "Name": "语文",
477 | "Initial": "语",
478 | "TeacherName": "张老师",
479 | "IsOutDoor": false,
480 | "AttachedObjects": { /* ... */ }
481 | },
482 | "guid_of_subject_2": {
483 | // ...
484 | }
485 | }
486 | ```
487 |
488 | ### 4.8 课表组 (`Datas/ClassPlanGroup/.json`)
489 |
490 | 这个文件不是由服务器直接分发,而是 `Profile.json` 的一部分。但如果服务器要管理课表组,其结构与 ClassIsland 客户端 `Profile.ClassPlanGroups` 中的单个 `ClassPlanGroup` 对象类似。
491 | 在服务器端,课表组信息通常内嵌在 `ClassPlan` 的 `AssociatedGroup` 字段(GUID)中,并在客户端 `Profile.json` 中查找具体信息。
492 | 服务器可以分发一个完整的 `Profile.json` 文件作为 `DefaultSettings` 或自定义资源类型的一部分,其中就包含 `ClassPlanGroups`。
493 |
494 | ```json
495 | // 这是 Profile.json 中 ClassPlanGroups 的一部分
496 | {
497 | // ...其他Profile属性
498 | "ClassPlanGroups": {
499 | "ACAF4EF0-E261-4262-B941-34EA93CB4369": { // DefaultGroupGuid
500 | "Name": "默认课表组",
501 | "IsGlobal": false
502 | },
503 | "00000000-0000-0000-0000-000000000000": { // GlobalGroupGuid
504 | "Name": "全局课表群",
505 | "IsGlobal": true
506 | },
507 | "guid_of_custom_group_1": {
508 | "Name": "高一年级",
509 | "IsGlobal": false
510 | }
511 | }
512 | // ...
513 | }
514 | ```
515 |
516 | ### 4.9 预定日程 (`Datas/OrderedSchedule/.json`)
517 |
518 | 这个文件不是由服务器直接分发,而是 `Profile.json` 的一部分。
519 | 在服务器端,预定日程信息通常内嵌在 `Profile.json` 的 `OrderedSchedules` 字段中。
520 | 服务器可以分发一个完整的 `Profile.json` 文件作为 `DefaultSettings` 或自定义资源类型的一部分,其中就包含 `OrderedSchedules`。
521 |
522 | ```json
523 | // 这是 Profile.json 中 OrderedSchedules 的一部分
524 | {
525 | // ...其他Profile属性
526 | "OrderedSchedules": {
527 | "YYYY-MM-DDTHH:MM:SSZ": { // 日期键 (通常只有日期部分有效)
528 | "ClassPlanId": "guid_of_class_plan_for_this_date"
529 | }
530 | // ... 更多预定
531 | }
532 | // ...
533 | }
534 | ```
535 |
536 | ### 4.10 默认客户端设置 (`Datas/DefaultSettings/.json`)
537 |
538 | 结构与 ClassIsland 客户端的 `Settings.json` (`ClassIsland.Models.Settings`) 对象类似。包含客户端的各种行为和外观设置。
539 |
540 | ```json
541 | {
542 | "Theme": 2, // 0=跟随系统, 1=亮色, 2=暗色
543 | "IsCustomBackgroundColorEnabled": false,
544 | "BackgroundColor": "ARGB Hex, e.g., #FF000000",
545 | "PrimaryColor": "ARGB Hex",
546 | "SecondaryColor": "ARGB Hex",
547 | "SingleWeekStartTime": "YYYY-MM-DDTHH:MM:SSZ",
548 | // ... 大量其他客户端设置,参考 ClassIsland/Models/Settings.cs
549 | "WindowDockingLocation": 1, // 0-5
550 | "Opacity": 0.5,
551 | "Scale": 1.0,
552 | "CurrentComponentConfig": "Default", // 组件配置方案名
553 | "IsAutomationEnabled": false,
554 | "CurrentAutomationConfig": "Default", // 自动化配置方案名
555 | // ...
556 | }
557 | ```
558 |
559 | ### 4.11 策略 (`Datas/Policy/.json`)
560 |
561 | 结构与 ClassIsland 客户端的 `ManagementPolicy.cs` 对象类似。
562 |
563 | ```json
564 | {
565 | "DisableProfileEditing": false, // 禁止编辑档案(所有内容)
566 | "DisableProfileClassPlanEditing": false, // 禁止编辑课表
567 | "DisableProfileTimeLayoutEditing": false, // 禁止编辑时间表
568 | "DisableProfileSubjectsEditing": false, // 禁止编辑科目
569 | "DisableSettingsEditing": false, // 禁止编辑应用设置
570 | "DisableSplashCustomize": false, // 禁止自定义启动画面
571 | "DisableDebugMenu": true, // 禁用调试菜单
572 | "AllowExitManagement": true, // 允许客户端主动退出集控
573 | "DisableEasterEggs": false // 禁用彩蛋
574 | }
575 | ```
576 |
577 | ### 4.12 行动 (`Action.cs`, `ActionSet.cs`)
578 |
579 | 通常嵌套在 `TimeLayoutItem` (当 `TimeType` 为3时) 或自动化工作流中。
580 |
581 | ```json
582 | // ActionSet 结构
583 | {
584 | "IsEnabled": true,
585 | "Name": "我的行动组",
586 | "Guid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // 内部标识
587 | "IsOn": false, // 运行时状态,标记是否已触发但未恢复
588 | "IsRevertEnabled": true, // 是否启用规则不再满足时的自动恢复
589 | "Actions": [
590 | // Action 结构数组
591 | {
592 | "Id": "classisland.os.run", // 行动类型ID
593 | "Settings": { // 特定于行动类型的设置
594 | "Value": "notepad.exe",
595 | "Args": ""
596 | }
597 | },
598 | {
599 | "Id": "classisland.settings.theme",
600 | "Settings": {
601 | "Value": 1 // 0=系统, 1=亮, 2=暗
602 | }
603 | }
604 | ]
605 | }
606 | ```
607 |
608 | ### 4.13 规则集 (`Ruleset.cs`, `RuleGroup.cs`, `Rule.cs`)
609 |
610 | 用于自动化和组件隐藏等条件判断。
611 |
612 | ```json
613 | // Ruleset 结构
614 | {
615 | "Mode": 0, // 0=Or (任意组满足), 1=And (所有组满足)
616 | "IsReversed": false, // 是否反转整个规则集的判断结果
617 | "Groups": [
618 | // RuleGroup 结构数组
619 | {
620 | "Rules": [
621 | // Rule 结构数组
622 | {
623 | "IsReversed": false, // 是否反转此规则的判断结果
624 | "Id": "classisland.lessons.timeState", // 规则ID
625 | "Settings": { // 特定于规则的设置
626 | "State": 1 // 0=None, 1=OnClass, 2=Prepare, 3=Breaking, 4=AfterSchool
627 | }
628 | },
629 | {
630 | "Id": "classisland.windows.className",
631 | "Settings": {
632 | "Text": "Notepad",
633 | "UseRegex": false
634 | }
635 | }
636 | ],
637 | "Mode": 1, // 0=Or (任意规则满足), 1=And (所有规则满足)
638 | "IsReversed": false, // 是否反转此规则组的判断结果
639 | "IsEnabled": true
640 | }
641 | // ...更多规则组
642 | ]
643 | }
644 | ```
645 |
646 | ### 4.14 附加设置 (`AttachableSettingsObject` 的 `AttachedObjects` 属性)
647 |
648 | 这是一个通用的键值对结构,用于在各种配置对象(如`Subject`, `TimeLayoutItem`, `ClassPlan`, `TimeLayout`)上附加额外的、由插件或核心功能定义的特定设置。
649 |
650 | * **键 (string)**: 附加设置的唯一 GUID。
651 | * **值 (object)**: 对应附加设置的具体配置对象。其结构由定义该附加设置的模块/插件决定。
652 |
653 | **通用结构**:
654 | ```json
655 | "AttachedObjects": {
656 | "GUID_OF_ATTACHED_SETTING_1": {
657 | "IsAttachSettingsEnabled": true, // 或 false,控制此附加设置是否在此对象上生效
658 | // ...特定于此附加设置的其他属性
659 | "SomeProperty": "SomeValue",
660 | "AnotherProperty": 123
661 | },
662 | "GUID_OF_ATTACHED_SETTING_2": {
663 | "IsAttachSettingsEnabled": false,
664 | // ...
665 | }
666 | }
667 | ```
668 | 例如,在 `Subject` 对象中,一个用于课程提醒的附加设置可能如下:
669 | ```json
670 | // In a Subject object
671 | "AttachedObjects": {
672 | "08F0D9C3-C770-4093-A3D0-02F3D90C24BC": { // ClassNotificationAttachedSettings GUID
673 | "IsAttachSettingsEnabled": true,
674 | "IsClassOnNotificationEnabled": true,
675 | "IsClassOnPreparingNotificationEnabled": true,
676 | "IsClassOffNotificationEnabled": false,
677 | "ClassPreparingDeltaTime": 30,
678 | "ClassOnPreparingText": "请准备好上这门特别的课!"
679 | }
680 | }
681 | ```
682 | 客户端会根据优先级(如:科目 > 时间点 > 课表 > 时间表 > 全局默认)来决定最终应用的附加设置。
683 |
684 | ## 5. 注意事项
685 |
686 | * **URL 模板**: 服务器端的 `ManagementServerConnection` 和 `ServerlessConnection` 中的 `DecorateUrl` 方法会替换 URL 模板中的 `{cuid}` (客户端唯一ID), `{id}` (客户端自定义ID), 和 `{host}` (服务器主机名)。
687 | * **版本控制**: Manifest 中的 `Version` 字段以及每个资源条目的 `Version` 用于客户端判断是否需要下载新配置。
688 | * **错误处理**:
689 | * HTTP API: 标准 HTTP 状态码。
690 | * gRPC API: `Retcode` 枚举。
691 | * **数据存储**: 服务器端所有可分发的数据文件(课表、时间表等)都存储在 `Datas/` 目录下的对应子目录中,文件名即为资源名 (如 `default.json`,`custom_plan.json`)。
692 |
--------------------------------------------------------------------------------
/BuildInClasses.py:
--------------------------------------------------------------------------------
1 | class RGB:
2 | def __init__(self, r, g, b):
3 | self.r = r
4 | self.g = g
5 | self.b = b
6 |
7 | def __str__(self):
8 | return "RGB({}, {}, {})".format(self.r, self.g, self.b)
9 |
10 |
11 | class RichText:
12 | def __init__(
13 | self,
14 | text: str,
15 | font_color: RGB,
16 | background_color: RGB,
17 | ):
18 | self.text = text
19 | self.font_color = font_color
20 | self.background_color = background_color
21 |
22 | def __str__(self):
23 | return self.text
24 |
25 | class Sentence:
26 | def __init__(self):
27 | self.text = ""
28 | self.texts = []
29 |
30 | def resolve(self, raw: str):
31 | word_cache = []
32 | for character_index in range(len(raw)):
33 | match raw[character_index]:
34 | case "\n":
35 | pass
36 |
37 |
--------------------------------------------------------------------------------
/CIMS.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 | #region Only directly run allowed.
4 | if __name__ != "__main__":
5 | import sys
6 |
7 | sys.exit(0)
8 | #endregion
9 |
10 |
11 | #region Presets
12 | #region 首次运行判定
13 | try:
14 | open(".installed").close()
15 | installed = True
16 | except FileNotFoundError:
17 | installed = False
18 | #endregiono
19 |
20 |
21 | #region 导入辅助库
22 | import argparse
23 | import asyncio
24 | import json
25 | from json import JSONDecodeError
26 | import os
27 | import sys
28 |
29 | #endregion
30 |
31 |
32 | #region 初始化数据目录
33 | for _folder in ["./logs", "./Datas", "./Datas/ClassPlan", "./Datas/DefaultSettings",
34 | "./Datas/Policy", "./Datas/Subjects", "./Datas/TimeLayout"]:
35 | try:
36 | os.mkdir(_folder)
37 | except FileExistsError:
38 | pass
39 | #endregion
40 |
41 |
42 | #region 检查数据文件
43 | for _file in ["./settings.json"] + ["./Datas/{}.json".format(name) for
44 | name in ["client_status", "clients",
45 | "pre_register", "profile_config"]] + ["./Datas/{}/default.json".format(
46 | name) for name in ["ClassPlan", "DefaultSettings", "Policy", "Subjects", "TimeLayout"]]:
47 | try:
48 | with open(_file) as f:
49 | json.load(f)
50 | except (FileNotFoundError, JSONDecodeError):
51 | with open(_file, "w") as f:
52 | f.write("{}")
53 | #endregion
54 |
55 |
56 | #region 检查项目信息配置
57 | try:
58 | with open("project_info.json") as f:
59 | json.load(f)
60 | except (FileNotFoundError, JSONDecodeError):
61 | with open("project_info.json", "w") as f:
62 | json.dump({
63 | "name": "CIMS-backend",
64 | "description": "ClassIsland Management Server on Python",
65 | "author": "git@miniopensource.com",
66 | "version": "1.1beta2sp3",
67 | "url": "https://github.com/MINIOpenSource/CIMS-backend"
68 | }, f)
69 | #endregion
70 |
71 |
72 | #region 导入项目内建库
73 | import Datas
74 | import logger
75 | import BuildInClasses
76 | import QuickValues
77 | import ManagementServer
78 |
79 | #endregion
80 |
81 |
82 | #region 首次运行
83 | if installed:
84 | with open("settings.json") as s:
85 | _set = json.load(s)
86 | else:
87 | _set = {
88 | "gRPC": {
89 | "prefix": "http",
90 | "host": "localhost",
91 | "mp_port": 50051,
92 | "port": 50051
93 | },
94 | "api": {
95 | "prefix": "http",
96 | "host": "localhost",
97 | "mp_port": 50050,
98 | "port": 50050
99 | },
100 | "command": {
101 | "prefix": "http",
102 | "host": "localhost",
103 | "mp_port": 50052,
104 | "port": 50052
105 | },
106 | "organization_name": "CIMS Default Organization",
107 | }
108 |
109 | for part in ["gRPC", "api", "command"]:
110 | _input = input(
111 | "{part} host and port used in ManagementPreset.json "
112 | "(formatted as {prefix}://{host}:{port} and port must be given)"
113 | "(Enter directly to use default settings):".format(part=part,
114 | prefix=_set[part]["prefix"],
115 | host=_set[part]["host"],
116 | port=_set[part]["mp_port"]))
117 | _part_set = True
118 | while _part_set:
119 | try:
120 | if _input.startswith("http://"):
121 | print("HTTP is not safe and HTTPS recommended.\n" if not _input.startswith(
122 | "http://localhost") else "",
123 | end="")
124 | if not _input.startswith(("https://", "http://")):
125 | raise ValueError
126 | _set[part]["prefix"] = _input.split(":")[0]
127 | _set[part]["host"] = _input.split(":")[1][2:]
128 | _set[part]["mp_port"] = int(_input.split(":")[2])
129 | # if _set[part]["port"] not in list(range(-1, 65536)):
130 | # raise KeyError
131 | _part_set = False
132 | except (IndexError, ValueError):
133 | if _input == "":
134 | _part_set = False
135 | else:
136 | _input = input("Invalid input, retry:")
137 | except KeyError:
138 | _input = input("Invalid input, retry:")
139 | if _input != "":
140 | _input = input("{part} listening port(Enter directly to use the same as above):".format(part=part))
141 | _part_set = True
142 | while _part_set:
143 | try:
144 | _set[part]["port"] = int(_input)
145 | _part_set = False
146 | except ValueError:
147 | if _input == "":
148 | _set[part]["port"] = _set[part]["mp_port"]
149 | _part_set = False
150 | else:
151 | _input = input("Invalid port, retry:")
152 | else:
153 | _set[part]["port"] = _set[part]["mp_port"]
154 | pass
155 |
156 | _input = input("Organization name:")
157 | _set["organization_name"] = _input if _input != "" else "CIMS Default Organization"
158 |
159 | with open("settings.json", "w") as s:
160 | json.dump(_set, s)
161 |
162 | open(".installed", "w").close()
163 |
164 |
165 | async def refresh():
166 | await asyncio.gather(
167 | ManagementServer.command.Settings.refresh(),
168 | ManagementServer.api.Settings.refresh(),
169 | ManagementServer.gRPC.Settings.refresh()
170 | )
171 |
172 |
173 | asyncio.run(refresh())
174 | #endregion
175 |
176 |
177 | #region 传参初始化
178 | parser = argparse.ArgumentParser(
179 | description="ClassIsland Management Server Backend"
180 | )
181 |
182 | parser.add_argument(
183 | "-g",
184 | "--generate-management-preset",
185 | action="store_true",
186 | help="Generate ManagementPreset.json on the program root."
187 | )
188 |
189 | parser.add_argument(
190 | "-r",
191 | "--restore",
192 | action="store_true",
193 | help="Restore, and delete all existed data"
194 | )
195 |
196 | args = parser.parse_args()
197 |
198 |
199 | #endregion
200 | #endregion
201 |
202 |
203 | #region 启动器
204 | async def start():
205 | await asyncio.gather(
206 | ManagementServer.gRPC.start(_set["gRPC"]["port"]),
207 | ManagementServer.api.start(_set["api"]["port"]),
208 | ManagementServer.command.start(_set["command"]["port"]),
209 | )
210 |
211 |
212 | #endregion
213 |
214 |
215 | #region 操作函数
216 | if args.restore:
217 | if input("Continue?(y/n with default n)") in ("y", "Y"):
218 | import os
219 |
220 | os.remove(".installed")
221 | os.remove("settings.json")
222 | os.remove("ManagementPreset.json")
223 | # if input("Remove datas?"):
224 | # # for _json in ["./Datas/client_status.json", "./Datas/clients.json", "./"]
225 | # pass
226 | elif args.generate_management_preset:
227 | with open("ManagementPreset.json", "w") as mp:
228 | json.dump({
229 | "ManagementServerKind": 1,
230 | "ManagementServer": "{prefix}://{host}:{port}".format(prefix=_set["api"]["prefix"],
231 | host=_set["api"]["host"],
232 | port=_set["api"]["mp_port"]),
233 | "ManagementServerGrpc": "{prefix}://{host}:{port}".format(prefix=_set["gRPC"]["prefix"],
234 | host=_set["gRPC"]["host"],
235 | port=_set["gRPC"]["mp_port"])
236 | }, mp)
237 | else:
238 | print("\033[2JWelcome to use CIMS.")
239 | asyncio.run(start())
240 | #endregion
241 |
--------------------------------------------------------------------------------
/CIMS.spacescript:
--------------------------------------------------------------------------------
1 | object signature:private.uni env(.internal.env){.toolkit.column, .toolkit.transfer, .toolkit.compiler}:
2 | .column.policy.set(frozen=false, limitation=-1)
3 | .transfer.internal.resources.finder.set(matcher="*")
4 | .compiler.resource.index(){"(.*)"}?:matchcase
5 | .endblock
6 |
7 | object signature:conf.only network-environment(.services.network-environment){.services.network}:
8 | .network.ports.register((50050, 50051, 50052))
9 | .network.connector.firewall.disable()
10 | .endblock
11 |
12 | use ext .compiler.ext.py312
13 | use ext .transfer.py3
14 |
15 | .compiler.ext.py312.add(
16 | ("CIMS.py", "/ManagementServer/*.py", "/Datas/__init__.py", "/logger/__init__.py", "/Protobuf/(*)/*.py")
17 | )
18 |
19 | .compiler.ext.py312:grpc-tool.add(
20 | ("/Protobuf/(*)/*.proto")
21 | )
22 |
23 | .transfer.py3.add("CIMS.py"){dependence.finder.auto}
24 |
25 | .column.add(.transfer.succeed().catch("CIMS.py", .transfer.py3))
26 |
--------------------------------------------------------------------------------
/Datas/.gitignore:
--------------------------------------------------------------------------------
1 | client_status.json
2 | clients.json
3 | pre_register.json
4 | profile_config.json
5 | ClassPlan
6 | DefaultSettings
7 | Policy
8 | Subjects
9 | TimeLayout
10 |
11 | *.json
--------------------------------------------------------------------------------
/Datas/ClassPlan/default.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/DefaultSettings/default.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/Policy/default.json:
--------------------------------------------------------------------------------
1 | {"DisableProfileClassPlanEditing": true, "DisableProfileTimeLayoutEditing": true, "DisableProfileSubjectsEditing": true, "DisableProfileEditing": true, "DisableSettingsEditing": true, "DisableSplashCustomize": true, "DisableDebugMenu": true, "AllowExitManagement": true}
--------------------------------------------------------------------------------
/Datas/Subjects/default.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/TimeLayout/default.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/__init__.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | import time
4 |
5 |
6 | class Resource:
7 | def __init__(self, path, name=None):
8 | self.path: str = path
9 | self.name: str = name if name is not None else path
10 | self.file_list: list[str] = [f[:-5] for f in os.listdir(f"Datas/{self.path}")]
11 |
12 | def refresh(self) -> list[str]:
13 | self.file_list = [f[:-5] for f in filter(lambda x: x.endswith(".json"), os.listdir(f"Datas/{self.path}"))]
14 | return self.file_list
15 |
16 | def read(self, name: str) -> dict:
17 | self.refresh()
18 | if name not in self.file_list:
19 | for n in self.file_list:
20 | if n in name or name in n:
21 | raise FileNotFoundError(f"{self.name} '{name}' not found. Did you mean '{n}'?")
22 | raise FileNotFoundError(f"{self.name} '{name}' not found.")
23 | else:
24 | with open(f"Datas/{self.path}/{name}.json", encoding="utf-8") as f:
25 | return json.load(f)
26 |
27 | def write(self, name: str, data: dict) -> None:
28 | self.refresh()
29 | if name not in self.file_list:
30 | raise FileNotFoundError(f"{self.name} {name} not found.")
31 | else:
32 | with open(f"Datas/{self.path}/{name}.json") as f:
33 | with open(f"Datas/{self.path}/{name}.json.bak", "w") as b:
34 | b.write(f.read())
35 | b.close()
36 | with open(f"Datas/{self.path}/{name}.json", "w") as f:
37 | json.dump(data, f)
38 |
39 | def delete(self, name: str) -> None:
40 | if name not in self.refresh():
41 | raise FileNotFoundError(f"{self.name} {name} not found.")
42 | else:
43 | os.remove(f"Datas/{self.path}/{name}.json")
44 | self.refresh()
45 |
46 | def rename(self, name: str, new_name: str) -> None:
47 | self.refresh()
48 | if name not in self.file_list:
49 | raise FileNotFoundError(f"{self.name} {name} not found.")
50 | elif new_name not in self.file_list:
51 | raise FileExistsError(f"{self.name} {new_name} exists, please delete it first.")
52 | else:
53 | os.renames(f"Datas/{self.path}/{name}.json", f"Datas/{self.path}/{new_name}.json")
54 |
55 | def new(self, name: str) -> None:
56 | self.refresh()
57 | if name in self.file_list:
58 | raise FileExistsError(f"{self.name} {name} exists, please delete it first.")
59 | else:
60 | with open(f"Datas/{self.path}/{name}.json", "w") as f:
61 | json.dump({}, f)
62 | self.refresh()
63 |
64 | def __repr__(self):
65 | self.refresh()
66 | return f"{self.name}[" + ", ".join(self.file_list) + "]"
67 |
68 | def __str__(self):
69 | self.refresh()
70 | return f"{self.name}[" + ", ".join(self.file_list) + "]"
71 |
72 | def __iter__(self):
73 | self.refresh()
74 | for item in self.file_list:
75 | yield item, f"Datas/{self.path}/{item}.json"
76 |
77 | def __getitem__(self, item):
78 | self.refresh()
79 | if item in self.file_list:
80 | return f"Datas/{self.path}/{item}.json"
81 | else:
82 | for n in self.file_list:
83 | if n in item or item in n:
84 | raise IndexError(f"{self.name} '{item}' not found. Did you mean '{n}'?")
85 | raise IndexError(f"{self.name} '{item}' not found.")
86 |
87 |
88 | ClassPlan = Resource("ClassPlan", "ClassPlan")
89 | DefaultSettings = Resource("DefaultSettings", "DefaultSettings")
90 | Policy = Resource("Policy", "Policy")
91 | Subjects = Resource("Subjects", "Subjects")
92 | TimeLayout = Resource("TimeLayout", "TimeLayout")
93 |
94 |
95 | class _ClientStatus:
96 | def __init__(self):
97 | with open("Datas/client_status.json") as f:
98 | self.client_status: dict[str: [dict[str: bool | float]]] = json.load(f)
99 |
100 | def refresh(self) -> dict[str: [dict[str: bool | float]]]:
101 | with open("Datas/client_status.json") as f:
102 | self.client_status = json.load(f)
103 | return self.client_status
104 |
105 | def update(self, uid):
106 | self.client_status[uid] = {
107 | "isOnline": True,
108 | "lastHeartbeat": time.time()
109 | }
110 | with open("Datas/client_status.json", "w") as f:
111 | json.dump(self.client_status, f)
112 |
113 | def offline(self, uid):
114 | self.client_status[uid]["isOnline"] = False
115 | with open("Datas/client_status.json", "w") as f:
116 | json.dump(self.client_status, f)
117 |
118 |
119 | ClientStatus = _ClientStatus()
120 |
121 |
122 | class _ProfileConfig:
123 | def __init__(self):
124 | with open("Datas/profile_config.json") as f:
125 | self.profile_config: dict[str: dict[str: str]] = json.load(f)
126 |
127 | with open("Datas/pre_register.json") as f:
128 | self.pre_registers = json.load(f)
129 |
130 | def refresh(self) -> dict[str: dict[str: str]]:
131 | with open("Datas/profile_config.json") as f:
132 | self.profile_config = json.load(f)
133 | return self.profile_config
134 |
135 | def register(self, uid, id):
136 | with open("Datas/pre_register.json") as f:
137 | try:
138 | self.profile_config[uid] = json.load(f)[id]
139 | except KeyError:
140 | self.profile_config[uid] = {
141 | "ClassPlan": "default",
142 | "Settings": "default",
143 | "Subjects": "default",
144 | "Policy": "default",
145 | "TimeLayout": "default"
146 | }
147 | with open("Datas/profile_config.json", "w") as f:
148 | json.dump(self.profile_config, f)
149 | self.refresh()
150 |
151 | def pre_register(self, id, conf=None):
152 | if conf is None:
153 | conf = {
154 | "ClassPlan": "default",
155 | "Settings": "default",
156 | "Subjects": "default",
157 | "Policy": "default",
158 | "TimeLayout": "default"
159 | }
160 | self.pre_registers[id] = conf
161 | with open("Datas/pre_register.json", "w") as f:
162 | json.dump(self.pre_registers, f)
163 | self.refresh()
164 |
165 |
166 | ProfileConfig = _ProfileConfig()
167 |
168 |
169 | class _Clients:
170 | def __init__(self):
171 | with open("Datas/clients.json") as f:
172 | self.clients: dict[str: str] = json.load(f)
173 |
174 | def refresh(self) -> dict[str: str]:
175 | with open("Datas/clients.json") as f:
176 | self.clients = json.load(f)
177 | return self.clients
178 |
179 | def register(self, uid, id):
180 | self.clients[uid] = id
181 | with open("Datas/clients.json", "w") as f:
182 | json.dump(self.clients, f)
183 | ProfileConfig.register(uid, id)
184 | self.refresh
185 |
186 |
187 | Clients = _Clients()
188 |
--------------------------------------------------------------------------------
/Datas/client_status.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/clients.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/pre_register.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/Datas/profile_config.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU 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 |
635 | Copyright (C)
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 .
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 | Copyright (C)
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 | .
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 | .
675 |
--------------------------------------------------------------------------------
/ManagementServer.vercel/__init__.py:
--------------------------------------------------------------------------------
1 | from . import api, gRPC, command
2 |
--------------------------------------------------------------------------------
/ManagementServer.vercel/api.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 |
4 | #region Presets
5 | #region 导入项目内建库
6 | import Datas
7 | import logger
8 | import BuildInClasses
9 | import QuickValues
10 | #endregion
11 |
12 |
13 | #region 导入辅助库
14 | import time
15 | import json
16 | #endregion
17 |
18 |
19 | #region 导入 FastAPI 相关库
20 | import uvicorn
21 | from starlette.middleware.cors import CORSMiddleware
22 | from fastapi import FastAPI, Query
23 | from fastapi.requests import Request
24 | from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, PlainTextResponse, RedirectResponse, StreamingResponse
25 | from fastapi.exceptions import HTTPException
26 | #endregion
27 |
28 |
29 | #region 导入配置文件
30 | class _Settings:
31 | def __init__(self):
32 | self.conf_name:str = "settings.json"
33 | self.conf_dict:dict = json.load(open(self.conf_name))
34 |
35 | @property
36 | async def refresh(self) -> dict:
37 | self.conf_dict = json.load(open(self.conf_name))
38 | return self.conf_dict
39 |
40 | Settings = _Settings()
41 | #endregion
42 |
43 |
44 | #region 定义 API
45 | api = FastAPI()
46 | api.add_middleware(
47 | CORSMiddleware,
48 | allow_origins=["*"],
49 | allow_methods=["*"],
50 | allow_headers=["*"]
51 | )
52 | #endregion
53 |
54 |
55 | #region 内建辅助函数和辅助参量
56 | async def _get_manifest_entry(base_url, name, version, host, port):
57 | return {
58 | "Value": "{host}:{port}{base_url}?name={name}".format(
59 | base_url=base_url, name=name, host=host, port=port),
60 | "Version": version, }
61 |
62 |
63 | log = logger.Logger()
64 | #endregion
65 | #endregion
66 |
67 |
68 | #region Main
69 | #region 配置文件分发 APIs
70 | @api.get("/api/v1/client/{client_uid}/manifest")
71 | async def manifest(client_uid:str | None=None, version:int=int(time.time())) -> dict:
72 | log.log("Client {client_uid} get manifest.".format(client_uid=client_uid), QuickValues.Log.info)
73 | host = Settings.conf_dict.get("api", {}).get("prefix", "http://") + Settings.conf_dict.get("api").get("host", "127.0.0.1")
74 | port = Settings.conf_dict.get("api", {}).get("port", 50050)
75 | profile_config = Datas.ProfileConfig.profile_config
76 | base_url = "/api/v1/client/"
77 | config = profile_config.get(client_uid, {"ClassPlan": "default", "TimeLayout": "default", "Subjects": "default",
78 | "Settings": "default", "Policy": "default"})
79 | return {
80 | "ClassPlanSource": await _get_manifest_entry(f"{base_url}ClassPlan", config["ClassPlan"], version, host, port),
81 | "TimeLayoutSource": await _get_manifest_entry(f"{base_url}TimeLayout", config["TimeLayout"], version, host, port),
82 | "SubjectsSource": await _get_manifest_entry(f"{base_url}Subjects", config["Subjects"], version, host, port),
83 | "DefaultSettingsSource": await _get_manifest_entry(f"{base_url}DefaultSettings", config["Settings"], version, host, port),
84 | "PolicySource": await _get_manifest_entry(f"{base_url}Policy", config["Policy"], version, host, port),
85 | "ServerKind": 1,
86 | "OrganizationName": Settings.conf_dict.get("api", {}).get("OrganizationName", "CIMS default organization"),
87 | }
88 |
89 |
90 | @api.get("/api/v1/client/{resource_type}")
91 | async def policy(resource_type, name:str) -> dict:
92 | match resource_type:
93 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
94 | log.log("{resource_type}[{name}] gotten.".format(resource_type=resource_type,name=name), QuickValues.Log.info)
95 | return getattr(Datas, resource_type).read(name)
96 | case _:
97 | log.log("Unexpected {resource_type}[{name}] gotten.".format(resource_type=resource_type, name=name), QuickValues.Log.error)
98 | raise HTTPException(status_code=404)
99 | #endregion
100 |
101 |
102 | #region 外部操作方法
103 | @api.get("/api/refresh")
104 | async def refresh() -> None:
105 | log.log("Settings refreshed.", QuickValues.Log.info)
106 | _ = Settings.refresh
107 | return None
108 | #endregion
109 |
110 |
111 | #region 启动函数
112 | async def start(port:int=50050):
113 | config = uvicorn.Config(app=api, port=port, host="0.0.0.0", log_level="debug")
114 | server = uvicorn.Server(config)
115 | await server.serve()
116 | log.log("API server successfully start on {port}".format(port=port), QuickValues.Log.info)
117 | #endregion
118 | #endregion
119 |
120 |
121 | app=api
122 |
123 |
124 | #region Running directly processor
125 | if __name__ == "__main__":
126 | start()
127 | #endregion
128 |
--------------------------------------------------------------------------------
/ManagementServer.vercel/command.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 | #region Presets
4 | #region 导入项目内建库
5 | import Datas
6 | import logger
7 | import BuildInClasses
8 | import QuickValues
9 | #endregion
10 |
11 |
12 | #region 导入辅助库
13 | import json
14 | #endregion
15 |
16 |
17 | #region 导入 gRPC 库
18 | from ManagementServer import gRPC
19 | #endregion
20 |
21 |
22 | #region 导入 Protobuf 构建文件
23 | from Protobuf.Client import (ClientCommandDeliverScReq_pb2, ClientCommandDeliverScReq_pb2_grpc,
24 | ClientRegisterCsReq_pb2, ClientRegisterCsReq_pb2_grpc)
25 | from Protobuf.Command import (SendNotification_pb2, SendNotification_pb2_grpc,
26 | HeartBeat_pb2, HeartBeat_pb2_grpc)
27 | from Protobuf.Enum import (CommandTypes_pb2, CommandTypes_pb2_grpc,
28 | Retcode_pb2, Retcode_pb2_grpc)
29 | from Protobuf.Server import (ClientCommandDeliverScRsp_pb2, ClientCommandDeliverScRsp_pb2_grpc,
30 | ClientRegisterScRsp_pb2, ClientRegisterScRsp_pb2_grpc)
31 | from Protobuf.Service import (ClientCommandDeliver_pb2, ClientCommandDeliver_pb2_grpc,
32 | ClientRegister_pb2, ClientRegister_pb2_grpc)
33 | #endregion
34 |
35 |
36 | #region 导入 FastAPI 相关库
37 | import uvicorn
38 | from starlette.middleware.cors import CORSMiddleware
39 | from fastapi import FastAPI, Query
40 | from fastapi.requests import Request
41 | from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, PlainTextResponse, RedirectResponse, StreamingResponse
42 | from fastapi.exceptions import HTTPException
43 | #endregion
44 |
45 |
46 | #region 导入配置文件
47 | class _Settings:
48 | def __init__(self):
49 | self.conf_name:str = "settings.json"
50 | self.conf_dict:dict = json.load(open(self.conf_name))
51 |
52 | @property
53 | async def refresh(self) -> dict:
54 | self.conf_dict = json.load(open(self.conf_name))
55 | return self.conf_dict
56 |
57 | Settings = _Settings()
58 | #endregion
59 |
60 |
61 | #region 定义 API 并声明 CORS
62 | command = FastAPI()
63 | command.add_middleware(
64 | CORSMiddleware,
65 | allow_origins=["*"],
66 | allow_methods=["*"],
67 | allow_headers=["*"]
68 | )
69 | #endregion
70 |
71 |
72 | #region 内建辅助函数和辅助参量
73 | log = logger.Logger()
74 | #endregion
75 | #endregion
76 |
77 |
78 | #region Main
79 | #region 客户端配置文件管理相关 API
80 | @command.get("/command/datas/{resource_type}/create")
81 | async def create(resource_type:str, name:str) -> None:
82 | match resource_type:
83 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
84 | log.log("{resource_type}[{name}] Created.".format(resource_type=resource_type, name=name), QuickValues.Log.info)
85 | return getattr(Datas, resource_type).new(name)
86 | case _:
87 | log.log("Unexpected {resource_type}[{name}] not created.".format(resource_type=resource_type, name=name), QuickValues.Log.error)
88 | raise HTTPException(status_code=404)
89 |
90 |
91 | @command.delete("/command/datas/{resource_type}")
92 | @command.delete("/command/datas/{resource_type}/")
93 | @command.delete("/command/datas/{resource_type}/delete")
94 | @command.get("/command/datas/{resource_type}/delete")
95 | async def delete(resource_type:str, name:str) -> None:
96 | match resource_type:
97 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
98 | log.log("{resource_type}[{name}] deleted.".format(resource_type=resource_type, name=name), QuickValues.Log.info)
99 | return getattr(Datas, resource_type).delete(name)
100 | case _:
101 | log.log("Unexpected {resource_type}[{name}] not deleted.".format(resource_type=resource_type, name=name), QuickValues.Log.error)
102 | raise HTTPException(status_code=404)
103 |
104 |
105 | @command.get("/command/datas/{resource_type}/list")
106 | async def _list(resource_type:str) -> list[str]:
107 | match resource_type:
108 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
109 | log.log("List {resource_type}.".format(resource_type=resource_type), QuickValues.Log.info)
110 | return getattr(Datas, resource_type).refresh()
111 | case _:
112 | log.log("Unexpected {resource_type} bot listed..".format(resource_type=resource_type), QuickValues.Log.error)
113 | raise HTTPException(status_code=404)
114 |
115 |
116 | @command.get("/command/datas/{resource_type}/rename")
117 | async def rename(resource_type:str, name:str, target:str) -> None:
118 | match resource_type:
119 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
120 | log.log("Resource {resource_type}[{name}] renamed into {target}".format(resource_type=resource_type, name=name, target=target), QuickValues.Log.info)
121 | return getattr(Datas, resource_type).rename(name, target)
122 | case _:
123 | log.log("Unexpected {resource_type}[{name}] not renamed into {target}".format(resource_type=resource_type, name=name, target=target), QuickValues.Log.error)
124 | raise HTTPException(status_code=404)
125 |
126 |
127 | @command.put("/command/datas/{resource_type}")
128 | @command.put("/command/datas/{resource_type}/")
129 | @command.put("/command/datas/{resource_type}/write")
130 | @command.post("/command/datas/{resource_type}")
131 | @command.post("/command/datas/{resource_type}/")
132 | @command.post("/command/datas/{resource_type}/write")
133 | @command.get("/command/datas/{resource_type}/write")
134 | async def write(resource_type:str, name:str, request:Request):
135 | match resource_type:
136 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
137 | log.log("Resource {resource_type}[{name}] written with {count} bytes.".format(resource_type=resource_type, name=name, count=len(str(request.body()))), QuickValues.Log.info)
138 | return getattr(Datas, resource_type).write(name, await request.body())
139 | case _:
140 | log.log("Resource {resource_type}[{name}] not written with {count} bytes.".format(resource_type=resource_type, name=name, count=len(str(request.body()))), QuickValues.Log.error)
141 | raise HTTPException(status_code=404)
142 | #endregion
143 |
144 |
145 | #region 服务器配置文件管理相关 API
146 | @command.get("/command/server/settings")
147 | async def setting():
148 | log.log("Settings gotten.", QuickValues.Log.info)
149 | return Settings.conf_dict
150 |
151 |
152 | @command.put("/command/server/settings")
153 | @command.post("/command/server/settings")
154 | async def update_settings(request:Request):
155 | log.log("Settings changed.", QuickValues.Log.critical)
156 | with open(Settings.conf_name, "w") as f:
157 | json.dump(request.body(), f)
158 | #endregion
159 |
160 |
161 | #region 客户端信息管理相关 API
162 | @command.get("/command/clients/list")
163 | async def list_client(request: Request):
164 | log.log("List clients from {client}.".format(
165 | client="{host}:{port}".format(host=request.client.host, port=request.client.port)), QuickValues.Log.info)
166 | return Datas.Clients.refresh()
167 |
168 |
169 | @command.get("/command/clients/status")
170 | async def status(request: Request):
171 | log.log("List clients status from {client}.".format(
172 | client="{host}:{port}".format(host=request.client.host, port=request.client.port)), QuickValues.Log.info)
173 | return Datas.ClientStatus.refresh()
174 |
175 |
176 | @command.post("/command/clients/pro_register")
177 | @command.put("/command/clients/pre_register")
178 | @command.get("/command/clients/pre_register")
179 | async def pre_register(id:str, request:Request):
180 | Datas.Clients.pre_register(id=id, conf=request)
181 | #endregion
182 |
183 |
184 | #region 指令下发 API
185 | @command.get("/command/client/{client_uid}/restart")
186 | async def restart(client_uid:str):
187 | await gRPC.command(client_uid, CommandTypes_pb2.RestartApp)
188 |
189 |
190 | @command.get("/command/client/{client_uid}/send_notification")
191 | async def send_notification(client_uid: str,
192 | message_mask: str,
193 | message_content: str,
194 | overlay_icon_left: int = 0,
195 | overlay_icon_right: int = 0,
196 | is_emergency: bool = False,
197 | is_speech_enabled: bool = True,
198 | is_effect_enabled: bool = True,
199 | is_sound_enabled: bool = True,
200 | is_topmost: bool = True,
201 | duration_seconds: float = 5.0,
202 | repeat_counts: int = 1):
203 | await gRPC.command(client_uid, CommandTypes_pb2.SendNotification,
204 | SendNotification_pb2.SendNotification(
205 | MessageMask=message_mask,
206 | MessageContent=message_content,
207 | OverlayIconLeft=overlay_icon_left,
208 | OverlayIconRight=overlay_icon_right,
209 | IsEmergency=is_emergency,
210 | IsSpeechEnabled=is_speech_enabled,
211 | IsEffectEnabled=is_effect_enabled,
212 | IsSoundEnabled=is_sound_enabled,
213 | IsTopmost=is_topmost,
214 | DurationSeconds=duration_seconds,
215 | RepeatCounts=repeat_counts
216 | ).SerializeToString())
217 |
218 | @command.get("/command/client/{client_uid}/update_data")
219 | async def update_data(client_uid:str):
220 | await gRPC.command(client_uid, CommandTypes_pb2.DataUpdated)
221 | #endregion
222 |
223 |
224 | #region 外部操作方法
225 | @command.get("/api/refresh")
226 | async def refresh() -> None:
227 | log.log("Settings refreshed.", QuickValues.Log.info)
228 | _ = Settings.refresh
229 | return None
230 | #endregion
231 |
232 |
233 | #region 启动函数
234 | async def start(port:int=50052):
235 | config = uvicorn.Config(app=command, port=port, host="0.0.0.0", log_level="error", access_log=False)
236 | server = uvicorn.Server(config)
237 | await server.serve()
238 | log.log("Command backend successfully start on {port}".format(port=port), QuickValues.Log.info)
239 | #endregion
240 | #endregion
241 |
242 |
243 | app=command
244 |
245 |
246 | #region Running directly processor
247 | if __name__ == "__main__":
248 | start()
249 | #endregion
250 |
--------------------------------------------------------------------------------
/ManagementServer.vercel/gRPC.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 |
4 | #region Presets
5 | #region 导入项目内建库
6 | import Datas
7 | import logger
8 | import BuildInClasses
9 | import QuickValues
10 | #endregion
11 |
12 |
13 | #region 导入辅助库
14 | import grpc.aio
15 | import json
16 | import os
17 | import time
18 | import uuid
19 | from concurrent.futures import ThreadPoolExecutor
20 |
21 | from fastapi import HTTPException
22 | #endregion
23 |
24 |
25 | #region 导入 Protobuf 构建文件
26 | from Protobuf.Client import (ClientCommandDeliverScReq_pb2, ClientCommandDeliverScReq_pb2_grpc,
27 | ClientRegisterCsReq_pb2, ClientRegisterCsReq_pb2_grpc)
28 | from Protobuf.Command import (SendNotification_pb2, SendNotification_pb2_grpc,
29 | HeartBeat_pb2, HeartBeat_pb2_grpc)
30 | from Protobuf.Enum import (CommandTypes_pb2, CommandTypes_pb2_grpc,
31 | Retcode_pb2, Retcode_pb2_grpc)
32 | from Protobuf.Server import (ClientCommandDeliverScRsp_pb2, ClientCommandDeliverScRsp_pb2_grpc,
33 | ClientRegisterScRsp_pb2, ClientRegisterScRsp_pb2_grpc)
34 | from Protobuf.Service import (ClientCommandDeliver_pb2, ClientCommandDeliver_pb2_grpc,
35 | ClientRegister_pb2, ClientRegister_pb2_grpc)
36 | #endregion
37 |
38 |
39 | #region 导入配置文件
40 | class _Settings:
41 | def __init__(self):
42 | self.conf_name:str = "settings.json"
43 | self.conf_dict:dict = json.load(open(self.conf_name))
44 |
45 | @property
46 | async def refresh(self) -> dict:
47 | self.conf_dict = json.load(open(self.conf_name))
48 | return self.conf_dict
49 |
50 | Settings = _Settings()
51 | #endregion
52 |
53 |
54 | #region 内建辅助函数和辅助参量
55 | log = logger.Logger()
56 | #endregion
57 | #endregion
58 |
59 |
60 | #region Main
61 | # region 命令传递通道服务
62 | class ClientCommandDeliverServicer(ClientCommandDeliver_pb2_grpc.ClientCommandDeliverServicer):
63 | _instance = None
64 |
65 | def __new__(cls, *args, **kwargs):
66 | if not cls._instance:
67 | cls._instance = super(ClientCommandDeliverServicer, cls).__new__(cls, *args, **kwargs)
68 | cls._instance.clients = {}
69 | cls._instance.executor = ThreadPoolExecutor(max_workers=10)
70 | return cls._instance
71 |
72 | async def ListenCommand(self, request_iterator, context: grpc.aio.ServicerContext):
73 | metadata = context.invocation_metadata()
74 | client_uid = "" # Initialize client_uid
75 | for m in metadata: # Iterate through the metadata list
76 | if m.key == 'cuid':
77 | client_uid = m.value
78 | break # find it then break.
79 |
80 | if not client_uid:
81 | await context.abort(grpc.StatusCode.INVALID_ARGUMENT, "Client UID is required.")
82 | return
83 | log.log("Client {client_uid} connected.".format(client_uid=client_uid), QuickValues.Log.info)
84 | self.clients[client_uid] = context
85 | Datas.ClientStatus.update(client_uid)
86 |
87 | try:
88 | async for request in request_iterator:
89 | if request.Type == CommandTypes_pb2.Ping:
90 | Datas.ClientStatus.update(client_uid)
91 | log.log("Receive ping from {client_uid}".format(client_uid=client_uid), QuickValues.Log.info)
92 | await context.write(ClientCommandDeliverScRsp_pb2.ClientCommandDeliverScRsp(
93 | RetCode=Retcode_pb2.Success,
94 | Type=CommandTypes_pb2.Pong
95 | ))
96 | else:
97 | log.log("Unexpected request {request} received from {client_uid}".format(request=request,
98 | client_uid=client_uid))
99 | except Exception as e:
100 | log.log("Client {client_uid} disconnected: {e}".format(client_uid=client_uid, e=e), QuickValues.Log.info)
101 | finally:
102 | self.clients.pop(client_uid, None)
103 | Datas.ClientStatus.offline(client_uid)
104 |
105 |
106 | #endregion
107 |
108 |
109 | #region 命令推送器
110 | async def command(client_uid:str, command_type:CommandTypes_pb2.CommandTypes, payload:bytes=b''):
111 | servicer = ClientCommandDeliverServicer()
112 | if client_uid not in servicer.clients:
113 | log.log("Send {command} to {client_uid}, failed.".format(command=command_type, client_uid=client_uid), QuickValues.Log.error)
114 | raise HTTPException(status_code=404, detail=f"Client not found or not connected: {client_uid}")
115 | log.log("Send {command} to {client_uid}".format(command=command_type, client_uid=client_uid), QuickValues.Log.info)
116 | await servicer.clients[client_uid].write(ClientCommandDeliver_pb2.ClientCommandDeliverScRsp(
117 | RetCode=Retcode_pb2.Success,
118 | Type=command_type,
119 | Payload=payload
120 | ))
121 | #endregion
122 |
123 |
124 | #region 注册服务
125 | class ClientRegisterServicer(ClientRegister_pb2_grpc.ClientRegisterServicer):
126 | async def Register(self, request:ClientRegisterCsReq_pb2.ClientRegisterCsReq,
127 | context:grpc.aio.ServicerContext) -> ClientRegisterScRsp_pb2.ClientRegisterScRsp:
128 | clients = Datas.Clients.refresh()
129 | client_uid = request.clientUid
130 | client_id = request.clientId
131 | Datas.Clients.register(client_uid, client_id)
132 | if client_uid in clients:
133 | log.log("Client {client_uid} registered as {client_id}, but register again.".format(
134 | client_uid=client_uid, client_id=client_id), QuickValues.Log.warning)
135 | return ClientRegisterScRsp_pb2.ClientRegisterScRsp(Retcode=Retcode_pb2.Registered,
136 | Message=f"Client already registered: {client_uid}")
137 | else:
138 | Datas.ClientStatus.register(client_uid, client_id)
139 | log.log("Client {client_uid} registered as {client_id}".format(
140 | client_uid=client_uid, client_id=client_id), QuickValues.Log.info)
141 | return ClientRegisterScRsp_pb2.ClientRegisterScRsp(Retcode=Retcode_pb2.Success,
142 | Message=f"Client registered: {client_uid}")
143 |
144 | async def UnRegister(self, request, context):
145 | return ClientRegisterScRsp_pb2.ClientRegisterScRsp(Retcode=Retcode_pb2.ServerInternalError,
146 | Message="Not implemented")
147 | #endregion
148 |
149 |
150 | #region 启动函数
151 | async def start(port=50051):
152 | server = grpc.aio.server()
153 | ClientRegister_pb2_grpc.add_ClientRegisterServicer_to_server(ClientRegisterServicer(), server)
154 | ClientCommandDeliver_pb2_grpc.add_ClientCommandDeliverServicer_to_server(ClientCommandDeliverServicer(), server)
155 | server.add_insecure_port("0.0.0.0:{port}".format(port=port))
156 | log.log("Starting gRPC server on {listen_addr}".format(listen_addr="0.0.0.0:{port}".format(port=port)), QuickValues.Log.info)
157 | await server.start()
158 | await server.wait_for_termination()
159 | #endregion
160 | #endregion
161 |
162 |
163 | #region Running Directly processor
164 | if __name__ == "__main__":
165 | start()
166 | #endregion
167 |
--------------------------------------------------------------------------------
/ManagementServer/__init__.py:
--------------------------------------------------------------------------------
1 | from . import api, gRPC, command
2 |
--------------------------------------------------------------------------------
/ManagementServer/api.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 |
4 | #region Presets
5 | #region 导入项目内建库
6 | import Datas
7 | import logger
8 | import BuildInClasses
9 | import QuickValues
10 | #endregion
11 |
12 |
13 | #region 导入辅助库
14 | import time
15 | import json
16 | #endregion
17 |
18 |
19 | #region 导入 FastAPI 相关库
20 | import uvicorn
21 | from starlette.middleware.cors import CORSMiddleware
22 | from fastapi import FastAPI, Query
23 | from fastapi.requests import Request
24 | from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, PlainTextResponse, RedirectResponse, \
25 | StreamingResponse
26 | from fastapi.exceptions import HTTPException
27 |
28 |
29 | #endregion
30 |
31 |
32 | #region 导入配置文件
33 | class _Settings:
34 | def __init__(self):
35 | self.conf_name: str = "settings.json"
36 | self.conf_dict: dict = json.load(open(self.conf_name))
37 |
38 | async def refresh(self) -> dict:
39 | self.conf_dict = json.load(open(self.conf_name))
40 | return self.conf_dict
41 |
42 |
43 | Settings = _Settings()
44 | #endregion
45 |
46 |
47 | #region 定义 API
48 | api = FastAPI()
49 | api.add_middleware(
50 | CORSMiddleware,
51 | allow_origins=["*"],
52 | allow_methods=["*"],
53 | allow_headers=["*"]
54 | )
55 |
56 |
57 | #endregion
58 |
59 |
60 | #region 内建辅助函数和辅助参量
61 | async def _get_manifest_entry(base_url, name, version, host, port):
62 | return {
63 | "Value": "{host}:{port}{base_url}?name={name}".format(
64 | base_url=base_url, name=name, host=host, port=port),
65 | "Version": version, }
66 |
67 |
68 | log = logger.Logger()
69 |
70 |
71 | #endregion
72 | #endregion
73 |
74 |
75 | #region Main
76 | #region 配置文件分发 APIs
77 | @api.get("/api/v1/client/{client_uid}/manifest")
78 | async def manifest(client_uid: str | None = None, version: int = int(time.time())) -> dict:
79 | log.log("Client {client_uid} get manifest.".format(client_uid=client_uid), QuickValues.Log.info)
80 | host = (Settings.conf_dict.get("api", {}).get("prefix", "http") + "://" +
81 | Settings.conf_dict.get("api", {}).get("host", "127.0.0.1"))
82 | port = Settings.conf_dict.get("api", {}).get("mp_port", 50050)
83 |
84 | profile_config = Datas.ProfileConfig.refresh()
85 | base_url = "/api/v1/client/"
86 | config = profile_config.get(client_uid, {"ClassPlan": "default", "TimeLayout": "default", "Subjects": "default",
87 | "Settings": "default", "Policy": "default"})
88 | return {
89 | "ClassPlanSource": await _get_manifest_entry(f"{base_url}ClassPlan", config["ClassPlan"], version, host, port),
90 | "TimeLayoutSource": await _get_manifest_entry(f"{base_url}TimeLayout", config["TimeLayout"], version, host,
91 | port),
92 | "SubjectsSource": await _get_manifest_entry(f"{base_url}Subjects", config["Subjects"], version, host, port),
93 | "DefaultSettingsSource": await _get_manifest_entry(f"{base_url}DefaultSettings", config["Settings"], version,
94 | host, port),
95 | "PolicySource": await _get_manifest_entry(f"{base_url}Policy", config["Policy"], version, host, port),
96 | "ServerKind": 1,
97 | "OrganizationName": Settings.conf_dict.get("api", {}).get("OrganizationName", "CIMS default organization"),
98 | }
99 |
100 |
101 | @api.get("/api/v1/client/{resource_type}")
102 | async def policy(resource_type, name: str) -> dict:
103 | match resource_type:
104 | case "ClassPlan" | "DefaultSettings" | "Policy" | "Subjects" | "TimeLayout":
105 | log.log("{resource_type}[{name}] gotten.".format(resource_type=resource_type, name=name),
106 | QuickValues.Log.info)
107 | return getattr(Datas, resource_type).read(name)
108 | case _:
109 | log.log("Unexpected {resource_type}[{name}] gotten.".format(resource_type=resource_type, name=name),
110 | QuickValues.Log.error)
111 | raise HTTPException(status_code=404)
112 |
113 |
114 | #endregion
115 |
116 |
117 | #region 外部操作方法
118 | @api.get("/api/refresh")
119 | async def refresh() -> None:
120 | log.log("Settings refreshed.", QuickValues.Log.info)
121 | _ = Settings.refresh
122 | return None
123 |
124 |
125 | #endregion
126 |
127 |
128 | #region 启动函数
129 | async def start(port: int = 50050):
130 | config = uvicorn.Config(app=api, port=port, host="0.0.0.0", log_level="debug")
131 | server = uvicorn.Server(config)
132 | await server.serve()
133 | log.log("API server successfully start on {port}".format(port=port), QuickValues.Log.info)
134 |
135 |
136 | #endregion
137 | #endregion
138 |
139 |
140 | #region Running directly processor
141 | if __name__ == "__main__":
142 | log.log(message="Directly started, refused.", status=QuickValues.Log.error)
143 | #endregion
144 |
--------------------------------------------------------------------------------
/ManagementServer/command.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 | #region Presets
4 | #region 导入项目内建库
5 | import Datas
6 | import logger
7 | import BuildInClasses
8 | import QuickValues
9 | #endregion
10 |
11 |
12 | #region 导入辅助库
13 | import json
14 | import time
15 | import asyncio
16 | #endregion
17 |
18 |
19 | #region 导入 gRPC 库
20 | from ManagementServer import gRPC
21 | #endregion
22 |
23 |
24 | #region 导入 Protobuf 构建文件
25 | from Protobuf.Client import (ClientCommandDeliverScReq_pb2, ClientCommandDeliverScReq_pb2_grpc,
26 | ClientRegisterCsReq_pb2, ClientRegisterCsReq_pb2_grpc)
27 | from Protobuf.Command import (SendNotification_pb2, SendNotification_pb2_grpc,
28 | HeartBeat_pb2, HeartBeat_pb2_grpc)
29 | from Protobuf.Enum import (CommandTypes_pb2, CommandTypes_pb2_grpc,
30 | Retcode_pb2, Retcode_pb2_grpc)
31 | from Protobuf.Server import (ClientCommandDeliverScRsp_pb2, ClientCommandDeliverScRsp_pb2_grpc,
32 | ClientRegisterScRsp_pb2, ClientRegisterScRsp_pb2_grpc)
33 | from Protobuf.Service import (ClientCommandDeliver_pb2, ClientCommandDeliver_pb2_grpc,
34 | ClientRegister_pb2, ClientRegister_pb2_grpc)
35 | #endregion
36 |
37 |
38 | #region 导入 FastAPI 相关库
39 | import uvicorn
40 | from starlette.middleware.cors import CORSMiddleware
41 | from fastapi import FastAPI, Query, Body, Request, HTTPException
42 | from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, PlainTextResponse, RedirectResponse, \
43 | StreamingResponse
44 |
45 |
46 | #endregion
47 |
48 |
49 | #region 导入配置文件
50 | class _Settings:
51 | def __init__(self):
52 | self.conf_name: str = "settings.json"
53 | self.conf_dict: dict = json.load(open(self.conf_name))
54 |
55 | async def refresh(self) -> dict:
56 | self.conf_dict = json.load(open(self.conf_name))
57 | return self.conf_dict
58 |
59 |
60 | Settings = _Settings()
61 | #endregion
62 |
63 |
64 | #region 定义 API 并声明 CORS
65 | command = FastAPI()
66 | command.add_middleware(
67 | CORSMiddleware,
68 | allow_origins=["*"],
69 | allow_credentials=True,
70 | allow_methods=["*"],
71 | allow_headers=["*"]
72 | )
73 | #endregion
74 |
75 |
76 | #region 内建辅助函数和辅助参量
77 | log = logger.Logger()
78 | RESOURCE_TYPES = ["ClassPlan", "DefaultSettings", "Policy", "Subjects", "TimeLayout"]
79 |
80 |
81 | #endregion
82 | #endregion
83 |
84 |
85 | #region Main
86 | #region 客户端配置文件管理相关 API (/command/datas/)
87 | @command.get("/command/datas/{resource_type}/create", summary="创建配置文件", tags=["配置文件管理"])
88 | async def create(resource_type: str, name: str):
89 | """创建新的配置文件。"""
90 | if resource_type in RESOURCE_TYPES:
91 | log.log(f"尝试创建配置文件:类型={resource_type}, 名称={name}", QuickValues.Log.info)
92 | try:
93 | getattr(Datas, resource_type).new(name)
94 | log.log(f"配置文件 {resource_type}[{name}] 已创建。", QuickValues.Log.info)
95 | return {"message": f"配置文件 {resource_type}[{name}] 已创建。"}
96 | except FileExistsError as e:
97 | log.log(f"创建失败:{e}", QuickValues.Log.warning)
98 | raise HTTPException(status_code=409, detail=str(e)) # 409 Conflict
99 | except Exception as e:
100 | log.log(f"创建配置文件 {resource_type}[{name}] 时发生错误: {e}", QuickValues.Log.error)
101 | raise HTTPException(status_code=500, detail=f"创建文件时出错: {e}")
102 | else:
103 | raise HTTPException(status_code=404, detail=f"无效的资源类型: {resource_type}")
104 |
105 |
106 | @command.delete("/command/datas/{resource_type}")
107 | @command.delete("/command/datas/{resource_type}/")
108 | @command.delete("/command/datas/{resource_type}/delete")
109 | @command.get("/command/datas/{resource_type}/delete")
110 | async def delete(resource_type: str, name: str):
111 | """删除指定的配置文件。"""
112 | if resource_type in RESOURCE_TYPES:
113 | log.log(f"尝试删除配置文件:类型={resource_type}, 名称={name}", QuickValues.Log.info)
114 | try:
115 | getattr(Datas, resource_type).delete(name)
116 | log.log(f"配置文件 {resource_type}[{name}] 已删除。", QuickValues.Log.info)
117 | return {"message": f"配置文件 {resource_type}[{name}] 已删除。"}
118 | except FileNotFoundError as e:
119 | log.log(f"删除失败:{e}", QuickValues.Log.warning)
120 | raise HTTPException(status_code=404, detail=str(e))
121 | except Exception as e:
122 | log.log(f"删除配置文件 {resource_type}[{name}] 时发生错误: {e}", QuickValues.Log.error)
123 | raise HTTPException(status_code=500, detail=f"删除文件时出错: {e}")
124 | else:
125 | raise HTTPException(status_code=404, detail=f"无效的资源类型: {resource_type}")
126 |
127 |
128 | @command.get("/command/datas/{resource_type}/list")
129 | async def list_config_files(resource_type: str) -> list[str]:
130 | """列出指定类型的配置文件。"""
131 | if resource_type in RESOURCE_TYPES:
132 | log.log(f"尝试列出配置文件:类型={resource_type}", QuickValues.Log.info)
133 | try:
134 | # Datas.Resource.refresh() 返回列表
135 | return getattr(Datas, resource_type).refresh()
136 | except Exception as e:
137 | log.log(f"列出配置文件 {resource_type} 时发生错误: {e}", QuickValues.Log.error)
138 | raise HTTPException(status_code=500, detail=f"列出文件时出错: {e}")
139 | else:
140 | raise HTTPException(status_code=404, detail=f"无效的资源类型: {resource_type}")
141 |
142 |
143 | @command.put("/command/datas/{resource_type}/rename", summary="重命名配置文件", tags=["配置文件管理"])
144 | async def rename(resource_type: str, name: str, target: str):
145 | """重命名配置文件。"""
146 | if resource_type in RESOURCE_TYPES:
147 | log.log(f"尝试重命名配置文件:类型={resource_type}, 原名称={name}, 新名称={target}", QuickValues.Log.info)
148 | if not target: # 目标名称不能为空
149 | raise HTTPException(status_code=400, detail="目标名称不能为空。")
150 | try:
151 | getattr(Datas, resource_type).rename(name, target)
152 | log.log(f"配置文件 {resource_type}[{name}] 已重命名为 {target}。", QuickValues.Log.info)
153 | return {"message": f"配置文件 {resource_type}[{name}] 已重命名为 {target}。"}
154 | except FileNotFoundError as e:
155 | log.log(f"重命名失败:{e}", QuickValues.Log.warning)
156 | raise HTTPException(status_code=404, detail=str(e))
157 | except FileExistsError as e:
158 | log.log(f"重命名失败:{e}", QuickValues.Log.warning)
159 | raise HTTPException(status_code=409, detail=str(e)) # 409 Conflict
160 | except Exception as e:
161 | log.log(f"重命名配置文件 {resource_type}[{name}] 时发生错误: {e}", QuickValues.Log.error)
162 | raise HTTPException(status_code=500, detail=f"重命名文件时出错: {e}")
163 | else:
164 | raise HTTPException(status_code=404, detail=f"无效的资源类型: {resource_type}")
165 |
166 |
167 | @command.put("/command/datas/{resource_type}")
168 | @command.put("/command/datas/{resource_type}/")
169 | @command.put("/command/datas/{resource_type}/write")
170 | @command.post("/command/datas/{resource_type}")
171 | @command.post("/command/datas/{resource_type}/")
172 | @command.post("/command/datas/{resource_type}/write")
173 | @command.get("/command/datas/{resource_type}/write")
174 | async def write(resource_type: str, name: str, request: Request):
175 | """写入配置文件内容 (期望 Body 为 JSON)。"""
176 | if resource_type in RESOURCE_TYPES:
177 | body = await request.body()
178 | content_length = len(body)
179 | log.log(f"尝试写入配置文件:类型={resource_type}, 名称={name}, 大小={content_length}字节", QuickValues.Log.info)
180 | try:
181 | # 将 body 解码并解析为 dict
182 | data_dict = json.loads(body.decode('utf-8'))
183 | getattr(Datas, resource_type).write(name, data_dict) # Datas.Resource.write 需要 dict
184 | log.log(f"配置文件 {resource_type}[{name}] 已写入 {content_length} 字节。", QuickValues.Log.info)
185 | return {"message": f"配置文件 {resource_type}[{name}] 已写入 {content_length} 字节。"}
186 | except FileNotFoundError as e:
187 | log.log(f"写入失败:{e}", QuickValues.Log.warning)
188 | raise HTTPException(status_code=404, detail=str(e))
189 | except json.JSONDecodeError:
190 | log.log(f"写入配置文件 {resource_type}[{name}] 失败: 请求体不是有效的 JSON。", QuickValues.Log.error)
191 | raise HTTPException(status_code=400, detail="请求体不是有效的 JSON 数据。")
192 | except Exception as e:
193 | log.log(f"写入配置文件 {resource_type}[{name}] 失败: {e}", QuickValues.Log.error)
194 | raise HTTPException(status_code=500, detail=f"写入文件时出错: {e}")
195 | else:
196 | raise HTTPException(status_code=404, detail=f"无效的资源类型: {resource_type}")
197 |
198 |
199 | #endregion
200 |
201 |
202 | #region 服务器配置文件管理相关 API (/command/server/)
203 | @command.get("/command/server/settings")
204 | async def get_settings() -> dict:
205 | """获取当前服务器的配置信息。"""
206 | log.log("请求获取服务器配置。", QuickValues.Log.info)
207 | await Settings.refresh()
208 | return Settings.conf_dict
209 |
210 |
211 | @command.put("/command/server/settings")
212 | @command.post("/command/server/settings")
213 | async def update_settings(request: Request):
214 | """使用请求体中的 JSON 数据更新服务器配置文件。"""
215 | log.log("尝试更新服务器配置。", QuickValues.Log.critical)
216 | try:
217 | new_settings = await request.json()
218 | # 可以在这里添加验证逻辑,确保新设置包含必要字段
219 | with open(Settings.conf_name, "w", encoding='utf-8') as f:
220 | json.dump(new_settings, f)
221 | await Settings.refresh()
222 | log.log("服务器配置已更新。", QuickValues.Log.info)
223 | # 可能需要通知其他模块配置已更改
224 | return {"message": "服务器配置已成功更新。"}
225 | except json.JSONDecodeError:
226 | log.log("更新服务器配置失败:请求体不是有效的 JSON。", QuickValues.Log.error)
227 | raise HTTPException(status_code=400, detail="请求体不是有效的 JSON 数据。")
228 | except IOError as e:
229 | log.log(f"更新服务器配置失败:写入文件时发生错误: {e}", QuickValues.Log.error)
230 | raise HTTPException(status_code=500, detail=f"写入配置文件时发生错误: {e}")
231 |
232 |
233 | @command.get("/command/server/version")
234 | async def version() -> dict:
235 | """获取服务器的版本和组织名称等信息。"""
236 | log.log("Server ver gotten.", QuickValues.Log.info)
237 | await Settings.refresh()
238 | with open("project_info.json") as pi:
239 | return {
240 | "backend_version": json.load(pi)["version"],
241 | "organization_name": Settings.conf_dict["organization_name"]
242 | }
243 |
244 |
245 | @command.get("/command/server/ManagementPreset.json")
246 | async def mp():
247 | """提供用于下载集控预设配置文件的接口。"""
248 | log.log("请求下载集控预设配置。", QuickValues.Log.info)
249 | with open("ManagementPreset.json", "w") as mp:
250 | json.dump({
251 | "ManagementServerKind": 1,
252 | "ManagementServer": "{prefix}://{host}:{port}".format(prefix=Settings.conf_dict["api"]["prefix"],
253 | host=Settings.conf_dict["api"]["host"],
254 | port=Settings.conf_dict["api"]["mp_port"]),
255 | "ManagementServerGrpc": "{prefix}://{host}:{port}".format(prefix=Settings.conf_dict["gRPC"]["prefix"],
256 | host=Settings.conf_dict["gRPC"]["host"],
257 | port=Settings.conf_dict["gRPC"]["mp_port"])
258 | }, mp)
259 | return FileResponse("ManagementPreset.json")
260 |
261 |
262 | @command.get("/command/server/export")
263 | def export_server_data():
264 | """提供用于导出服务器所有配置数据的接口。"""
265 | raise NotImplementedError
266 |
267 |
268 | #endregion
269 |
270 |
271 | #region 客户端信息管理相关 API (/command/clients/)
272 | @command.get("/command/clients/list")
273 | async def list_clients(request: Request) -> list[str]:
274 | """获取所有已注册客户端的 UID 列表。"""
275 | log.log(f"来自 {request.client.host}:{request.client.port} 的请求,列出已注册客户端 UID。", QuickValues.Log.info)
276 | try:
277 | return list(Datas.Clients.refresh().keys()) # Clients.clients 是 dict
278 | except Exception as e:
279 | log.log(f"获取客户端列表时出错: {e}", QuickValues.Log.error)
280 | raise HTTPException(status_code=500, detail="获取客户端列表失败。")
281 |
282 |
283 | @command.get("/command/clients/status")
284 | async def list_client_status(request: Request) -> list[dict]:
285 | """获取所有客户端的综合状态信息(包括名称、UID、在线状态等)。"""
286 | log.log(f"来自 {request.client.host}:{request.client.port} 的请求,获取客户端状态。", QuickValues.Log.info)
287 | try:
288 | clients_data = Datas.Clients.refresh() # uid: id (name)
289 | status_data = Datas.ClientStatus.refresh() # uid: {isOnline, lastHeartbeat}
290 | result = []
291 | known_uids = set(clients_data.keys()) | set(status_data.keys())
292 |
293 | for uid in known_uids:
294 | client_info = {
295 | "uid": uid,
296 | "name": clients_data.get(uid, "未知名称"), # 从 clients.json 获取名称
297 | "status": "unknown",
298 | "last_seen": None
299 | }
300 | if uid in status_data:
301 | client_info["status"] = "online" if status_data[uid].get("isOnline", False) else "offline"
302 | last_hb = status_data[uid].get("lastHeartbeat")
303 | if last_hb:
304 | # 转换为易读的时间格式
305 | try:
306 | client_info["last_seen"] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last_hb))
307 | except ValueError: # 时间戳可能无效
308 | client_info["last_seen"] = "无效时间戳"
309 | else:
310 | # 在 clients.json 中但不在 status.json 中的,视为从未连接或状态未知
311 | client_info["status"] = "unknown"
312 |
313 | result.append(client_info)
314 |
315 | return result
316 | except Exception as e:
317 | log.log(f"获取客户端状态时出错: {e}", QuickValues.Log.error)
318 | raise HTTPException(status_code=500, detail="获取客户端状态失败。")
319 |
320 |
321 | @command.post("/command/clients/pre_register")
322 | @command.put("/command/clients/pre_register")
323 | @command.get("/command/clients/pre_register")
324 | async def pre_register_client(data: dict = Body(...)):
325 | """预先注册一个客户端,并指定其配置。 Body: {"id": "client_id", "config": {"ClassPlan": ...}}"""
326 | client_id = data.get("id")
327 | config = data.get("config")
328 | if not client_id:
329 | raise HTTPException(status_code=400, detail="缺少客户端 ID 'id'。")
330 | if config is not None and not isinstance(config, dict):
331 | raise HTTPException(status_code=400, detail="'config' 必须是一个字典。")
332 |
333 | log.log(f"尝试预注册客户端:ID={client_id}, 配置={config}", QuickValues.Log.info)
334 | try:
335 | # Datas.ProfileConfig.pre_register 会处理 None config
336 | Datas.ProfileConfig.pre_register(id=client_id, conf=config)
337 | log.log(f"客户端 {client_id} 已预注册。", QuickValues.Log.info)
338 | return {"message": f"客户端 {client_id} 已成功预注册。"}
339 | except Exception as e:
340 | log.log(f"预注册客户端 {client_id} 失败: {e}", QuickValues.Log.error)
341 | raise HTTPException(status_code=500, detail=f"预注册失败: {e}")
342 |
343 |
344 | @command.get("/command/clients/pre_registered/list", summary="列出预注册客户端", tags=["客户端管理"])
345 | async def list_pre_registered_clients(request: Request) -> list[dict]:
346 | """获取所有已预注册但尚未连接的客户端及其配置。"""
347 | log.log(f"来自 {request.client.host}:{request.client.port} 的请求,列出预注册客户端。", QuickValues.Log.info)
348 | try:
349 | # 从 Datas.ProfileConfig 读取 pre_registers
350 | pre_reg_data = Datas.ProfileConfig.pre_registers
351 | # 转换为列表格式
352 | result = [{"id": id, "config": config} for id, config in pre_reg_data.items()]
353 | return result
354 | except Exception as e:
355 | log.log(f"获取预注册列表时出错: {e}", QuickValues.Log.error)
356 | raise HTTPException(status_code=500, detail="获取预注册列表失败。")
357 |
358 |
359 | @command.delete("/command/clients/pre_registered/delete", summary="删除预注册客户端", tags=["客户端管理"])
360 | async def delete_pre_registered_client(client_id: str = Query(..., description="要删除的预注册客户端 ID")):
361 | """删除一个预注册的客户端条目。"""
362 | log.log(f"尝试删除预注册客户端:ID={client_id}", QuickValues.Log.info)
363 | try:
364 | if client_id in Datas.ProfileConfig.pre_registers:
365 | del Datas.ProfileConfig.pre_registers[client_id]
366 | # 持久化更改
367 | with open("Datas/pre_register.json", "w", encoding="utf-8") as f:
368 | json.dump(Datas.ProfileConfig.pre_registers, f)
369 | log.log(f"预注册客户端 {client_id} 已删除。", QuickValues.Log.info)
370 | return {"message": f"预注册客户端 {client_id} 已成功删除。"}
371 | else:
372 | raise HTTPException(status_code=404, detail=f"预注册客户端 ID '{client_id}' 未找到。")
373 | except Exception as e:
374 | log.log(f"删除预注册客户端 {client_id} 失败: {e}", QuickValues.Log.error)
375 | raise HTTPException(status_code=500, detail=f"删除预注册条目失败: {e}")
376 |
377 |
378 | @command.put("/command/clients/pre_registered/update", summary="更新预注册客户端配置", tags=["客户端管理"])
379 | async def update_pre_registered_client(data: dict = Body(...)):
380 | """更新一个已预注册客户端的配置。 Body: {"id": "client_id", "config": {"ClassPlan": ...}}"""
381 | client_id = data.get("id")
382 | config = data.get("config")
383 | if not client_id:
384 | raise HTTPException(status_code=400, detail="缺少客户端 ID 'id'。")
385 | if not isinstance(config, dict): # config 必须提供且为字典
386 | raise HTTPException(status_code=400, detail="'config' 必须提供且为一个字典。")
387 |
388 | log.log(f"尝试更新预注册客户端配置:ID={client_id}, 新配置={config}", QuickValues.Log.info)
389 | try:
390 | if client_id in Datas.ProfileConfig.pre_registers:
391 | Datas.ProfileConfig.pre_registers[client_id] = config
392 | # 持久化更改
393 | with open("Datas/pre_register.json", "w", encoding="utf-8") as f:
394 | json.dump(Datas.ProfileConfig.pre_registers, f)
395 | log.log(f"预注册客户端 {client_id} 的配置已更新。", QuickValues.Log.info)
396 | return {"message": f"预注册客户端 {client_id} 的配置已成功更新。"}
397 | else:
398 | raise HTTPException(status_code=404, detail=f"预注册客户端 ID '{client_id}' 未找到。")
399 | except Exception as e:
400 | log.log(f"更新预注册客户端 {client_id} 失败: {e}", QuickValues.Log.error)
401 | raise HTTPException(status_code=500, detail=f"更新预注册条目失败: {e}")
402 |
403 |
404 | #endregion
405 |
406 |
407 | #region 客户端管理 API (/command/client/)
408 | #region 客户端信息管理 API
409 | @command.get("/command/client/{client_uid}/details", summary="获取单个客户端详情", tags=["客户端管理"])
410 | async def get_client_details(client_uid: str, request: Request) -> dict:
411 | """获取指定客户端的详细信息,包括配置。"""
412 | log.log(f"来自 {request.client.host}:{request.client.port} 的请求,获取客户端 {client_uid} 的详情。",
413 | QuickValues.Log.info)
414 | try:
415 | # 组合来自 status 和 profile_config 的信息
416 | all_statuses = await list_client_status(request) # 复用上面的函数获取基本状态
417 | client_detail = next((client for client in all_statuses if client["uid"] == client_uid), None)
418 |
419 | if not client_detail:
420 | # 也许只在 pre_register 里?
421 | pre_reg_info = Datas.ProfileConfig.pre_registers.get(client_uid)
422 | if pre_reg_info:
423 | client_detail = {"uid": client_uid, "name": "预注册设备", "status": "pre-registered",
424 | "config_profile": pre_reg_info}
425 | else:
426 | raise HTTPException(status_code=404, detail=f"客户端 {client_uid} 未找到。")
427 |
428 | # 获取配置信息
429 | profile_config = Datas.ProfileConfig.profile_config.get(client_uid, {})
430 | client_detail["config_profile"] = profile_config
431 |
432 | # 可以补充其他信息,例如从 gRPC 连接状态获取 IP 等(如果 gRPC 层提供)
433 | # client_detail["ip_address"] = gRPC.get_client_ip(client_uid) # 假设有此方法
434 |
435 | return client_detail
436 | except HTTPException:
437 | raise # 重新抛出 404
438 | except Exception as e:
439 | log.log(f"获取客户端 {client_uid} 详情时出错: {e}", QuickValues.Log.error)
440 | raise HTTPException(status_code=500, detail="获取客户端详情失败。")
441 |
442 |
443 | #endregion
444 |
445 |
446 | #region 客户端指令下发 API
447 | @command.get("/command/client/{client_uid}/restart")
448 | async def restart(client_uid: str):
449 | await gRPC.command(client_uid, CommandTypes_pb2.RestartApp)
450 |
451 |
452 | @command.get("/command/client/{client_uid}/send_notification")
453 | async def send_notification(client_uid: str,
454 | message_mask: str,
455 | message_content: str,
456 | overlay_icon_left: int = 0,
457 | overlay_icon_right: int = 0,
458 | is_emergency: bool = False,
459 | is_speech_enabled: bool = True,
460 | is_effect_enabled: bool = True,
461 | is_sound_enabled: bool = True,
462 | is_topmost: bool = True,
463 | duration_seconds: float = 5.0,
464 | repeat_counts: int = 1):
465 | await gRPC.command(client_uid, CommandTypes_pb2.SendNotification,
466 | SendNotification_pb2.SendNotification(
467 | MessageMask=message_mask,
468 | MessageContent=message_content,
469 | OverlayIconLeft=overlay_icon_left,
470 | OverlayIconRight=overlay_icon_right,
471 | IsEmergency=is_emergency,
472 | IsSpeechEnabled=is_speech_enabled,
473 | IsEffectEnabled=is_effect_enabled,
474 | IsSoundEnabled=is_sound_enabled,
475 | IsTopmost=is_topmost,
476 | DurationSeconds=duration_seconds,
477 | RepeatCounts=repeat_counts
478 | ).SerializeToString())
479 |
480 |
481 | @command.get("/command/client/{client_uid}/update_data")
482 | async def update_data(client_uid: str):
483 | await gRPC.command(client_uid, CommandTypes_pb2.DataUpdated)
484 |
485 | @command.post("/command/client/batch_action")
486 | async def batch_action(data:dict = Body(...)):
487 | match data.get("action"):
488 | case "send_notification":
489 | await asyncio.gather(*[send_notification(uid, **data.get("payload")) for uid in data.get("client_uids")])
490 | case "restart":
491 | await asyncio.gather(*[restart(uid) for uid in data.get("client_uids")])
492 | case "update_data":
493 | await asyncio.gather(*[update_data(uid) for uid in data.get("client_uids")])
494 |
495 |
496 |
497 | #endregion
498 |
499 |
500 | #endregion
501 |
502 |
503 | #region 外部操作方法
504 | @command.get("/api/refresh")
505 | async def refresh() -> None:
506 | log.log("Settings refreshed.", QuickValues.Log.info)
507 | _ = Settings.refresh
508 | return None
509 |
510 |
511 | #endregion
512 |
513 |
514 | #region 启动函数
515 | async def start(port: int = 50052):
516 | config = uvicorn.Config(app=command, port=port, host="0.0.0.0", log_level="error", access_log=False)
517 | server = uvicorn.Server(config)
518 | await server.serve()
519 | log.log("Command backend successfully start on {port}".format(port=port), QuickValues.Log.info)
520 |
521 |
522 | #endregion
523 | #endregion
524 |
525 |
526 | #region Running directly processor
527 | if __name__ == "__main__":
528 | log.log(message="Directly started, refused.", status=QuickValues.Log.error)
529 | #endregion
530 |
--------------------------------------------------------------------------------
/ManagementServer/gRPC.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 |
4 | #region Presets
5 | #region 导入项目内建库
6 | import Datas
7 | import logger
8 | import BuildInClasses
9 | import QuickValues
10 | #endregion
11 |
12 |
13 | #region 导入辅助库
14 | import grpc.aio
15 | import json
16 | import os
17 | import time
18 | import uuid
19 | from concurrent.futures import ThreadPoolExecutor
20 |
21 | from fastapi import HTTPException
22 | #endregion
23 |
24 |
25 | #region 导入 Protobuf 构建文件
26 | from Protobuf.Client import (ClientCommandDeliverScReq_pb2, ClientCommandDeliverScReq_pb2_grpc,
27 | ClientRegisterCsReq_pb2, ClientRegisterCsReq_pb2_grpc)
28 | from Protobuf.Command import (SendNotification_pb2, SendNotification_pb2_grpc,
29 | HeartBeat_pb2, HeartBeat_pb2_grpc)
30 | from Protobuf.Enum import (CommandTypes_pb2, CommandTypes_pb2_grpc,
31 | Retcode_pb2, Retcode_pb2_grpc)
32 | from Protobuf.Server import (ClientCommandDeliverScRsp_pb2, ClientCommandDeliverScRsp_pb2_grpc,
33 | ClientRegisterScRsp_pb2, ClientRegisterScRsp_pb2_grpc)
34 | from Protobuf.Service import (ClientCommandDeliver_pb2, ClientCommandDeliver_pb2_grpc,
35 | ClientRegister_pb2, ClientRegister_pb2_grpc)
36 |
37 |
38 | #endregion
39 |
40 |
41 | #region 导入配置文件
42 | class _Settings:
43 | def __init__(self):
44 | self.conf_name: str = "settings.json"
45 | self.conf_dict: dict = json.load(open(self.conf_name))
46 |
47 | async def refresh(self) -> dict:
48 | self.conf_dict = json.load(open(self.conf_name))
49 | return self.conf_dict
50 |
51 |
52 | Settings = _Settings()
53 | #endregion
54 |
55 |
56 | #region 内建辅助函数和辅助参量
57 | log = logger.Logger()
58 |
59 |
60 | #endregion
61 | #endregion
62 |
63 |
64 | #region Main
65 | # region 命令传递通道服务
66 | class ClientCommandDeliverServicer(ClientCommandDeliver_pb2_grpc.ClientCommandDeliverServicer):
67 | _instance = None
68 |
69 | def __new__(cls, *args, **kwargs):
70 | if not cls._instance:
71 | cls._instance = super(ClientCommandDeliverServicer, cls).__new__(cls, *args, **kwargs)
72 | cls._instance.clients = {}
73 | cls._instance.executor = ThreadPoolExecutor(max_workers=10)
74 | return cls._instance
75 |
76 | async def ListenCommand(self, request_iterator, context: grpc.aio.ServicerContext):
77 | metadata = context.invocation_metadata()
78 | client_uid = "" # Initialize client_uid
79 | for m in metadata: # Iterate through the metadata list
80 | if m.key == 'cuid':
81 | client_uid = m.value
82 | break # find it then break.
83 |
84 | if not client_uid:
85 | await context.abort(grpc.StatusCode.INVALID_ARGUMENT, "Client UID is required.")
86 | return
87 | log.log("Client {client_uid} connected.".format(client_uid=client_uid), QuickValues.Log.info)
88 | self.clients[client_uid] = context
89 | Datas.ClientStatus.update(client_uid)
90 |
91 | try:
92 | async for request in request_iterator:
93 | if request.Type == CommandTypes_pb2.Ping:
94 | Datas.ClientStatus.update(client_uid)
95 | log.log("Receive ping from {client_uid}".format(client_uid=client_uid), QuickValues.Log.info)
96 | await context.write(ClientCommandDeliverScRsp_pb2.ClientCommandDeliverScRsp(
97 | RetCode=Retcode_pb2.Success,
98 | Type=CommandTypes_pb2.Pong
99 | ))
100 | else:
101 | log.log("Unexpected request {request} received from {client_uid}".format(request=request,
102 | client_uid=client_uid))
103 | except Exception as e:
104 | log.log("Client {client_uid} disconnected: {e}".format(client_uid=client_uid, e=e), QuickValues.Log.info)
105 | finally:
106 | self.clients.pop(client_uid, None)
107 | Datas.ClientStatus.offline(client_uid)
108 |
109 |
110 | #endregion
111 |
112 |
113 | #region 命令推送器
114 | async def command(client_uid: str, command_type: CommandTypes_pb2.CommandTypes, payload: bytes = b''):
115 | servicer = ClientCommandDeliverServicer()
116 | if client_uid not in servicer.clients:
117 | log.log("Send {command} to {client_uid}, failed.".format(command=command_type, client_uid=client_uid),
118 | QuickValues.Log.error)
119 | raise HTTPException(status_code=404, detail=f"Client not found or not connected: {client_uid}")
120 | log.log("Send {command} to {client_uid}".format(command=command_type, client_uid=client_uid), QuickValues.Log.info)
121 | await servicer.clients[client_uid].write(ClientCommandDeliverScRsp_pb2.ClientCommandDeliverScRsp(
122 | RetCode=Retcode_pb2.Success,
123 | Type=command_type,
124 | Payload=payload
125 | ))
126 |
127 |
128 | #endregion
129 |
130 |
131 | #region 注册服务
132 | class ClientRegisterServicer(ClientRegister_pb2_grpc.ClientRegisterServicer):
133 | async def Register(self, request: ClientRegisterCsReq_pb2.ClientRegisterCsReq,
134 | context: grpc.aio.ServicerContext) -> ClientRegisterScRsp_pb2.ClientRegisterScRsp:
135 | clients = Datas.Clients.refresh()
136 | client_uid = request.clientUid
137 | client_id = request.clientId
138 | if client_uid in clients:
139 | log.log("Client {client_uid} registered as {client_id}, but register again.".format(
140 | client_uid=client_uid, client_id=client_id), QuickValues.Log.warning)
141 | Datas.Clients.register(client_uid, client_id)
142 | return ClientRegisterScRsp_pb2.ClientRegisterScRsp(Retcode=Retcode_pb2.Registered,
143 | Message=f"Client already registered: {client_uid}")
144 | else:
145 | Datas.ClientStatus.register(client_uid, client_id)
146 | log.log("Client {client_uid} registered as {client_id}".format(
147 | client_uid=client_uid, client_id=client_id), QuickValues.Log.info)
148 | Datas.Clients.register(client_uid, client_id)
149 | return ClientRegisterScRsp_pb2.ClientRegisterScRsp(Retcode=Retcode_pb2.Success,
150 | Message=f"Client registered: {client_uid}")
151 |
152 | async def UnRegister(self, request, context):
153 | return ClientRegisterScRsp_pb2.ClientRegisterScRsp(Retcode=Retcode_pb2.ServerInternalError,
154 | Message="Not implemented")
155 |
156 |
157 | #endregion
158 |
159 |
160 | #region 启动函数
161 | async def start(port=50051):
162 | server = grpc.aio.server()
163 | ClientRegister_pb2_grpc.add_ClientRegisterServicer_to_server(ClientRegisterServicer(), server)
164 | ClientCommandDeliver_pb2_grpc.add_ClientCommandDeliverServicer_to_server(ClientCommandDeliverServicer(), server)
165 | server.add_insecure_port("0.0.0.0:{port}".format(port=port))
166 | log.log("Starting gRPC server on {listen_addr}".format(listen_addr="0.0.0.0:{port}".format(port=port)),
167 | QuickValues.Log.info)
168 | await server.start()
169 | await server.wait_for_termination()
170 |
171 |
172 | #endregion
173 | #endregion
174 |
175 |
176 | #region Running Directly processor
177 | if __name__ == "__main__":
178 | log.log(message="Directly started, refused.", status=QuickValues.Log.error)
179 | #endregion
180 |
--------------------------------------------------------------------------------
/Protobuf/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/Protobuf/.gitignore
--------------------------------------------------------------------------------
/Protobuf/Client/ClientCommandDeliverScReq.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Client;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Client";
4 |
5 | import "Protobuf/Enum/CommandTypes.proto";
6 |
7 | message ClientCommandDeliverScReq {
8 | Enum.CommandTypes Type = 2;
9 | bytes Payload = 3;
10 | }
11 |
--------------------------------------------------------------------------------
/Protobuf/Client/ClientRegisterCsReq.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Client;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Client";
4 |
5 | message ClientRegisterCsReq {
6 | string clientUid = 1;
7 | string clientId = 2;
8 | }
9 |
--------------------------------------------------------------------------------
/Protobuf/Client/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/Protobuf/Client/__init__.py
--------------------------------------------------------------------------------
/Protobuf/Command/HeartBeat.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Command;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Command";
4 |
5 | message HeartBeat {
6 | bool isOnline = 1;
7 | }
8 |
--------------------------------------------------------------------------------
/Protobuf/Command/SendNotification.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Command;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Command";
4 |
5 | message SendNotification {
6 | string MessageMask=1;
7 | string MessageContent=2;
8 | int32 OverlayIconLeft=3;
9 | int32 OverlayIconRight=4;
10 | bool IsEmergency=5;
11 | // 提醒设置
12 | bool IsSpeechEnabled=6;
13 | bool IsEffectEnabled=7;
14 | bool IsSoundEnabled=8;
15 | bool IsTopmost=9;
16 | // 显示设置
17 | double DurationSeconds=10; // 单次显示持续时间
18 | int32 RepeatCounts=11;
19 | }
20 |
--------------------------------------------------------------------------------
/Protobuf/Command/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/Protobuf/Command/__init__.py
--------------------------------------------------------------------------------
/Protobuf/Enum/CommandTypes.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Enum;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Enum";
4 |
5 | enum CommandTypes {
6 | DefaultCommand=0;
7 | // Misc
8 | ServerConnected=1;
9 | // Heartbeat
10 | Ping=2;
11 | Pong=3;
12 | // Commands
13 | RestartApp=4;
14 | SendNotification=5;
15 | DataUpdated=6;
16 | }
--------------------------------------------------------------------------------
/Protobuf/Enum/Retcode.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Enum;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Enum";
4 |
5 | enum Retcode {
6 | Unspecified = 0; // None = 0;
7 | Success = 200;
8 | ServerInternalError = 500;
9 | InvalidRequest = 404;
10 | // service: ClientRegister
11 | Registered = 10001;
12 | ClientNotFound = 10002;
13 | // service: ClientCommandDeliver
14 |
15 | }
--------------------------------------------------------------------------------
/Protobuf/Enum/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/Protobuf/Enum/__init__.py
--------------------------------------------------------------------------------
/Protobuf/Server/ClientCommandDeliverScRsp.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Server;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Server";
4 |
5 | import "Protobuf/Enum/CommandTypes.proto";
6 | import "Protobuf/Enum/Retcode.proto";
7 |
8 | message ClientCommandDeliverScRsp {
9 | Enum.Retcode RetCode = 1;
10 | Enum.CommandTypes Type = 2;
11 | bytes Payload = 3;
12 | }
13 |
--------------------------------------------------------------------------------
/Protobuf/Server/ClientRegisterScRsp.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Server;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Server";
4 |
5 | import "Protobuf/Enum/Retcode.proto";
6 |
7 | message ClientRegisterScRsp {
8 | Enum.Retcode Retcode = 1;
9 | string Message = 2;
10 | }
11 |
--------------------------------------------------------------------------------
/Protobuf/Server/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/Protobuf/Server/__init__.py
--------------------------------------------------------------------------------
/Protobuf/Service/ClientCommandDeliver.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Service;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Service";
4 |
5 | import "Protobuf/Server/ClientCommandDeliverScRsp.proto";
6 | import "Protobuf/Client/ClientCommandDeliverScReq.proto";
7 |
8 | service ClientCommandDeliver {
9 | rpc ListenCommand (stream Client.ClientCommandDeliverScReq) returns (stream Server.ClientCommandDeliverScRsp);
10 | }
--------------------------------------------------------------------------------
/Protobuf/Service/ClientRegister.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 | package ClassIsland.Shared.Protobuf.Service;
3 | option csharp_namespace = "ClassIsland.Shared.Protobuf.Service";
4 |
5 | import "Protobuf/Client/ClientRegisterCsReq.proto";
6 | import "Protobuf/Server/ClientRegisterScRsp.proto";
7 |
8 | service ClientRegister {
9 | rpc Register (Client.ClientRegisterCsReq) returns (Server.ClientRegisterScRsp);
10 |
11 | rpc UnRegister (Client.ClientRegisterCsReq) returns (Server.ClientRegisterScRsp);
12 | }
--------------------------------------------------------------------------------
/Protobuf/Service/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/Protobuf/Service/__init__.py
--------------------------------------------------------------------------------
/Protobuf/__init__.py:
--------------------------------------------------------------------------------
1 | from .Client import (ClientCommandDeliverScReq_pb2, ClientCommandDeliverScReq_pb2_grpc,
2 | ClientRegisterCsReq_pb2, ClientRegisterCsReq_pb2_grpc)
3 | from .Command import (SendNotification_pb2, SendNotification_pb2_grpc,
4 | HeartBeat_pb2, HeartBeat_pb2_grpc)
5 | from .Enum import (CommandTypes_pb2, CommandTypes_pb2_grpc,
6 | Retcode_pb2, Retcode_pb2_grpc)
7 | from .Server import (ClientCommandDeliverScRsp_pb2, ClientCommandDeliverScRsp_pb2_grpc,
8 | ClientRegisterScRsp_pb2, ClientRegisterScRsp_pb2_grpc)
9 | from .Service import (ClientCommandDeliver_pb2, ClientCommandDeliver_pb2_grpc,
10 | ClientRegister_pb2, ClientRegister_pb2_grpc)
--------------------------------------------------------------------------------
/QuickValues.py:
--------------------------------------------------------------------------------
1 | class Log:
2 | info = "[INFO]"
3 | standard = "[STAN]"
4 | warning = "[WARN]"
5 | critical = "[CRIT]"
6 | error = "[EROR]"
7 | debug = "[DBUG]"
8 | danger = "[DAGR]"
9 |
10 | def __init__(self):
11 | self.info = "[INFO]"
12 | self.standard = "[STAN]"
13 | self.warning = "[WARN]"
14 | self.critical = "[CRIT]"
15 | self.error = "[EROR]"
16 | self.debug = "[DBUG]"
17 | self.danger = "[DAGR]"
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 基于 Python 的适用于 [ClassIsland](https://github.com/classisland/classisland) 的集控服务器
2 |
3 | [](https://app.fossa.com/projects/git%2Bgithub.com%2Fkaokao221%2FClassIslandManagementServer.py?ref=badge_shield)
4 |
5 | [加入讨论区](https://qm.qq.com/ez2uhHJv2w)
6 |
7 | 集控服务器分为三个部分,分别是[`api`](./ManagementServer/api.py)[`command`](./ManagementServer/command.py)[`gRPC`](./ManagementServer/gRPC.py),分别用于:
8 |
9 | | 组件 | [`api`](./ManagementServer/api.py) | [`command`](./ManagementServer/command.py) | [`gRPC`](./ManagementServer/gRPC.py) |
10 | |----|--------------------------------------|--------------------------------------------|--------------------------------------|
11 | | 用途 | 向客户端分发配置文件 | 通过API以集控服务器为中介获取客户端状态、向客户端发送指令 | 与客户端建立gRPC链接 |
12 | | 端口 | [50050](http://127.0.0.1:50050/docs) | [50052](http://127.0.0.1:50052/docs) | 50051 |
13 |
14 | ## *实验性* 快速部署(适用于 Linux 平台):
15 |
16 | 快速部署将始终安装在 `/www/CIMS/backend` 目录,你可以使用 `rm -rf /www/CIMS/backend` 来彻底移除使用部署脚本部署的 `CIMS-backend`
17 |
18 | ```bash
19 | bash -c "$(curl -sSL https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/main/install.sh)"
20 | ```
21 |
22 | 启动
23 |
24 | ```bash
25 | cd /www/CIMS/backend && source venv/bin/activate && python CIMS.py
26 | ```
27 |
28 | ## 如何使用?
29 |
30 | 以下是使用 ClassIsland 集控服务器的步骤:
31 |
32 | 1. **环境准备**:
33 | * **Python:** 确保你的系统已安装 Python 3.8+,推荐 Python 3.12+,推荐自行编译完整的 Python 3.12 & OpenSSL 3 环境。
34 | * **Node.js and npm:** 如果你需要使用 WebUI,请确保已安装 Node.js (v22+) 和 npm。
35 | * **Git (Optional):** 如果你想从 GitHub 克隆仓库,则需要安装 Git。
36 | 2. **克隆代码:**
37 | ```bash
38 | git clone https://github.com/MINIOpenSource/CIMS-backend.git
39 | cd CIMS-backend
40 | ```
41 | * 如果你不使用 Git,可以下载 ZIP 压缩包并解压。
42 | 3. **创建 venv 并安装依赖:**
43 | ```bash
44 | python -m venv venv
45 | ./venv/Scripts/python.exe -m pip install -r requirements.txt
46 | # Windows 环境
47 | ```
48 | ```bash
49 | python3 -m venv venv
50 | ./venv/bin/python3 -m pip install -r requirements.txt
51 | # Linux 环境
52 | ```
53 | 在 Linux 环境中,可能出现 venv / pip 不可用报错,请根据相关提示从命令行安装 venv 和 pip 后重新创建虚拟环境并安装依赖。
54 | 4. **构建 Protobuf 文件:**
55 | ```bash
56 | ./venv/Scripts/python.exe -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. ./Protobuf/Client/ClientCommandDeliverScReq.proto ./Protobuf/Client/ClientRegisterCsReq.proto ./Protobuf/Command/HeartBeat.proto ./Protobuf/Command/SendNotification.proto ./Protobuf/Enum/CommandTypes.proto ./Protobuf/Enum/Retcode.proto ./Protobuf/Server/ClientCommandDeliverScRsp.proto ./Protobuf/Server/ClientRegisterScRsp.proto ./Protobuf/Service/ClientCommandDeliver.proto ./Protobuf/Service/ClientRegister.proto
57 | # Windows 环境
58 | ```
59 | ```bash
60 | ./venv/bin/python3 -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. ./Protobuf/Client/ClientCommandDeliverScReq.proto ./Protobuf/Client/ClientRegisterCsReq.proto ./Protobuf/Command/HeartBeat.proto ./Protobuf/Command/SendNotification.proto ./Protobuf/Enum/CommandTypes.proto ./Protobuf/Enum/Retcode.proto ./Protobuf/Server/ClientCommandDeliverScRsp.proto ./Protobuf/Server/ClientRegisterScRsp.proto ./Protobuf/Service/ClientCommandDeliver.proto ./Protobuf/Service/ClientRegister.proto
61 | # Linux 环境
62 | ```
63 | 这将会构建 `.proto` 文件生成对应的 Python 代码,以用于 gRPC 通信。
64 | 5. **启动服务器:**
65 | * **使用 `CIMS.py` :**
66 | > 第一次启动时,会进行引导配置
67 | ```bash
68 | ./venv/Scripts/python.exe CIMS.py
69 | # Windows 环境
70 | ```
71 | ```bash
72 | ./venv/bin/python3 CIMS.py
73 | # Linux 环境
74 | ```
75 | 生成集控预设文件(`ManagementPreset.json`):
76 | ```bash
77 | ./venv/Scripts/python.exe CIMS.py -g
78 | # Windows 环境
79 | ```
80 | ```bash
81 | ./venv/bin/python3 CIMS.py -g
82 | # Linux 环境
83 | ```
84 | > 当出现一些意料之外的问题时,可以尝试使用`-r`参数清除本地的配置文件以尝试修复,在此之前,请手动备份数据:
85 | > ```bash
86 | > ./venv/Scripts/python.exe CIMS.py -r
87 | > # Windows 环境
88 | > ```
89 | > ```bash
90 | > ./venv/bin/python3 CIMS.py -r
91 | > # Linux 环境
92 | > ```
93 | 6. **访问 API:**
94 | * 你可以在浏览器中访问 `http://127.0.0.1:50050/docs` (或你设置的端口)查看 API 文档.
95 |
96 | ## 功能清单
97 |
98 | - [x]分发文件
99 | - [x]发送通知
100 | - [x]重启客户端
101 | - [x]批量操作
102 |
103 | #### 下一个版本更新
104 |
105 | - [ ]实验性的分用户管理能力
106 |
107 | ## 羊癫疯 Fossa
108 | [](https://app.fossa.com/projects/git%2Bgithub.com%2Fkaokao221%2FClassIslandManagementServer.py?ref=badge_large)
109 |
110 | ## Star 历史
111 | [](https://starchart.cc/kaokao221/ClassIslandManagementServer.py)
112 |
--------------------------------------------------------------------------------
/Shell.py:
--------------------------------------------------------------------------------
1 | #! -*- coding:utf-8 -*-
2 |
3 |
4 | #region 导入辅助库
5 | import argparse
6 | import asyncio
7 | import json
8 | from json import JSONDecodeError
9 | import os
10 | import sys
11 | import msvcrt
12 | #endregion
13 |
14 |
15 | #region 预置控制字符
16 | BLACK_CHARACTER = "\033[30m"
17 | RED_CHARACTER = "\033[31m"
18 | GREEN_CHARACTER = "\033[32m"
19 | YELLOW_CHARACTER = "\033[33m"
20 | BLUE_CHARACTER = "\033[34m"
21 | MAGENTA_CHARACTER = "\033[35m"
22 | CYAN_CHARACTER = "\033[36m"
23 | WHITE_CHARACTER = "\033[37m"
24 |
25 | BLACK_BACKGROUND = "\033[40m"
26 | RED_BACKGROUND = "\033[41m"
27 | GREEN_BACKGROUND = "\033[42m"
28 | YELLOW_BACKGROUND = "\033[43m"
29 | BLUE_BACKGROUND = "\033[44m"
30 | MAGENTA_BACKGROUND = "\033[45m"
31 | CYAN_BACKGROUND = "\033[46m"
32 | WHITE_BACKGROUND = "\033[47m"
33 |
34 | BRIGHT_BLACK_CHARACTER = "\033[90m"
35 | BRIGHT_RED_CHARACTER = "\033[91m"
36 | BRIGHT_GREEN_CHARACTER = "\033[92m"
37 | BRIGHT_YELLOW_CHARACTER = "\033[93m"
38 | BRIGHT_BLUE_CHARACTER = "\033[94m"
39 | BRIGHT_MAGENTA_CHARACTER = "\033[95m"
40 | BRIGHT_CYAN_CHARACTER = "\033[96m"
41 | BRIGHT_WHITE_CHARACTER = "\033[97m"
42 |
43 | BRIGHT_BLACK_BACKGROUND = "\033[100m"
44 | BRIGHT_RED_BACKGROUND = "\033[101m"
45 | BRIGHT_GREEN_BACKGROUND = "\033[102m"
46 | BRIGHT_YELLOW_BACKGROUND = "\033[103m"
47 | BRIGHT_BLUE_BACKGROUND = "\033[104m"
48 | BRIGHT_MAGENTA_BACKGROUND = "\033[105m"
49 | BRIGHT_CYAN_BACKGROUND = "\033[106m"
50 | BRIGHT_WHITE_BACKGROUND = "\033[107m"
51 |
52 | RESET = "\033[0m"
53 |
54 | HIGHLIGHT = "\033[1m"
55 | UNDERLINE = "\033[4m"
56 | BLINK = "\033[5m"
57 | REVERSE = "\033[7m"
58 |
59 | FRAME = "\033[51m"
60 | ENCIRCLE = "\033[52m"
61 | OVERLINE = "\033[53m"
62 |
63 | MOVE_UP = lambda n: "\033[%dA" % n
64 | MOVE_DOWN = lambda n: "\033[%dB" % n
65 | MOVE_LEFT = lambda n: "\033[%dC" % n
66 | MOVE_RIGHT = lambda n: "\033[%dD" % n
67 |
68 | SET_MOUSE_PLACE = lambda y, x: "\033[{};{}H".format(y, x)
69 |
70 | CLEAR = "\033[2J"
71 |
72 | CLEAR_LINE_AFTER = "\033[K"
73 |
74 | MOUSE_DISAPPEAR = "\033?25l"
75 | MOUSE_APPEAR = "\033?25h"
76 |
77 | ascii_format = lambda _str: _str.format(BLACK_CHARACTER=BLACK_CHARACTER,
78 | RED_CHARACTER=RED_CHARACTER,
79 | GREEN_CHARACTER=GREEN_CHARACTER)
80 | #endregion
81 |
82 |
83 | #region 尝试获取窗口尺寸
84 | try:
85 | columns, lines = os.get_terminal_size()
86 | except OSError:
87 | print(f"{MAGENTA_BACKGROUND}{BRIGHT_RED_CHARACTER}{UNDERLINE}{HIGHLIGHT}Get terminal size failed, Shell will be closed.{RESET}")
88 | sys.exit(0)
89 | #endregion
90 |
91 |
92 | print(f"{CLEAR}{SET_MOUSE_PLACE(0,0)}Loading Server...")
93 |
94 |
95 | class ServerConnectingFailed(ConnectionRefusedError):
96 | def __init__(self, *args, **kwargs):
97 | pass
98 |
99 |
100 | class IncompletedError(NameError):
101 | def __init__(self, *args, **kwargs):
102 | pass
103 |
104 |
105 | class Shell:
106 | def __init__(self,
107 | *args,
108 | address:str="127.0.0.1",
109 | port:int=50052,
110 | ascii_ctrl:bool=True,
111 | **kwargs):
112 | self.address:str = address
113 | self.port:int = port
114 | self.ascii_ctrl:bool = ascii_ctrl
115 | self.args = args
116 | self.kwargs = kwargs
117 |
118 | self.websocket = None
119 |
120 | def input_(self, __param:str):
121 | __input:list[bytes] = []
122 | while __input[-1] not in (b'\r', b'\n'):
123 | raise IncompletedError
124 |
125 |
--------------------------------------------------------------------------------
/abstract.py:
--------------------------------------------------------------------------------
1 | r=input;o=open
2 | if __name__!="__main__":import sys as _;_.exit(0)
3 | try:o(".installed").close();_i=True
4 | except:_i=False
5 | import argparse,asyncio,json,os,sys
6 | from json import JSONDecodeError
7 | for _r in["./logs","./Datas","./Datas/ClassPlan","./Datas/DefaultSettings","./Datas/Policy","./Datas/Subjects","./Datas/TimeLayout"]:
8 | try:os.mkdir(_r)
9 | except:...
10 | for _f in["./settings.json"]+["./Datas/{}.json".format(name)for name in["client_status","clients","pre_register","profile_config"]]+["./Datas/{}/default.json".format(name)for name in["ClassPlan","DefaultSettings","Policy","Subjects","TimeLayout"]]:
11 | try:json.load(o(_f))
12 | except:o(_f,"w").write("{}")
13 | try:json.load(o("project_info.json"))
14 | except:json.dump({"name":"CIMS-backend","description":"ClassIsland Management Server on Python","author":"kaokao221","version":"1.1beta2","url":"https://github.com/MINIoSource/CIMS-backend"},o("project_info.json","w"))
15 | import Datas,logger,BuildInClasses,QuickValues,ManagementServer
16 | if _i:_s=json.load(o("settings.json"))
17 | else:
18 | _s={}
19 | for part in["gRPC","api","command"]:
20 | _n=r("{} host and port used in ManagementPreset.json (formatted as {}://{}:{} and port must be given)(Enter directly to use default settings):".format(part,_s[part]["prefix"],_s[part]["host"],_s[part]["mp_port"]));_ps=True
21 | while _ps:
22 | try:
23 | if _n.startswith("http://"):print("HTTP is not safe and HTTPS recommended.\n"if not _n.startswith("http://localhost")else "",end="")
24 | if not _n.startswith(("https://","http://")):raise ValueError
25 | _s[part]["prefix"]=_n.split(":")[0] + "://";_s[part]["host"]=_n.split(":")[1][2:];_s[part]["mp_port"]=int(_n.split(":")[2]);_ps=False
26 | except KeyError:
27 | _n=r("Invalid r,retry:")
28 | except:
29 | if _n == "":_ps=False
30 | else:_n=r("Invalid r,retry:")
31 | if _n != "":
32 | _n=r("{part} listening port(Enter directly to use the same as above):".format(part=part));_ps=True
33 | while _ps:
34 | try:
35 | _s[part]["port"]=int(_n); _ps=False
36 | except ValueError:
37 | if _n == "":_s[part]["port"]=_s[part]["mp_port"];_ps=False
38 | else:_n=r("Invalid port,retry:")
39 | else:_s[part]["port"]=_s[part]["mp_port"]
40 | _n=r("Organization name:");_s["organization_name"]=_n if _n != "" else "CIMS Default Organization";json.dump(_s,o("settings.json","w"));o(".installed","w").close()
41 | async def refresh():await asyncio.gather(ManagementServer.command.Settings.refresh(),ManagementServer.api.Settings.refresh(),ManagementServer.gRPC.Settings.refresh());asyncio.run(refresh())
42 | ps=argparse.ArgumentParser(description="ClassIsland Management Server Backend");ps.add_argument("-g","--generate-management-preset",action="store_true",help="Generate ManagementPreset.json on the program root.");ps.add_argument("-r","--restore",action="store_true",help="Restore,and delete all existed data");a=ps.parse_args()
43 | async def start():await asyncio.gather(ManagementServer.gRPC.start(_s["gRPC"]["port"]),ManagementServer.api.start(_s["api"]["port"]),ManagementServer.command.start(_s["command"]["port"]),)
44 | if a.restore:
45 | if r("Continue?(y/n with default n)") in ("y","Y"):import os;os.remove(".installed");os.remove("settings.json");os.remove("ManagementPreset.json")
46 | elif a.generate_management_preset:json.dump({"ManagementServerKind":1,"ManagementServer":"{prefix}://{host}:{port}".format(prefix=_s["api"]["prefix"],host=_s["api"]["host"],port=_s["api"]["mp_port"]),"ManagementServerGrpc":"{prefix}://{host}:{port}".format(prefix=_s["gRPC"]["prefix"],host=_s["gRPC"]["host"],port=_s["gRPC"]["mp_port"])},o("ManagementPreset.json","w"))
47 | else:print("\033[2JWelcome to use CIMS1.0v1sp0patch1");asyncio.run(start())
--------------------------------------------------------------------------------
/change-visble.txt:
--------------------------------------------------------------------------------
1 | 1.0-v1-发行版本
--------------------------------------------------------------------------------
/changelog.txt:
--------------------------------------------------------------------------------
1 | 1.0v1: 发行版本。
2 | 1.0v1sp0patch1: 新增 nuitka-ubuntu.sh 用于简化构建,更新版本号,更正 README.md 的仓库位置。
3 | 1.0v1sp0patch2: 将日志输出到控制台(实验性),更正部分链接的拼写错误,新建文件夹(i18n),更正部分格式问题。
4 | 1.0v1sp0patch3: 变更 refresh 语法,更正预设格式,更正初始化流,增加服务器版本方法和预设下载方法,变更 README.md,稍作修缮。
5 | 1.1beta1: 对齐 WebUI 的接口,完善操作方法。
6 | 1.1beta1sp1: 修复 API 的 manifest 生成问题。
7 | 1.1beta1sp2: 更正因为保存 JSON 时指定 ASCII 的问题。
8 | 1.1beta2: 实现批量操作能力。
9 | 1.1beta2sp1: 多了点抽象的东西,修了一个奇怪的问题,并加了 .gitignore 若干。
10 | 1.1beta2sp2: 修复注册设备的问题,改进 API 访问逻辑。
11 | 1.1beta2sp3: 更正 API 分发端口选择问题。
--------------------------------------------------------------------------------
/i18n/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/i18n/__init__.py
--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # 定义仓库 URL 和目标目录
4 | REPO_URL="https://github.com/MINIOpenSource/CIMS-backend.git"
5 | DEST_DIR="/www/CIMS/backend"
6 |
7 | # 获取操作系统信息以确定发行版
8 | OS_RELEASE=$(cat /etc/os-release)
9 | if [[ "$OS_RELEASE" =~ "ubuntu" ]]; then
10 | DISTRIBUTION="ubuntu"
11 | PACKAGE_MANAGER="apt-get"
12 | elif [[ "$OS_RELEASE" =~ "centos" ]]; then
13 | DISTRIBUTION="centos"
14 | PACKAGE_MANAGER="yum"
15 | elif [[ "$OS_RELEASE" =~ "fedora" ]]; then
16 | DISTRIBUTION="fedora"
17 | PACKAGE_MANAGER="dnf"
18 | else
19 | echo "未检测到受支持的 Linux 发行版 (Ubuntu, CentOS, Fedora)。将尝试使用 apt-get (Debian 系) 作为默认包管理器。"
20 | DISTRIBUTION="unknown"
21 | PACKAGE_MANAGER="apt-get"
22 | fi
23 |
24 | # 检查是否安装 git
25 | if ! command -v git &> /dev/null
26 | then
27 | echo "Git 未安装。脚本需要 git 来克隆仓库。"
28 | echo "请确保 git 已安装后再运行此脚本。"
29 | exit 1
30 | fi
31 |
32 | # 询问用户是否需要自动安装 venv 和 pip
33 | read -p "是否需要在 venv 或 pip 未找到时自动安装它们? (y/n): " -n 1 -r
34 | echo # 换行
35 | if [[ $REPLY =~ ^[Yy]$ ]]
36 | then
37 | AUTO_INSTALL_DEPS="yes"
38 | else
39 | AUTO_INSTALL_DEPS="no"
40 | fi
41 |
42 | # 函数:检查并安装包
43 | check_and_install_package() {
44 | package_name="$1"
45 | check_command="$2"
46 | install_command="$3"
47 |
48 | if ! command -v "$check_command" &> /dev/null; then
49 | if [[ "$AUTO_INSTALL_DEPS" == "yes" ]]; then
50 | echo "${package_name} 未找到,尝试自动安装..."
51 | sudo $PACKAGE_MANAGER update # 更新包列表
52 | if sudo $PACKAGE_MANAGER install -y "$install_command"; then
53 | echo "${package_name} 安装成功。"
54 | else
55 | echo "自动安装 ${package_name} 失败。请手动安装 ${package_name} 后重试。"
56 | exit 1
57 | fi
58 | else
59 | echo "${package_name} 未找到,且您选择不自动安装。脚本需要 ${package_name}。"
60 | echo "请手动安装 ${package_name} 后重试。"
61 | exit 1
62 | fi
63 | fi
64 | }
65 |
66 | # 检查并安装 venv (python3-venv 或 virtualenv)
67 | if ! command -v python3 &> /dev/null; then
68 | echo "Python 3 未找到。请确保 Python 3 已安装。"
69 | exit 1
70 | fi
71 |
72 | check_and_install_package "venv (python3-venv)" "python3 -m venv" "python3-venv"
73 | check_and_install_package "pip" "pip3" "python3-pip"
74 |
75 |
76 | # 克隆仓库
77 | echo "克隆仓库到 ${DEST_DIR}..."
78 | mkdir -p "$(dirname "$DEST_DIR")" # 确保父目录存在
79 | git clone "$REPO_URL" "$DEST_DIR"
80 | if [ $? -ne 0 ]; then
81 | echo "克隆仓库失败,请检查网络连接或仓库地址。"
82 | exit 1
83 | fi
84 | cd "$DEST_DIR"
85 |
86 | # 创建虚拟环境
87 | echo "创建虚拟环境 venv..."
88 | python3 -m venv venv
89 | if [ $? -ne 0 ]; then
90 | echo "创建虚拟环境失败。"
91 | exit 1
92 | fi
93 |
94 | # 激活虚拟环境并安装依赖
95 | echo "安装依赖..."
96 | source /www/CIMS/backend/venv/bin/activate
97 | pip3 install -r requirements.txt
98 | python3 -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. ./Protobuf/Client/ClientCommandDeliverScReq.proto ./Protobuf/Client/ClientRegisterCsReq.proto ./Protobuf/Command/HeartBeat.proto ./Protobuf/Command/SendNotification.proto ./Protobuf/Enum/CommandTypes.proto ./Protobuf/Enum/Retcode.proto ./Protobuf/Server/ClientCommandDeliverScRsp.proto ./Protobuf/Server/ClientRegisterScRsp.proto ./Protobuf/Service/ClientCommandDeliver.proto ./Protobuf/Service/ClientRegister.proto
99 | if [ $? -ne 0 ]; then
100 | echo "安装依赖失败。请检查 requirements.txt 文件或网络连接。"
101 | deactivate
102 | exit 1
103 | fi
104 |
105 | deactivate # 退出虚拟环境
106 |
107 | echo "仓库克隆、虚拟环境创建和依赖安装完成。"
108 | echo "项目已准备就绪,位于 ${DEST_DIR} 目录。"
109 |
110 | exit 0
--------------------------------------------------------------------------------
/logger/__init__.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import sys
3 | from BuildInClasses import RichText
4 | import os
5 | import json
6 |
7 |
8 | class Logger:
9 | """
10 | Enhanced Logger
11 | """
12 |
13 | def __init__(self):
14 | """
15 | Enhanced logger
16 | """
17 | self.logger_file = None
18 | self.log_header = """ Log from {project_name} with MINI Logger
19 |
20 | {project_name}: {project_description}
21 | Developed by {project_author} at {project_url}.
22 | Version: {project_version}
23 |
24 | {time_during:>120}"""
25 |
26 | def log(self, message: str | RichText, status: str | RichText):
27 | """
28 | Logs a message to the logger file.
29 | There will 120 cols in log file.
30 | :param message: Message to log, need str.
31 | :param status: Recommend from QuickValues.Log, need 4 alphabets.
32 | :return:
33 | """
34 | message += " "
35 | try:
36 | self.logger_file = open("logs/{}.log".format(datetime.now().strftime("%Y-%m-%d %H")), "a")
37 | except FileNotFoundError:
38 | project_info = json.load(open("project_info.json", "r"))
39 | self.logger_file = open("logs/{}.log".format(datetime.now().strftime("%Y-%m-%d %H")), "w")
40 | self.logger_file.write(self.log_header.format(
41 | "?",
42 | project_name=project_info["name"],
43 | project_version=project_info["version"],
44 | project_description=project_info["description"],
45 | project_url=project_info["url"],
46 | project_author=project_info["author"],
47 | time_during="[Date {} {}:00 - {}:00]".format(datetime.now().strftime("%Y-%m-%d"),
48 | str(datetime.now().hour),
49 | str(datetime.now().hour + 1)),
50 | ) + "\n" + "=" * 120 + "\n")
51 | self.logger_file.close()
52 | self.logger_file = open("logs/{}.log".format(datetime.now().strftime("%Y-%m-%d %H")), "a")
53 | status_message = "[{} on line {} at {}]".format(
54 | status if type(status) is str else status.text,
55 | sys._getframe().f_back.f_lineno,
56 | sys.argv[0])
57 | if len(message) < 91:
58 | if len(message + status_message) > 91:
59 | self.logger_file.write(
60 | "[{}] {}\n".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), message)
61 | )
62 | self.logger_file.write("{}{}\n".format(" " * (120 - len(status_message)), status_message))
63 | else:
64 | self.logger_file.write(
65 | "[{}] {}{}{}\n".format(
66 | datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
67 | message,
68 | " " * (91 - len(status_message) - len(message)),
69 | status_message
70 | )
71 | )
72 | elif len(message + status_message) < 182:
73 | self.logger_file.write(
74 | "[{}] {}\n{}{}{}{}\n".format(
75 | datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
76 | message[0:91],
77 | " " * 29,
78 | message[91:],
79 | " " * (91 - len(message[91:]) - len(status_message)),
80 | status_message
81 | )
82 | )
83 | else:
84 | self.logger_file.write(
85 | "[{}] {}\n".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), message[0:91])
86 | )
87 | for i in [(i + 1) * 91 for i in range(int(len(message) / 91) - 1)]:
88 | self.logger_file.write("{}{}\n".format(" " * 29, message[i:i + 91]))
89 | if len(message[(int(len(message) / 91)) * 91:]) < 91:
90 | if len(message[(int(len(message) / 91)) * 91:] + status_message) > 91:
91 | self.logger_file.write(
92 | "{}{}\n".format(" " * 29, message[(int(len(message) / 91)) * 91:])
93 | )
94 | self.logger_file.write("{}{}\n".format(" " * (120 - len(status_message)), status_message))
95 | else:
96 | self.logger_file.write(
97 | "{}{}{}{}\n".format(
98 | " " * 29,
99 | message[(int(len(message) / 91)) * 91:],
100 | " " * (91 - len(status_message) - len(message[(int(len(message) / 91)) * 91:])),
101 | status_message
102 | )
103 | )
104 | self.logger_file.write("{}\n".format("=" * 120))
105 | print("[{}] ".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")),
106 | message, " | ", status, "\n", "=" * 120, sep="")
107 | self.logger_file.flush()
108 | self.logger_file.close()
109 |
110 |
111 | class Logs:
112 | """
113 | Unfinished
114 | """
115 |
116 | def __init__(self):
117 | pass
118 |
--------------------------------------------------------------------------------
/logs/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MINIOpenSource/CIMS-backend/08d343ee57f584db887bf8c00fa94fde7c949ddc/logs/.gitignore
--------------------------------------------------------------------------------
/nuitka-build.bat:
--------------------------------------------------------------------------------
1 | nuitka --standalone --show-progress --show-memory --onefile --include-package=starlette --include-package=asyncio --include-package=json --include-package=fastapi --include-package=uvicorn --include-package=grpc --include-package=uuid --include-module=ManagementServer --include-module=logger --include-module=Datas --include-module=Protobuf --include-module=BuildInClasses --include-module=QuickValues --output-dir=output .\CIMS.py
--------------------------------------------------------------------------------
/nuitka-ubuntu.sh:
--------------------------------------------------------------------------------
1 | git pull
2 | ./venv/bin/python3 -m nuitka --standalone --show-progress --show-memory --onefile --include-package=starlette --include-package=asyncio --include-package=json --include-package=fastapi --include-package=uvicorn --include-package=grpc --include-package=uuid --include-module=ManagementServer --include-module=logger --include-module=Datas --include-module=Protobuf --include-module=BuildInClasses --include-module=QuickValues --output-dir=output ./CIMS.py
--------------------------------------------------------------------------------
/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": 2,
3 | "builds": [
4 | {
5 | "src": "CIMS.py",
6 | "use": "@vercel/python"
7 | }
8 | ],
9 | "routes": [
10 | {
11 | "src": "/api/.*",
12 | "dest": "CIMS.py"
13 | },
14 | {
15 | "src": "/command/.*",
16 | "dest": "CIMS.py"
17 | }
18 | ]
19 | }
--------------------------------------------------------------------------------
/project_info.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "CIMS-backend",
3 | "description": "ClassIsland Management Server on Python",
4 | "author": "git@miniopensource.com",
5 | "version": "1.1beta2sp3",
6 | "url": "https://github.com/MINIOpenSource/CIMS-backend"
7 | }
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | grpcio
2 | grpcio-tools
3 | fastapi
4 | uvicorn
5 | starlette
6 | psutil
7 | opentelemetry-sdk
8 | opentelemetry-api
9 | opentelemetry-exporter-otlp-proto-http
10 | opentelemetry-instrumentation-fastapi
11 | opentelemetry-instrumentation-grpc
12 | opentelemetry-semantic-conventions
--------------------------------------------------------------------------------
/updater.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import os
3 | import sys
4 |
5 | def update_and_restart(repo_url, project_dir, service_name):
6 | """
7 | Downloads code from a GitHub repository, replaces the existing code, and restarts a service.
8 |
9 | Args:
10 | repo_url (str): The URL of the GitHub repository.
11 | project_dir (str): The local directory where the project is located.
12 | service_name (str): The name of the service to restart.
13 | """
14 | try:
15 | # 1. Navigate to the project directory
16 | os.chdir(project_dir)
17 |
18 | # 2. Fetch and reset to the latest changes from the remote repository
19 | print(f"Updating code from {repo_url}...")
20 | subprocess.run(["git", "fetch", "origin"], check=True)
21 | subprocess.run(["git", "reset", "--hard", "origin/main"], check=True) # Assuming 'main' is the main branch
22 | print("Code updated successfully.")
23 |
24 | # 3. Restart the service
25 | print(f"Restarting service: {service_name}...")
26 | subprocess.run(["sudo", "systemctl", "restart", service_name], check=True)
27 | print(f"Service {service_name} restarted successfully.")
28 |
29 | except subprocess.CalledProcessError as e:
30 | print(f"Error during update or restart: {e}")
31 | sys.exit(1)
32 | except FileNotFoundError as e:
33 | print(f"Error: Command not found: {e}")
34 | sys.exit(1)
35 | except Exception as e:
36 | print(f"An unexpected error occurred: {e}")
37 | sys.exit(1)
38 |
39 |
40 | # Example usage (replace with your actual values):
41 | # update_and_restart("https://github.com/yourusername/yourrepo.git", "/path/to/your/project", "your_service_name")
42 |
43 |
--------------------------------------------------------------------------------
/vercel.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": 2,
3 | "builds": [
4 | {
5 | "src": "-m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. ./Protobuf/Client/ClientCommandDeliverScReq.proto ./Protobuf/Client/ClientRegisterCsReq.proto ./Protobuf/Command/HeartBeat.proto ./Protobuf/Command/SendNotification.proto ./Protobuf/Enum/CommandTypes.proto ./Protobuf/Enum/Retcode.proto ./Protobuf/Server/ClientCommandDeliverScRsp.proto ./Protobuf/Server/ClientRegisterScRsp.proto ./Protobuf/Service/ClientCommandDeliver.proto ./Protobuf/Service/ClientRegister.proto",
6 | "use": "@vercel/python"
7 | },
8 | {
9 | "src": "ManagementServer.vercel/api.py",
10 | "use": "@vercel/python"
11 | },
12 | {
13 | "src": "ManagementServer.vercel/command.py",
14 | "use": "@vercel/python"
15 | }
16 | ],
17 | "routes": [
18 | {
19 | "src": "/api/(.*)",
20 | "dest": "ManagementServer.vercel/api.py"
21 | },
22 | {
23 | "src": "/command/(.*)",
24 | "dest": "ManagementServer.vercel/command.py"
25 | }
26 | ]
27 | }
--------------------------------------------------------------------------------