-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebserverListener.py
229 lines (172 loc) · 6.65 KB
/
webserverListener.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import json
import os
import time
from datetime import date, datetime
from typing import List
from flask import redirect, request
from flask_cors import CORS
import pandalearning as pdl
from .pdlearn import user
from .webServerConf import UserInfo, WebMessage, WebQrUrl, app, web_db
@app.before_first_request
def create_db():
'创建表格、插入数据'
# Recreate database each time for demo
web_db.drop_all()
web_db.create_all()
def request_parse(req_data):
data = None
if req_data.method == 'POST':
data = req_data.json
elif req_data.method == 'GET':
data = req_data.args
return data
def resp(code=200, data=dict(), status='success', resp_code=200):
resp = {'code': code, 'data': data, 'status': status}
return resp, resp_code
def resp_ok(resp_data=dict()):
resp = {'code': 200, 'data': resp_data, 'status': "success"}
return resp
def web_log_and_resp_ok(resp_data=dict()):
web_log(resp_data)
return resp_ok(resp_data)
def resp_db_ok(res_rows=None):
resp = {'code': 200, 'data': [
dict(zip(result.keys(), result)) for result in res_rows], 'status': "success"}
return resp
def serialize(model):
from sqlalchemy.orm import class_mapper
columns = [c.key for c in class_mapper(model.__class__).columns]
return dict((c, getattr(model, c)) for c in columns)
def resp_models_ok(models=[None]):
if not isinstance(models, List):
models = [models]
list_json_models = [serialize(model) for model in models]
resp = {'code': 200, 'data':
list_json_models, 'status': "success"}
return resp
def resp_not_found(resp_msg=None):
resp = {'code': 404, 'msg': resp_msg, 'status': "404 NOT FOUND"}
return resp, 404
def resp_err(resp_msg=None):
resp = {'code': 500, 'msg': resp_msg, 'status': "ERRO"}
return resp, 500
def web_log(send_log):
print(send_log)
web_db.session.add(WebMessage(send_log))
web_db.session.commit()
@app.route('/')
def hello_world():
return redirect('/static/index.html', code=302)
@app.route('/jump')
def jump_app():
return redirect('/static/jump.html', code=302)
@app.route('/api/sleep/<sleep_time>')
def sleep(sleep_time):
time.sleep(float(sleep_time))
resp_data = dict()
resp_data['sleep'] = sleep_time
return resp_ok(resp_data)
@app.route('/api/now')
def now():
return resp_ok(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
@app.route('/api/update')
def update():
try:
shell = "git -C /xuexi/code/TechXueXi pull $Sourcepath $pullbranche "
req_data = request_parse(request)
params = req_data['params'] if 'params' in req_data else ''
if len(params) > 1:
shell += params[1]
msg = os.popen(shell).readlines()[-1]
if "up to date" in msg:
msg += "当前代码已经是最新的了"
return web_log_and_resp_ok("当前代码已经是最新的了")
else:
os.popen("cp -r /xuexi/code/TechXueXi/SourcePackages/* /xuexi")
return web_log_and_resp_ok("代码更新完成"+msg)
except Exception as e:
return resp_err("更新失败:"+str(e))
@app.route('/api/list')
def list():
return resp_models_ok(web_db.session.query(UserInfo).all())
@app.route('/api/refresh_all_cookies')
def refresh_all_cookies():
user_status = user.refresh_all_cookies(display_score=True)
user_infos = web_db.session.query(UserInfo).all()
for user_info in user_infos:
web_db.session.delete(user_info)
for (uid, status) in user_status.items():
web_db.session.add(UserInfo(uid, status))
web_db.session.commit()
return list()
@app.route('/api/add')
def add():
pdl.add_user()
return web_log_and_resp_ok('ヾ(o◕∀◕)ノヾ登录成功,首次登录请手动开始学习ヾ(≧O≦)〃嗷~')
@app.route('/api/learn')
def learn():
''' 新线程无法操控内存数据库'''
# web_db.session.add(WebMessage('新线程无法操控内存数据库'))
# web_db.session.commit()
# return resp_models_ok(WebMessage('新线程无法操控内存数据库'))
names = pdl.get_all_user_name()
if len(names) <= 1:
return web_log_and_resp_ok('请添加用户')
else:
pdl.start(None)
return web_log_and_resp_ok('全部账号开始学习:{}'.format(names))
@app.route('/api/learn_by_nick_name/<nick_name>')
def learn_by_nick_name(nick_name):
names = pdl.get_all_user_name()
if len(names) <= 1:
return web_log_and_resp_ok('请添加用户')
else:
names = pdl.get_all_user_name()
for name in names:
if nick_name == name:
pdl.start(nick_name)
return web_log_and_resp_ok('开始学习:{}'.format(nick_name))
@app.route('/api/learn_by_uid/<uid>')
def learn_by_uid(uid):
pdl.start_learn(uid, None)
return web_log_and_resp_ok('开始学习:{}'.format(user.get_fullname(uid)))
@app.route('/api/list_user')
def list_user():
return resp_ok(user.list_user(printing=False))
@app.route('/api/remove_cookie/<uid>')
def remove_cookie(uid):
user_name = user.get_fullname(uid)
msg = 'uid: {} ,username: {} 状态清除成功'.format(uid, user_name)
user.remove_cookie(uid)
web_log(msg)
return resp_models_ok(WebMessage(msg))
@app.route('/api/list_qrurls')
def list_qrurls():
qrurls = web_db.session.query(WebQrUrl).all()
# print(
# '二维码:', [((datetime.now() - qrurl.timestamp).seconds, qrurl.timestamp) for qrurl in qrurls])
for qrurl in qrurls:
# print('--------------------------------\n秒:{}\n--------------------------------'.format(
# (datetime.now() - qrurl.timestamp).seconds))
if (datetime.now() - qrurl.timestamp).seconds > 300:
web_log('超时,二维码已被移除: {}'.format(qrurl.id))
web_db.session.delete(qrurl)
web_db.session.commit()
return resp_models_ok(qrurls)
@app.route('/api/list_messages')
def list_messages():
messages = web_db.session.query(WebMessage).all()
# print(
# '消息:', [(datetime.now() - message.timestamp).seconds for message in messages])
for message in messages:
# print('--------------------------------\n分:{}\n--------------------------------'.format(
# (datetime.now() - message.timestamp).seconds/60))
if (datetime.now() - message.timestamp).seconds > 300:
# web_log('超时,消息已被移除: {} - {}'.format(message.id, message.timestamp))
web_db.session.delete(message)
web_db.session.commit()
return resp_models_ok(messages)
if __name__ == "__main__":
CORS(app, supports_credentials=True)
app.run(host='0.0.0.0', port='80', debug=True)