Skip to content

Commit

Permalink
Merge pull request #2 from wyf9/dev
Browse files Browse the repository at this point in the history
v3
  • Loading branch information
wyf9 authored Nov 13, 2024
2 parents 3e0862b + 87373eb commit f7fb26e
Show file tree
Hide file tree
Showing 4 changed files with 156 additions and 45 deletions.
41 changes: 26 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# sleepy

Are you sleeping?
> Are you sleeping?
一个查看个人在线状态的 Flask 网站,让他人能知道你不在而不是故意吊他/她

[演示](#preview) / [部署](#部署) / [使用](#使用) / [关于](#关于)
[**演示**](#preview) / [**部署**](#部署) / [**使用**](#使用) / [**关于**](#关于)

> ver: `2.0`, configver: `2`
<!-- > ver: `2.0`, configver: `2` -->

## Preview

Expand All @@ -22,13 +22,22 @@ Are you sleeping?

![server-1](img/server-1.png)

> ↑ 使用的 ssh 工具: WindTerm
## 部署

理论上全平台通用, 安装了 Python 即可 *(开发环境: Debian linux)*
> [!WARNING]
> 如果要创建自用的 repo 而不是贡献此仓库, 建议使用模板创建而非直接 Fork (Fork 不能设置私有, 意味着 *他人可以看到你的配置信息, **包括 `secret`***)
- 使用模板创建: [link here](https://github.com/new?template_name=sleepy&template_owner=wyf9) or 直接选择右上角的 `Use this template`:

![use this template](img/use-this-template.png)

进入 repo 创建页, 即可选择仓库类型为 `Private`.

---

1. Clone 本仓库 (建议先 Fork)
理论上全平台通用, 安装了 Python >= **3.6** 即可

1. Clone 本仓库 (建议先 Fork / Use this template)

```shell
git clone https://github.com/wyf9/sleepy.git
Expand All @@ -44,7 +53,7 @@ cd sleepy
# or windows:
# .\install_lib.bat
# 也可自行安装: pip install -r requirements.txt
# 其实只有 FLask (目前)
# 其实只有 Flask (目前)
```

3. 编辑配置文件
Expand All @@ -55,7 +64,7 @@ cd sleepy
python3 server.py
```

如果不出意外,会提示: `[Warning] [YYYY-MM-DD hh:mm:ss] data.json not exist, creating`,同时目录下出现 `data.json` 文件,编辑该文件中的配置即可 (示例请 [查看 `example.jsonc`](./example.jsonc) )
如果不出意外,会提示: `data.json not exist, creating`,同时目录下出现 `data.json` 文件,编辑该文件中的配置并重新运行即可 (示例请 [查看 `example.jsonc`](./example.jsonc) )

## 使用

Expand All @@ -73,7 +82,7 @@ python3 server.py
python3 start.py
```

相比直接启动, 启动器可实现在服务器退出后自动重启
相比直接启动, 启动器可实现在服务器退出 *(如开启 debug 后更改时自动保存导致有语法错误)* 后自动重启

<details>
<summary>点击展开</summary>
Expand Down Expand Up @@ -119,8 +128,6 @@ Press CTRL+C to quit
| `/set?secret=<secret>&status=<status>` | 设置状态 (url 参数) |
| `/set/<secret>/<status>` | 设置状态 (路径) |

> 以下是 4 个接口的解释
1. `/query`:

获取当前的状态 (无需鉴权)
Expand Down Expand Up @@ -182,7 +189,7 @@ Press CTRL+C to quit
"set_to": 0 // 设置到的状态码
}

// 2. 失败 - 鉴权失败 (密钥错误)
// 2. 失败 - 密钥错误
{
"success": false, // 请求是否成功
"code": "not authorized", // 返回代码
Expand All @@ -201,8 +208,12 @@ Press CTRL+C to quit

同上 `3.`, 唯一的不同是 url 格式

## 客户端示例

`_example/` 目录下, 可参考

## 关于

本项目灵感由 Bilibili UP @ [WinMEMZ](https://space.bilibili.com/417031122) 而来: [site](https://maao.cc/sleepy/) / [blog](https://www.maodream.com/archives/192/), 并~~部分~~借鉴了前端代码。在此十分感谢。
本项目灵感由 Bilibili UP @ [WinMEMZ](https://space.bilibili.com/417031122) 而来: [site](https://maao.cc/sleepy/) / [blog](https://www.maodream.com/archives/192/), 并~~部分借鉴~~使用了前端代码, 在此十分感谢。

如有 Bug / 建议, 请 [issue](https://github.com/wyf9/sleepy/issues/new).
如有 Bug / 建议, 请 [issue](https://github.com/wyf9/sleepy/issues/new) or [More contact](https://wyf9.top/#/contact).
106 changes: 106 additions & 0 deletions _example/cmd_console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/usr/bin/python3
# coding:utf-8

'''
一个 python 命令行示例
by @wyf9
'''

import requests
import json
global server

# 密钥
SECRET = 'YourSecret'
# 服务列表, 末尾不加 `/`
SERVER_LIST = ['https://example.com',
'http://192.168.114.114',
'http://192.168.191.191:9810']
# 请求重试次数
RETRY = 3


def get(url):
for t1 in range(RETRY):
t = t1 + 1
try:
x = requests.get(url)
return x.text
except:
print(f'Retrying... {t}/{RETRY}')
if t >= RETRY:
print('Max retry limit!')
raise
continue


def loadjson(url):
raw = get(url)
try:
return json.loads(raw)
except json.decoder.JSONDecodeError:
print('Error decoding json!\nRaw data:\n"""')
print(raw)
print('"""')
raise
except:
print('Error:')
raise


def main():
print('\n---\nSelect Server:')
serverlst_show = ''
for n1 in range(len(SERVER_LIST)):
n = n1 + 1
serverlst_show += f' {n}. {SERVER_LIST[n1]}\n'
print(f'''
0. Quit
{serverlst_show}''')
while True:
try:
inp = int(input('> '))
if inp == 0:
return 0
else:
server = SERVER_LIST[inp - 1]
print(f'Selected server: {server}')
break
except:
print('invaild input')

print('\n---\nStatus now:')
stnow = loadjson(f'{server}/query')
try:
print(f'success: [{stnow["success"]}], status: [{stnow["status"]}], info_name: [{
stnow["info"]["name"]}], info_desc: [{stnow["info"]["desc"]}], info_color: [{stnow["info"]["color"]}]')
except KeyError:
print(f'RawData: {stnow}')

print('\n---\nSelect status:')

stlst = loadjson(f'{server}/get/status_list')
for n in stlst:
print(f'{n["id"]} - {n["name"]} - {n["desc"]}')

st = input('\n> ')
'''
print(get())
{
"success": true,
"code": "OK",
"set_to": 0
}
'''
ret = loadjson(f'{server}/set/{SECRET}/{st}')
try:
print(
f'success: [{ret["success"]}], code: [{ret["code"]}], set_to: [{ret["set_to"]}]')
except:
print(f'RawData: {ret}')
input('\n---\nPress Enter to exit.')
return 0


if __name__ == "__main__":
main()
Binary file added img/use-this-template.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 24 additions & 30 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def query():
d.load()
showip(request, '/query')
st = d.data['status']
stlst = d.data['status_list']
# stlst = d.data['status_list']
try:
stinfo = d.data['status_list'][st]
except:
Expand All @@ -96,39 +96,33 @@ def get_status_list():
return u.format_dict(stlst)


@app.route('/set', methods=['GET', 'POST'])
@app.route('/set')
def set_normal():
showip(request, '/set')
if request.method == "GET":
status = escape(request.args.get("status"))
try:
status = int(status)
except:
return reterr(
code='bad request',
message="argument 'status' must be a number"
)
secret = escape(request.args.get("secret"))
u.info(f'status: {status}, secret: "{secret}"')
secret_real = d.dget('secret')
if secret == secret_real:
d.dset('status', status)
u.info('set success')
ret = {
'success': True,
'code': 'OK',
'set_to': status
}
return u.format_dict(ret)
else:
return reterr(
code='not authorized',
message='invaild secret'
)
else:
status = escape(request.args.get("status"))
try:
status = int(status)
except:
return reterr(
code='bad request',
message='only support GET request now'
message="argument 'status' must be a number"
)
secret = escape(request.args.get("secret"))
u.info(f'status: {status}, secret: "{secret}"')
secret_real = d.dget('secret')
if secret == secret_real:
d.dset('status', status)
u.info('set success')
ret = {
'success': True,
'code': 'OK',
'set_to': status
}
return u.format_dict(ret)
else:
return reterr(
code='not authorized',
message='invaild secret'
)


Expand Down

0 comments on commit f7fb26e

Please sign in to comment.