forked from cc-d/ieddit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ieddit.py
1955 lines (1567 loc) · 62.7 KB
/
ieddit.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
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, redirect, flash, url_for, Blueprint, g
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, exists
from werkzeug.security import generate_password_hash, check_password_hash
from flask_caching import Cache
from flask_session import Session
from flask_session_captcha import FlaskSessionCaptcha
from datetime import timedelta, datetime
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address, get_ipaddr
import time
import re
import config
import base64
#from subprocess import call
import os
import _thread
import urllib.parse
from functools import wraps
import requests
from email.mime.text import MIMEText
from models import *
from functions import *
app = Flask(__name__)
app.config.from_object('config')
cache = Cache(app, config={'CACHE_TYPE': config.CACHE_TYPE})
if (config.SENTRY_ENABLED):
import sentry_sdk
from sentry_sdk.integrations.flask import \
FlaskIntegration
sentry_sdk.init(
config.SENTRY_DSN,
integrations=[FlaskIntegration()]
)
db = SQLAlchemy(app)
db.session.rollback()
Session(app)
captcha = FlaskSessionCaptcha(app)
limiter = Limiter(
app,
key_func=get_ipaddr,
default_limits=config.LIMITER_DEFAULTS
)
cache.clear()
cache_bust = '?' + str(time.time()).split('.')[0]
@app.before_request
def before_request():
g.cache_bust = cache_bust
if app.debug:
g.start = time.time()
session.permanent = True
try:
request.sub
except:
request.sub = False
if 'blocked_subs' not in session:
if 'username' in session:
session['blocked_subs'] = get_blocked_subs(session['username'])
else:
session['blocked_subs'] = []
request.is_mod = False
uri = request.environ['REQUEST_URI']
if len(uri) > 2:
if uri[:3] == '/i/':
getsub = re.findall('\/i\/([a-zA-Z1-9-_]*)', request.environ['REQUEST_URI'])
if len(getsub) > 0:
if getsub[0] != 'all':
getsub[0] = normalize_sub(getsub[0])
oldsub = request.sub
request.sub = getsub[0]
if 'username' in session:
if session['username'] in get_sub_mods(request.sub):
request.is_mod = True
if oldsub != request.sub:
request.subtitle = get_subtitle(request.sub)
if 'username' in session:
has_messages(session['username'])
if 'blocked' not in session:
session['blocked'] = {'comment_id':[], 'post_id':[], 'other_user':[]}
# disabled due to lack of use
#if 'set_darkmode_initial' not in session:
# session['darkmode'] = True
# if 'username' in session:
# u = db.session.query(Iuser).filter_by(username=session['username'])
# u.darkmode = True
# db.session.commit()
# session['set_darkmode_initial'] = True
@app.after_request
def apply_headers(response):
if response.status_code == 500:
db.session.rollback()
print(str(vars(response)))
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers['X-Content-Type-Options'] = 'nosniff'
if config.CSP:
response.headers['Content-Security-Policy'] = "default-src 'self' *.ieddit.com ieddit.com; img-src *; style-src" +\
" 'self' 'unsafe-inline' *.ieddit.com ieddit.com; script-src 'self' 'unsafe-inline' *.ieddit.com ieddit.com;"
#response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
#response.headers["Pragma"] = "no-cache"
#response.headers["Expires"] = "0"
#response.headers['Cache-Control'] = 'public, max-age=0'
session['last_url'] = request.url
if app.debug:
if hasattr(g, 'start'):
load_time = str(time.time() - g.start)
print('\n[Load: %s]' % load_time)
if request.environ['REQUEST_METHOD'] == 'POST':
cache.clear()
return response
@app.teardown_request
def teardown_request(exception):
if exception:
db.session.rollback()
db.session.remove()
def only_cache_get(*args, **kwargs):
if request.method == 'GET':
return False
return True
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_style(sub=None):
if sub != None:
sub = db.session.query(Sub).filter_by(name=normalize_sub(sub)).first()
return sub.css
return None
app.jinja_env.globals.update(get_style=get_style)
def catch_all_exceptions(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
print('\n\nCaught unkown error in catch_all_exceptions wrapped function %s .\n\n' % f, e)
return decorated_function
def notbanned(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'username' not in session:
return redirect(url_for('login'))
busers = db.session.query(Iuser).filter_by(banned=True).all()
bnames = [a.username for a in busers]
if session['username'] in bnames:
return redirect('/')
return f(*args, **kwargs)
return decorated_function
def send_email(etext=None, subject=None, to=None, from_domain=config.MAIL_FROM):
if config.MAIL_TYPE == 'mailgun':
etext = '<html><head><body>' + etext + '</body></html>'
r = requests.post(config.MG_URL + '/messages',
auth=('api', config.MG_API_KEY),
data={'from': 'no-reply <%s>' % (from_domain),
'to': [to, from_domain], 'subject':subject, 'html':etext})
print('sending email %s %s %s %s' % (MIMEText(etext, 'html'), subject, to, from_domain))
print(r.status_code)
print(r.text)
print('email %s %s %s' % (to, from_domain, subject))
return True
# i hate sending external requests
@app.route('/suggest_title')
@limiter.limit("5/minute")
def suggest_title(url=None):
import requests
from bs4 import BeautifulSoup
import urllib.parse
url = request.args.get('u')
url = urllib.parse.unquote(url)
r = requests.get(url, proxies=config.PROXIES)
if r.status_code == 200:
try:
soup = BeautifulSoup(r.text)
title = soup.find('meta', property='og:title')
if title != None:
title = title.get('content', None)
return title
else:
return soup.title.string
except Exception as e:
return ''
return ''
@app.route('/fonts/<file>')
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def send_font(file=None, methods=['GET']):
if file != None:
if len(re.findall('^.*.*$', file)) != 1:
return str(re.findall('^.*.*$'))
else:
return app.send_static_file(file)
else:
return '403'
@app.route('/sitemap.xml')
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def sitemap():
return app.send_static_file('sitemap.xml')
@app.route('/robots.txt')
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def robotstxt():
return app.send_static_file('robots.txt')
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_subtitle(sub):
try:
title = db.session.query(Sub).filter_by(name=sub).first()
title = title.title
except:
title = None
return title
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def has_messages(username):
if 'username' in session:
messages = db.session.query(Message).filter_by(sent_to=username, read=False).count()
if messages != None:
if messages > 0:
session['has_messages'] = True
session['unread_messages'] = messages
return True
return False
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_sub_mods(sub, admin=True):
mod_subs = db.session.query(Moderator).filter_by(sub=sub).all()
if admin == False:
return [m.username for m in mod_subs]
admins = db.session.query(Iuser).filter_by(admin=True).all()
for a in admins:
mod_subs.append(a)
return [m.username for m in mod_subs]
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_banned_subs(username):
subs = db.session.query(Ban).filter_by(username=username).all()
b = []
for s in subs:
b.append(s.sub)
return b
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def is_mod(obj, username):
if hasattr(obj, 'inurl_title'):
post = obj
if db.session.query(db.session.query(Moderator).filter(Moderator.username.like(username),
Moderator.sub.like(obj.sub)).exists()).scalar():
return True
elif hasattr(obj, 'parent_id'):
if db.session.query(db.session.query(Moderator).filter(Moderator.username.like(session['username']),
Moderator.sub.like(obj.sub)).exists()).scalar():
return True
return False
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def is_admin(username):
if db.session.query(db.session.query(Iuser).filter_by(admin=True, username=username).exists()).scalar():
#if 'admin' in session:
return True
return False
def set_rate_limit():
if 'username' in session:
session['rate_limit'] = int(time.time()) + (config.RATE_LIMIT_TIME)
#cache.clear()
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def normalize_username(username, dbuser=False):
if username == None:
return False
username = db.session.query(Iuser).filter(func.lower(Iuser.username) == func.lower(username)).first()
if username != None:
if dbuser:
return username
return username.username
return False
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def normalize_sub(sub):
subl = db.session.query(Sub).filter(func.lower(Sub.name) == func.lower(sub)).first()
if subl != None:
return subl.name
return sub
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_all_subs(explore=False):
subs = db.session.query(Sub).all()
if explore == False:
return subs
else:
esubs = []
for sub in subs:
if hasattr(sub, 'rules'):
if sub.rules != None:
sub.new_rules = pseudo_markup(sub.rules)
if hasattr(sub, 'rules'):
if sub.rules != None:
sub.new_rules = pseudo_markup(sub.rules)
sub.posts = sub.get_posts(count=True)
if sub.posts == 0:
continue
sub.comments = sub.get_comments(count=True)
sub.score = sub.comments + sub.posts
esubs.append(sub)
esubs.sort(key=lambda x: x.score, reverse=True)
return esubs
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_pgp_from_username(username):
u = normalize_username(username)
if u == False:
return False
else:
pgp = db.session.query(Pgp).filter_by(username=normalize_username(username)).first()
if pgp != None:
return pgp
return False
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_user_from_name(username):
if username == '' or username == False or username == None:
return False
return normalize_username(username, dbuser=True)
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_user_from_id(uid):
if uid == None or uid == False:
return False
return db.session.query(Iuser).filter_by(id=uid).first()
@app.route('/login/', methods=['GET', 'POST'])
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def login():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if config.CAPTCHA_ENABLE:
if request.form.get('captcha') == '':
flash('no captcha', 'danger')
return redirect(url_for('login'))
if captcha.validate() == False:
flash('invalid captcha', 'danger')
return redirect(url_for('login'))
if username == None or password == None:
flash('Username or Password missing.', 'danger')
return redirect(url_for('login'), 302)
if username == '' or password == '' or len(username) > 20 or len(password) > 100:
flash('Username or Password empty.', 'danger')
return redirect(url_for('login'), 302)
if db.session.query(db.session.query(Iuser)
.filter_by(username=username)
.exists()).scalar():
login_user = db.session.query(Iuser).filter_by(username=username).first()
hashed_pw = login_user.password
if check_password_hash(hashed_pw, password):
logout()
[session.pop(key) for key in list(session.keys())]
session['username'] = login_user.username
session['user_id'] = login_user.id
if login_user.admin:
session['admin'] = login_user.admin
session['hide_sub_style'] = login_user.hide_sub_style
if hasattr(login_user, 'anonymous'):
if login_user.anonymous:
session['anonymous'] = True
session['darkmode'] = login_user.darkmode
if get_pgp_from_username(login_user.username):
session['pgp_enabled'] = True
return redirect(url_for('index'), 302)
flash('Username or Password incorrect.', 'danger')
return redirect(url_for('login'), 302)
@app.route('/logout', methods=['POST', 'GET'])
def logout():
[session.pop(key) for key in list(session.keys())]
return redirect(url_for('index'), 302)
@app.route('/register', methods=['POST'])
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def register():
if request.method == 'POST':
if config.CAPTCHA_ENABLE:
if request.form.get('captcha') == '':
flash('no captcha', 'danger')
return redirect(url_for('register'))
if captcha.validate() == False:
flash('invalid captcha', 'danger')
return redirect(url_for('login'))
username = request.form.get('username')
password = request.form.get('password')
email = request.form.get('email')
if 'username' in session:
flash('already logged in', 'danger')
return redirect('/')
if username == None or password == None:
flash('username or password missing', 'danger')
return redirect(url_for('login'))
if verify_username(username):
if db.session.query(db.session.query(Iuser).filter(func.lower(Iuser.username) == func.lower(username)).exists()).scalar():
flash('username exists', 'danger')
return redirect(url_for('login'))
else:
flash('invalid username', 'danger')
return redirect(url_for('login'))
if len(password) > 100 or len(password) < 1:
flash('password length invalid', 'danger')
return redirect(url_for('login'))
if email != None and email != '':
if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
flash('invalid email', 'danger')
return redirect(url_for('login'))
new_user = Iuser(username=username, email=email,
password=generate_password_hash(password))
db.session.add(new_user)
db.session.commit()
logout()
session['username'] = new_user.username
session['user_id'] = new_user.id
set_rate_limit()
#cache.clear()
return redirect(config.URL, 302)
@app.route('/')
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def index():
return subi(subi='all', nsfw=False)
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def is_sub_nsfw(sub):
s = db.session.query(Sub).filter_by(name=sub).first()
if s.nsfw:
return True
return False
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_subi(subi, user_id=None, posts_only=False, deleted=False, offset=0, limit=15, nsfw=True, d=None, s=None):
if offset != None:
offset = int(offset)
if subi != 'all':
subname = db.session.query(Sub).filter(func.lower(Sub.name) == subi.lower()).first()
if subname == None:
return {'error':'sub does not exist'}
subi = subname.name
posts = db.session.query(Post).filter_by(sub=subi, deleted=False)
elif user_id != None:
posts = db.session.query(Post).filter_by(author_id=user_id, deleted=False)
else:
posts = db.session.query(Post).filter_by(deleted=False)
# .order_by((Post.created).desc())
# posts = db.session.query(Post).filter_by(deleted=False).order_by((Post.ups - Post.downs).desc())
if d == 'hour':
ago = datetime.now() - timedelta(hours=1)
elif d == 'day':
ago = datetime.now() - timedelta(hours=24)
elif d == 'week':
ago = datetime.now() - timedelta(days=7)
elif d == 'month':
ago = datetime.now() - timedelta(days=31)
else:
ago = datetime.now() - timedelta(days=9999)
if d:
posts.filter(Post.created > ago)
if s == 'top':
posts = posts.order_by((Post.ups - Post.downs).desc())
posts = posts.all()
elif s == 'new':
posts = posts.order_by((Post.created).desc())
posts = posts.all()
else:
posts = posts.all()
for p in posts:
p.hot = hot(p.ups, p.downs, p.created)
posts.sort(key=lambda x: x.hot, reverse=True)
#posts = [post for post in posts if post.created > ago]
if nsfw == False:
posts = [p for p in posts if p.nsfw == False]
more = False
pc = len(posts)
if pc > limit:
more = True
try:
offset + 1
except:
offset = 0
if 'blocked_subs' in session and 'username' in session:
posts = [c for c in posts if c.sub not in session['blocked_subs']]
posts = posts[offset:offset+limit]
stid = False
for p in posts:
if p.stickied == True:
stid = p.id
if subi != 'all':
if stid:
posts = [post for post in posts if post.id != stid]
if subi != 'all':
sticky = db.session.query(Post).filter(func.lower(Post.sub) == subi.lower(), Post.stickied == True).first()
if sticky:
if 'blocked_subs' in session:
if sticky.sub in session['blocked_subs']:
pass
else:
posts.insert(0, sticky)
else:
posts.insert(0, sticky)
if 'blocked' in session:
posts = [post for post in posts if post.id not in session['blocked']['post_id']]
posts = [post for post in posts if post.author_id not in session['blocked']['other_user']]
if more and len(posts) > 0:
posts[len(posts)-1].more = True
p = []
for post in posts:
if is_sub_nsfw(post.sub):
post.sub_nsfw = True
else:
post.sub_nsfw = False
if hasattr(post, 'text'):
post.new_text = pseudo_markup(post.text)
if thumb_exists(post.id):
post.thumbnail = 'thumbnails/thumb-' + str(post.id) + '.PNG'
if get_youtube_vid_id(post.url):
post.video = 'https://www.youtube.com/embed/%s?version=3&enablejsapi=1' % get_youtube_vid_id(post.url)
post.mods = get_sub_mods(post.sub)
post.created_ago = time_ago(post.created)
if subi != 'all':
post.site_url = config.URL + '/i/' + subi + '/' + str(post.id) + '/' + post.inurl_title
post.remote_url_parsed = post_url_parse(post.url)
post.comment_count = db.session.query(Comment).filter_by(post_id=post.id).count()
if 'user_id' in session and 'username' in session:
v = post.has_voted(session['user_id'])
if v != None:
post.has_voted = v.vote
if db.session.query(db.session.query(Moderator).filter(Moderator.username.like(session['username']), Moderator.sub.like(post.sub)).exists()).scalar():
post.is_mod = True
p.append(post)
return p
@app.route('/i/<subi>/')
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def subi(subi, user_id=None, posts_only=False, offset=0, limit=15, nsfw=True, show_top=True, s=None, d=None):
offset = request.args.get('offset')
d = request.args.get('d')
s = request.args.get('s')
subi = normalize_sub(subi)
if request.environ['QUERY_STRING'] == '':
session['off_url'] = request.url + '?offset=15'
session['prev_off_url'] = request.url
else:
if offset == None:
session['off_url'] = request.url + '&offset=15'
session['prev_off_url'] = request.url
else:
if (int(offset) - 15) > 0:
session['prev_off_url'] = request.url.replace('offset=' + offset, 'offset=' + str(int(offset) -15))
else:
session['prev_off_url'] = re.sub('[&\?]?offset=(\d+)', '', request.url)
session['off_url'] = request.url.replace('offset=' + offset, 'offset=' + str(int(offset) +15))
if request.url.find('offset=') == -1:
session['prev_off_url'] = False
session['top_url'] = re.sub('[&\?]?s=\w+', '', request.url) + '&s=top'
session['new_url'] = re.sub('[&\?]?s=\w+', '', request.url) + '&s=new'
session['hot_url'] = re.sub('[&\?]?s=\w+', '', request.url) + '&s=hot'
session['hour_url'] = re.sub('[&\?]?d=\w+', '', request.url) + '&d=hour'
session['day_url'] = re.sub('[&\?]?d=\w+', '', request.url) + '&d=day'
session['week_url'] = re.sub('[&\?]?d=\w+', '', request.url) + '&d=week'
session['month_url'] = re.sub('[&\?]?d=\w+', '', request.url) + '&d=month'
for a in ['top_url', 'new_url', 'day_url', 'week_url', 'hour_url', 'month_url', 'hot_url']:
if session[a].find('/&') != -1:
session[a] = session[a].replace('/&', '/?')
if 'prev_off_url' in session:
if session['prev_off_url']:
if session['prev_off_url'].find('/&'):
session['prev_off_url'] = session['prev_off_url'].replace('/&', '/?')
sub_posts = get_subi(subi=subi, user_id=user_id, posts_only=posts_only, deleted=False, offset=offset, limit=15, d=d, s=s, nsfw=nsfw)
if type(sub_posts) == dict:
if 'error' in sub_posts.keys():
flash(sub_posts['error'], 'danger')
return redirect('/')
for p in sub_posts:
if hasattr(p, 'self_text'):
if p.self_text != None:
p.new_self_text = pseudo_markup(p.self_text)
if posts_only:
return sub_posts
return render_template('sub.html', posts=sub_posts, url=config.URL, show_top=show_top)
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_cached_children(comment, deleted=False):
return comment.get_children(deleted=deleted)
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def recursive_children(comment=None, current_depth=0, max_depth=8, deleted=False):
found_children = []
found_children.append(comment)
children = comment.get_children(deleted=deleted).all()
while len(children) > 0 and current_depth < max_depth :
print(children)
for c in children:
print(c)
if c not in found_children:
found_children.append(c)
c2 = c.get_children(deleted=deleted).all()
if c2 != None:
[children.append(c3) for c3 in c2]
ex = [x for x in children if x != c]
children = ex
current_depth += 1
return found_children
@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def c_get_comments(sub=None, post_id=None, inurl_title=None, comment_id=False, sort_by=None, comments_only=False, user_id=None, deleted=False):
post = None
parent_comment = None
if not comments_only:
if post_id != None:
post = db.session.query(Post).filter_by(id=post_id).first()
post.mods = get_sub_mods(post.sub)
post.comment_count = db.session.query(Comment).filter_by(post_id=post.id).count()
post.created_ago = time_ago(post.created)
post.remote_url_parsed = post_url_parse(post.url)
if is_sub_nsfw(post.sub):
post.sub_nsfw = True
else:
post.sub_nsfw = False
if hasattr(post, 'text'):
post.new_text = pseudo_markup(post.text)
if thumb_exists(post.id):
post.thumbnail = 'thumbnails/thumb-' + str(post.id) + '.PNG'
elif hasattr(post, 'url'):
post.thumbnail = 'globe.png'
if hasattr(post, 'self_text'):
if post.self_text != None:
post.new_self_text = pseudo_markup(post.self_text)
if get_youtube_vid_id(post.url):
post.video = 'https://www.youtube.com/embed/%s?version=3&enablejsapi=1' % get_youtube_vid_id(post.url)
else:
post = None
if 'user_id' in session:
post.has_voted = db.session.query(Vote).filter_by(post_id=post.id, user_id=session['user_id']).first()
if post.has_voted != None:
post.has_voted = post.has_voted.vote
if comment_id == None:
print(1)
comments = db.session.query(Comment).filter_by(post_id=post_id, deleted=deleted).all()
show_blocked = False
else:
print(2)
comments = []
parent_comment = db.session.query(Comment).filter_by(id=comment_id).first()
show_blocked = False
# if direct link, just show it
if parent_comment.id in session['blocked']['comment_id'] or parent_comment.author_id in session['blocked']['other_user']:
flash('you are viewing a comment you have blocked', 'danger')
show_blocked = True
comments = recursive_children(comment=parent_comment, deleted=True)
else:
print(3)
comments = db.session.query(Comment).filter(Comment.author_id == user_id,
Comment.deleted == deleted).order_by(Comment.created.desc()).all()
show_blocked = False
if 'blocked_subs' in session and 'username' in session:
comments = [c for c in comments if c.sub_name not in session['blocked_subs']]
if 'blocked' in session and show_blocked != True:
comments = [c for c in comments if c.id not in session['blocked']['comment_id']]
comments = [c for c in comments if c.id not in session['blocked']['other_user']]
#print(comments)
for c in comments:
c.score = (c.ups - c.downs)
c.new_text = pseudo_markup(c.text)
c.mods = get_sub_mods(c.sub_name)
c.created_ago = time_ago(c.created)
if 'user_id' in session:
c.has_voted = db.session.query(Vote).filter_by(comment_id=c.id, user_id=session['user_id']).first()
if c.has_voted != None:
c.has_voted = c.has_voted.vote
if Comment.sub_name:
if db.session.query(db.session.query(Moderator).filter(Moderator.username.like(session['username']), Moderator.sub.like(Comment.sub_name)).exists()).scalar():
Comment.is_mod = True
else:
Comment.is_mod = False
return comments, post, parent_comment
@app.route('/i/<sub>/<post_id>/<inurl_title>/<comment_id>/sort-<sort_by>')
@app.route('/i/<sub>/<post_id>/<inurl_title>/<comment_id>/')
@app.route('/i/<sub>/<post_id>/<inurl_title>/sort-<sort_by>')
@app.route('/i/<sub>/<post_id>/<inurl_title>/')
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def get_comments(sub=None, post_id=None, inurl_title=None, comment_id=None, sort_by=None, comments_only=False, user_id=None):
print(comment_id)
try:
if sub == None or post_id == None or inurl_title == None:
if not comments_only:
return 'badlink'
sub = normalize_sub(sub)
if comment_id == None:
is_parent = False
else:
is_parent = True
comments, post, parent_comment = c_get_comments(sub=sub, post_id=post_id, inurl_title=inurl_title, comment_id=comment_id, sort_by=sort_by, comments_only=comments_only, user_id=user_id)
if post != None and 'username' in session:
if db.session.query(db.session.query(Moderator).filter(Moderator.username.like(session['username']), Moderator.sub.like(post.sub)).exists()).scalar():
post.is_mod = True
if comments_only:
return comments
if not comment_id:
tree = create_id_tree(comments)
else:
tree = create_id_tree(comments, parent_id=comment_id)
tree = comment_structure(comments, tree)
last = '%s/i/%s/%s/%s/' % (config.URL, sub, post_id, post.inurl_title)
if comment_id != False and comment_id != None:
last = last + str(comment_id)
session['last_return_url'] = last
return render_template('comments.html', comments=comments, post_id=post_id,
post_url='%s/i/%s/%s/%s/' % (config.URL, sub, post_id, post.inurl_title),
post=post, tree=tree, parent_comment=parent_comment, is_parent=is_parent,
config=config)
except Exception as e:
print(str(e))
return(str(e))
db.session.rollback()
# need to entirely rewrite how comments are handled once everything else is complete
# this sort of recursion KILLS performance, especially when combined with the already
# terrible comment_structure function.
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def list_of_child_comments(comment_id, sort_by=None):
comments = {}
current_comments = []
if sort_by == 'new':
start = db.session.query(Comment).filter(Comment.parent_id == comment_id, Comment.deleted == False)\
.order_by((Comment.created).asc()).all()
else:
start = db.session.query(Comment).filter(Comment.parent_id == comment_id, Comment.deleted == False)\
.order_by((Comment.ups - Comment.downs).desc()).all()
for c in start:
current_comments.append(c.id)
comments[c.id] = c
while len(current_comments) > 0:
for current_c in current_comments:
if sort_by == 'new':
get_comments = db.session.query(Comment).filter(Comment.parent_id == current_c)\
.order_by((Comment.created).asc()).all()
else:
get_comments = db.session.query(Comment).filter(Comment.parent_id == current_c)\
.order_by((Comment.ups - Comment.downs).desc()).all()
for c in get_comments:
current_comments.append(c.id)
comments[c.id] = c
current_comments.remove(current_c)
print(comments)
return comments
@app.route('/create', methods=['POST', 'GET'])
@notbanned
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def create_sub():
if request.method == 'POST':
subname = request.form.get('subname')
if subname.lower() == 'all':
flash('reserved name')
return redirect(url_for('create_sub'))
if config.CAPTCHA_ENABLE:
if request.form.get('captcha') == '':
flash('no captcha', 'danger')
return redirect(url_for('create_sub'))
if captcha.validate() == False:
flash('invalid captcha', 'danger')
return redirect(url_for('create_sub'))
if 'rate_limit' in session and config.RATE_LIMIT == True:
rl = session['rate_limit'] - time.time()
if rl > 0:
flash('rate limited, try again in %s seconds' % str(rl), 'danger')
return redirect('/')
if subname != None and verify_subname(subname) and 'username' in session:
if len(subname) > 30 or len(subname) < 1:
return 'invalid length'
already = db.session.query(Sub).filter(func.lower(Sub.name) == subname.lower()).first()
if already != None:
flash('sub already exists', 'danger')
return redirect('/create')
title = request.form.get('title')
new_sub = Sub(name=subname, created_by=session['username'], created_by_id=session['user_id'], title=title)
db.session.add(new_sub)
db.session.commit()
new_mod = Moderator(username=new_sub.created_by, sub=new_sub.name)
db.session.add(new_mod)
db.session.commit()
set_rate_limit()
flash('You have created a new sub! Mod actions are under the "info" tab.', 'success')
return redirect(config.URL + '/i/' + subname, 302)
if verify_subname(subname) == False:
flash('Invalid sub name. Valid Characters are A-Z 1-9 - _ ')
return(redirect(config.URL + '/create'))
return 'invalid'
elif request.method == 'GET':
if 'username' not in session:
flash('please log in to create subs', 'danger')
return redirect(url_for('login'))
return render_template('create.html')
@app.route('/u/<username>/', methods=['GET'])
#@cache.memoize(config.DEFAULT_CACHE_TIME, unless=only_cache_get)
def view_user(username):
vuser = db.session.query(Iuser).filter(func.lower(Iuser.username) == func.lower(username)).first()
mod_of = db.session.query(Moderator).filter_by(username=vuser.username).all()
mods = {}
for s in mod_of:
mods[s.sub] = s.rank
vuser.mods = mods
posts = vuser.get_recent_posts()#.all()
comments = vuser.get_recent_comments()#.all()
for p in posts:
p.created_ago = time_ago(p.created)
p.comment_count = db.session.query(Comment).filter_by(post_id=p.id).count()
p.mods = get_sub_mods(p.sub)
if 'user_id' in session:
v = p.has_voted(session['user_id'])
if v != None:
p.has_voted = str(v.vote)
if p.self_text != None:
p.new_self_text = pseudo_markup(p.self_text)
p.remote_url_parsed = post_url_parse(p.url)
comments_with_posts = []
for c in comments:
c.mods = get_sub_mods(c.sub_name)
cpost = db.session.query(Post).filter_by(id=c.post_id).first()
comments_with_posts.append((c, cpost))
c.new_text = pseudo_markup(c.text)
c.created_ago = time_ago(c.created)
if 'user_id' in session:
c.has_voted = db.session.query(Vote).filter_by(comment_id=c.id, user_id=session['user_id']).first()
if c.has_voted != None:
c.has_voted = c.has_voted.vote
if Comment.sub_name:
if db.session.query(db.session.query(Moderator).filter(Moderator.username.like(session['username']), Moderator.sub.like(Comment.sub_name)).exists()).scalar():
Comment.is_mod = True
else:
Comment.is_mod = False
return render_template('user.html', vuser=vuser, posts=posts, url=config.URL, comments_with_posts=comments_with_posts, userpage=True)
@limiter.limit('25 per minute')