-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.py
executable file
·396 lines (342 loc) · 11.8 KB
/
main.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#!/usr/bin/env python3
# encoding:utf-8
import json
import os
from datetime import datetime
import commonmark
import flask
from flask import Flask, request, render_template, url_for, flash
from flask_login import current_user, login_required
from sqlalchemy import desc
from werkzeug.utils import redirect
import config_t
import v2ray_config
from auth import auth as auth_blueprint
from auth import login_manager
from data_model import db, Article, Tag, Message, Link
from my_utils import my_secure_filename, hgihtlight_word
app = Flask(__name__)
app.config.from_object(config_t)
db.init_app(app)
login_manager.init_app(app)
app.register_blueprint(auth_blueprint)
app.jinja_env.globals.update(hgihtlight_word=hgihtlight_word)
@app.errorhandler(404)
def page_not_found(e):
# note that we set the 404 status explicitly
return render_template('404.html', error=e), 404
# @app.route("/utils")
# def utils():
# tag = Tag.query.all()
# for a in tag:
# print(a.name)
# tagmap = Tagmap.query.filter_by(tag_id=a.id).all()
# print(len(tagmap))
# for ar in tagmap:
# print(ar.article)
# print(ar.article.title)
#
# return render_template('utils.html')
def get_tag_dict():
tag_dict = {}
tags = Tag.query.all()
for tag in tags:
tag_dict[tag.name] = (tag.id, len(tag.articles.all()))
return tag_dict
def root_required(func):
# 装饰器,有些操作只有我能执行,验证current_user为管理员
def access_is_0(*args, **kwargs):
if current_user.access == 0:
func(*args, **kwargs)
else:
# flash("You have no permission to access this page")
# TODO: diffrent call from diffrent path
return "ERROR PERMISSION"
return access_is_0
@app.route('/')
def index():
url_page = request.args.get("page", 1, type=int)
url_tag = request.args.get("tag", type=int)
if url_tag:
c_tag = Tag.query.filter_by(id=url_tag).first()
pagination = c_tag.articles.order_by(desc(Article.time)).paginate(url_page,
per_page=app.config['POSTS_PER_PAGE'],
error_out=True)
else:
pagination = Article.query.order_by(desc(Article.time)).paginate(url_page,
per_page=app.config['POSTS_PER_PAGE'],
error_out=True)
articles = pagination.items
return render_template('index.html', articles=articles, pagination=pagination, tag_dict=get_tag_dict(),
args=request.args)
@app.route('/up', methods=['GET', 'POST'])
def my_upload():
if request.method == "POST":
if not current_user.is_anonymous:
f = request.files['inputfile']
if os.name == "posix":
upload_path = os.path.join("/myvps", 'upload', my_secure_filename(f.filename))
else:
upload_path = os.path.join("e:\\tmp", '', my_secure_filename(f.filename))
f.save(upload_path)
return redirect(url_for('my_upload'))
else:
flask.abort(401)
return render_template('up.html')
@app.route('/write_article', methods=['GET'])
@login_required
def write_article():
return render_template('write_article.html')
@app.route('/post_article', methods=['POST'])
@login_required
def post_article():
if current_user.access != 0:
# flash("当前用户没有权限发布文章!")
return "Cant access!"
try:
article_info = json.loads(str(request.get_data(), encoding="utf-8"))
article = Article(
author=current_user.id,
time=datetime.now(),
title=article_info["title"],
text=article_info["main"])
if len(article_info["title"]) == 0:
return "Has No Title!"
new_list = map(str.strip, article_info["tags"])
db.session.add(article)
for i in new_list:
if len(i) == 0:
continue
tag = Tag.query.filter_by(name=i).first()
if tag:
tag.articles.append(article)
pass
else:
new_tag = Tag(name=i)
db.session.add(new_tag)
new_tag.articles.append(article)
db.session.commit()
except Exception as e:
print(e)
db.session.rollback()
return "Unknown error!"
return "OK"
@app.route('/modify_article/<a_id>', methods=['POST'])
@login_required
def modify_article(a_id):
if current_user.access != 0:
# flash("当前用户没有修改文章!")
return "Cant access!"
try:
article = Article.query.get(int(a_id))
article_info = json.loads(str(request.get_data(), encoding="utf-8"))
article.text = article_info["main"]
article.title = article_info["title"]
if len(article_info["title"]) == 0:
return "Has No Title!"
# todo handle tags
# new_list = map(str.strip, article_info["tags"])
# for i in new_list:
# if len(i) == 0:
# continue
# tag = Tag.query.filter_by(name=i).first()
# if tag:
# if not article in tag.articles:
# tag.articles.append(article)
# else:
# new_tag = Tag(name=i)
# db.session.add(new_tag)
# new_tag.articles.append(article)
db.session.commit()
except Exception as e:
print(e)
db.session.rollback()
return "Unknown error!"
return "OK"
@app.route('/select_tags')
def select_tags():
rs = []
rs_all = Tag.query.all()
for i in rs_all:
rs.append(i.name)
return json.dumps(rs, ensure_ascii=False)
@app.route("/article/<a_id>")
def a_article(a_id):
article = Article.query.get(int(a_id))
if not article:
flask.abort(404)
parser = commonmark.Parser()
ast = parser.parse(article.text)
renderer = commonmark.HtmlRenderer()
html = renderer.render(ast)
article_dict = {
"title": article.title,
"time": str(article.time),
"text": html,
"author": article.user.name
}
return render_template("article.html", id=a_id, tag_dict=get_tag_dict(), article_dict=article_dict)
@app.route("/article_info/<a_id>")
def a_article_info(a_id):
article = Article.query.get(int(a_id))
article_json = {
"title": article.title,
"time": str(article.time),
"text": article.text,
"author": article.user.name
}
return json.dumps(article_json, ensure_ascii=False)
@app.route("/article/delete/<a_id>")
@login_required
def del_article(a_id):
if current_user.access != 0:
return "Cant access!"
article = Article.query.get(int(a_id))
db.session.delete(article)
db.session.commit()
flash("已删除一篇文章!")
return redirect(url_for("index"))
@app.route("/article/modify/<a_id>")
@login_required
def modify_articcle(a_id):
if current_user.access != 0:
return "Cant access!"
article = Article.query.get(int(a_id))
return render_template('write_article.html', article=article)
@app.route("/search")
def search_article():
k = request.args.get("keyword")
if len(k) == 0:
return redirect(url_for("index"))
ar = Article.query.filter(Article.title.like("%" + k + "%"))
pagination = ar.order_by(desc(Article.time)).paginate(1, per_page=1024, error_out=True)
return render_template('index.html', articles=pagination.items, pagination=pagination, tag_dict=get_tag_dict(),
args=request.args, search_keyword=k)
@app.route("/utils")
def utils_src():
return redirect(url_for("utils", wh="up"))
@app.route("/utils/<wh>")
def utils(wh):
if wh == "message":
pass
elif wh == "links":
rs_all = Link.query.all()
return render_template(wh + ".html", util_id=wh, links=rs_all)
return render_template(wh + ".html", util_id=wh)
@app.route("/add_mess", methods=['POST'])
def add_mess():
mess_info = json.loads(str(request.get_data(), encoding="utf-8"))
mess = Message(
message=mess_info['mess'],
time=datetime.now()
)
if mess.message == "":
flask.abort(500)
return
db.session.add(mess)
db.session.commit()
return "OK"
@app.route("/add_links", methods=['POST'])
@login_required
def add_links():
link_info = json.loads(str(request.get_data(), encoding="utf-8"))
link = Link(
title=link_info['title'],
link=link_info['addr']
)
if link.title == "" or link.link == "":
flask.abort(500)
return
db.session.add(link)
db.session.commit()
return "OK"
@app.route("/get_mess")
def get_mess():
if current_user.access != 0:
flask.abort(500)
n = int(request.args.get("n"))
if n is None or n == 0:
n = 10
rs_all = Message.query.order_by(desc(Message.id)).all()
rs = []
for i, j in enumerate(rs_all):
if i > n:
break
rs.append(j.message)
return json.dumps(rs, ensure_ascii=False)
@app.route("/hex/<t_string>", methods=['POST', 'GET'])
def get_hex(t_string):
try:
sp = request.args.get("sp")
except Exception:
pass
if not sp or len(sp) == 0:
sp=r'\x'
tar = t_string + "\n"
en = t_string.encode(encoding="utf-8")
s1 = ''.join([sp + '%02x' % b for b in en])
tar += "utf-8 encode, len( " + str(len(en)) + " ): " + s1 + "\n"
en = t_string.encode(encoding="gbk")
s1 = ''.join([sp + '%02x' % b for b in en])
tar += "gbk encode, len( " + str(len(en)) + " ): " + s1 + "\n"
en = t_string.encode(encoding="utf-16")
s1 = ''.join([sp + '%02x' % b for b in en])
tar += "utf-16 encode, len( " + str(len(en)) + " ): " + s1 + "\n"
return render_template("hex.html", hex_str=tar)
@app.route("/test_json", methods=['POST', 'GET'])
def get_test_json():
rs = {
"type": "string",
"data": "测试字符串。中文。",
"format":
{
"line_spacing": 3,
"para_spacing": 1.72,
"font": "Consolas",
"font_size": 12,
"bold": True ,
"extra":[
{
"extra_1":"hi",
"extra_2":"hello",
},
{
"extra_3": "hi",
"extra_4": "hello",
"extra_5": "另一串中文"
}
]
}
}
return json.dumps(rs, ensure_ascii=False)
@app.route("/gen_v2ray_config", methods=['POST'])
def gen_v2ray_config():
v_info = json.loads(str(request.get_data(), encoding="utf-8"))
rs = v2ray_config.get_v2ray_config(v_info)
(use_c, use_s, use_re, conf_c, conf_s, data_re) = rs
conf_r = ""
if data_re[0] == 1:
conf_r = render_template("nginx.conf", port=data_re[1], server_name=data_re[2], path=data_re[3],
be_proxy=data_re[4], tls_config=data_re[5], ssl=data_re[6])
elif data_re[0] == 2:
conf_r = render_template("Caddyfile-ws", domain=data_re[1], tls=data_re[2], path=data_re[3],
be_proxy=data_re[4])
elif data_re[0] == 3:
conf_r = render_template("Caddyfile-h2", domain=data_re[1], path=data_re[2], be_proxy=data_re[3],
host_domain=data_re[4])
else:
use_re = False
if not use_c:
conf_c = "N/A"
if not use_s:
conf_s = "N/A"
if not use_re:
conf_r = "N/A"
config = {
"c": conf_c,
"s": conf_s,
"r": conf_r
}
return json.dumps(config)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000, debug=True)