├── .vscode └── launch.json ├── DSM.md ├── Dockerfile ├── FNOS.md ├── LICENSE ├── README.md ├── UNRAID.md ├── app ├── PCbemfa.py ├── PCfunctions.py ├── PCrun.py ├── PCshutdown.py ├── PCweb.py ├── VERSION ├── change.log ├── data │ └── .pass ├── default │ └── config.yaml ├── static │ ├── css │ │ ├── changelog.css │ │ ├── code.css │ │ ├── config.css │ │ ├── default.css │ │ ├── index.css │ │ └── logs.css │ ├── favicon.ico │ ├── icon-theme.png │ ├── icon.png │ └── js │ │ ├── clipboard.min.js │ │ ├── code.js │ │ ├── config.js │ │ ├── highlight.min.js │ │ ├── index.js │ │ ├── logs.js │ │ └── theme.js └── templates │ ├── changelog.html │ ├── code.html │ ├── config.html │ ├── index.html │ └── logs.html ├── doc └── PowerControl教程.pdf ├── iStoreOS.md ├── icon ├── powercontrol-圆角.png ├── powercontrol.png ├── powercontrol宽图.png ├── powercontrol宽图透明.png └── powercontrol透明背景.png ├── requirements.txt └── software ├── PCshutdown.exe └── WakeOnLanMonitor.exe /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python 调试程序: 当前文件", 9 | "type": "debugpy", 10 | "request": "launch", 11 | "program": "${file}", 12 | "console": "integratedTerminal", 13 | "cwd": "${workspaceFolder}/app" 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /DSM.md: -------------------------------------------------------------------------------- 1 | # 群晖添加容器详细指引([常规](https://github.com/viklion/PowerControl/blob/main/DSM.md#常规部署) 或 [compose](https://github.com/viklion/PowerControl/blob/main/DSM.md#compose部署)) 2 | ## 常规部署 3 | > * *如需非root用户启动容器,可选择命令行部署或compose部署* 4 | 1. 打开Container Manager 5 | 6 | 点击注册表 7 | 8 | 右上角输入`powercontrol` 9 | 10 | 点击`viklion/powercontrol` 11 | 12 | 点击下载 13 | 14 | 选择标签`latest` 15 | 16 | ![dsm01](https://github.com/user-attachments/assets/92a9d65f-2c76-4fa6-9811-c751d21edc61) 17 | 18 | 1. 点击容器-新增 19 | 20 | 映像选择`viklion/powercontrol:latest` 21 | 22 | 容器名称:`powercontrol`(可自由更改) 23 | 24 | 点击`启用自动重新启动` 25 | 26 | ![dsm02](https://github.com/user-attachments/assets/5cf8ff9a-2896-4d4f-b903-e1159135e047) 27 | 28 | 1. 点击添加文件夹,选择存放配置文件和日志文件的文件夹 29 | 30 | ![dsm03](https://github.com/user-attachments/assets/0cbd9a25-5151-4ffa-a8eb-4163bf6858a1) 31 | 32 | 1. 填入映射的容器文件夹`/app/data` 33 | 34 | ![dsm04](https://github.com/user-attachments/assets/017ac052-46e2-44a7-9600-4a37687ffab3) 35 | 36 | 1. 环境变量新增: 37 | 38 | `WEB_PORT` `填入你想设置的端口号,默认:7678` 39 | 40 | `WEB_KEY` `填入你想设置的密钥,默认:admin` 41 | 42 | ![dsm05](https://github.com/user-attachments/assets/bba761ff-bc54-4952-92ae-1ff0d183c75f) 43 | 44 | 1. 网络选择`host` 45 | 46 | ![dsm06](https://github.com/user-attachments/assets/9413fe65-fdc6-4113-bf33-53cc090f87bc) 47 | 48 | 1. 容器启动后访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 49 | 50 | ## compose部署 51 | 1. 打开Container Manager 52 | 53 | 点击`项目` 54 | 55 | 点击`新增` 56 | 57 | ![dsm08](https://github.com/user-attachments/assets/84b7cd1c-eeed-4887-a3e3-a2a72a8371a5) 58 | 59 | 1. 项目名称:`powercontrol`(可自由更改) 60 | 61 | 路径:选择存放compose配置文件的文件夹 62 | 63 | 来源:选择`创建docker-compose.yml` 64 | 65 | 点击本项目github首页中Docker Compose右上角复制按钮,粘贴到下方 66 | 67 | 修改相关参数(如何查看映射文件夹完整路径、如何查看uid和gid见下方) 68 | 69 | 容器启动后访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 70 | 71 | ![dsm09](https://github.com/user-attachments/assets/d956f512-90c5-40e4-adfb-49382b79c132) 72 | 73 | 1. 查看映射文件夹完整路径 74 | 75 | 打开`File Station` 76 | 77 | 定位到需要存放容器配置和日志的文件夹 78 | 79 | 右键文件夹,点击`属性` 80 | 81 | 复制`位置`中的路径 82 | 83 | 替换compose yml中的`/your/path` 84 | 85 | ![dsm10](https://github.com/user-attachments/assets/fccc4f82-1da1-4203-9c54-3d9c7ac978d6) 86 | 87 | ![dsm11](https://github.com/user-attachments/assets/58bb28b1-dcdc-43ff-a487-10fc4e617b3e) 88 | 89 | 1. (选填)如需非root用户启动容器,查询uid和gid 90 | 91 | ssh连上群晖 92 | 93 | 输入id 登录用户名,如`id viklion` 94 | 95 | ![dsm12](https://github.com/user-attachments/assets/5501786c-2b9f-4d4e-8a77-3cbbcded8213) 96 | 97 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # 使用官方的 Python 作为基础镜像 2 | FROM python:3.12.8-alpine 3 | 4 | # 信息 5 | LABEL name="PowerControl" \ 6 | maintainer="viklion" \ 7 | github="https://github.com/viklion/PowerControl" 8 | 9 | # 设置参数 10 | ENV TZ=Asia/Shanghai 11 | 12 | # 设置工作目录 13 | WORKDIR /app 14 | 15 | # 安装包、其他操作 16 | RUN apk add --no-cache --update shadow libcap tzdata samba sshpass curl openssh-client && \ 17 | ln -fs /usr/share/zoneinfo/${TZ} /etc/localtime && \ 18 | echo ${TZ} > /etc/timezone && \ 19 | rm -rf /var/cache/apk/* && \ 20 | chmod u+s /bin/ping && \ 21 | setcap cap_net_raw+ep $(which python3.12) 22 | 23 | # 安装python模块 24 | COPY requirements.txt /app/ 25 | RUN pip install --no-cache-dir -r requirements.txt 26 | 27 | # 创建一些用户和组 28 | RUN for i in $(seq 1000 1005) $(seq 1025 1030); do \ 29 | useradd -d /app -u $i -g 100 PCuser$i; \ 30 | groupadd -g $i PCuser$i; \ 31 | done 32 | 33 | # 复制文件 34 | COPY --chmod=755 software /app/static/ 35 | COPY --chmod=755 doc /app/static/ 36 | COPY --chmod=755 app LICENSE /app/ 37 | 38 | # 版本 39 | ARG VERSION="2.92" 40 | 41 | # 设置容器启动时运行的命令 42 | CMD ["python", "PCrun.py"] 43 | -------------------------------------------------------------------------------- /FNOS.md: -------------------------------------------------------------------------------- 1 | # 飞牛添加容器详细指引([常规](https://github.com/viklion/PowerControl/blob/main/FNOS.md#常规部署) 或 [compose](https://github.com/viklion/PowerControl/blob/main/FNOS.md#compose部署)) 2 | ## 常规部署 3 | > * *如需非root用户启动容器,可选择命令行部署或compose部署* 4 | 1. 打开docker 5 | 6 | 点击`镜像仓库` 7 | 8 | 右上角输入`powercontrol`回车 9 | 10 | 找到`viklion/powercontrol`点击下载图标 11 | 12 | 选择标签`latest` 13 | 14 | ![20250603183549_1](https://github.com/user-attachments/assets/8a6307a8-2f08-4261-84d6-26fde55e7561) 15 | 16 | 1. 点击容器-添加容器 17 | 18 | 镜像名称选择`viklion/powercontrol:latest` 19 | 20 | 容器名称:`powercontrol`(可自由更改) 21 | 22 | 点击`开机自动开启`(其实就是“启用自动重新启动”,即容器异常退出会自动重启容器,不知道为什么飞牛要写成“开机自动开启”) 23 | 24 | ![20250603183550_2](https://github.com/user-attachments/assets/5ca6d4f3-1d25-4d2a-a283-9dae46055889) 25 | 26 | 1. 存储位置-点击添加路径,选择存放配置文件和日志文件的文件夹 27 | 28 | ![20250603183550_3](https://github.com/user-attachments/assets/677c15ee-01be-4e78-95ea-0f978478d0c9) 29 | 30 | ![20250603183549_4](https://github.com/user-attachments/assets/eee75ca5-1d70-41f0-b32e-b0471ded989f) 31 | 32 | 1. 填入映射的容器文件夹`/app/data` 33 | 34 | ![20250603183550_5](https://github.com/user-attachments/assets/c8c8f0e2-6ce4-4e7a-8114-da2af74abae1) 35 | 36 | 1. 环境变量新增: 37 | 38 | `WEB_PORT` `填入你想设置的端口号,默认:7678` 39 | 40 | `WEB_KEY` `填入你想设置的密钥,默认:admin` 41 | 42 | ![20250603183550_6](https://github.com/user-attachments/assets/3eac7a64-9f0a-49dd-a4de-f3edeed7d34a) 43 | 44 | 1. 网络选择`host` 45 | 46 | ![20250603183549_7](https://github.com/user-attachments/assets/23c93184-85f6-449f-8b10-10b7b1ae1f2d) 47 | 48 | 1. 容器启动后访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 49 | 50 | ## compose部署 51 | 1. 打开docker 52 | 53 | 点击`Compose` 54 | 55 | 点击`新增项目` 56 | 57 | 1. 项目名称:`powercontrol`(可自由更改) 58 | 59 | 路径:选择存放compose配置文件的文件夹 60 | 61 | 来源:选择`创建docker-compose.yml` 62 | 63 | 点击本项目github首页中Docker Compose右上角复制按钮,粘贴到下方 64 | 65 | 修改相关参数(如何查看映射文件夹完整路径、如何查看uid和gid见下方) 66 | 67 | 容器启动后访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 68 | 69 | ![fn01](https://github.com/user-attachments/assets/f0020dbc-35e3-4f0c-b0f1-4ec3716a2931) 70 | 71 | 1. 查看映射文件夹完整路径 72 | 73 | 打开`文件管理` 74 | 75 | 定位到需要存放容器配置和日志的文件夹 76 | 77 | 右键文件夹,点击`详细信息` 78 | 79 | 点击`位置`中的`复制原始路径` 80 | 81 | 替换compose yml中的`/your/path` 82 | 83 | ![fn02](https://github.com/user-attachments/assets/68daa13b-41cf-4b69-97a0-5faa888a18ea) 84 | 85 | ![fn03](https://github.com/user-attachments/assets/5da4e3b3-eaa0-4240-87c9-fd884a985a32) 86 | 87 | 1. (选填)如需非root用户启动容器,查询uid和gid 88 | 89 | ssh连上飞牛 90 | 91 | 输入id 登录用户名,如`id viklion` 92 | 93 | ![fn04](https://github.com/user-attachments/assets/2bbaf4d2-971d-4809-9bc3-bc5d51c2e594) 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![logo](https://github.com/user-attachments/assets/8738de3a-23a3-48d1-bb91-23b152551122) 2 | 3 | # PowerControl 4 | docker容器远程网络唤醒设备,远程关闭windows设备,通过访问网页控制,并可依赖巴法云接入米家,通过米家远程操作(需要小爱音箱)
5 | **米家控制受米家、巴法平台稳定性因素影响*
6 | `linux/amd64, linux/arm/v7, linux/arm64, linux/386` 7 | 8 | ## 部署 9 | * [视频教程(bilibili)](https://www.bilibili.com/video/BV1cykZY7Er9) 10 | 11 | * 小白级详细部署教程:[UNRAID](https://github.com/viklion/PowerControl/blob/main/UNRAID.md) • [群晖](https://github.com/viklion/PowerControl/blob/main/DSM.md) • [飞牛](https://github.com/viklion/PowerControl/blob/main/FNOS.md) • [iStoreOS](https://github.com/viklion/PowerControl/blob/main/iStoreOS.md) 12 | 13 |
14 | 15 | 不要直接复制命令运行,需要修改参数
16 | > 1、将容器/app/data目录映射到你的主机目录,存放配置文件和日志文件:
17 |     `修改/your/path`
18 | 2、修改环境变量:
19 |     `WEB_PORT:网页端口`
20 |     `WEB_KEY:密钥` 21 | 22 | **不设置环境变量则使用默认参数`port:7678`,`key:admin`* 23 | ### 1、Docker CLI 24 | + 默认root用户运行 25 | ``` 26 | docker run -d -v /your/path:/app/data -e WEB_PORT=7678 -e WEB_KEY=admin --network host --restart unless-stopped --name powercontrol viklion/powercontrol:latest 27 | ``` 28 | + 设置指定user运行(-u uid:gid)
29 | **重要:如果切换非root运行,请务必检查映射目录的读写权限(配置文件、日志文件),如遇写入错误,请递归修改权限* 30 | ``` 31 | docker run -d -u 1000:100 -v /your/path:/app/data -e WEB_PORT=7678 -e WEB_KEY=admin --network host --restart unless-stopped --name powercontrol viklion/powercontrol:latest 32 | ``` 33 | 34 | ### 2、Docker Compose 35 | ``` 36 | services: 37 | powercontrol: 38 | image: viklion/powercontrol:latest 39 | container_name: powercontrol 40 | volumes: 41 | - /your/path:/app/data 42 | environment: 43 | - WEB_PORT=7678 44 | - WEB_KEY=admin 45 | # 默认root用户运行,去掉下行的#,设置指定user运行(uid:gid) 46 | #user: 1000:100 47 | restart: unless-stopped 48 | network_mode: host 49 | ``` 50 | 51 | ## 配置 52 | 访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 53 | 54 | ## 界面 55 | ![index](https://github.com/user-attachments/assets/3df4b928-0cf9-4deb-a478-5681dc77b586) 56 | 57 | ![config](https://github.com/user-attachments/assets/ac7eba15-5e32-4495-a015-931a4e3ca7a6) 58 | 59 | 60 | -------------------------------------------------------------------------------- /UNRAID.md: -------------------------------------------------------------------------------- 1 | # UNRAID添加容器详细指引 2 | 1. docker界面左下角点击添加容器 3 | 4 | ![unraid-01](https://github.com/user-attachments/assets/93eb7afc-b56e-4a1f-8f89-37fbeadbeb82) 5 | 6 | 1. 名称填入`powercontrol`(可自由更改) 7 | 8 | 存储库填入`viklion/powercontrol:latest` 9 | 10 | 网络类型选择`Host` 11 | 12 | 然后点击添加另一个路径、端口、变量、标签或设备 13 | 14 | ![unraid-04](https://github.com/user-attachments/assets/ead45847-37d1-4c82-9a64-ae9243bbf506) 15 | 16 | 1. 配置类型选择`路径` 17 | 18 | 名称:`config` 19 | 20 | 容器路径:`/app/data` 21 | 22 | 主机路径:`/mnt/user/appdata/powercontrol` 23 | 24 | 访问模式:`读/写` 25 | 26 | ![unraid-05](https://github.com/user-attachments/assets/05f3bded-564c-4ae3-a42b-aa0978489611) 27 | 28 | 1. 再次点击添加另一个路径、端口、变量、标签或设备 29 | 30 | 配置类型选择`变量` 31 | 32 | 名称:`WEB_PORT` 33 | 34 | 键:`WEB_PORT` 35 | 36 | 值:`填入你想设置的端口号,默认:7678` 37 | 38 | ![unraid-06](https://github.com/user-attachments/assets/72126401-ce88-43a1-8405-83c43c0ed895) 39 | 40 | 1. 再次点击添加另一个路径、端口、变量、标签或设备 41 | 42 | 配置类型选择`变量` 43 | 44 | 名称:`WEB_KEY` 45 | 46 | 键:`WEB_KEY` 47 | 48 | 值:`填入你想设置的密钥,默认:admin` 49 | 50 | ![unraid-07](https://github.com/user-attachments/assets/0b68c338-1515-4590-bacf-039a0f32b839) 51 | 52 | 1. 右上角点击高级视图 53 | 54 | ![unraid-02](https://github.com/user-attachments/assets/da9104a4-ec17-4d16-8c2f-92db44bbff3b) 55 | 56 | 1. 额外参数中填入`--restart unless-stopped` 57 | 58 | ![unraid-08](https://github.com/user-attachments/assets/7a485371-2694-4bbb-96e4-bed5132cb77f) 59 | 60 | 1. (选填)非root用户启动容器 61 | 62 | 额外参数中填入`-u uid:gid` 63 | 64 | 如何查询uid和gid 65 | 66 | 右上角点击终端 67 | 68 | ![unraid-03](https://github.com/user-attachments/assets/089039c4-0291-4412-ba56-e175b56525d5) 69 | 70 | 输入id 共享访问的用户,如`id viklion` 71 | 72 | ![unraid-09](https://github.com/user-attachments/assets/80ebfd45-edd5-404f-ad70-7d60797595f5) 73 | 74 | 1. 容器启动后访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 75 | 76 | 1. 如果拉取镜像遇到网络(梯子)问题 77 | 78 | 尝试将存储库修改为`docker.1panel.live/viklion/powercontrol:latest` 79 | -------------------------------------------------------------------------------- /app/PCbemfa.py: -------------------------------------------------------------------------------- 1 | import socket, time 2 | from PCfunctions import write_log, send_message, pcwol, pcshutdown, get_time, extra_log 3 | from datetime import datetime 4 | 5 | class PCbemfa(): 6 | def __init__(self ,funcs_data): 7 | self.server_ip = 'bemfa.com' 8 | self.server_port = 8344 9 | self.fd = funcs_data 10 | self.enabled = self.fd.bemfa_enabled 11 | if self.enabled: 12 | self.uid = self.fd.bemfa_uid 13 | self.topic = self.fd.bemfa_topic 14 | self.ping_enabled = self.fd.ping_enabled 15 | self.bemfa_reconnect_count = 0 16 | extra_log("bemfa初始化成功",2, '_bemfa') 17 | 18 | # 订阅 19 | def connTCP(self): 20 | while True: 21 | try: 22 | # 创建socket 23 | self.tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 24 | self.tcp_client_socket.settimeout(120) 25 | # 连接服务器 26 | self.tcp_client_socket.connect((self.server_ip, self.server_port)) 27 | # 发送订阅指令 28 | substr = f'cmd=1&uid={self.uid}&topic={self.topic}\r\n' 29 | self.tcp_client_socket.send(substr.encode('utf-8')) 30 | # 写入日志 31 | extra_log("bemfa订阅成功", 2, '_bemfa') 32 | break 33 | except: 34 | extra_log("bemfa订阅失败,1分钟后重试...", 3, '_bemfa') 35 | time.sleep(60) 36 | 37 | # 心跳 38 | def send_heartbeat_packet(self): 39 | # 发送心跳 40 | try: 41 | self.tcp_client_socket.send('ping\r\n'.encode('utf-8')) 42 | write_log("已发送bemfa心跳包",1,'_bemfa') 43 | except: 44 | extra_log("发送bemfa心跳包失败",3, '_bemfa') 45 | 46 | # 开启定时发送心跳包 47 | def add_send_heartbeat_packet_job(self): 48 | try: 49 | self.fd.scheduler.add_job(self.send_heartbeat_packet, 'interval', seconds=60, next_run_time=datetime.now(), id='send_heartbeat_packet_job') 50 | extra_log("bemfa心跳包定时发送已启动", 2, '_bemfa') 51 | except Exception as e: 52 | extra_log("开启bemfa心跳包定时发送任务失败:"+str(e),3, '_bemfa') 53 | 54 | # 关闭定时发送心跳包 55 | def remove_send_heartbeat_packet_job(self): 56 | try: 57 | self.fd.scheduler.remove_job('send_heartbeat_packet_job') 58 | extra_log("关闭bemfa心跳包定时发送", 2, '_bemfa') 59 | except Exception as e: 60 | extra_log("关闭bemfa心跳包定时发送任务失败:"+str(e),3, '_bemfa') 61 | 62 | # 更新巴法云的设备状态 63 | def update_bemfa(self): 64 | pc_state = self.fd.pc_state 65 | if pc_state: 66 | try: 67 | substr = f'cmd=2&uid={self.uid}&topic={self.topic}/up&msg={pc_state[1]}\r\n' 68 | self.tcp_client_socket.send(substr.encode("utf-8")) 69 | write_log("bemfa设备状态更新:"+pc_state[0], 1, '_bemfa') 70 | except Exception as e: 71 | extra_log("更新bemfa设备状态失败:"+str(e),3, '_bemfa') 72 | 73 | # 开启定时更新巴法云的设备状态 74 | def add_update_bemfa_job(self): 75 | if self.ping_enabled: 76 | try: 77 | self.fd.scheduler.add_job(self.update_bemfa, 'interval', seconds=60, next_run_time=datetime.now(), id='update_bemfa_job') 78 | extra_log("bemfa设备状态定时更新已启动", 2, '_bemfa') 79 | except Exception as e: 80 | extra_log("开启bemfa设备状态定时更新任务失败:"+str(e),3, '_bemfa') 81 | 82 | # 关闭定时更新巴法云的设备状态 83 | def remove_update_bemfa_job(self): 84 | if self.ping_enabled: 85 | try: 86 | self.fd.scheduler.remove_job('update_bemfa_job') 87 | extra_log("关闭bemfa设备状态定时更新", 2, '_bemfa') 88 | except Exception as e: 89 | extra_log("关闭bemfa设备状态定时更新任务失败:"+str(e),3, '_bemfa') 90 | 91 | # 重置重连次数 92 | def reset_reconnect_count(self): 93 | self.bemfa_reconnect_count = 0 94 | 95 | # 重置重连次数定时任务 96 | def add_reset_reconnect_count_job(self): 97 | self.fd.scheduler.add_job(self.reset_reconnect_count, 'cron', hour=0, minute=0, id='reset_reconnect_count_job') 98 | 99 | # 收到消息后执行开关机 100 | def power_control(self, state): 101 | if state == 'on' : 102 | rs = pcwol() 103 | if rs: 104 | if rs == 'done': 105 | extra_log('已发送唤醒指令(bemfa)',2, '_bemfa') 106 | send_message('已发送唤醒指令') 107 | else: 108 | extra_log('发送唤醒指令失败(bemfa)' + ' → ' + rs ,3, '_bemfa') 109 | send_message('发送唤醒指令失败') 110 | else: 111 | extra_log('未启用网络唤醒(bemfa)' ,3, '_bemfa') 112 | send_message('未启用网络唤醒') 113 | elif state == 'off': 114 | rs = pcshutdown() 115 | if rs: 116 | if 'succeeded' in rs: 117 | extra_log("已发送关机指令(bemfa)" + ' → ' + rs ,2, '_bemfa') 118 | send_message('已发送关机指令') 119 | else: 120 | extra_log("关机指令发送失败(bemfa)" + ' → ' + rs ,3, '_bemfa') 121 | send_message('关机指令发送失败') 122 | else: 123 | extra_log('未启用远程关机(bemfa)' ,3, '_bemfa') 124 | send_message('未启用远程关机') 125 | 126 | # 主循环 127 | def mainloop(self): 128 | while True: 129 | try: 130 | # 接收服务器发送过来的数据 131 | recv_Data = self.tcp_client_socket.recv(1024) 132 | recv_str = str(recv_Data.decode('utf-8')) 133 | write_log(recv_str.replace('\n', '').replace('\r', ''),1,'_bemfa') 134 | except Exception as e: 135 | extra_log("接收bemfa服务器消息出错,重新订阅...Error: " + str(e), 3, '_bemfa') 136 | break 137 | 138 | if not recv_Data: 139 | extra_log("bemfa服务器未返回任何数据,重新订阅...",3, '_bemfa') 140 | break 141 | 142 | elif f'uid={self.uid}' in recv_str: 143 | # 收到开机消息 144 | if 'msg=on' in recv_str: 145 | self.power_control('on') 146 | # 收到关机消息 147 | elif 'msg=off' in recv_str: 148 | self.power_control('off') 149 | 150 | # 启动 151 | def run(self, retry=False): 152 | if self.enabled: 153 | if not retry: 154 | extra_log("bemfa服务启动",2, '_bemfa') 155 | self.add_reset_reconnect_count_job() 156 | elif retry: 157 | self.bemfa_reconnect_count += 1 158 | extra_log(f"正在重新订阅bemfa(今日第{self.bemfa_reconnect_count}次)",2, '_bemfa') 159 | self.remove_send_heartbeat_packet_job() 160 | self.remove_update_bemfa_job() 161 | if self.fd.push_enabled: 162 | if self.fd.push_bemfa_reconnect: 163 | if self.bemfa_reconnect_count <= 5: 164 | send_message( f'重新订阅bemfa提醒', desp=f'正在重新订阅bemfa(今日第{self.bemfa_reconnect_count}次)\n\n断连时间:{get_time()}\n\n可能的原因:网络发生短暂断开;bemfa服务器偶然断连。\n\n*当天重连推送达5次后将不再推送,请查看日志。', retry=True) 165 | elif self.bemfa_reconnect_count == 6: 166 | extra_log("今日重连推送已达5次,将不再推送", 2, '_bemfa') 167 | try: 168 | self.tcp_client_socket.close() 169 | except Exception as e: 170 | extra_log("关闭TCP连接失败,Error: " + str(e), 3, '_bemfa') 171 | if self.bemfa_reconnect_count > 5: 172 | if self.bemfa_reconnect_count == 6: 173 | extra_log(rf"今日重连已达5次,后续重连将有60秒的等待时间",2, '_bemfa') 174 | extra_log(rf"等待60秒...",2, '_bemfa') 175 | time.sleep(60) 176 | self.connTCP() 177 | self.add_send_heartbeat_packet_job() 178 | self.add_update_bemfa_job() 179 | self.mainloop() 180 | self.run(retry=True) -------------------------------------------------------------------------------- /app/PCfunctions.py: -------------------------------------------------------------------------------- 1 | import yaml, json, os, time, socket, subprocess, requests, shutil, threading 2 | from datetime import datetime, timedelta 3 | from wakeonlan import send_magic_packet 4 | from pythonping import ping 5 | from serverchan_sdk import sc_send 6 | from apscheduler.schedulers.background import BackgroundScheduler 7 | 8 | class PCfuncs(): 9 | start_time = time.time() 10 | yaml_file = 'config.yaml' 11 | yaml_path = os.path.join(os.getcwd(), 'data', yaml_file) 12 | default_path = os.path.join(os.getcwd(), 'default', yaml_file) 13 | log_path = os.path.join(os.getcwd(), 'data', 'logs') 14 | pc_state = [] 15 | 16 | def __init__(self): 17 | self.yaml_changed = False 18 | self.is_power_off = False 19 | self.scheduler = BackgroundScheduler() 20 | self.scheduler.start() 21 | 22 | # 检查目录权限 23 | self.check_permission('r') 24 | self.check_permission('w') 25 | 26 | # 检查是否存在配置文件,没有则拷贝一份 27 | self.check_yaml() 28 | 29 | # 读取配置文件 30 | yd = self.read_config_yaml() 31 | 32 | # 读取默认配置文件 33 | yd_default = self.read_default_yaml() 34 | 35 | # 更新YAML 36 | self.update_yaml(yd ,yd_default) 37 | if self.yaml_changed: 38 | self.write_config_yaml(yd) 39 | p_print('配置文件已更新新内容') 40 | 41 | # 参数 42 | PCfuncs.version = get_version() 43 | PCfuncs.bemfa_enabled = checkbool(yd['bemfa']['enabled']) 44 | if PCfuncs.bemfa_enabled: 45 | PCfuncs.bemfa_uid = trans_str(yd['bemfa']['uid']) 46 | PCfuncs.bemfa_topic = trans_str(yd['bemfa']['topic']) 47 | PCfuncs.device_name = trans_str(yd['devices']['name']) 48 | PCfuncs.device_ip = trans_str(yd['devices']['ip']) 49 | PCfuncs.wol_enabled = checkbool(yd['devices']['wol']['enabled']) 50 | if PCfuncs.wol_enabled: 51 | PCfuncs.wol_mac = trans_str(yd['devices']['wol']['mac']) 52 | PCfuncs.wol_destination = trans_str(yd['devices']['wol']['destination']) 53 | PCfuncs.wol_port = int(yd['devices']['wol']['port']) 54 | PCfuncs.wol_interface = trans_str(yd['devices']['wol']['interface']).lower() 55 | PCfuncs.shutdown_enabled = checkbool(yd['devices']['shutdown']['enabled']) 56 | if PCfuncs.shutdown_enabled: 57 | PCfuncs.shutdown_method_netrpc = checkbool(yd['devices']['shutdown']['method']['netrpc']) 58 | PCfuncs.shutdown_method_udp = checkbool(yd['devices']['shutdown']['method']['udp']) 59 | PCfuncs.shutdown_method_shell = checkbool(yd['devices']['shutdown']['method']['shell']) 60 | PCfuncs.shutdown_time = trans_str(yd['devices']['shutdown']['time']) 61 | if PCfuncs.shutdown_method_netrpc: 62 | PCfuncs.shutdown_pc_account = trans_str(yd['devices']['shutdown']['account']) 63 | PCfuncs.shutdown_pc_password = trans_str(yd['devices']['shutdown']['password']) 64 | elif PCfuncs.shutdown_method_shell: 65 | PCfuncs.shell_script = trans_str(yd['devices']['shutdown']['shell_script']) 66 | PCfuncs.shell_script_allowed = tuple(yd['devices']['shutdown']['shell_script_allowed']) 67 | PCfuncs.shutdown_timeout = int(yd['devices']['shutdown']['timeout']) 68 | PCfuncs.ping_enabled = checkbool(yd['devices']['ping']['enabled']) 69 | if PCfuncs.ping_enabled: 70 | PCfuncs.ping_time = int(yd['devices']['ping']['time']) 71 | PCfuncs.log_enabled = checkbool(yd['functions']['log']['enabled']) 72 | if PCfuncs.log_enabled: 73 | PCfuncs.log_level = int(yd['functions']['log']['level']) 74 | PCfuncs.clear_log_enabled = checkbool(yd['functions']['log']['clear_log']['enabled']) 75 | if PCfuncs.clear_log_enabled: 76 | PCfuncs.log_keep_days = int(yd['functions']['log']['clear_log']['keep_days']) 77 | PCfuncs.push_enabled = checkbool(yd['functions']['push_notifications']['enabled']) 78 | if PCfuncs.push_enabled: 79 | PCfuncs.push_bemfa_reconnect = checkbool(yd['functions']['push_notifications']['bemfa_reconnect']) 80 | PCfuncs.push_serverchan_turbo_enabled = checkbool(yd['functions']['push_notifications']['ServerChan_turbo']['enabled']) 81 | if PCfuncs.push_serverchan_turbo_enabled: 82 | PCfuncs.push_serverchan_turbo_SendKey = trans_str(yd['functions']['push_notifications']['ServerChan_turbo']['SendKey']) 83 | PCfuncs.push_serverchan_turbo_channel = trans_str(yd['functions']['push_notifications']['ServerChan_turbo']['channel']) 84 | PCfuncs.push_serverchan3_enabled = checkbool(yd['functions']['push_notifications']['ServerChan3']['enabled']) 85 | if PCfuncs.push_serverchan3_enabled: 86 | PCfuncs.push_serverchan3_SendKey = trans_str(yd['functions']['push_notifications']['ServerChan3']['SendKey']) 87 | PCfuncs.push_qmsg_enabled = checkbool(yd['functions']['push_notifications']['Qmsg']['enabled']) 88 | if PCfuncs.push_qmsg_enabled: 89 | PCfuncs.push_qmsg_key = trans_str(yd['functions']['push_notifications']['Qmsg']['key']) 90 | PCfuncs.push_qmsg_qq = trans_str(yd['functions']['push_notifications']['Qmsg']['qq']) 91 | PCfuncs.push_wechat_webhook_enabled = checkbool(yd['functions']['push_notifications']['WeChat_webhook']['enabled']) 92 | if PCfuncs.push_wechat_webhook_enabled: 93 | PCfuncs.push_wechat_webhook_url = trans_str(yd['functions']['push_notifications']['WeChat_webhook']['url']) 94 | 95 | # 本机ip 96 | PCfuncs.local_ip = get_ip_address() 97 | 98 | # 判断处理参数 99 | if PCfuncs.device_name: 100 | PCfuncs.device_name = f'[{PCfuncs.device_name}]' 101 | if PCfuncs.wol_destination == 'broadcast_ip_global': 102 | PCfuncs.wol_destination = '255.255.255.255' 103 | elif PCfuncs.wol_destination == 'broadcast_ip_direct': 104 | PCfuncs.wol_destination = PCfuncs.device_ip.rsplit('.', 1)[0] + '.255' 105 | elif PCfuncs.wol_destination == 'device_ip': 106 | PCfuncs.wol_destination = PCfuncs.device_ip 107 | if PCfuncs.wol_interface == 'default': 108 | PCfuncs.wol_interface = PCfuncs.local_ip 109 | elif PCfuncs.wol_interface == 'none': 110 | PCfuncs.wol_interface = None 111 | 112 | print_and_log('----------------------------------', 2) 113 | print_and_log('PowerControl启动', 2) 114 | send_message('PowerControl启动') 115 | if self.yaml_changed: 116 | write_log('配置文件已更新新内容', 2) 117 | print_and_log('获取本机ip:'+PCfuncs.local_ip, 2) 118 | 119 | # 启动定时任务 120 | self.add_ping_job() 121 | self.add_clear_log_job() 122 | 123 | # 检查目录权限 124 | def check_permission(self, mode): 125 | path = os.path.join(os.getcwd(), 'data') 126 | # 检查目录是否存在 127 | if not os.path.exists(path): 128 | p_print(f"{path} 不存在") 129 | 130 | if mode == 'r': 131 | # 检查目录是否可读 132 | if os.access(path, os.R_OK): 133 | p_print(f"{path} 有读取权限") 134 | else: 135 | p_print(f"{path} 无读取权限") 136 | elif mode == 'w': 137 | # 检查目录是否可写 138 | if os.access(path, os.W_OK): 139 | p_print(f"{path} 有写入权限") 140 | else: 141 | p_print(f"{path} 无写入权限") 142 | elif mode == 'x': 143 | # 检查目录是否可执行 144 | if os.access(path, os.X_OK): 145 | p_print(f"{path} 有执行权限") 146 | else: 147 | p_print(f"{path} 无执行权限") 148 | 149 | # 检查YAML文件 150 | def check_yaml(self): 151 | # 检查当前目录下是否存在yaml文件 152 | if not os.path.isfile(self.yaml_path): 153 | try: 154 | # 从default目录拷贝文件到当前目录 155 | shutil.copy(self.default_path, self.yaml_path) 156 | p_print(f"已生成'{self.yaml_file}'") 157 | except Exception as e: 158 | p_print(f"生成'{self.yaml_file}'失败: {e}") 159 | else: 160 | p_print(f"'{self.yaml_file}'存在") 161 | 162 | # 读取用户YAML文件 163 | def read_config_yaml(self): 164 | try: 165 | with open(self.yaml_path, 'r',encoding='GBK') as f: 166 | return yaml.safe_load(f) 167 | except Exception as e: 168 | p_print("读取配置文件出错:" + str(e)) 169 | return {} 170 | # 读取默认YAML文件 171 | def read_default_yaml(self): 172 | try: 173 | with open(self.default_path, 'r',encoding='GBK') as f: 174 | return yaml.safe_load(f) 175 | except Exception as e: 176 | p_print(str(e)) 177 | return {} 178 | 179 | # 更新YAML文件 180 | def update_yaml(self ,config_yaml ,default_yaml): 181 | try: 182 | for key, value in default_yaml.items(): 183 | if key in config_yaml: 184 | if isinstance(value, dict): 185 | if isinstance(config_yaml[key], dict): 186 | # 如果两个值都是字典,则递归合并 187 | self.update_yaml(config_yaml[key], value) 188 | else: 189 | # 如果原yaml中的值不是字典,则更新为默认值 190 | config_yaml[key] = value 191 | self.yaml_changed = True 192 | else: 193 | # 如果键在原yaml中不存在,则添加该键 194 | config_yaml[key] = value 195 | self.yaml_changed = True 196 | except Exception as e: 197 | p_print("更新配置文件出错:" + str(e)) 198 | self.yaml_changed = False 199 | 200 | # 保存YAML文件 201 | def write_config_yaml(self ,data): 202 | try: 203 | with open(self.yaml_path, 'w',encoding='GBK') as f: 204 | yaml.safe_dump(data, f, default_flow_style=False, sort_keys=False, allow_unicode=True) 205 | p_print("保存配置文件成功") 206 | return True 207 | except Exception as e: 208 | p_print("保存配置文件出错:" + str(e)) 209 | return str(e) 210 | 211 | # 定时ping检测设备状态 212 | def ping_check(self ,is_power_off): 213 | try: 214 | ping_result = pcping() 215 | write_log('\n' + ping_result + '\n' + '----------------------------------', 1 ,'_ping') 216 | if 'Reply' in ping_result: 217 | is_power_off = False 218 | new_state = ["在线","on"] 219 | elif 'timed out' in ping_result: 220 | if not is_power_off: 221 | self.ping_check(True) 222 | return 223 | new_state = ["离线","off"] 224 | if self.pc_state != new_state: 225 | self.pc_state = new_state 226 | print_and_log(f"设备状态更新:{self.pc_state[0]}",2) 227 | send_message(f"状态更新:{self.pc_state[0]}") 228 | except Exception as e: 229 | extra_log("ping出错:" + str(e),3,'_ping') 230 | 231 | # 开启定时ping 232 | def add_ping_job(self): 233 | if self.ping_enabled: 234 | try: 235 | self.scheduler.add_job(self.ping_check, 'interval', seconds=self.ping_time, args=(self.is_power_off,) ,next_run_time=datetime.now(), id='ping_job') 236 | print_and_log("Ping服务已启动", 2) 237 | except Exception as e: 238 | print_and_log("启动定时ping任务出错:" + str(e),3) 239 | 240 | # 开启定时清理日志 241 | def add_clear_log_job(self): 242 | if self.log_enabled: 243 | if self.clear_log_enabled: 244 | try: 245 | self.scheduler.add_job(clear_log, 'cron', hour=12, next_run_time=datetime.now(), id='clear_log_job') 246 | print_and_log("日志定时清理已启动(每天中午12点)", 2) 247 | except Exception as e: 248 | print_and_log("启动定时清理日志任务出错:" + str(e),3) 249 | 250 | # 统计运行时间 251 | def run_time(self): 252 | run_timedelta = timedelta(seconds=time.time()-self.start_time) 253 | # 获取天、小时、分钟和秒 254 | days = run_timedelta.days 255 | hours, remainder = divmod(run_timedelta.seconds, 3600) 256 | minutes, seconds = divmod(remainder, 60) 257 | return f"已运行:{days}天{hours}小时{minutes}分钟{seconds}秒" 258 | 259 | #--------------------------------------------------------------------------------------------------------- 260 | # 获取当前时间 261 | def get_time(): 262 | return datetime.now().strftime('%Y-%m-%d %H:%M:%S') 263 | 264 | # 获取本机ip地址 265 | def get_ip_address(): 266 | try: 267 | # 创建一个socket对象 268 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 269 | # 连接到目标网址 270 | s.connect(("192.168.255.255", 80)) 271 | # 获取本地IP地址 272 | ip_address = s.getsockname()[0] 273 | # 关闭socket连接 274 | s.close() 275 | return ip_address 276 | except socket.error: 277 | return "无法获取IP地址" 278 | 279 | # 读取版本信息 280 | def get_version(): 281 | try: 282 | with open("VERSION", "r") as f: 283 | return f.read().strip() 284 | except: 285 | return "版本号获取失败" 286 | 287 | # 带时间的print 288 | def p_print(content): 289 | print(get_time() + ' ' +content) 290 | 291 | # 返回布尔值 292 | def checkbool(bool_str): 293 | return str(bool_str).lower() == 'true' 294 | 295 | # 转变字符串并去掉空格 296 | def trans_str(thing): 297 | if thing is None: 298 | return '' 299 | return str(thing).strip() 300 | 301 | # 日志记录 302 | def write_log(content, level, nameadd = ''): 303 | if PCfuncs.log_enabled: 304 | if PCfuncs.log_level == 1 or level >= PCfuncs.log_level: 305 | try: 306 | if not os.path.exists(PCfuncs.log_path): 307 | # 如果不存在,则创建logs文件夹 308 | os.makedirs(PCfuncs.log_path) 309 | # 打开日志文件,"a"追加写入 310 | time_day = datetime.now().strftime('%Y-%m-%d') 311 | with open(os.path.join(PCfuncs.log_path ,rf'{time_day}{nameadd}.log'), 'a',encoding='GBK') as file: 312 | if level == 1: 313 | front = '[Result]: ' 314 | elif level == 2: 315 | front = '[Status]: ' 316 | elif level == 3: 317 | front = '[Error]: ' 318 | file.write(PCfuncs.device_name + front + get_time() + ' ' + content + '\n') 319 | except Exception as e: 320 | p_print(get_time() + " 写入日志出错了:\n" + str(e)) 321 | 322 | # 清理日志 323 | def clear_log(): 324 | if os.path.exists(PCfuncs.log_path): 325 | keep_days = PCfuncs.log_keep_days 326 | # 获取今天的日期 327 | today = datetime.today() 328 | # 需要保留的最早日期 329 | if keep_days == 0: # 只保留当天日志 330 | keep_date = datetime(today.year, today.month, today.day) 331 | else: 332 | keep_date = today - timedelta(days=keep_days) 333 | # 遍历日志目录 334 | for filename in os.listdir(PCfuncs.log_path): 335 | # 只处理.log文件 336 | if filename.endswith(".log"): 337 | try: 338 | # 获取文件的完整路径 339 | file_path = os.path.join(PCfuncs.log_path, filename) 340 | # 获取文件的最后修改时间 341 | file_mtime = os.path.getmtime(file_path) 342 | # 将最后修改时间转换为 datetime 对象 343 | file_date = datetime.fromtimestamp(file_mtime) 344 | # 对比日期,删除早于保留日期的文件 345 | if file_date < keep_date: 346 | os.remove(file_path) 347 | print_and_log(f"已删除日志: {filename}", 2) 348 | except Exception as e: 349 | # 如果发生异常输出错误信息 350 | print_and_log(f"删除日志 {filename} 出错: {str(e)}", 3) 351 | 352 | # 同时打印和日志记录 353 | def print_and_log(content, level): 354 | p_print(content) 355 | write_log(content, level) 356 | 357 | # 扩展日志记录 358 | def extra_log(content, level, nameadd): 359 | print_and_log(content,level) 360 | write_log(content,1, nameadd) 361 | 362 | # 消息推送 363 | def send_message(title, desp='', retry=False): 364 | if PCfuncs.push_enabled: 365 | if not retry: 366 | send = threading.Thread(target=send_message_main, args=(title, desp,)) 367 | send.start() 368 | elif retry: 369 | re_send = threading.Thread(target=re_send_message_main, args=(title, desp,)) 370 | re_send.start() 371 | def send_message_main(title, desp=''): 372 | response = {} 373 | if PCfuncs.push_enabled: 374 | response['serverchan_turbo'] = send_message_serverchan_turbo(title, desp) 375 | response['serverchan3'] = send_message_serverchan3(title, desp) 376 | response['qmsg'] = send_message_qmsg(title, desp) 377 | response['wechat_webhook'] = send_message_wechat_webhook(title, desp) 378 | return response 379 | 380 | # 断网下等待网络恢复重新发送 381 | def re_send_message_main(title, desp): 382 | while True: 383 | try: 384 | rs = str(ping('www.baidu.com', timeout = 1, count = 1)) 385 | except: 386 | time.sleep(10) 387 | continue 388 | if 'timed out' in rs: 389 | time.sleep(10) 390 | continue 391 | elif 'Reply' in rs: 392 | send_message(title, desp) 393 | break 394 | 395 | # Server酱Turbo推送 396 | def send_message_serverchan_turbo(title, desp=''): 397 | if PCfuncs.push_serverchan_turbo_enabled: 398 | try: 399 | data = { 400 | 'title': PCfuncs.device_name + title, 401 | 'desp': get_time() + ' ' + desp, 402 | 'channel': PCfuncs.push_serverchan_turbo_channel 403 | } 404 | rs = requests.post(f'https://sctapi.ftqq.com/{PCfuncs.push_serverchan_turbo_SendKey}.send', data=data).json() 405 | write_log("Server酱Turbo推送返回:" + str(rs), 1, '_message') 406 | return rs 407 | except Exception as e: 408 | rs = str(e) 409 | print_and_log("Server酱Turbo推送消息出错", 3) 410 | write_log("Server酱Turbo推送消息出错:" + rs, 1, '_message') 411 | return rs 412 | 413 | # Server酱3推送 414 | def send_message_serverchan3(title, desp=''): 415 | if PCfuncs.push_serverchan3_enabled: 416 | try: 417 | rs = sc_send(f"{PCfuncs.push_serverchan3_SendKey}", PCfuncs.device_name + title, get_time() + ' ' + desp, {"tags": "PowerControl"}) 418 | write_log("Server酱3推送返回:" + str(rs), 1, '_message') 419 | return rs 420 | except Exception as e: 421 | rs = str(e) 422 | print_and_log("Server酱3推送消息出错", 3) 423 | write_log("Server酱3推送消息出错:" + rs, 1, '_message') 424 | return rs 425 | 426 | # Qmsg酱推送 427 | def send_message_qmsg(title, desp=''): 428 | if PCfuncs.push_qmsg_enabled: 429 | try: 430 | data = { 431 | 'msg': PCfuncs.device_name + title + '\n' + get_time() + ' ' + desp, 432 | 'qq': PCfuncs.push_qmsg_qq 433 | } 434 | rs = requests.post(f'https://qmsg.zendee.cn/send/{PCfuncs.push_qmsg_key}', data=data).json() 435 | # 移除 'ad' 广告字段 436 | if 'ad' in rs: 437 | del rs['ad'] 438 | write_log("Qmsg酱推送返回:" + str(rs), 1, '_message') 439 | return rs 440 | except Exception as e: 441 | rs = str(e) 442 | print_and_log("Qmsg酱推送消息出错", 3) 443 | write_log("Qmsg酱推送消息出错:" + rs, 1, '_message') 444 | return rs 445 | 446 | # 企业微信群机器人推送 447 | def send_message_wechat_webhook(title, desp=''): 448 | if PCfuncs.push_wechat_webhook_enabled: 449 | try: 450 | headers = {"Content-Type": "application/json"} 451 | data = { 452 | 'msgtype': 'text', 453 | 'text': { 454 | 'content': f'{PCfuncs.device_name}{title}\n{get_time()} {desp}', 455 | }, 456 | } 457 | rs = requests.post(PCfuncs.push_wechat_webhook_url, json=data, headers=headers).json() 458 | write_log("企业微信群机器人推送返回:" + str(rs), 1, '_message') 459 | return rs 460 | except Exception as e: 461 | rs = str(e) 462 | print_and_log("企业微信群机器人推送消息出错", 3) 463 | write_log("企业微信群机器人推送消息出错:" + rs, 1, '_message') 464 | return rs 465 | 466 | # 关机 467 | def pcshutdown(): 468 | if PCfuncs.shutdown_enabled: 469 | if PCfuncs.shutdown_method_netrpc: 470 | try: 471 | # 构建命令 472 | command = [ 473 | "net", "rpc", "shutdown", 474 | "-f", "-t", PCfuncs.shutdown_time, "-C", f"设备将于{PCfuncs.shutdown_time}秒后关闭", 475 | "-U", f"{PCfuncs.shutdown_pc_account}%{PCfuncs.shutdown_pc_password}", "-I", PCfuncs.device_ip 476 | ] 477 | # 使用 subprocess.run() 执行命令并获取输出 478 | result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=PCfuncs.shutdown_timeout) 479 | return result.stdout.replace('\n', '').replace('\r', '') 480 | except Exception as e: 481 | return str(e) 482 | elif PCfuncs.shutdown_method_udp: 483 | try: 484 | # 创建一个UDP socket 485 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 486 | # 设置超时时间 487 | sock.settimeout(PCfuncs.shutdown_timeout) 488 | # 目标主机和端口 489 | host = PCfuncs.device_ip 490 | port = 17678 491 | # 要发送的消息 492 | data = { 493 | 'cmd': 'shutdown', 494 | 'time': PCfuncs.shutdown_time, 495 | } 496 | # 将字典序列化为JSON字符串 497 | json_data = json.dumps(data) 498 | # 发送数据 499 | _ = sock.sendto(json_data.encode(),(host, port)) 500 | # 接收响应 501 | response, _ = sock.recvfrom(1024) 502 | return response.decode('utf-8') 503 | except Exception as e: 504 | return str(e) 505 | finally: 506 | # 关闭socket 507 | sock.close() 508 | elif PCfuncs.shutdown_method_shell: 509 | if PCfuncs.shell_script.startswith(PCfuncs.shell_script_allowed): 510 | try: 511 | # 执行并获取shell命令的结果 512 | result = subprocess.run(PCfuncs.shell_script, shell=True, capture_output=True, text=True, check=True, timeout=PCfuncs.shutdown_timeout) 513 | if result.stdout: 514 | return 'succeeded:' + result.stdout 515 | else: 516 | return 'succeeded: 已执行指令' 517 | except subprocess.TimeoutExpired as e: 518 | # 处理sshpass超时但已经成功执行的报错 519 | if 'sshpass' in PCfuncs.shell_script: 520 | return 'succeeded: 已执行指令' 521 | else: 522 | return str(e) 523 | except Exception as e: 524 | return str(e) 525 | else: 526 | return "Error:不允许的指令" 527 | return None 528 | 529 | # 网络唤醒 530 | def pcwol(): 531 | if PCfuncs.wol_enabled: 532 | try: 533 | # 唤醒设备 534 | send_magic_packet(PCfuncs.wol_mac, ip_address = PCfuncs.wol_destination, port = PCfuncs.wol_port, interface = PCfuncs.wol_interface) 535 | return 'done' 536 | except Exception as e: 537 | return str(e) 538 | return None 539 | 540 | # ping 541 | def pcping(): 542 | if PCfuncs.ping_enabled: 543 | # ping设备 544 | return str(ping(PCfuncs.device_ip, timeout = 1, count = 1)).replace('\r\n', '→').replace('→→', ' → ') -------------------------------------------------------------------------------- /app/PCrun.py: -------------------------------------------------------------------------------- 1 | import os, threading 2 | from PCfunctions import PCfuncs, p_print 3 | from PCweb import PCweb 4 | from PCbemfa import PCbemfa 5 | 6 | # 读取环境变量 7 | web_port = int(os.getenv('WEB_PORT', '7678')) 8 | web_key = str(os.getenv('WEB_KEY', 'admin')) 9 | p_print("WEB_PORT: "+ str(web_port)) 10 | p_print("WEB_KEY: "+ web_key) 11 | 12 | # 初始化配置 13 | funcs_data = PCfuncs() 14 | # 初始化web 15 | pc_web = PCweb(web_port, web_key, funcs_data) 16 | # 初始化bemfa 17 | pc_bemfa = PCbemfa(funcs_data) 18 | 19 | # 启动web 20 | def run_web(): 21 | pc_web.run() 22 | # 接入巴法 23 | def run_bemfa(): 24 | pc_bemfa.run() 25 | 26 | # 创建线程 27 | thread_web = threading.Thread(target=run_web) 28 | thread_bemfa = threading.Thread(target=run_bemfa) 29 | 30 | # 启动线程 31 | thread_web.start() 32 | thread_bemfa.start() 33 | 34 | thread_web.join() 35 | thread_bemfa.join() 36 | -------------------------------------------------------------------------------- /app/PCshutdown.py: -------------------------------------------------------------------------------- 1 | import socket, json, subprocess, os 2 | from time import sleep 3 | from win11toast import toast 4 | 5 | def get_ip_address(): 6 | try: 7 | # 创建一个socket对象 8 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 9 | # 连接到目标网址 10 | s.connect(("192.168.255.255", 80)) 11 | # 获取本地IP地址 12 | ip_address = s.getsockname()[0] 13 | # 关闭socket连接 14 | s.close() 15 | return ip_address 16 | except: 17 | sleep(10) 18 | get_ip_address() 19 | 20 | def ptoast(title,text): 21 | try: 22 | toast(title,text) 23 | except: 24 | pass 25 | 26 | UDP_IP = get_ip_address() # 自动获取本地ip地址 27 | UDP_PORT = 17678 # 接收端口 28 | 29 | try: 30 | sock = socket.socket(socket.AF_INET, # Internet 31 | socket.SOCK_DGRAM) # UDP 32 | sock.bind(('0.0.0.0', UDP_PORT)) 33 | ptoast("PCshutdown已启动",f"本机ip:{UDP_IP},监听端口:{UDP_PORT},将保持后台运行") 34 | except Exception as e: 35 | ptoast("PCshutdown已退出","启动失败:" + str(e)) 36 | os._exit(0) 37 | 38 | while True: 39 | try: 40 | data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes 41 | # 将接收到的数据解码并反序列化 42 | json_data = data.decode() 43 | received_data = json.loads(json_data) 44 | if received_data['cmd'] == "shutdown": 45 | subprocess.Popen(['shutdown', '-s', '-t', str(received_data['time'])], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 46 | sent = sock.sendto('succeeded'.encode('utf-8'), addr) 47 | except Exception as e: 48 | sent = sock.sendto('failed'.encode('utf-8'), addr) 49 | ptoast("PCshutdown命令执行失败","error:" + str(e)) 50 | continue 51 | 52 | -------------------------------------------------------------------------------- /app/PCweb.py: -------------------------------------------------------------------------------- 1 | import os, json 2 | from PCfunctions import trans_str, get_time, pcwol, pcshutdown, pcping, send_message, send_message_main, write_log, extra_log 3 | from flask import Flask, request, render_template, redirect, url_for, flash, send_file, Response, send_from_directory, jsonify 4 | from flask_cors import CORS 5 | 6 | # Flask 7 | app = Flask(__name__) 8 | CORS(app) 9 | app.secret_key = 'PowerControlWeb' 10 | 11 | # 首页跳转 12 | @app.route('/', methods=['GET', 'POST']) 13 | def index(): 14 | data = {'version': WebData.fd.version} 15 | user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 16 | if request.method == 'POST': 17 | web_key = trans_str(request.get_json().get('key')) 18 | if web_key != WebData.web_key: 19 | extra_log(f'ip:{user_ip} 跳转配置页失败,错误的KEY:{web_key}', 3, '_web') 20 | return jsonify({"success": False, "message": "KEY不正确"}), 400 21 | return jsonify({"success": True}) 22 | write_log(f'ip:{user_ip} 访问首页', 1, '_web') 23 | return render_template('index.html', config=data, run_time= WebData.fd.run_time()) 24 | 25 | # pdf教程 26 | @app.route('/pdf', methods=['GET']) 27 | def pdf(): 28 | return send_file('static/PowerControl教程.pdf', mimetype='application/pdf') 29 | 30 | # 配置页 31 | @app.route('/config', methods=['GET', 'POST']) 32 | def config(): 33 | # 获取请求中的密钥 34 | web_key = request.args.get('key') 35 | user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 36 | if web_key != WebData.web_key: 37 | extra_log(f'ip:{user_ip} 访问配置页失败,错误的KEY:{web_key}', 3, '_web') 38 | return '请在url中填入正确的key', 401 39 | yaml_config = WebData.fd.read_config_yaml() 40 | yaml_config['version'] = WebData.fd.version 41 | if request.method == 'POST': 42 | # 获取表单数据 43 | yaml_config['bemfa']['enabled'] = bool(request.form.get('bemfa.enabled')) 44 | yaml_config['bemfa']['uid'] = trans_str(request.form.get('bemfa.uid')) 45 | yaml_config['bemfa']['topic'] = trans_str(request.form.get('bemfa.topic')) 46 | yaml_config['devices']['name'] = trans_str(request.form.get('devices.name')) 47 | yaml_config['devices']['ip'] = trans_str(request.form.get('devices.ip')) 48 | yaml_config['devices']['wol']['enabled'] = bool(request.form.get('devices.wol.enabled')) 49 | yaml_config['devices']['wol']['mac'] = trans_str(request.form.get('devices.wol.mac')) 50 | yaml_config['devices']['wol']['destination'] = trans_str(request.form.get('devices.wol.destination')) 51 | yaml_config['devices']['wol']['port'] = int(request.form.get('devices.wol.port')) 52 | yaml_config['devices']['shutdown']['enabled'] = bool(request.form.get('devices.shutdown.enabled')) 53 | yaml_config['devices']['shutdown']['method']['netrpc'] = bool(request.form.get('devices.shutdown.method.netrpc')) 54 | yaml_config['devices']['shutdown']['method']['udp'] = bool(request.form.get('devices.shutdown.method.udp')) 55 | yaml_config['devices']['shutdown']['method']['shell'] = bool(request.form.get('devices.shutdown.method.shell')) 56 | yaml_config['devices']['shutdown']['account'] = trans_str(request.form.get('devices.shutdown.account')) 57 | yaml_config['devices']['shutdown']['password'] = trans_str(request.form.get('devices.shutdown.password')) 58 | yaml_config['devices']['shutdown']['shell_script'] = trans_str(request.form.get('devices.shutdown.shell_script')) 59 | yaml_config['devices']['shutdown']['time'] = int(request.form.get('devices.shutdown.time')) 60 | yaml_config['devices']['shutdown']['timeout'] = int(request.form.get('devices.shutdown.timeout')) 61 | yaml_config['devices']['ping']['enabled'] = bool(request.form.get('devices.ping.enabled')) 62 | yaml_config['devices']['ping']['time'] = int(request.form.get('devices.ping.time')) 63 | yaml_config['functions']['log']['enabled'] = bool(request.form.get('functions.log.enabled')) 64 | yaml_config['functions']['log']['level'] = int(request.form.get('functions.log.level')) 65 | yaml_config['functions']['log']['clear_log']['enabled'] = bool(request.form.get('functions.log.clear_log.enabled')) 66 | yaml_config['functions']['log']['clear_log']['keep_days'] = int(request.form.get('functions.log.clear_log.keep_days')) 67 | yaml_config['functions']['push_notifications']['enabled'] = bool(request.form.get('functions.push_notifications.enabled')) 68 | yaml_config['functions']['push_notifications']['bemfa_reconnect'] = bool(request.form.get('functions.push_notifications.bemfa_reconnect')) 69 | yaml_config['functions']['push_notifications']['ServerChan_turbo']['enabled'] = bool(request.form.get('functions.push_notifications.ServerChan_turbo.enabled')) 70 | yaml_config['functions']['push_notifications']['ServerChan_turbo']['SendKey'] = trans_str(request.form.get('functions.push_notifications.ServerChan_turbo.SendKey')) 71 | yaml_config['functions']['push_notifications']['ServerChan_turbo']['channel'] = trans_str(request.form.get('functions.push_notifications.ServerChan_turbo.channel')) 72 | yaml_config['functions']['push_notifications']['ServerChan3']['enabled'] = bool(request.form.get('functions.push_notifications.ServerChan3.enabled')) 73 | yaml_config['functions']['push_notifications']['ServerChan3']['SendKey'] = trans_str(request.form.get('functions.push_notifications.ServerChan3.SendKey')) 74 | yaml_config['functions']['push_notifications']['Qmsg']['enabled'] = bool(request.form.get('functions.push_notifications.Qmsg.enabled')) 75 | yaml_config['functions']['push_notifications']['Qmsg']['key'] = trans_str(request.form.get('functions.push_notifications.Qmsg.key')) 76 | yaml_config['functions']['push_notifications']['Qmsg']['qq'] = trans_str(request.form.get('functions.push_notifications.Qmsg.qq')) 77 | yaml_config['functions']['push_notifications']['WeChat_webhook']['enabled'] = bool(request.form.get('functions.push_notifications.WeChat_webhook.enabled')) 78 | yaml_config['functions']['push_notifications']['WeChat_webhook']['url'] = trans_str(request.form.get('functions.push_notifications.WeChat_webhook.url')) 79 | # 保存配置 80 | save_yaml = WebData.fd.write_config_yaml(yaml_config) 81 | if save_yaml == True: 82 | flash(get_time() + '\n' +'配置保存成功,请重启服务或容器生效') 83 | extra_log('配置保存成功', 2, '_web') 84 | else: 85 | flash(get_time() + '\n' +'配置保存失败:' + str(save_yaml)) 86 | extra_log('配置保存失败:' + str(save_yaml), 3, '_web') 87 | return redirect(url_for('config')+ f'?key={web_key}') 88 | if not WebData.fd.ping_enabled: 89 | flash(get_time() + '\n' +'未启用ping,设备状态未知') 90 | else: 91 | if WebData.fd.pc_state: 92 | flash(get_time() + '\n' + WebData.fd.device_name + ' ' + WebData.fd.pc_state[0]) 93 | else: 94 | flash(get_time() + '\n' + WebData.fd.device_name + ' ' + '设备状态未知,等待下次ping查询') 95 | write_log(f'ip:{user_ip} 访问配置页', 1, '_web') 96 | return render_template('config.html', config=yaml_config, run_time= WebData.fd.run_time()) 97 | 98 | # 关机 99 | @app.route('/shutdown', methods=['GET']) 100 | def shutdown(): 101 | # 获取请求中的密钥 102 | web_key = request.args.get('key') 103 | user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 104 | if web_key != WebData.web_key: 105 | extra_log(f'ip:{user_ip} 访问关机接口失败,错误的KEY:{web_key}', 3, '_web') 106 | return '请在url中填入正确的key', 401 107 | write_log(f'ip:{user_ip} 访问关机接口', 1, '_web') 108 | rs = pcshutdown() 109 | if rs: 110 | if 'succeeded' in rs: 111 | message = 'success' 112 | message_cn = '已发送关机指令' 113 | extra_log(f'{message_cn}(web) → {rs}',2, '_web') 114 | else: 115 | message = 'error' 116 | message_cn = '发送关机指令失败' 117 | extra_log(f'{message_cn}(web) → {rs}' ,3, '_web') 118 | else: 119 | message = 'error' 120 | message_cn = '未启用远程关机' 121 | extra_log(f'{message_cn}(web)' ,3, '_web') 122 | rs_json = {"device_name": WebData.fd.device_name, 123 | "device_ip": WebData.fd.device_ip, 124 | "message_cn": message_cn, 125 | "message": message, 126 | "result": rs 127 | } 128 | send_message(message_cn) 129 | return Response( 130 | json.dumps(rs_json, ensure_ascii=False), 131 | mimetype='application/json; charset=utf-8' 132 | ), 200 133 | 134 | # 网络唤醒 135 | @app.route('/wol', methods=['GET']) 136 | def wol(): 137 | web_key = request.args.get('key') 138 | user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 139 | if web_key != WebData.web_key: 140 | extra_log(f'ip:{user_ip} 访问网络唤醒接口失败,错误的KEY:{web_key}', 3, '_web') 141 | return '请在url中填入正确的key', 401 142 | write_log(f'ip:{user_ip} 访问网络唤醒接口', 1, '_web') 143 | rs = pcwol() 144 | if rs: 145 | if rs == 'done': 146 | message = 'success' 147 | message_cn = '已发送唤醒指令' 148 | extra_log(f'{message_cn}(web)', 2, '_web') 149 | else: 150 | message = 'error' 151 | message_cn = '发送唤醒指令失败' 152 | extra_log(f'{message_cn}(web) → {rs}' , 3, '_web') 153 | else: 154 | message = 'error' 155 | message_cn = '未启用网络唤醒' 156 | extra_log(f'{message_cn}(web)' ,3, '_web') 157 | rs_json = {"device_name": WebData.fd.device_name, 158 | "device_ip": WebData.fd.device_ip, 159 | "message_cn": message_cn, 160 | "message": message, 161 | "result": rs 162 | } 163 | send_message(message_cn) 164 | return Response( 165 | json.dumps(rs_json, ensure_ascii=False), 166 | mimetype='application/json; charset=utf-8' 167 | ), 200 168 | 169 | # ping 170 | @app.route('/ping', methods=['GET']) 171 | def ping(): 172 | web_key = request.args.get('key') 173 | user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 174 | if web_key != WebData.web_key: 175 | extra_log(f'ip:{user_ip} 访问ping接口失败,错误的KEY:{web_key}', 3, '_web') 176 | return '请在url中填入正确的key', 401 177 | write_log(f'ip:{user_ip} 访问ping接口', 1, '_web') 178 | if not WebData.fd.ping_enabled: 179 | return '未启用ping!', 403 180 | try: 181 | ping_result = pcping() 182 | if 'Reply' in ping_result: 183 | device_status_cn = "在线" 184 | device_status = "on" 185 | elif 'timed out' in ping_result: 186 | device_status_cn = "离线" 187 | device_status = "off" 188 | rs_json = {"device_name": WebData.fd.device_name, 189 | "device_ip": WebData.fd.device_ip, 190 | "device_status_cn": device_status_cn, 191 | "device_status": device_status, 192 | "ping_result" : ping_result 193 | } 194 | return Response( 195 | json.dumps(rs_json, ensure_ascii=False), 196 | mimetype='application/json; charset=utf-8' 197 | ), 200 198 | except Exception as e: 199 | return 'error:' + str(e) ,200 200 | 201 | # restart 202 | @app.route('/restart', methods=['POST']) 203 | def restart(): 204 | # 获取请求中的密钥 205 | web_key = request.args.get('key') 206 | if web_key == WebData.web_key: 207 | extra_log('程序退出,准备重启', 2, '_web') 208 | os._exit(0) 209 | 210 | # 测试消息推送 211 | @app.route('/testpush', methods=['GET']) 212 | def testpush(): 213 | web_key = request.args.get('key') 214 | if web_key != WebData.web_key: 215 | return '请在url中填入正确的key', 401 216 | rs = send_message_main('PowerControl消息推送测试') 217 | rs = {key: value for key, value in rs.items() if value is not None} 218 | if rs: 219 | return Response( 220 | json.dumps(rs, ensure_ascii=False), 221 | mimetype='application/json; charset=utf-8' 222 | ), 200 223 | else: 224 | return '至少启用一个推送通道' 225 | 226 | # 更新日志 227 | @app.route('/changelog', methods=['GET']) 228 | def change_log(): 229 | try: 230 | # 读取 change.log 文件内容 231 | with open('change.log', 'r', encoding='GBK') as file: 232 | log_content = file.read() 233 | except Exception as e: 234 | log_content = "读取change.log文件失败" + ' → ' + str(e) 235 | extra_log(log_content , 3, '_web') 236 | return render_template('changelog.html', log_content=log_content) 237 | 238 | # 下载 239 | @app.route('/download', methods=['GET']) 240 | def download(): 241 | file = request.args.get('file') 242 | if file == 'pcshutdown': 243 | return send_from_directory('static', 'PCshutdown.exe', as_attachment=True) 244 | elif file == 'wolmonitor': 245 | return send_from_directory('static', 'WakeOnLanMonitor.exe', as_attachment=True) 246 | 247 | # 代码 248 | @app.route('/code', methods=['GET']) 249 | def copy_code(): 250 | return render_template('code.html') 251 | 252 | # 获取log文件列表 253 | @app.route('/logs', methods=['GET']) 254 | def list_logs(): 255 | web_key = request.args.get('key') 256 | user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 257 | if web_key != WebData.web_key: 258 | extra_log(f'ip:{user_ip} 访问日志失败,KEY不正确(传入的KEY:{web_key})', 3, '_web') 259 | return '请在url中填入正确的key', 401 260 | write_log(f'ip:{user_ip} 访问日志', 1, '_web') 261 | log_dir = WebData.fd.log_path 262 | # 检查目录是否存在 263 | if not os.path.exists(log_dir): 264 | return "日志目录不存在", 404 265 | # 获取目录中的所有 .log 文件 266 | log_files = [f for f in os.listdir(log_dir) if f.endswith('.log')] 267 | # 倒序排列 268 | log_files.sort(reverse=True) 269 | # 返回文件列表 270 | return render_template('logs.html', log_files=log_files) 271 | 272 | # 查看log文件内容 273 | @app.route('/logs/', methods=['GET']) 274 | def view_log_content(filename): 275 | web_key = request.args.get('key') 276 | if web_key != WebData.web_key: 277 | return '请在url中填入正确的key', 401 278 | log_dir = WebData.fd.log_path 279 | log_path = os.path.join(log_dir, filename) 280 | # 检查文件是否存在 281 | if not os.path.isfile(log_path): 282 | return "文件不存在", 404 283 | try: 284 | # 打开并读取文件内容 285 | with open(log_path, 'r', encoding='GBK') as file: 286 | log_content = file.read() 287 | # 返回文件内容的 JSON 数据 288 | return Response( 289 | json.dumps({'log_content': log_content}, ensure_ascii=False), 290 | mimetype='application/json; charset=utf-8' 291 | ), 200 292 | except Exception as e: 293 | return str(e), 500 294 | 295 | '''---------------------------------------------------------------------------------''' 296 | class WebData(): 297 | web_key = '' 298 | fd = '' 299 | class PCweb(): 300 | def __init__(self, web_port, web_key, funcs_data): 301 | self.web_port = web_port 302 | WebData.web_key = web_key 303 | WebData.fd = funcs_data 304 | extra_log("web初始化成功",2, '_web') 305 | def run(self): 306 | extra_log("web服务启动", 2, '_web') 307 | app.run(host='0.0.0.0', port=self.web_port) -------------------------------------------------------------------------------- /app/VERSION: -------------------------------------------------------------------------------- 1 | V2.92 -------------------------------------------------------------------------------- /app/change.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/app/change.log -------------------------------------------------------------------------------- /app/data/.pass: -------------------------------------------------------------------------------- 1 | pass 2 | -------------------------------------------------------------------------------- /app/default/config.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/app/default/config.yaml -------------------------------------------------------------------------------- /app/static/css/changelog.css: -------------------------------------------------------------------------------- 1 | /* changelog.html */ 2 | 3 | body { 4 | font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 5 | background-color: #f5f5f5; 6 | margin: 0; 7 | padding: 0; 8 | } 9 | 10 | .container { 11 | max-width: 800px; 12 | margin: 0 auto; 13 | padding: 20px; 14 | background-color: white; 15 | border-radius: 10px; 16 | box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); 17 | transition: background-color 0.5s, color 0.5s; 18 | } 19 | 20 | h1 { 21 | text-align: center; 22 | color: #4CAF50; 23 | margin-bottom: 30px; 24 | } 25 | 26 | .line-container { 27 | display: flex; 28 | align-items: center; 29 | margin: 10px 0; 30 | gap: 10px; 31 | display: flex; 32 | justify-content: center; 33 | } 34 | 35 | .icon-image { 36 | height: 35px; 37 | width: auto; 38 | vertical-align: middle; 39 | cursor: pointer; 40 | } 41 | 42 | .log-content { 43 | white-space: pre-wrap; 44 | /* 保留换行和空格 */ 45 | word-wrap: break-word; 46 | /* 自动换行 */ 47 | font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 48 | font-size: 16px; 49 | color: #333; 50 | background-color: #f9f9f9; 51 | padding: 15px; 52 | border-radius: 10px; 53 | line-height: 1.6; 54 | transition: background-color 0.5s, color 0.5s; 55 | } 56 | 57 | .error-message { 58 | color: red; 59 | text-align: center; 60 | font-size: 18px; 61 | } 62 | 63 | body.dark-mode { 64 | background-color: #333; 65 | color: #ffffffd6; 66 | } 67 | 68 | body.dark-mode .container { 69 | background-color: #3f3f3f; 70 | box-shadow: 0 4px 10px rgba(255, 255, 255, 0.1); 71 | } 72 | 73 | body.dark-mode .log-content { 74 | color: #ffffffd6; 75 | background-color: #333; 76 | } -------------------------------------------------------------------------------- /app/static/css/code.css: -------------------------------------------------------------------------------- 1 | /* code.html */ 2 | body { 3 | font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 4 | background-color: white; 5 | margin: 0; 6 | padding: 0; 7 | margin-left: 20px; 8 | margin-right: 20px; 9 | } 10 | 11 | h1 { 12 | color: #4CAF50; 13 | } 14 | 15 | h3 { 16 | margin-bottom: -15px; 17 | } 18 | 19 | .line-container { 20 | display: flex; 21 | align-items: center; 22 | margin: 10px 0; 23 | gap: 10px; 24 | justify-content: space-between; 25 | } 26 | 27 | .icon-image { 28 | height: 35px; 29 | width: auto; 30 | vertical-align: middle; 31 | cursor: pointer; 32 | } 33 | 34 | pre { 35 | position: relative; 36 | /* 为了让按钮定位到代码块内部 */ 37 | } 38 | 39 | code { 40 | background: #ebebeb; 41 | color: #3b3b3b; 42 | font-family: Consolas; 43 | font-size: 14px; 44 | scrollbar-width: thin; 45 | border-radius: 10px; 46 | transition: background-color 0.5s, 47 | color 0.5s; 48 | } 49 | 50 | /* 复制按钮样式 */ 51 | .copy-btn { 52 | position: absolute; 53 | top: 10px; 54 | left: 10px; 55 | background-color: #4CAF50; 56 | color: white; 57 | border: none; 58 | padding: 5px 10px; 59 | border-radius: 5px; 60 | cursor: pointer; 61 | font-size: 14px; 62 | } 63 | 64 | .copy-btn:hover { 65 | background-color: #45a049; 66 | } 67 | 68 | body.dark-mode { 69 | background-color: #333; 70 | color: #ffffffd6; 71 | } 72 | 73 | body.dark-mode code { 74 | background: #1A1B26; 75 | color: #ffffffd6; 76 | } -------------------------------------------------------------------------------- /app/static/css/config.css: -------------------------------------------------------------------------------- 1 | /* config.html */ 2 | 3 | body { 4 | font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 5 | background-color: #f4f4f9; 6 | color: #333; 7 | margin: 0 auto; 8 | padding: 0; 9 | max-width: 1024px; 10 | overflow-x: hidden; 11 | box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); 12 | border-radius: 10px; 13 | } 14 | 15 | h1, 16 | h3 { 17 | color: #2e2d3b; 18 | } 19 | 20 | h1 { 21 | font-size: 28px; 22 | margin-top: 10px; 23 | margin-bottom: 10px; 24 | text-align: center 25 | } 26 | 27 | h2 { 28 | font-size: 22px; 29 | color: orangered; 30 | margin-bottom: 10px; 31 | border-bottom: 2px solid #ffcdbb; 32 | padding-bottom: 5px; 33 | } 34 | 35 | h3 { 36 | font-size: 16px; 37 | margin: 0px; 38 | text-align: right; 39 | color: #888; 40 | } 41 | 42 | p { 43 | background-color: #ebebeb; 44 | padding: 10px; 45 | border-radius: 5px; 46 | margin-bottom: 10px; 47 | display: inline-flex; 48 | color: #2e2d3b; 49 | } 50 | 51 | .head-container { 52 | padding: 10px 20px; 53 | background-color: #4CAF50; 54 | color: white; 55 | box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 56 | display: flex; 57 | justify-content: left; 58 | } 59 | 60 | .head-container a { 61 | font-size: 16px; 62 | font-weight: 500; 63 | color: white; 64 | text-decoration: none; 65 | margin-right: 20px; 66 | transition: all 0.3s ease; 67 | } 68 | 69 | .head-container a:hover { 70 | color: #2e2d3b; 71 | } 72 | 73 | /* 图标图片 */ 74 | .icon-image { 75 | height: 25px; 76 | /* 图标的高度适应容器 */ 77 | width: auto; 78 | /* 图标的宽度自动调整,保持比例 */ 79 | vertical-align: middle; 80 | /* 垂直居中 */ 81 | margin-top: -12px; 82 | margin-bottom: -10px; 83 | cursor: pointer; 84 | } 85 | 86 | .line-container { 87 | display: flex; 88 | align-items: center; 89 | margin: 10px 0; 90 | gap: 10px; 91 | } 92 | 93 | .input-label { 94 | width: 180px; 95 | min-width: 180px; 96 | max-width: 100%; 97 | border: 1px solid #dddddd00; 98 | border-radius: 4px; 99 | font-size: 18px; 100 | color: #333; 101 | margin: 5px 0; 102 | padding-top: 4px; 103 | padding-bottom: 4px; 104 | padding-left: 10px; 105 | transition: width 0.2s ease-in-out; 106 | text-overflow: ellipsis; 107 | outline: none; 108 | } 109 | 110 | .checkbox-label { 111 | font-size: 16px; 112 | } 113 | 114 | .checkbox-label2 { 115 | font-size: 14px; 116 | } 117 | 118 | input[type="submit"], 119 | button { 120 | background-color: #28a745; 121 | border: none; 122 | color: white; 123 | font-size: 16px; 124 | cursor: pointer; 125 | border-radius: 5px; 126 | transition: all 0.3s ease; 127 | margin-top: 10px; 128 | } 129 | 130 | input[type="submit"]:hover, 131 | button:hover { 132 | background-color: #218838; 133 | } 134 | 135 | .textlink { 136 | font-size: 14px; 137 | color: #4CAF50; 138 | text-decoration: none; 139 | cursor: pointer; 140 | transition: all 0.3s ease; 141 | } 142 | 143 | .textlink:hover { 144 | color: #ff6600; 145 | } 146 | 147 | #flash-messages ul { 148 | margin: 20px 0; 149 | padding: 0; 150 | list-style-type: none; 151 | } 152 | 153 | #flash-messages ul li { 154 | background-color: #ebebeb; 155 | color: red; 156 | padding: 10px; 157 | border-radius: 5px; 158 | margin-bottom: 10px; 159 | } 160 | 161 | .hidden { 162 | opacity: 0; 163 | max-height: 0; 164 | visibility: hidden; 165 | /* transition: max-height 0.3s ease, opacity 0.3s ease, visibility 0.3s ease; */ 166 | transition: all 0.3s ease; 167 | } 168 | .visible { 169 | opacity: 1; 170 | max-height: 1000px; 171 | visibility: visible; 172 | /* transition: max-height 0.3s ease, opacity 0.3s ease, visibility 0.3s ease; */ 173 | transition: all 0.3s ease; 174 | } 175 | 176 | .default-hr { 177 | width: 100%; 178 | border: none; 179 | height: 2px; 180 | background-color: #e0e0e0; 181 | } 182 | 183 | .dashed-hr { 184 | width: 100%; 185 | border: 1px dashed #e0e0e0; 186 | } 187 | 188 | @media (max-width: 768px) { 189 | .head-container-wrapper { 190 | position: relative; 191 | display: flex; 192 | align-items: center; 193 | overflow: hidden; 194 | } 195 | 196 | .head-container { 197 | display: flex; 198 | flex-direction: row; 199 | position: relative; 200 | top: 5%; 201 | overflow-x: auto; 202 | /* 添加横向滚动效果 */ 203 | -webkit-overflow-scrolling: touch; 204 | scrollbar-width: thin; 205 | /* 隐藏滚动条 */ 206 | scroll-behavior: smooth; 207 | /* 平滑滚动效果 */ 208 | overscroll-behavior-x: contain; 209 | /* 添加横向滚动的 OverScroll 效果 */ 210 | width: 100%; 211 | } 212 | 213 | .head-container a { 214 | margin: 0; 215 | margin-right: 25px; 216 | font-size: 14px; 217 | flex: 0 0 auto; 218 | /* 确保每个 h2 和 a 元素不会缩小 */ 219 | min-width: fit-content; 220 | /* 使内容自适应宽度 */ 221 | } 222 | 223 | .head-container a:last-child { 224 | margin-right: 0; 225 | flex-grow: 1; 226 | white-space: nowrap; 227 | } 228 | 229 | /* 左侧模糊提示 */ 230 | .blur-left { 231 | position: absolute; 232 | left: 0; 233 | top: 0; 234 | width: 80px; 235 | height: 100%; 236 | background: linear-gradient(to right, rgba(164, 233, 166, 1), rgba(255, 255, 255, 0)); 237 | pointer-events: none; 238 | /* 防止影响滚动 */ 239 | opacity: 0; 240 | /* 默认透明 */ 241 | transition: opacity 0.3s ease; 242 | /* 淡入淡出效果 */ 243 | z-index: 10; 244 | /* 确保在内容之上 */ 245 | } 246 | 247 | /* 右侧模糊提示 */ 248 | .blur-right { 249 | position: absolute; 250 | right: 0; 251 | top: 0; 252 | width: 80px; 253 | height: 100%; 254 | background: linear-gradient(to left, rgba(164, 233, 166, 1), rgba(255, 255, 255, 0)); 255 | pointer-events: none; 256 | opacity: 0; 257 | /* 默认透明 */ 258 | transition: opacity 0.3s ease; 259 | /* 淡入淡出效果 */ 260 | z-index: 10; 261 | /* 确保在内容之上 */ 262 | } 263 | 264 | .input-label { 265 | font-size: 16px; 266 | } 267 | 268 | .checkbox-label { 269 | font-size: 14px; 270 | } 271 | 272 | input[type="submit"], 273 | button { 274 | width: 100%; 275 | } 276 | } 277 | 278 | /* 深色模式 */ 279 | body.dark-mode { 280 | background-color: #333; 281 | color: #ffffffd6; 282 | box-shadow: 0 2px 10px rgba(255, 255, 255, 0.1); 283 | } 284 | 285 | body.dark-mode .head-container { 286 | box-shadow: 0 4px 6px rgba(255, 255, 255, 0.1); 287 | } 288 | 289 | body.dark-mode .head-container a { 290 | color: #2e2d3b; 291 | } 292 | 293 | body.dark-mode .head-container a:hover { 294 | color: #f4f4f9; 295 | } 296 | 297 | body.dark-mode h1, 298 | h3 { 299 | color: #888; 300 | } 301 | 302 | body.dark-mode h2 { 303 | color: #f9703ddb; 304 | border-bottom: 2px solid #ffcdbb8f; 305 | } 306 | 307 | body.dark-mode p { 308 | background-color: #555555; 309 | color: #ffffffd6; 310 | } 311 | 312 | body.dark-mode #flash-messages ul li { 313 | background-color: #555555; 314 | color: #ffff99d6; 315 | } 316 | 317 | body.dark-mode .input-label { 318 | background-color: #555555; 319 | color: #ffffffd6; 320 | } 321 | 322 | body.dark-mode .textlink:hover { 323 | color: #f9703ddb; 324 | } 325 | 326 | body.dark-mode .default-hr { 327 | background-color: #888888; 328 | } 329 | 330 | body.dark-mode .dashed-hr { 331 | border: 1px dashed #888888; 332 | } 333 | 334 | body.dark-mode input[type="submit"], 335 | body.dark-mode button { 336 | color: #2e2d3b; 337 | } 338 | 339 | body.dark-mode .blur-left { 340 | background: linear-gradient(to right, #218838, #ffffff00); 341 | } 342 | 343 | body.dark-mode .blur-right { 344 | background: linear-gradient(to left, #218838, #ffffff00); 345 | } -------------------------------------------------------------------------------- /app/static/css/default.css: -------------------------------------------------------------------------------- 1 | pre code.hljs { 2 | display: block; 3 | overflow-x: auto; 4 | padding: 1em 5 | } 6 | code.hljs { 7 | padding: 3px 5px 8 | } 9 | /*! 10 | Theme: Default 11 | Description: Original highlight.js style 12 | Author: (c) Ivan Sagalaev 13 | Maintainer: @highlightjs/core-team 14 | Website: https://highlightjs.org/ 15 | License: see project LICENSE 16 | Touched: 2021 17 | */ 18 | /* 19 | This is left on purpose making default.css the single file that can be lifted 20 | as-is from the repository directly without the need for a build step 21 | 22 | Typically this "required" baseline CSS is added by `makestuff.js` during build. 23 | */ 24 | pre code.hljs { 25 | display: block; 26 | overflow-x: auto; 27 | padding: 1em 28 | } 29 | code.hljs { 30 | padding: 3px 5px 31 | } 32 | /* end baseline CSS */ 33 | .hljs { 34 | background: #ebebeb; 35 | color: #3b3b3b 36 | } 37 | /* Base color: saturation 0; */ 38 | .hljs-subst { 39 | /* default */ 40 | 41 | } 42 | /* purposely ignored */ 43 | .hljs-formula, 44 | .hljs-attr, 45 | .hljs-property, 46 | .hljs-params { 47 | 48 | } 49 | .hljs-comment { 50 | color: #697070 51 | } 52 | .hljs-tag, 53 | .hljs-punctuation { 54 | color: #444a 55 | } 56 | .hljs-tag .hljs-name, 57 | .hljs-tag .hljs-attr { 58 | color: #444 59 | } 60 | .hljs-keyword, 61 | .hljs-attribute, 62 | .hljs-selector-tag, 63 | .hljs-meta .hljs-keyword, 64 | .hljs-doctag, 65 | .hljs-name { 66 | font-weight: bold 67 | } 68 | /* User color: hue: 0 */ 69 | .hljs-type, 70 | .hljs-string, 71 | .hljs-number, 72 | .hljs-selector-id, 73 | .hljs-selector-class, 74 | .hljs-quote, 75 | .hljs-template-tag, 76 | .hljs-deletion { 77 | color: #ff6d38 78 | } 79 | .hljs-title, 80 | .hljs-section { 81 | color: #ff6d38; 82 | font-weight: bold 83 | } 84 | .hljs-regexp, 85 | .hljs-symbol, 86 | .hljs-variable, 87 | .hljs-template-variable, 88 | .hljs-link, 89 | .hljs-selector-attr, 90 | .hljs-operator, 91 | .hljs-selector-pseudo { 92 | color: #ff6d38 93 | } 94 | /* Language color: hue: 90; */ 95 | .hljs-literal { 96 | color: #695 97 | } 98 | .hljs-built_in, 99 | .hljs-bullet, 100 | .hljs-code, 101 | .hljs-addition { 102 | color: #397300 103 | } 104 | /* Meta color: hue: 200 */ 105 | .hljs-meta { 106 | color: #1f7199 107 | } 108 | .hljs-meta .hljs-string { 109 | color: #38a 110 | } 111 | /* Misc effects */ 112 | .hljs-emphasis { 113 | font-style: italic 114 | } 115 | .hljs-strong { 116 | font-weight: bold 117 | } -------------------------------------------------------------------------------- /app/static/css/index.css: -------------------------------------------------------------------------------- 1 | /* index.html */ 2 | 3 | body { 4 | font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 5 | background-color: #f4f4f9; 6 | color: #333; 7 | margin: 0 auto; 8 | padding: 0; 9 | max-width: 1024px; 10 | overflow-x: hidden; 11 | box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); 12 | border-radius: 10px; 13 | height: 600px; 14 | } 15 | 16 | h1, 17 | h3 { 18 | color: #2e2d3b; 19 | } 20 | 21 | h1 { 22 | font-size: 28px; 23 | margin-top: 30px; 24 | margin-bottom: 10px; 25 | text-align: center 26 | } 27 | 28 | h3 { 29 | font-size: 16px; 30 | margin: 0px; 31 | text-align: right; 32 | color: #888; 33 | } 34 | 35 | p { 36 | background-color: #ebebeb; 37 | padding: 10px; 38 | border-radius: 5px; 39 | margin-bottom: 10px; 40 | display: inline-flex; 41 | color: #2e2d3b; 42 | } 43 | 44 | .head-container { 45 | padding: 10px 20px; 46 | background-color: #4CAF50; 47 | color: white; 48 | box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 49 | display: flex; 50 | justify-content: left; 51 | } 52 | 53 | .head-container a { 54 | font-size: 16px; 55 | font-weight: 500; 56 | color: white; 57 | text-decoration: none; 58 | margin-right: 20px; 59 | transition: all 0.3s ease; 60 | } 61 | 62 | .head-container a:hover { 63 | color: #2e2d3b; 64 | } 65 | 66 | /* 图标图片 */ 67 | .icon-image { 68 | height: 25px; 69 | /* 图标的高度适应容器 */ 70 | width: auto; 71 | /* 图标的宽度自动调整,保持比例 */ 72 | vertical-align: middle; 73 | /* 垂直居中 */ 74 | margin-top: -12px; 75 | margin-bottom: -10px; 76 | cursor: pointer; 77 | } 78 | 79 | .line-container { 80 | display: flex; 81 | justify-content: center; 82 | margin-top: 80px; 83 | } 84 | 85 | .key-input { 86 | padding-left: 15px; 87 | border: 1px solid #dddddd00; 88 | outline: none; 89 | width: 60%; 90 | height: 50px; 91 | border-radius: 5px 0 0 5px; 92 | box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); 93 | box-sizing: border-box; 94 | font-size: 22px; 95 | letter-spacing: 2px; 96 | text-align: center; 97 | } 98 | 99 | .key-button { 100 | width: 120px; 101 | height: 50px; 102 | line-height: 50px; 103 | border-radius: 0 5px 5px 0; 104 | cursor: pointer; 105 | font-size: 18px; 106 | text-align: center; 107 | background-color: #28a745; 108 | box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); 109 | color: white; 110 | user-select: none; 111 | transition: 0.3s ease; 112 | } 113 | 114 | .key-button:hover { 115 | background-color: #218838; 116 | } 117 | 118 | .message { 119 | opacity: 0; 120 | background-color: #ebebeb; 121 | color: red; 122 | padding: 10px; 123 | border-radius: 5px; 124 | text-align: center; 125 | width: 120px; 126 | margin: 10px auto; 127 | transition: 0.3s ease; 128 | } 129 | 130 | .hidden { 131 | opacity: 0; 132 | visibility: hidden; 133 | transition: opacity 0.3s ease, visibility 0.3s ease; 134 | } 135 | 136 | .visible { 137 | opacity: 1; 138 | visibility: visible; 139 | transition: opacity 0.3s ease, visibility 0.3s ease; 140 | } 141 | 142 | @media (max-width: 768px) { 143 | .head-container-wrapper { 144 | position: relative; 145 | display: flex; 146 | align-items: center; 147 | overflow: hidden; 148 | } 149 | 150 | .head-container { 151 | display: flex; 152 | flex-direction: row; 153 | position: relative; 154 | top: 5%; 155 | overflow-x: auto; 156 | /* 添加横向滚动效果 */ 157 | -webkit-overflow-scrolling: touch; 158 | scrollbar-width: thin; 159 | /* 隐藏滚动条 */ 160 | scroll-behavior: smooth; 161 | /* 平滑滚动效果 */ 162 | overscroll-behavior-x: contain; 163 | /* 添加横向滚动的 OverScroll 效果 */ 164 | width: 100%; 165 | } 166 | 167 | .head-container a { 168 | margin: 0; 169 | margin-right: 25px; 170 | font-size: 14px; 171 | flex: 0 0 auto; 172 | /* 确保每个 h2 和 a 元素不会缩小 */ 173 | min-width: fit-content; 174 | /* 使内容自适应宽度 */ 175 | } 176 | 177 | .head-container a:last-child { 178 | margin-right: 0; 179 | flex-grow: 1; 180 | white-space: nowrap; 181 | } 182 | 183 | /* 左侧模糊提示 */ 184 | .blur-left { 185 | position: absolute; 186 | left: 0; 187 | top: 0; 188 | width: 80px; 189 | height: 100%; 190 | background: linear-gradient(to right, rgba(164, 233, 166, 1), rgba(255, 255, 255, 0)); 191 | pointer-events: none; 192 | /* 防止影响滚动 */ 193 | opacity: 0; 194 | /* 默认透明 */ 195 | transition: opacity 0.3s ease; 196 | /* 淡入淡出效果 */ 197 | z-index: 10; 198 | /* 确保在内容之上 */ 199 | } 200 | 201 | /* 右侧模糊提示 */ 202 | .blur-right { 203 | position: absolute; 204 | right: 0; 205 | top: 0; 206 | width: 80px; 207 | height: 100%; 208 | background: linear-gradient(to left, rgba(164, 233, 166, 1), rgba(255, 255, 255, 0)); 209 | pointer-events: none; 210 | opacity: 0; 211 | /* 默认透明 */ 212 | transition: opacity 0.3s ease; 213 | /* 淡入淡出效果 */ 214 | z-index: 10; 215 | /* 确保在内容之上 */ 216 | } 217 | 218 | .key-button { 219 | width: 80px; 220 | font-size: 16px; 221 | } 222 | } 223 | 224 | /* 深色模式 */ 225 | body.dark-mode { 226 | background-color: #333; 227 | color: #ffffffd6; 228 | box-shadow: 0 2px 10px rgba(255, 255, 255, 0.1); 229 | } 230 | 231 | body.dark-mode .head-container { 232 | box-shadow: 0 4px 6px rgba(255, 255, 255, 0.1); 233 | } 234 | 235 | body.dark-mode .head-container a { 236 | color: #2e2d3b; 237 | } 238 | body.dark-mode .head-container a:hover { 239 | color: #f4f4f9; 240 | } 241 | 242 | body.dark-mode h1, 243 | h3 { 244 | color: #888; 245 | } 246 | 247 | body.dark-mode h2 { 248 | color: #f9703ddb; 249 | border-bottom: 2px solid #ffcdbb8f; 250 | } 251 | 252 | body.dark-mode p { 253 | background-color: #555555; 254 | color: #ffffffd6; 255 | } 256 | 257 | body.dark-mode .message { 258 | background-color: #555555; 259 | color: #ffff99d6; 260 | } 261 | 262 | body.dark-mode .key-input { 263 | background-color: #555555; 264 | color: #ffffffd6; 265 | box-shadow: 0 2px 10px rgba(255, 255, 255, 0.1); 266 | } 267 | 268 | body.dark-mode .key-button { 269 | color: #2e2d3b; 270 | box-shadow: 0 2px 10px rgba(255, 255, 255, 0.1); 271 | } 272 | 273 | body.dark-mode .blur-left { 274 | background: linear-gradient(to right, #218838, #ffffff00); 275 | } 276 | 277 | body.dark-mode .blur-right { 278 | background: linear-gradient(to left, #218838, #ffffff00); 279 | } -------------------------------------------------------------------------------- /app/static/css/logs.css: -------------------------------------------------------------------------------- 1 | /* logs.html */ 2 | 3 | body { 4 | font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 5 | background-color: #f5f5f5; 6 | color: #333; 7 | margin: 0; 8 | padding: 0; 9 | } 10 | 11 | h2 { 12 | color: #4CAF50; 13 | } 14 | 15 | .container { 16 | display: flex; 17 | height: 100vh; 18 | overflow: hidden; 19 | } 20 | 21 | .line-container { 22 | display: flex; 23 | align-items: center; 24 | margin: 10px 0; 25 | gap: 10px; 26 | justify-content: space-between; 27 | } 28 | 29 | .icon-image { 30 | height: 35px; 31 | width: auto; 32 | vertical-align: middle; 33 | cursor: pointer; 34 | } 35 | 36 | .sidebar { 37 | width: 250px; 38 | background-color: #fff; 39 | padding: 20px; 40 | border-right: 1px solid #ddd; 41 | overflow-y: auto; 42 | z-index: 10; 43 | transition: left 0.3s ease,background-color 0.5s; 44 | position: relative; 45 | } 46 | 47 | .sidebar h2 { 48 | text-align: center; 49 | color: #4CAF50; 50 | margin-bottom: 20px; 51 | } 52 | 53 | .file-list { 54 | list-style-type: none; 55 | padding: 0; 56 | } 57 | 58 | .file-list li { 59 | margin: 10px 0; 60 | padding: 5px; 61 | background-color: #f9f9f9; 62 | border-radius: 5px; 63 | cursor: pointer; 64 | text-align: center; 65 | transition: background-color 0.3s; 66 | } 67 | 68 | .file-list li:hover { 69 | background-color: #4CAF50; 70 | } 71 | 72 | .file-list li.selected { 73 | background-color: #218838; 74 | color: white; 75 | } 76 | 77 | .content { 78 | flex: 1; 79 | background-color: white; 80 | padding: 20px; 81 | overflow-y: auto; 82 | transition: background-color 0.5s; 83 | } 84 | 85 | .content pre { 86 | background-color: #f9f9f9; 87 | padding: 20px; 88 | border-radius: 10px; 89 | white-space: pre-wrap; 90 | word-wrap: break-word; 91 | font-size: 14px; 92 | line-height: 1.6; 93 | } 94 | 95 | .error-line { 96 | color: red; 97 | } 98 | 99 | /* 在小屏幕下隐藏文件列表 */ 100 | @media screen and (max-width: 768px) { 101 | .sidebar { 102 | position: fixed; 103 | top: 0; 104 | left: -300px; 105 | /* 默认隐藏 */ 106 | bottom: 0; 107 | z-index: 10; 108 | } 109 | 110 | .sidebar.open { 111 | left: 0; 112 | /* 滑出 */ 113 | } 114 | 115 | #toggleButton { 116 | display: block; 117 | } 118 | } 119 | 120 | /* 切换按钮样式 */ 121 | #toggleButton { 122 | display: none; 123 | position: absolute; 124 | top: 50%; 125 | left: -20px; 126 | transform: translateY(-50%); 127 | width: 40px; 128 | height: 40px; 129 | background-color: #4CAF50; 130 | color: white; 131 | border: none; 132 | /* 圆形按钮 */ 133 | /* border-radius: 50%; */ 134 | text-align: right; 135 | line-height: 40px; 136 | font-size: 20px; 137 | cursor: pointer; 138 | z-index: 20; 139 | } 140 | 141 | #toggleButton:hover { 142 | background-color: #45a049; 143 | } 144 | 145 | /* 更改箭头样式 */ 146 | #toggleButton.open { 147 | left: 250px; 148 | /* 向右滑动显示按钮 */ 149 | } 150 | 151 | body.dark-mode { 152 | background-color: #333; 153 | color: #ffffffd6; 154 | } 155 | 156 | body.dark-mode .sidebar { 157 | background-color: #333; 158 | border-right: 1px solid #555555; 159 | } 160 | 161 | body.dark-mode .content { 162 | background-color: #333; 163 | } 164 | 165 | body.dark-mode .content pre { 166 | background-color: #555555; 167 | } 168 | 169 | body.dark-mode .error-line { 170 | color: #ffff99d6; 171 | } 172 | 173 | body.dark-mode .file-list li { 174 | background-color: #555555; 175 | } 176 | 177 | body.dark-mode .file-list li:hover { 178 | background-color: #4CAF50; 179 | } 180 | 181 | body.dark-mode .file-list li.selected { 182 | background-color: #218838; 183 | color: white; 184 | } -------------------------------------------------------------------------------- /app/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/app/static/favicon.ico -------------------------------------------------------------------------------- /app/static/icon-theme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/app/static/icon-theme.png -------------------------------------------------------------------------------- /app/static/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/app/static/icon.png -------------------------------------------------------------------------------- /app/static/js/clipboard.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * clipboard.js v2.0.10 3 | * https://clipboardjs.com/ 4 | * 5 | * Licensed MIT © Zeno Rocha 6 | */ 7 | !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ClipboardJS=e():t.ClipboardJS=e()}(this,function(){return n={686:function(t,e,n){"use strict";n.d(e,{default:function(){return o}});var e=n(279),i=n.n(e),e=n(370),u=n.n(e),e=n(817),c=n.n(e);function a(t){try{return document.execCommand(t)}catch(t){return}}var f=function(t){t=c()(t);return a("cut"),t};var l=function(t){var e,n,o,r=1 0) { 18 | blurLeft.style.opacity = 1; // 显示左侧模糊提示 19 | } else { 20 | blurLeft.style.opacity = 0; // 隐藏左侧模糊提示 21 | } 22 | 23 | // 检查右侧是否有可滑动元素 24 | if (headContainer.scrollLeft < headContainer.scrollWidth - headContainer.clientWidth) { 25 | blurRight.style.opacity = 1; // 显示右侧模糊提示 26 | } else { 27 | blurRight.style.opacity = 0; // 隐藏右侧模糊提示 28 | } 29 | } 30 | 31 | // ---------------------------------------------------------------------------------------------------- 32 | // 获取当前页面的 URL 33 | const currentUrl = new URL(window.location.href); 34 | // 获取 URL 中的 key 参数 35 | const key = currentUrl.searchParams.get('key'); 36 | // 如果 key 参数存在,则修改相关跳转 37 | if (key) { 38 | var form = document.getElementById('restart'); 39 | form.action = `/restart?key=${key}`; 40 | document.getElementById('logs').href = `/logs?key=${key}`; 41 | document.getElementById('go_wol').href = `/wol?key=${key}`; 42 | document.getElementById('go_shutdown').href = `/shutdown?key=${key}`; 43 | document.getElementById('go_ping').href = `/ping?key=${key}`; 44 | document.getElementById('go_push').href = `/testpush?key=${key}`; 45 | } 46 | // 监听表单提交事件 47 | document.getElementById('restart').addEventListener('submit', function (event) { 48 | event.preventDefault(); // 防止表单默认提交 49 | 50 | // 使用 Fetch API 发送 POST 请求(不关心响应) 51 | fetch(form.action, { 52 | method: 'POST', 53 | }) 54 | // 初始化倒计时 55 | let countdown = 5; 56 | 57 | // 添加 "即将刷新" 消息 58 | const flashMessages = document.getElementById('flash-messages'); 59 | const messageElement = document.createElement('ul'); 60 | const messageItem = document.createElement('li'); 61 | messageItem.innerHTML = `即将刷新 ${countdown}`; 62 | messageElement.appendChild(messageItem); 63 | flashMessages.appendChild(messageElement); 64 | 65 | // 设置定时器每秒更新一次消息 66 | const intervalId = setInterval(function () { 67 | countdown--; 68 | messageItem.innerHTML = `即将刷新 ${countdown}`; // 更新提示消息 69 | 70 | // 倒计时结束后刷新页面 71 | if (countdown < 1) { 72 | clearInterval(intervalId); // 清除定时器 73 | location.reload(); // 刷新页面 74 | } 75 | }, 1000); // 每隔1秒更新一次 76 | }); 77 | 78 | // ---------------------------------------------------------------------------------------------------- 79 | function go_func_show() { 80 | const items = [ 81 | 'bemfa', 'wol', 'shutdown', 'ping', 'push', 82 | 'serverchanturbo', 'serverchan3', 'qmsg', 'wechat_webhook' 83 | ]; 84 | 85 | items.forEach(item => { 86 | const enabled_id = `${item}_enabled`; 87 | const go_id = `go_${item}`; 88 | 89 | const goElement = document.getElementById(go_id); 90 | 91 | // 根据 enabled 元素的 checked 属性值,添加或移除 visible 类 92 | if (document.getElementById(enabled_id).checked) { 93 | goElement.classList.remove('hidden'); 94 | goElement.classList.add('visible'); 95 | } else { 96 | goElement.classList.remove('visible'); 97 | goElement.classList.add('hidden'); 98 | } 99 | }); 100 | } 101 | 102 | 103 | // 根据复选框状态更新对应内容的显示或隐藏 104 | function ifshow(event) { 105 | const checkbox = event.target; // 当前触发事件的复选框 106 | const targetId = checkbox.dataset.target; // 获取对应的内容 ID 107 | const targetElement = document.getElementById(targetId); // 获取目标内容元素 108 | 109 | if (checkbox.checked) { 110 | targetElement.classList.remove('hidden'); 111 | targetElement.classList.add('visible'); 112 | } else { 113 | targetElement.classList.remove('visible'); 114 | targetElement.classList.add('hidden'); 115 | } 116 | go_func_show(); 117 | } 118 | 119 | // 页面加载完成后为所有复选框添加事件监听 120 | document.addEventListener('DOMContentLoaded', () => { 121 | const checkboxes = document.querySelectorAll('.checkbox-label:not(#bemfa_reconnect_enabled)'); 122 | 123 | checkboxes.forEach(checkbox => { 124 | // 初始化显示状态 125 | const targetId = checkbox.dataset.target; 126 | const targetElement = document.getElementById(targetId); 127 | 128 | if (checkbox.checked) { 129 | targetElement.classList.remove('hidden'); 130 | } else { 131 | targetElement.classList.add('hidden'); 132 | } 133 | go_func_show() 134 | // 添加监听事件 135 | checkbox.addEventListener('change', ifshow); 136 | }); 137 | }); 138 | 139 | // ---------------------------------------------------------------------------------------------------- 140 | // 获取复选框和目标内容元素 141 | const netrpcCheckbox = document.getElementById('netrpc'); 142 | const udpCheckbox = document.getElementById('udp'); 143 | const shellCheckbox = document.getElementById('shell'); 144 | const netrpcConfig = document.getElementById('netrpcconfig'); 145 | const dl_pcshutdown = document.getElementById('dl_pcshutdown'); 146 | const shell_script = document.getElementById('shell_script'); 147 | const shutdown_delay_time = document.getElementById('shutdown_delay_time'); 148 | 149 | // 更新netrpcconfig的显示状态 150 | function ifshow_method_shutdown() { 151 | function showElement(element) { 152 | element.classList.remove('hidden'); 153 | element.classList.add('visible'); 154 | } 155 | 156 | function hideElement(element) { 157 | element.classList.remove('visible'); 158 | element.classList.add('hidden'); 159 | } 160 | 161 | hideElement(netrpcConfig); 162 | hideElement(dl_pcshutdown); 163 | hideElement(shell_script); 164 | hideElement(shutdown_delay_time); 165 | 166 | if (netrpcCheckbox.checked) { 167 | showElement(netrpcConfig); 168 | showElement(shutdown_delay_time); 169 | } else if (udpCheckbox.checked) { 170 | showElement(dl_pcshutdown); 171 | showElement(shutdown_delay_time); 172 | } else if (shellCheckbox.checked) { 173 | showElement(shell_script); 174 | } 175 | } 176 | 177 | // 勾选一个复选框时,取消另一个复选框的勾选 178 | function only_one_check(checkedCheckbox) { 179 | const checkboxes = [netrpcCheckbox, udpCheckbox, shellCheckbox]; 180 | checkboxes.forEach(checkbox => { 181 | // 如果当前复选框被勾选的复选框,则勾选 182 | if (checkbox !== checkedCheckbox) { 183 | checkbox.checked = false; 184 | } 185 | }); 186 | ifshow_method_shutdown(); 187 | } 188 | 189 | // 监听 190 | function handleCheckboxChange(checkbox) { 191 | if (checkbox.checked) { 192 | only_one_check(checkbox); 193 | } else { 194 | checkbox.checked = true; // 禁止取消勾选 195 | } 196 | } 197 | 198 | document.addEventListener('DOMContentLoaded', () => { 199 | ifshow_method_shutdown(); 200 | 201 | // 添加change事件监听 202 | netrpcCheckbox.addEventListener('change', () => handleCheckboxChange(netrpcCheckbox)); 203 | udpCheckbox.addEventListener('change', () => handleCheckboxChange(udpCheckbox)); 204 | shellCheckbox.addEventListener('change', () => handleCheckboxChange(shellCheckbox)); 205 | }); 206 | 207 | // ---------------------------------------------------------------------------------------------------- 208 | function submit_pcconfig() { 209 | document.getElementById("pcconfig").submit(); 210 | } 211 | 212 | // ---------------------------------------------------------------------------------------------------- 213 | // 动态调整输入框宽度 214 | document.addEventListener("DOMContentLoaded", function () { 215 | document.querySelectorAll(".input-label").forEach((input) => { 216 | // 默认宽度 217 | const defaultWidth = window.getComputedStyle(input).width; 218 | 219 | function adjustWidth() { 220 | // 创建一个临时span元素来计算文本长度 221 | let tempSpan = document.createElement("span"); 222 | tempSpan.style.visibility = "hidden"; 223 | tempSpan.style.position = "absolute"; // 避免影响布局 224 | tempSpan.style.whiteSpace = "nowrap"; // 确保单行计算宽度 225 | tempSpan.style.fontSize = window.getComputedStyle(input).fontSize; 226 | tempSpan.style.fontFamily = window.getComputedStyle(input).fontFamily; 227 | tempSpan.innerText = input.value || input.placeholder || "输入文本"; 228 | document.body.appendChild(tempSpan); 229 | 230 | // 计算并设置input宽度 231 | input.style.width = `${tempSpan.offsetWidth + 10}px`; 232 | 233 | document.body.removeChild(tempSpan); 234 | } 235 | 236 | // 监听用户输入或粘贴 237 | input.addEventListener("input", adjustWidth); 238 | // 监听焦点事件来调整宽度 239 | input.addEventListener("focus", adjustWidth); 240 | // 失去焦点时恢复默认宽度 241 | input.addEventListener("blur", function () { 242 | input.style.width = defaultWidth;; 243 | }); 244 | }); 245 | }); 246 | 247 | // ---------------------------------------------------------------------------------------------------- 248 | // 下载确认 249 | function confirmDownload() { 250 | var result = confirm("确认下载"); 251 | return result; 252 | } 253 | 254 | // ---------------------------------------------------------------------------------------------------- 255 | // 实时更新wol目标地址 256 | function update_wol_dest() { 257 | const ipInput = document.getElementById('device_ip').value; 258 | const broadcastIpDirect = document.getElementById('broadcast_ip_direct'); 259 | const broadcastDeviceIp = document.getElementById('broadcast_device_ip'); 260 | 261 | // 更新定向广播选项 262 | const broadcastIp = ipInput.slice(0, ipInput.lastIndexOf('.') + 1) + '255'; 263 | broadcastIpDirect.textContent = '定向广播(' + broadcastIp + ')'; 264 | 265 | // 更新设备IP选项 266 | broadcastDeviceIp.textContent = '设备ip(' + ipInput + ')'; 267 | } 268 | 269 | // 页面加载时更新 270 | window.onload = update_wol_dest; -------------------------------------------------------------------------------- /app/static/js/index.js: -------------------------------------------------------------------------------- 1 | // index.html 2 | 3 | // ---------------------------------------------------------------------------------------------------- 4 | // 顶部模糊效果 5 | window.addEventListener('DOMContentLoaded', checkBlur); 6 | window.addEventListener('resize', checkBlur); 7 | document.querySelector('.head-container').addEventListener('scroll', checkBlur); 8 | 9 | function checkBlur() { 10 | const headContainer = document.querySelector('.head-container'); 11 | const blurLeft = document.querySelector('.blur-left'); 12 | const blurRight = document.querySelector('.blur-right'); 13 | 14 | if (!headContainer || !blurLeft || !blurRight) return; 15 | 16 | // 检查左侧是否有可滑动元素 17 | if (headContainer.scrollLeft > 0) { 18 | blurLeft.style.opacity = 1; // 显示左侧模糊提示 19 | } else { 20 | blurLeft.style.opacity = 0; // 隐藏左侧模糊提示 21 | } 22 | 23 | // 检查右侧是否有可滑动元素 24 | if (headContainer.scrollLeft < headContainer.scrollWidth - headContainer.clientWidth) { 25 | blurRight.style.opacity = 1; // 显示右侧模糊提示 26 | } else { 27 | blurRight.style.opacity = 0; // 隐藏右侧模糊提示 28 | } 29 | } 30 | 31 | // ---------------------------------------------------------------------------------------------------- 32 | // 跳转按钮 33 | document.addEventListener("DOMContentLoaded", function () { 34 | let input = document.getElementById("webkey"); 35 | let button = document.getElementById("keybtn"); 36 | let message = document.getElementById("message"); 37 | 38 | function sendKey() { 39 | let key = input.value 40 | fetch("/", { 41 | method: "POST", 42 | headers: { 43 | "Content-Type": "application/json" 44 | }, 45 | body: JSON.stringify({ key: key }) 46 | }) 47 | .then(response => response.json()) 48 | .then(data => { 49 | if (data.success) { 50 | window.location.href = `/config?key=${key}`; 51 | } else { 52 | message.textContent = data.message; // 显示错误信息 53 | message.classList.remove("hidden"); 54 | message.classList.add("visible"); 55 | setTimeout(() => { 56 | message.classList.remove("visible"); 57 | message.classList.add("hidden"); 58 | }, 3000); // 3 秒后清空 59 | } 60 | }) 61 | .catch(error => console.error("Error:", error)); 62 | } 63 | 64 | // 监听按钮点击 65 | button.addEventListener("click", sendKey); 66 | 67 | // 监听输入框按键 68 | input.addEventListener("keydown", function (event) { 69 | if (event.key === "Enter") { 70 | event.preventDefault(); // 防止刷新页面 71 | sendKey(); 72 | } 73 | }); 74 | }); 75 | // ---------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------- /app/static/js/logs.js: -------------------------------------------------------------------------------- 1 | // logs.html 2 | 3 | // 加载文件内容 4 | function loadFileContent(filename, listItem) { 5 | // 取消其他文件的选中状态 6 | const allItems = document.querySelectorAll('.file-list li'); 7 | allItems.forEach(item => item.classList.remove('selected')); 8 | 9 | // 高亮当前选择的文件 10 | listItem.classList.add('selected'); 11 | 12 | // 更新文件名 13 | document.getElementById('fileName').textContent = filename; 14 | 15 | // 获取当前页面的 URL 16 | const currentUrl = new URL(window.location.href); 17 | // 获取 URL 中的 key 参数 18 | const key = currentUrl.searchParams.get('key'); 19 | // 构造 fetch 请求的 URL,带上 key 参数 20 | const fetchUrl = `/logs/${filename}?key=${key}`; 21 | 22 | // 请求文件内容 23 | fetch(fetchUrl) 24 | .then(response => response.json()) 25 | .then(data => { 26 | // 获取日志内容 27 | let logContent = data.log_content; 28 | 29 | // 将日志内容按行分割 30 | const lines = logContent.split('\n'); 31 | 32 | // 遍历每一行,检查是否包含 '[Error]',如果是,则添加红色样式 33 | const formattedLines = lines.map(line => { 34 | if (line.includes('[Error]')) { 35 | return `${line}`; 36 | } 37 | return line; 38 | }); 39 | 40 | // 将处理后的日志内容插入到页面 41 | document.getElementById('fileContent').innerHTML = formattedLines.join('
'); 42 | 43 | // 使用 DOM 的 scrollTop 属性将内容区域滚动到顶部 44 | const contentArea = document.getElementById('contentArea'); 45 | contentArea.scrollTop = 0; // 直接将 scrollTop 设置为 0 46 | }) 47 | .catch(error => alert('无法加载文件内容: ' + error)); 48 | 49 | // 点击文件后自动隐藏文件列表(仅移动端) 50 | if (window.innerWidth <= 768) { 51 | toggleSidebar(); 52 | } 53 | } 54 | 55 | // 切换文件列表的显示与隐藏 56 | function toggleSidebar() { 57 | const sidebar = document.getElementById('sidebar'); 58 | const button = document.getElementById('toggleButton'); 59 | 60 | // 判断文件列表是否显示 61 | if (sidebar.classList.contains('open')) { 62 | sidebar.classList.remove('open'); 63 | button.textContent = '>'; // 显示右箭头 64 | } else { 65 | sidebar.classList.add('open'); 66 | button.textContent = '<'; // 显示左箭头 67 | } 68 | } 69 | 70 | // 页面加载时显示切换按钮(移动端) 71 | window.addEventListener('resize', function () { 72 | const button = document.getElementById('toggleButton'); 73 | const sidebar = document.getElementById('sidebar'); 74 | if (window.innerWidth > 768) { 75 | button.style.display = 'none'; // 隐藏切换按钮 76 | sidebar.classList.add('open'); // 始终显示文件列表 77 | } else { 78 | button.style.display = 'block'; // 显示切换按钮 79 | sidebar.classList.remove('open'); // 隐藏文件列表 80 | } 81 | }); 82 | 83 | // 初始加载时处理屏幕尺寸并确保文件列表弹出(手机端) 84 | window.addEventListener('load', function () { 85 | if (window.innerWidth <= 768) { 86 | const sidebar = document.getElementById('sidebar'); 87 | sidebar.classList.add('open'); // 移动端首次加载时自动显示文件列表 88 | document.getElementById('toggleButton').textContent = '<'; // 设置按钮为左箭头 89 | } 90 | }); 91 | 92 | // 点击非列表区域时收起文件列表 93 | document.addEventListener('click', function (event) { 94 | const sidebar = document.getElementById('sidebar'); 95 | const button = document.getElementById('toggleButton'); 96 | const sidebarArea = sidebar.contains(event.target); 97 | const buttonArea = button.contains(event.target); 98 | 99 | if (!sidebarArea && !buttonArea && window.innerWidth <= 768) { 100 | sidebar.classList.remove('open'); 101 | button.textContent = '>'; // 恢复右箭头 102 | } 103 | }); 104 | 105 | // 初始加载时处理屏幕尺寸 106 | window.dispatchEvent(new Event('resize')); -------------------------------------------------------------------------------- /app/static/js/theme.js: -------------------------------------------------------------------------------- 1 | // 深色模式 2 | // 手动切换主题的功能 3 | function toggleTheme() { 4 | document.body.style.transition = "background-color 0.5s, color 0.5s"; 5 | document.body.classList.toggle('dark-mode'); 6 | // 保存用户选择的主题到 localStorage,确保页面刷新后保持设置 7 | const theme = document.body.classList.contains('dark-mode') ? 'dark' : 'light'; 8 | localStorage.setItem('theme', theme); 9 | } 10 | 11 | // 检测并设置当前的主题 12 | function detectAndApplyTheme() { 13 | const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; 14 | if (isDarkMode) { 15 | document.body.classList.add('dark-mode'); 16 | } else { 17 | document.body.classList.remove('dark-mode'); 18 | } 19 | } 20 | 21 | // 页面加载时应用用户上次选择的主题 22 | document.addEventListener('DOMContentLoaded', () => { 23 | const savedTheme = localStorage.getItem('theme'); 24 | if (savedTheme) { 25 | if (savedTheme === 'dark') { 26 | document.body.classList.add('dark-mode'); 27 | } else { 28 | document.body.classList.remove('dark-mode'); 29 | } 30 | } else { 31 | detectAndApplyTheme(); // 如果没有保存,自动检测系统主题 32 | } 33 | 34 | // 给图片添加点击事件,点击图片切换主题 35 | const themeToggleButton = document.getElementById('theme-toggle'); 36 | themeToggleButton.addEventListener('click', toggleTheme); 37 | }); -------------------------------------------------------------------------------- /app/templates/changelog.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 更新日志 11 | 12 | 13 |
14 |
15 |

