Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
669 lines (598 loc) · 25.5 KB
/
Copy pathapp.py
File metadata and controls
669 lines (598 loc) · 25.5 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
import hashlib
import os
import secrets
import re
import uuid
from datetime import timedelta
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
request, send_from_directory, session, url_for)
from config import ADMIN_PASSWORD, ADMIN_USERNAME, COOKIE_DAYS, MYSQL_CONFIG, SECRET_KEY
from extensions import csrf, db
from PIL import Image, ImageOps
from sqlalchemy import or_
SANITIZE_TAGS = {
"b", "i", "u", "s", "span", "div", "p", "br", "a",
"h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li",
"blockquote", "hr", "pre", "code", "img", "table",
"tbody", "tr", "td", "th", "thead", "tfoot", "figure",
"figcaption",
}
SANITIZE_ATTRS = {
"href", "src", "alt", "style", "color", "background-color",
"class", "id", "target", "rel",
"data-placeholder", "data-image-id",
}
SCAFFOLD_CLASSES = {
"te-code-controls", "te-code-copy-btn", "te-code-remove-btn",
"te-resize-bar", "te-resize-corner", "te-close-icon",
"te-image-resizer",
}
INLINE_HEADING_TAGS = {"h1", "h2", "h3", "h4", "h5", "h6", "p"}
BLOCK_CHILD_TAGS = {
"pre", "div", "p", "table", "figure", "ul", "ol",
"blockquote", "h1", "h2", "h3", "h4", "h5", "h6",
"hr", "img",
}
HOIST_OUT_OF = {
"h1", "h2", "h3", "h4", "h5", "h6", "p",
"span", "a", "b", "i", "u", "s", "em", "strong",
"figcaption",
}
def _safe_url(attr, value):
if attr in ("href", "src"):
v = value.lower()
v = "".join(ch for ch in v if ch not in "\t\n\r\x00 \x0b\x0c")
if v.startswith(("javascript:", "data:", "vbscript:",
"file:", "about:", "blob:")):
return None
return value
def _classes(el):
return (el.get("class") or "").split()
def sanitize_html(html):
if not html:
return html
from lxml import html as _lxml_html
doc = _lxml_html.fromstring(
"<html><body>" + html + "</body></html>")
body = doc.body
if body is None:
return ""
while True:
bad = [el for el in body.iter()
if el is not body
and not (isinstance(el.tag, str) and el.tag in SANITIZE_TAGS)]
if not bad:
break
for el in bad:
parent = el.getparent()
if parent is None:
continue
for child in list(el):
el.addprevious(child)
parent.remove(el)
for el in body.iter():
if not isinstance(el.tag, str):
continue
for attr in list(el.attrib):
if attr not in SANITIZE_ATTRS:
del el.attrib[attr]
else:
safe = _safe_url(attr, el.attrib[attr])
if safe is None:
del el.attrib[attr]
else:
el.attrib[attr] = safe
if el.tag == "a":
el.set("target", "_blank")
el.set("rel", "noopener noreferrer")
for el in list(body.iter()):
if isinstance(el.tag, str) \
and any(c in SCAFFOLD_CLASSES for c in _classes(el)):
parent = el.getparent()
if parent is None:
continue
for child in list(el):
el.addprevious(child)
parent.remove(el)
for el in list(body.iter()):
if isinstance(el.tag, str) and el.tag == "div" \
and "te-code-wrapper" in _classes(el):
parent = el.getparent()
if parent is None:
continue
pre = el.find("pre")
if pre is not None:
parent.replace(el, pre)
else:
for child in list(el):
el.addprevious(child)
parent.remove(el)
for el in list(body.iter()):
if isinstance(el.tag, str) \
and "is-loading" in _classes(el) \
and not "".join(el.itertext()).strip():
parent = el.getparent()
if parent is not None:
parent.remove(el)
for el in list(body.iter()):
if isinstance(el.tag, str) and el.tag == "pre" \
and not "".join(el.itertext()).strip():
parent = el.getparent()
if parent is not None:
parent.remove(el)
for el in list(body.iter()):
if isinstance(el.tag, str) and el.tag == "img" \
and not el.get("src"):
parent = el.getparent()
if parent is not None:
parent.remove(el)
for _ in range(8):
figs = [el for el in list(body.iter())
if isinstance(el.tag, str) and el.tag == "figure"
and not "".join(el.itertext()).strip()]
for el in figs:
parent = el.getparent()
if parent is not None:
parent.remove(el)
if not figs:
break
for _ in range(8):
removed = False
for el in list(body.iter()):
if isinstance(el.tag, str) \
and "te-image-container" in _classes(el):
img = el.find("img")
if img is None or not img.get("src"):
parent = el.getparent()
if parent is not None:
parent.remove(el)
removed = True
if not removed:
break
for _ in range(60):
moved = False
for el in list(body.iter()):
if not isinstance(el.tag, str):
continue
if el.tag not in BLOCK_CHILD_TAGS:
continue
parent = el.getparent()
if parent is None or parent is body:
continue
if not isinstance(parent.tag, str) \
or parent.tag not in HOIST_OUT_OF:
continue
target = parent
target.addnext(el)
moved = True
if not moved:
break
for el in list(body.iter()):
if isinstance(el.tag, str) \
and el.tag in ("h1", "h2", "h3", "h4", "h5", "h6") \
and not "".join(el.itertext()).strip():
parent = el.getparent()
if parent is not None:
parent.remove(el)
parts = []
for child in list(body):
parts.append(_lxml_html.tostring(
child, encoding="unicode", method="html"))
out = "".join(parts).strip()
if out in ("", "<p></p>", "<p><br></p>", "<p><br/></p>"):
return ""
return out
def create_app():
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = MYSQL_CONFIG
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["SECRET_KEY"] = SECRET_KEY
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=COOKIE_DAYS)
app.config["SESSION_PERMANENT"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["MAX_CONTENT_LENGTH"] = 25 * 1024 * 1024
db.init_app(app)
csrf.init_app(app)
from models import Blog, User
with app.app_context():
db.create_all()
@app.context_processor
def inject_user():
user = None
if session.get("user_id"):
user = User.query.get(session["user_id"])
if user is None:
session.pop("user_id", None)
return {"current_user": user}
@app.template_filter("fa")
def fa_digits(value):
return str(value).translate(str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹"))
@app.after_request
def no_cache(response):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
response.headers["Surrogate-Control"] = "no-store"
return response
COVER_DIR = os.path.join(app.static_folder, "covers")
os.makedirs(COVER_DIR, exist_ok=True)
IMAGES_DIR = os.path.join(app.static_folder, "uploads")
os.makedirs(IMAGES_DIR, exist_ok=True)
def crop_16_9(img):
w, h = img.size
target = 16 / 9
if w / h > target:
new_w = int(h * target)
x = (w - new_w) // 2
img = img.crop((x, 0, x + new_w, h))
else:
new_h = int(w / target)
y = (h - new_h) // 2
img = img.crop((0, y, w, y + new_h))
return img.resize((1280, 720), Image.LANCZOS)
def save_cover_file(cover):
try:
img = Image.open(cover.stream)
img = ImageOps.exif_transpose(img)
img = crop_16_9(img.convert("RGB"))
name = f"{uuid.uuid4().hex}.jpg"
img.save(os.path.join(COVER_DIR, name), "JPEG", quality=85, optimize=True)
return name
except Exception:
return None
def remove_cover_file(filename):
if filename:
path = os.path.join(COVER_DIR, os.path.basename(filename))
if os.path.exists(path):
os.remove(path)
MIME_EXT = {
"image/webp": ".webp", "image/jpeg": ".jpg", "image/png": ".png",
"image/gif": ".gif", "image/svg+xml": ".svg",
}
def save_image_file(file):
if not file or not file.filename:
return None
ext = MIME_EXT.get(file.content_type)
if not ext:
return None
try:
name = uuid.uuid4().hex + ext
file.save(os.path.join(IMAGES_DIR, name))
return name
except Exception:
return None
def remove_image_file(filename):
if filename:
path = os.path.join(IMAGES_DIR, os.path.basename(filename))
if os.path.exists(path):
os.remove(path)
@app.route("/upload_image", methods=["POST", "DELETE"])
def upload_image():
if not session.get("user_id"):
abort(404)
if request.method == "DELETE":
payload = request.get_json(silent=True) or {}
name = payload.get("id")
if not name:
return jsonify(ok=False), 400
remove_image_file(name)
return jsonify(ok=True)
img = request.files.get("file")
name = save_image_file(img)
if not name:
return jsonify(ok=False, error="تصورت قبول نشد"), 400
return jsonify(ok=True,
imageUrl=url_for("image", name=name, _external=True),
imageId=name)
@app.route("/images/<path:name>")
def image(name):
return send_from_directory(IMAGES_DIR, os.path.basename(name))
@app.route("/")
def home():
q = request.args.get("q", "").strip()
if q:
like = f"%{q}%"
blogs = Blog.query.filter(Blog.is_public == True) \
.filter(or_(Blog.title.like(like), Blog.body.like(like))) \
.order_by(Blog.created_at.desc()).all()
return render_template("home.html", blogs=blogs, q=q)
blogs = Blog.query.filter_by(is_public=True) \
.order_by(Blog.created_at.desc()).all()
return render_template("home.html", blogs=blogs)
@app.route("/covers/<path:name>")
def cover(name):
return send_from_directory(COVER_DIR, os.path.basename(name))
@app.route("/register", methods=["GET", "POST"])
def register():
if session.get("user_id"):
return redirect(url_for("home"))
if request.method == "POST":
username = request.form.get("username", "").strip()
name = request.form.get("name", "").strip()
last_name = request.form.get("last_name", "").strip()
password = request.form.get("password", "")
confirm = request.form.get("confirm", "")
if not re.fullmatch(r"[\w\-]{3,30}", username):
flash("نام کاربری باید ۳ تا ۳۰ کاراکتر (حروف، اعداد، - و _) باشد.", "error")
return redirect(url_for("register"))
if len(name) < 2:
flash("نام را وارد کنید (حداقل ۲ کاراکتر).", "error")
return redirect(url_for("register"))
if len(password) < 6:
flash("رمز عبور باید حداقل ۶ کاراکتر باشد.", "error")
return redirect(url_for("register"))
if password != confirm:
flash("تکرار رمز عبور با رمز عبور یکسان نیست.", "error")
return redirect(url_for("register"))
if User.query.filter_by(username=username).first():
flash("این نام کاربری قبلاً ثبت شده است.", "error")
return redirect(url_for("register"))
salt = secrets.token_hex(16)
pw_hash = hashlib.sha512((salt + password).encode()).hexdigest()
user = User(username=username, name=name[:50],
last_name=last_name[:50] or None,
salt=salt, password_hash=pw_hash)
db.session.add(user)
db.session.commit()
session["user_id"] = user.id
session.permanent = True
flash("حساب کاربری شما ساخته شد. خوش آمدید!", "success")
return redirect(url_for("home"))
return render_template("register.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if session.get("user_id"):
return redirect(url_for("home"))
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
user = User.query.filter_by(username=username).first()
if user is None:
flash("نام کاربری یا رمز عبور اشتباه است.", "error")
return redirect(url_for("login"))
candidate = hashlib.sha512(
(user.salt + password).encode()).hexdigest()
if not secrets.compare_digest(candidate, user.password_hash):
flash("نام کاربری یا رمز عبور اشتباه است.", "error")
return redirect(url_for("login"))
session["user_id"] = user.id
session.permanent = True
flash("خوش آمدید!", "success")
return redirect(url_for("home"))
return render_template("login.html")
@app.route("/logout")
def logout():
session.clear()
flash("از حساب خارج شدید.", "success")
return redirect(url_for("home"))
@app.route("/write", methods=["GET", "POST"])
def write():
if not session.get("user_id"):
flash("برای نوشتن باید وارد شوید.", "error")
return redirect(url_for("login"))
user = User.query.get(session["user_id"])
if request.method == "POST":
title = request.form.get("title", "").strip()
body = request.form.get("body", "").strip()
is_public = request.form.get("visibility") == "public"
cover_file = request.files.get("cover")
if not title:
flash("عنوان بلاگ را وارد کنید.", "error")
return redirect(url_for("write"))
title = title[:200]
if not body:
flash("متن بلاگ را بنویسید.", "error")
return redirect(url_for("write"))
body = sanitize_html(body)
if not body:
flash("متن بلاگ را بنویسید.", "error")
return redirect(url_for("write"))
token = secrets.token_urlsafe(24)
blog = Blog(title=title, body=body, token=token,
is_public=is_public, user_id=user.id)
if cover_file and cover_file.filename:
blog.cover = save_cover_file(cover_file)
db.session.add(blog)
db.session.commit()
blog.url = url_for("view_blog", token=token, _external=True)
flash("بلاگ شما منتشر شد. لینکش را با دوستتان به اشتراک بگذارید:", "success")
return render_template("write.html", blog=blog)
return render_template("write.html", blog=None)
@app.route("/edit/<int:blog_id>", methods=["GET", "POST"])
def edit_blog(blog_id):
if not session.get("user_id"):
flash("برای ویرایش باید وارد شوید.", "error")
return redirect(url_for("login"))
blog = Blog.query.get(blog_id)
if blog is None or blog.user_id != session["user_id"]:
abort(404)
if request.method == "POST":
title = request.form.get("title", "").strip()
body = request.form.get("body", "").strip()
is_public = request.form.get("visibility") == "public"
cover_file = request.files.get("cover")
remove_cover = request.form.get("remove_cover") == "1"
if not title:
flash("عنوان بلاگ را وارد کنید.", "error")
return redirect(url_for("edit_blog", blog_id=blog.id))
title = title[:200]
if not body:
flash("متن بلاگ را بنویسید.", "error")
return redirect(url_for("edit_blog", blog_id=blog.id))
body = sanitize_html(body)
if not body:
flash("متن بلاگ را بنویسید.", "error")
return redirect(url_for("edit_blog", blog_id=blog.id))
blog.title = title
blog.body = body
blog.is_public = is_public
if cover_file and cover_file.filename:
new_cover = save_cover_file(cover_file)
if new_cover:
remove_cover_file(blog.cover)
blog.cover = new_cover
elif remove_cover:
remove_cover_file(blog.cover)
blog.cover = None
db.session.commit()
flash("بلاگ به روز شد.", "success")
return redirect(url_for("profile"))
return render_template("write.html", blog=blog)
@app.route("/post/<token>")
def view_blog(token):
blog = Blog.query.filter_by(token=token).first()
if blog is None:
abort(404)
author = User.query.get(blog.user_id)
is_owner = session.get("user_id") == blog.user_id
if not blog.is_public and not is_owner:
flash("این بلاگ خصوصی است و فقط نویسندهاش میتواند آن را ببیند.", "error")
return redirect(url_for("home"))
return render_template("blog.html", blog=blog, author=author,
is_owner=is_owner)
@app.route("/settings", methods=["GET", "POST"])
def settings():
if not session.get("user_id"):
flash("برای تغییرات باید وارد شوید.", "error")
return redirect(url_for("login"))
user = User.query.get(session["user_id"])
if request.method == "POST":
which = request.form.get("which")
if which == "profile":
username = request.form.get("username", "").strip()
name = request.form.get("name", "").strip()
last_name = request.form.get("last_name", "").strip()
if not re.fullmatch(r"[\w\-]{3,30}", username):
flash("نام کاربری باید ۳ تا ۳۰ کاراکتر (حروف، اعداد، - و _) باشد.", "error")
return redirect(url_for("settings"))
if len(name) > 50 or len(last_name) > 50:
flash("اسم یا فامیل بیش از ۵۰ کاراکتر است.", "error")
return redirect(url_for("settings"))
if username != user.username:
if User.query.filter_by(username=username).first():
flash("این نام کاربری قبلاً ثبت شده است.", "error")
return redirect(url_for("settings"))
user.username = username
user.name = name or None
user.last_name = last_name or None
db.session.commit()
flash("پروفایل ذخیره شد.", "success")
elif which == "password":
current = request.form.get("current", "")
new_password = request.form.get("new", "")
confirm = request.form.get("confirm", "")
candidate = hashlib.sha512(
(user.salt + current).encode()).hexdigest()
if not secrets.compare_digest(candidate, user.password_hash):
flash("رمز عبور فعلی اشتباه است.", "error")
return redirect(url_for("settings"))
if len(new_password) < 6:
flash("رمز عبور جدید باید حداقل ۶ کاراکتر باشد.", "error")
return redirect(url_for("settings"))
if new_password != confirm:
flash("تکرار رمز عبور با رمز عبور یکسان نیست.", "error")
return redirect(url_for("settings"))
user.salt = secrets.token_hex(16)
user.password_hash = hashlib.sha512(
(user.salt + new_password).encode()).hexdigest()
db.session.commit()
flash("رمز عبور تغییر کرد.", "success")
else:
return redirect(url_for("settings"))
return redirect(url_for("settings"))
return render_template("settings.html", user=user)
@app.route("/profile")
def profile():
if not session.get("user_id"):
flash("برای دیدن پروفایل باید وارد شوید.", "error")
return redirect(url_for("login"))
user = User.query.get(session["user_id"])
blogs = Blog.query.filter_by(user_id=user.id)\
.order_by(Blog.created_at.desc()).all()
return render_template("profile.html", user=user, blogs=blogs)
@app.route("/delete/<int:blog_id>", methods=["POST"])
def delete_blog(blog_id):
if not session.get("user_id"):
abort(404)
blog = Blog.query.get(blog_id)
if blog is None or blog.user_id != session["user_id"]:
abort(404)
remove_cover_file(blog.cover)
db.session.delete(blog)
db.session.commit()
flash("بلاگ حذف شد.", "success")
return redirect(url_for("profile"))
@app.route("/toggle/<int:blog_id>", methods=["POST"])
def toggle_blog(blog_id):
if not session.get("user_id"):
abort(404)
blog = Blog.query.get(blog_id)
if blog is None or blog.user_id != session["user_id"]:
abort(404)
blog.is_public = not blog.is_public
db.session.commit()
flash("وضعیت عمومی/خصوصی بلاگ تغییر کرد.", "success")
return redirect(url_for("profile"))
@app.route("/admin", methods=["GET", "POST"])
def admin():
if not session.get("admin"):
if request.method == "POST":
if (request.form.get("admin_username") == ADMIN_USERNAME
and request.form.get("admin_password") == ADMIN_PASSWORD):
session["admin"] = True
session.permanent = True
flash("به پنل ادمین خوش آمدید.", "success")
return redirect(url_for("admin"))
else:
flash("نام کاربری یا رمز ادمین اشتباه است.", "error")
return redirect(url_for("admin"))
return render_template("admin.html")
users = User.query.all()
blogs = Blog.query.order_by(Blog.created_at.desc()).all()
return render_template("admin.html", users=users, blogs=blogs)
@app.route("/admin/logout")
def admin_logout():
session.pop("admin", None)
flash("از پنل ادمین خارج شدید.", "success")
return redirect(url_for("admin"))
@app.route("/admin/delete-user/<int:user_id>", methods=["POST"])
def admin_delete_user(user_id):
if not session.get("admin"):
abort(404)
user = User.query.get(user_id)
if user is None:
abort(404)
for b in user.blogs.all():
remove_cover_file(b.cover)
db.session.delete(user)
db.session.commit()
flash("کاربر و بلاگهایش حذف شد.", "success")
return redirect(url_for("admin"))
@app.route("/admin/delete-blog/<int:blog_id>", methods=["POST"])
def admin_delete_blog(blog_id):
if not session.get("admin"):
abort(404)
blog = Blog.query.get(blog_id)
if blog is None:
abort(404)
remove_cover_file(blog.cover)
db.session.delete(blog)
db.session.commit()
flash("بلاگ حذف شد.", "success")
return redirect(url_for("admin"))
@app.route("/admin/toggle-blog/<int:blog_id>", methods=["POST"])
def admin_toggle_blog(blog_id):
if not session.get("admin"):
abort(404)
blog = Blog.query.get(blog_id)
if blog is None:
abort(404)
blog.is_public = not blog.is_public
db.session.commit()
flash("وضعیت عمومی/خصوصی بلاگ تغییر کرد.", "success")
return redirect(url_for("admin"))
@app.errorhandler(404)
def not_found(e):
return render_template("404.html"), 404
return app
app = create_app()