更新日志

16 | PowerControl 17 |
18 | {% if log_content %} 19 |
{{ log_content }}
20 | {% else %} 21 |
无法加载更新日志,文件未找到。
22 | {% endif %} 23 |
24 | 25 | -------------------------------------------------------------------------------- /app/templates/code.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 代码块 15 | 16 | 17 |
18 |

代码

19 | PowerControl 21 |
22 | {% raw %} 23 | 24 |

1、docker-cli:

25 |
 26 |         
 27 |         
 28 | docker run -d -v /your/path:/app/data -e WEB_PORT=7678 -e WEB_KEY=yourkey --network host --restart unless-stopped --name powercontrol viklion/powercontrol:latest
 29 | # 默认root用户运行
 30 |         
 31 |     
32 |
 33 |         
 34 |         
 35 | docker run -d -u 1000:100 -v /your/path:/app/data -e WEB_PORT=7678 -e WEB_KEY=yourkey --network host --restart unless-stopped --name powercontrol viklion/powercontrol:latest
 36 | # 设置指定user运行(-u uid:gid)
 37 |         
 38 |     
39 | 40 | 41 |

2、docker-compose(注意检查缩进)

42 |
 43 |         
 44 |         
 45 | services:
 46 |   powercontrol:
 47 |     image: viklion/powercontrol:latest
 48 |     container_name: powercontrol
 49 |     volumes:
 50 |       - /your/path:/app/data
 51 |     environment:
 52 |       - WEB_PORT=7678
 53 |       - WEB_KEY=yourkey
 54 |     # 默认root用户运行,去掉下行的#,设置指定user运行(uid:gid)
 55 |     #user: 1000:100
 56 |     restart: unless-stopped
 57 |     network_mode: host
 58 |         
 59 |     
60 | 61 | 62 |

3、homeassistant configuration.yaml(注意检查缩进)

63 |
 64 |         
 65 |         
 66 | shell_command:
 67 |   ha_wol_pc: "curl http://192.168.2.75:1856/wol?key=1111"
 68 |   ha_shutdown_pc: "curl http://192.168.2.75:1856/shutdown?key=1111"
 69 | 
 70 | input_text:
 71 |   powercontrol_state:
 72 |     name: powercontrol_state
 73 |     initial: "off"
 74 | 
 75 | sensor:
 76 |   - platform: rest
 77 |     name: "powercontrol_pc_state"
 78 |     resource: "http://192.168.2.75:1856/ping?key=1111"
 79 |     method: GET
 80 |     scan_interval: 60
 81 |     value_template: "{{ value_json.device_status }}"
 82 | 
 83 | switch:
 84 |   - platform: template
 85 |     switches:
 86 |       my_pc:
 87 |         friendly_name: "电脑"
 88 |         unique_id: "my_pc_001"
 89 |         icon_template: mdi:desktop-tower-monitor
 90 |         value_template: "{{ states('input_text.powercontrol_state') == 'on' }}"
 91 |         turn_on:
 92 |           - service: shell_command.ha_wol_pc
 93 |           - service: input_text.set_value
 94 |             target:
 95 |               entity_id: input_text.powercontrol_state
 96 |             data:
 97 |               value: "on"
 98 |         turn_off:
 99 |           - service: shell_command.ha_shutdown_pc
100 |           - service: input_text.set_value
101 |             target:
102 |               entity_id: input_text.powercontrol_state
103 |             data:
104 |               value: "off"
105 |         
106 |     
107 | 108 | 109 |

4、homeassistant automations.yaml(注意检查缩进)

110 |
111 |         
112 |         
113 | - id: '20250108'
114 |   alias: 更新电脑在线状态
115 |   trigger:
116 |     - platform: time_pattern
117 |       minutes: "/1"
118 |   condition:
119 |     - condition: template
120 |       value_template: "{{ states('sensor.powercontrol_pc_state') != states('input_text.powercontrol_state') }}"
121 |   action:
122 |     - service: input_text.set_value
123 |       target:
124 |         entity_id: input_text.powercontrol_state
125 |       data:
126 |         value: "{{ states('sensor.powercontrol_pc_state') }}"
127 |         
128 |     
129 | {% endraw %} 130 | 131 | -------------------------------------------------------------------------------- /app/templates/config.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | PowerControl配置页 11 | 12 | 13 | 14 |
15 | 16 |
17 | 28 | 29 |
30 |
31 |
32 |

PowerControl配置 {{ config.version }}

33 |

by viklion

34 |

{{ run_time }}

35 |
36 |
37 | {% with messages = get_flashed_messages() %} 38 | {% if messages %} 39 |
    40 | {% for message in messages %} 41 |
  • {{ message | replace('\n', '
    ')| safe }}
  • 42 | {% endfor %} 43 |
44 | {% endif %} 45 | {% endwith %} 46 |
47 |
48 | 50 |
51 | 52 |
53 |
54 |
55 |

巴法:

56 |
57 | 接入巴法云:
58 | 前往巴法控制台 59 |
60 | 64 |

设备:

65 | 设备名称:
66 | 设备ip地址:
67 |
68 |
69 | 启用网络唤醒: 70 | 测试开机
71 |
72 | 83 |
84 |
85 | 启用远程关机: 86 | 测试关机
87 |
88 | 113 |
114 |
115 | 启用ping检测: 116 | 测试ping
117 |
118 | 121 |

日志:

122 | 启用日志记录:
123 | 131 |

推送:

132 |
133 | 启用消息推送:
134 | 测试消息推送 135 |
136 | 174 |
175 |
176 | 177 |
178 |
179 |
180 | 181 | -------------------------------------------------------------------------------- /app/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | PowerControl 12 | 13 | 14 | 15 |
16 | 17 |
18 |
19 | 20 | PowerControl 22 | 23 | github 24 | pdf教程 25 | 视频教程 26 | 更新日志 27 | 复制代码 28 | 29 |
30 | 31 |
32 |
33 |
34 |

PowerControl {{ config.version }}

35 |

by viklion

36 |

{{ run_time }}

37 |
38 |
39 | 40 |
跳转配置
41 |
42 |
43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /app/templates/logs.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 操作日志 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 28 | 29 | 30 |
31 |
32 |

左侧选择日志文件

33 | PowerControl 35 |
36 |
点击日志文件查看内容。
37 |
38 |
39 | 40 | -------------------------------------------------------------------------------- /doc/PowerControl教程.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/doc/PowerControl教程.pdf -------------------------------------------------------------------------------- /iStoreOS.md: -------------------------------------------------------------------------------- 1 | # iStoreOS添加容器详细指引 2 | 1. docker-镜像,输入`viklion/powercontrol:latest`,点击`拉取` 3 | 4 | ![ist04](https://github.com/user-attachments/assets/e009eefc-0784-46e6-b843-e705983dd201) 5 | 6 | 1. docker-容器,点击`新增` 7 | 8 | ![ist01](https://github.com/user-attachments/assets/53e79294-d497-4770-94f1-774586779a6b) 9 | 10 | 1. 容器名称:`powercontrol`(可自由更改) 11 | 12 | Docker镜像,选择`viklion/powercontrol:latest` 13 | 14 | 勾选`总是先拉取镜像` 15 | 16 | 重启策略:选择`Unless stopped` 17 | 18 | 网络:选择`host` 19 | 20 | 环境变量(别忘了点击'+'号):`WEB_PORT=你想设置的端口号,默认:7678` , `WEB_KEY=你想设置的密钥,默认:admin` 21 | 22 | 绑定挂载(别忘了点击'+'号):`/dockerdata/powercontrol:/app/data`或者`你自定义的存放配置文件和日志文件的文件夹:/app/data` 23 | 24 | ![ist02](https://github.com/user-attachments/assets/bd06b961-9e4a-44ec-86f8-6dec2a83c6b4) 25 | 26 | 1. 勾选容器,点击`启动` 27 | 28 | ![ist03](https://github.com/user-attachments/assets/246ca6c2-8bca-42ad-94c8-eb908f932230) 29 | 30 | 1. 容器启动后访问`ip:端口`进入首页,顶部跳转教程,输入KEY跳转配置 31 | -------------------------------------------------------------------------------- /icon/powercontrol-圆角.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/icon/powercontrol-圆角.png -------------------------------------------------------------------------------- /icon/powercontrol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/icon/powercontrol.png -------------------------------------------------------------------------------- /icon/powercontrol宽图.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/icon/powercontrol宽图.png -------------------------------------------------------------------------------- /icon/powercontrol宽图透明.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/icon/powercontrol宽图透明.png -------------------------------------------------------------------------------- /icon/powercontrol透明背景.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/icon/powercontrol透明背景.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | APScheduler==3.11.0 2 | blinker==1.9.0 3 | certifi==2024.12.14 4 | charset-normalizer==3.4.0 5 | click==8.1.8 6 | colorama==0.4.6 7 | Flask==3.1.0 8 | Flask-Cors==5.0.0 9 | idna==3.10 10 | itsdangerous==2.2.0 11 | Jinja2==3.1.5 12 | MarkupSafe==3.0.2 13 | pythonping==1.1.4 14 | PyYAML==6.0.2 15 | requests==2.32.3 16 | serverchan-sdk==1.0.6 17 | setuptools==75.1.0 18 | tzdata==2024.2 19 | tzlocal==5.2 20 | urllib3==2.3.0 21 | wakeonlan==3.1.0 22 | Werkzeug==3.1.3 23 | wheel==0.44.0 24 | -------------------------------------------------------------------------------- /software/PCshutdown.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/software/PCshutdown.exe -------------------------------------------------------------------------------- /software/WakeOnLanMonitor.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/viklion/PowerControl/b5f6c390652e7c1156dac98209acce40e2f337a5/software/WakeOnLanMonitor.exe --------------------------------------------------------------------------------