-
Notifications
You must be signed in to change notification settings - Fork 4
/
kumo.py
1604 lines (1356 loc) · 53.1 KB
/
kumo.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# kumo
# an imageboard for Google App Engine
#
# https://github.com/tslocum/kumo
__author__ = 'Trevor Slocum'
__license__ = 'GNU GPL v3'
MAX_THREADS = 50
THREADS_SHOWN_ON_FRONT_PAGE = 10
REPLIES_SHOWN_ON_FRONT_PAGE = 5
SECONDS_BETWEEN_NEW_THREADS = 30
SECONDS_BETWEEN_REPLIES = 10
MAX_IMAGE_SIZE_BYTES = 1024*1024
MAX_IMAGE_SIZE_DISPLAY = '1 MB'
MAX_DIMENSION_FOR_OP_IMAGE = 200
MAX_DIMENSION_FOR_REPLY_IMAGE = 200 #125
MAX_DIMENSION_FOR_IMAGE_CATALOG = 50
# Number of posts in a thread after which bumping thread disabled. 0 for disabled this option.
BUMP_LIMIT = 500
ANONYMOUS = 'Anonymous'
POST_TRIPCODE_CHARACTER = '!'
import StringIO
import sys
import string
import cgi
#import wsgiref.handlers
import Cookie
import os
import time
import datetime
import re
import zlib
import gettext
import struct
import math
import urllib
import logging
# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = False
import crypt
from crypt import crypt
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.api import images
import webapp2
import jinja2
from google.appengine.ext import db
from google.appengine.ext import search
from time import strftime
from datetime import datetime
from hashlib import md5
from hashlib import sha224
from StringIO import StringIO
from urlparse import urlparse, parse_qs
# Wishful thinking
gettext.bindtextdomain('kumo')
gettext.textdomain('kumo')
_ = gettext.gettext
# Initialize jinja2 environment
jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
def kumo_date(value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
jinja_environment.filters['date'] = kumo_date
def kumo_pluralize(cnt):
if cnt != 1:
return 's'
return ''
jinja_environment.filters['pluralize'] = kumo_pluralize
marking_rules = (
(re.compile('\*\*(?P<bold>.*?)\*\*', re.VERBOSE), r'<b>\g<bold></b>'),
(re.compile('__(?P<underline>.*?)__', re.VERBOSE), r'<span class="underline">\g<underline></span>'),
(re.compile('--(?P<strike>.*?)--', re.VERBOSE), r'<strike>\g<strike></strike>'),
(re.compile('%%(?P<spoiler>.*?)%%', re.VERBOSE), r'<span class="spoiler">\g<spoiler></span>'),
(re.compile('\*(?P<italic>.*?)\*', re.VERBOSE), r'<i>\g<italic></i>'),
(re.compile('_(?P<italic>.*?)_', re.VERBOSE), r'<i>\g<italic></i>'),
(re.compile('`(?P<code>.*?)`', re.VERBOSE), r'<code>\g<code></code>'),
)
# Begin Datastore models
# Page cache
class Page(db.Model):
identifier = db.StringProperty() # Board front pages are stored as 'front' for page 0, and 'front<n>' for each page thereafter. Res pages are stored as the thread OP's datstore key
contents = db.BlobProperty()
# Google account tracking and preferences
class UserPrefs(db.Model):
user = db.UserProperty() # User object
level = db.CategoryProperty(default='Normal') # TODO: Access level
name_override = db.StringProperty(default='')
posts = db.IntegerProperty(default=0) # Number of posts this user has made
posts_sage = db.IntegerProperty(default=0) # Number of sage posts this user has made
class Ban(db.Model):
ip = db.StringProperty()
reason = db.StringProperty()
placed = db.DateTimeProperty()
class Image(db.Model):
data = db.BlobProperty()
thumb_data = db.BlobProperty()
thumb_catalog_data = db.BlobProperty()
attachedpost = db.StringProperty()
class Post(search.SearchableModel):
postid = db.IntegerProperty() # Consecutive ID
parentid = db.IntegerProperty() # Parent of post, <None> if this post has no parent
author = db.UserProperty() # Google account used when making the post
posts = db.IntegerProperty() # Number of posts in a thread (this includes the OP)
image = db.StringProperty() # File attachment to post, stored here as a key to the actual instance, lowering memory when only fetching posts
image_filename = db.StringProperty() # Full filename of the stored file ([timestamp + postid].ext)
image_hex = db.StringProperty() # File hex for quick duplicate checks
image_mime = db.StringProperty() # File MIME
image_extension = db.StringProperty() # File extension (including period)
image_original = db.StringProperty() # Original filename when the file was uploaded
image_size = db.IntegerProperty() # Size of the file in bytes
image_size_formatted = db.StringProperty() # Formatted version of size (KB)
image_width = db.IntegerProperty() # Width of image
image_height = db.IntegerProperty() # Height of image
image_deleted = db.BooleanProperty()
thumb_filename = db.StringProperty() # Full filename of the stored file thumbnail ([timestamp + postid]s.ext)
thumb_width = db.IntegerProperty() # Width of thumbnail
thumb_height = db.IntegerProperty() #height of thumbnail
thumb_catalog_width = db.IntegerProperty() # Width of thumbnail (catalog)
thumb_catalog_height = db.IntegerProperty() #height of thumbnail (catalog)
#embed_video_url = db.StringProperty() # embeded video url
embedded_data = db.StringProperty() # embeded data
ip = db.StringProperty() # IP address used when making the post
nameblock = db.StringProperty() # Preprocessed HTML block containing the name, tripcode, and email of the post
anonymous = db.BooleanProperty() # Flag regarding if the poster's Google account should be displayed in the post, however it can also remove anything entered in the Name field
name = db.StringProperty()
tripcode = db.StringProperty()
email = db.StringProperty()
subject = db.StringProperty()
message = db.TextProperty()
short_message = db.TextProperty()
password = db.StringProperty() # Stored as a hash
date = db.DateTimeProperty(auto_now_add=True) # Datetime of when post was made
date_formatted = db.StringProperty() # Preprocessed formatting of the datetime
bumped = db.DateTimeProperty() # Datetime of when the post was bumped
deleted = db.BooleanProperty()
"""
youtube embed video
<iframe width="300" height="200" class="thumb" src="//www.youtube.com/embed/-PqTx56Vb58" frameborder="0" allowfullscreen=""></iframe>
"""
class Idx(db.Model):
name = db.StringProperty(required=True)
count = db.IntegerProperty(required=True)
class Ban(db.Model):
ip = db.StringProperty()
reason = db.StringProperty()
placed = db.DateTimeProperty()
# End Datastore models
class Thread():
relid = 0
navlinks = ''
posts = ''
replieshidden = 0
op_postid = 0
op_key = None
posts_in_thread = 0
class BaseRequestHandler(webapp2.RequestHandler):
"""Supplies a common template generation function.
When you call generate(), we augment the template variables supplied with
the current user in the 'user' variable and the current webapp request
in the 'request' variable.
"""
def generate(self, template_name, template_values={}, doreturn=False):
account_greeting = ''
loggedin = False
user = users.get_current_user()
if user:
loggedin = True
account_greeting = 'Welcome, ' + user.nickname() + '. '
url = users.create_logout_url(self.request.uri)
url_linktext = _('Log out')
else:
account_greeting = 'You may post anonymously, or '
url = users.create_login_url(self.request.uri)
url_linktext = _('Log in')
values = {
'request': self.request,
'user': users.GetCurrentUser(),
'account_url_pretext': account_greeting,
'account_url': url,
'account_url_linktext': url_linktext,
'loggedin': loggedin,
'administrator': users.is_current_user_admin(),
'administratorview': isAdminView(self),
'title': 'kumo',
'application_name': 'kumo',
'is_page': 'false',
'MAX_FILE_SIZE': MAX_IMAGE_SIZE_BYTES,
'maxsize_display': MAX_IMAGE_SIZE_DISPLAY,
'maxdimensions': MAX_DIMENSION_FOR_OP_IMAGE,
}
values.update(template_values)
directory = os.path.dirname(__file__)
path = os.path.join(directory, os.path.join('templates', template_name))
output = jinja_environment.get_template(template_name).render(values, debug=_DEBUG).encode('utf-8')
if doreturn:
return output
else:
self.response.out.write(output)
"""Simple self.redirect() replacement. Using the command provided in the SDK yields ugly refreshes."""
def redirect_meta(self, destination):
self.response.out.write('<meta http-equiv="refresh" content="0;url=' + destination + '">--> --> -->')
def error(self, error, is_exception=False):
global _DEBUG
if _DEBUG:
import traceback
if is_exception:
traceback.print_exc()
else:
traceback.print_stack()
template_values = {
'error': error,
}
self.generate('error.html', template_values)
class ViewImage(BaseRequestHandler):
def get(self, postkey, dummy_filename):
post = Post.get(postkey)
if post:
displayImage(self, post.image, post.image_mime)
else:
self.response.out.write('Could not find file %s.' % dummy_filename)
class ViewImageThumb(BaseRequestHandler):
def get(self, postkey, dummy_filename):
post = Post.get(postkey)
# and post.image_filename == dummy_filename
if post:
displayImage(self, post.image, post.image_mime, True)
else:
self.response.out.write('Could not find file %s.' % dummy_filename)
class ViewImageThumbCat(BaseRequestHandler):
def get(self, postkey, dummy_filename):
post = Post.get(postkey)
# and post.image_filename == dummy_filename
if post:
displayImage(self, post.image, post.image_mime, False, True)
else:
self.response.out.write('Could not find file %s.' % dummy_filename)
class FinishImage(BaseRequestHandler):
def post(self):
finish_id = self.request.POST['id']
file_data = self.request.POST['file'].file.read()
image = getImage(finish_id)
if image:
if not image.thumb_data:
image.thumb_data = file_data
image.put()
class FinishImageCat(BaseRequestHandler):
def post(self):
finish_id = self.request.POST['id']
file_data = self.request.POST['file'].file.read()
image = getImage(finish_id)
if image:
if not image.thumb_catalog_data:
image.thumb_catalog_data = file_data
image.put()
class MainPage(BaseRequestHandler):
def get(self, pagenum=0):
pagenum = int(pagenum)
if pagenum >= 0 and pagenum <= 9:
try:
fetchpage(self, 'front', pagenum)
except:
return self.error('Error: Application quota exceeded. Please wait a moment and try again.', True)
else:
return self.error('Invalid page number.')
class ResPage(BaseRequestHandler):
def get(self, thread, action=None):
thread = str(postIDToKey(thread))
if not action:
fetchpage(self, thread)
else:
threads = getposts(self, thread, 0, action)
writepage(self, threads, thread)
class Catalog(BaseRequestHandler):
def get(self):
page = Page.all().filter('identifier = ', 'catalog').get()
if not page:
page = Page(identifier='catalog')
threads = Post.all().filter('parentid = ', None).order('-bumped')
posts = []
rows = []
i = 0
for thread in threads:
posts.append(thread)
i += 1
if i == 12:
i = 0
rows.append(posts)
posts = []
# If there are more posts which were not placed in their own row
if posts != []:
# Add them to another row
rows.append(posts)
template_values = {
'rows': rows,
'catalogdimensions': MAX_DIMENSION_FOR_IMAGE_CATALOG,
}
page.contents = self.generate('catalog.html', template_values, True)
page.put()
self.response.out.write(page.contents)
class Panel(BaseRequestHandler):
def get(self):
template_values = {}
if users.get_current_user():
user_prefs = getUserPrefs(self)
template_values = {
'user_prefs': user_prefs,
}
self.generate('panel.html', template_values)
class Search(BaseRequestHandler):
def get(self):
results = None
numresults = None
query = self.request.get('query', '')
if query != '':
results = Post.all().search(query)
if results:
numresults = results.count()
if numresults == 0:
numresults = None
template_values = {
'query': query,
'results': results,
'numresults': numresults,
}
self.generate('search.html', template_values)
class Sitemap(BaseRequestHandler):
def get(self):
urls = []
posts = Post.all().filter('parentid = ', None).order('-bumped')
template_values = {
'now': datetime.now(),
'posts': posts,
}
self.response.headers['Content-Type'] = 'text/xml'
self.generate('sitemap.xml', template_values)
class Board(BaseRequestHandler):
def post(self):
parent_post = None
if not checkNotBanned(self, self.request.remote_addr):
return self.error('You are banned.')
request_parent = self.request.get('parent')
if request_parent:
post_ancestor = Post.get(request_parent)
# Make sure we are replying to a post starting a thread, not a reply
if post_ancestor:
if post_ancestor.parent is not None:
parent_post = post_ancestor
else:
return self.error('Error: That post is a reply.')
else:
return self.error('Error: Unable to locate thread.')
if parent_post:
post = Post(parent=parent_post)
post.parentid = parent_post.postid
post.posts = None
else:
post = Post()
post.parentid = None
post.posts = 1
post.postid = Counter('Post_ID').inc()
if post.postid == 0:
Counter('Post_ID').create(0)
return self.error('Database initialized. Please re-submit your post.', True)
post.name = cgi.escape(self.request.get('name')).strip()
name_match = re.compile(r'(.*)#(.*)').match(post.name)
if name_match:
if name_match.group(2):
post.name = name_match.group(1)
post.tripcode = tripcode(name_match.group(2))
msg = cgi.escape(self.request.get('message'))[0:20*1024]
msg = msg.strip()
paragraphs = msg.split('\n')
if len(msg) > 1.5*1024 or len(paragraphs) > 11:
short_msg = [paragraphs[0]]
c = len(short_msg[0])
for i in range(1,len(paragraphs)):
c += len(paragraphs[i])
if c > 1.5*1024 or len(short_msg) > 11:
break
short_msg.append(paragraphs[i])
if i < len(paragraphs):
post.short_message = clickableURLs(message_marking('<br>\n'.join(short_msg)))
if parent_post:
post.short_message = checkRefLinks(post.short_message, parent_post.postid)
else:
post.short_message = checkRefLinks(post.short_message, post.postid)
post.short_message = checkQuotes(post.short_message)
post.email = cgi.escape(self.request.get('email')).strip()
post.subject = cgi.escape(self.request.get('subject')).strip()
post.message = clickableURLs(message_marking(msg))
post.password = cgi.escape(self.request.get('password')).strip()
# Set cookies for auto-fill
cookie = Cookie.SimpleCookie(self.request.headers.get('Cookie'))
cookie['kumo_name'] = self.request.get('name').encode('utf-8')
if post.email.lower() != 'sage' and post.email.lower() != 'age':
cookie['kumo_email'] = post.email.encode('utf-8')
cookie['kumo_password'] = post.password.encode('utf-8')
self.response.headers['Set-cookie'] = str(cookie)
post.ip = str(self.request.remote_addr)
if self.request.get('anonymous', None) is not None:
post.anonymous = True
else:
post.anonymous = False
post.embedded_data = getVideoEmbed(self.request.get('embeddeddata'))
if post.embedded_data is None:
thefile = self.request.get('file', None)
image_data = None
if thefile is not None:
image_data = db.Blob(str(thefile))
imageinfo = getImageInfo(image_data)
if imageinfo[0] in ('image/gif', 'image/png', 'image/jpeg'):
image_origin = cgi.escape(self.request.params.get('file').filename).strip()
if parent_post:
maxsize = MAX_DIMENSION_FOR_REPLY_IMAGE
else:
maxsize = MAX_DIMENSION_FOR_OP_IMAGE
image = setPostImage(post, image_data, imageinfo, image_origin, maxsize)
if not isinstance(image, Image):
return self.error(image[0], image[1])
"""
if image_data:
if len(image_data) > MAX_IMAGE_SIZE_BYTES:
return self.error('Error: That file is too large.')
image = Image(data=image_data)
try:
image.put()
except:
return self.error('Error: That file is too large.', True)
post.image = str(image.key())
imageinfo = getImageInfo(image_data)
if imageinfo[0] in ('image/gif', 'image/png', 'image/jpeg'):
if imageinfo[1] > 0 and imageinfo[2] > 0:
is_not_duplicate = checkImageNotDuplicate(image_data)
if is_not_duplicate[0]:
post.image_original = cgi.escape(self.request.params.get('file').filename).strip()
post.image_mime = imageinfo[0]
post.image_size = len(image_data)
post.image_size_formatted = str(long(post.image_size / 1024)) + 'KB'
#if post.image_size > MAX_IMAGE_SIZE_BYTES:
# return self.error('Error: That file is too large.')
if post.image_mime == 'image/gif':
post.image_extension = '.gif'
else:
if post.image_mime == 'image/png':
post.image_extension = '.png'
else:
if post.image_mime == 'image/jpeg':
post.image_extension = '.jpg'
post.image_width = imageinfo[1]
post.image_height = imageinfo[2]
if parent_post:
maxsize = MAX_DIMENSION_FOR_REPLY_IMAGE
else:
maxsize = MAX_DIMENSION_FOR_OP_IMAGE
# Calculate the dimensions for the thumbnail for /thumb/
post.thumb_width, post.thumb_height = getThumbDimensions(post.image_width, post.image_height, maxsize)
# Calculate the dimensions for the thumbnail for /cat/
post.thumb_catalog_width, post.thumb_catalog_height = getThumbDimensions(post.image_width, post.image_height, MAX_DIMENSION_FOR_IMAGE_CATALOG)
post.image_hex = sha224(image_data).hexdigest()
else:
return self.error('Error: That image has already been posted <a href="' + threadURL(is_not_duplicate[1]) + '#' + str(is_not_duplicate[2]) + '">here</a>.')
else:
return self.error('Error: Unable to read image dimensions.')
else:
return self.error('Error:Only GIF, JPG, and PNG files are supported.')
post.image_deleted = False
"""
if users.get_current_user():
current_user = users.get_current_user()
user_prefs = getUserPrefs(self)
post.author = current_user
post.name = ''
if not post.image and not post.embedded_data:
if not parent_post:
return self.error('Error: Please upload an image or add video to start a thread.')
if post.message == '':
return self.error('Error: Please input a message, and/or upload an image or add video.')
if not checkNotFlooding(self, (post.parentid is not None)):
return self.error('Error: Flood detected.')
if post.password:
post.password = sha224(post.password).hexdigest()
else:
post.password = ''
post.nameblock = nameBlock(post)
post.deleted = False
if not parent_post:
post.bumped = datetime.now()
post.date_formatted = post.date.strftime("%y/%m/%d(%a)%H:%M:%S")
try:
if parent_post:
post.message = checkRefLinks(post.message, parent_post.postid)
else:
post.message = checkRefLinks(post.message, post.postid)
post.message = checkQuotes(post.message)
#post.message = checkAllowedHTML(post.message)
post.message = post.message.replace("\n", '<br>')
if post.image:
image.thumb_data = images.resize(image_data, post.thumb_width, post.thumb_height)
image.thumb_catalog_data = images.resize(image_data, post.thumb_catalog_width, post.thumb_catalog_height)
#post.image_filename = str(int(time.mktime(post.date.timetuple()))) + str(post.postid)
#post.thumb_filename = post.image_filename + 's' + post.image_extension
post.put()
if post.image:
image.attachedpost = str(post.key())
image.put()
post.put()
except:
if post.image:
image.delete()
return self.error('Error: Unable to store post in datastore.', True)
if users.get_current_user():
user_prefs.posts += 1
if post.email.lower() == 'sage':
user_prefs.posts_sage += 1
user_prefs.put()
if parent_post:
parent_post.posts += 1
if post.email.lower() != 'sage' and (BUMP_LIMIT==0 or parent_post.posts<BUMP_LIMIT):
parent_post.bumped = datetime.now()
parent_post.put()
threadupdated(self, request_parent)
else:
trimThreads(self)
threadupdated(self, None)
if parent_post:
self.redirect_meta(threadURL(parent_post.key()))
#self.redirect('/res/' + str(parent_post.key()) + '/l50')
else:
self.redirect_meta('/')
class Delete(BaseRequestHandler):
def post(self):
password = self.request.get('password', None)
if not checkNotBanned(self, self.request.remote_addr):
return self.error('You are banned.')
if password != '':
delete = self.request.get('delete', None)
if delete:
post = Post.get(delete)
if post:
if post.password == sha224(password).hexdigest():
imageonly = self.request.get('imageonly', None)
if imageonly:
if post.image:
deletePostImage(post)
else:
return self.error('That post does not have an image attached to it.')
else:
deletePost(self, post)
if post.parentid:
threadupdated(self, post.parent().key())
self.redirect_meta(threadURL(post.parent().key()))
elif not imageonly:
self.redirect_meta('/')
else:
threadupdated(self, post.key())
self.redirect_meta(threadURL(post.key()))
else:
return self.error('Error: Incorrect password.')
else:
return self.error('Error: Please check a box next to a post.')
else:
return self.error('Error: Please check a box next to a post.')
else:
return self.error('Error: Please enter a password.')
class AdminPage(BaseRequestHandler):
def get(self,arg1=None,arg2=None,arg3=None):
page_text = ''
if not users.is_current_user_admin():
return self.error('You are not authorized to view this page.')
if arg1:
if arg1 == 'delete':
post = Post.get(arg2)
if post:
deletePost(self, post)
page_text += 'Post removed'
else:
page_text += 'Error: Post not found'
elif arg1 == 'delete_image':
post = Post.get(arg2)
if post and post.image:
deletePostImage(post)
#threadURL(post.key())
if post.parentid:
self.redirect_meta('/res/' + str(post.parentid) + '.html?admin=view#' + str(post.postid))
threadupdated(self, postIDToKey(post.parentid))
else:
self.redirect_meta('/res/' + str(post.postid) + '.html?admin=view')
threadupdated(self, post.key())
return
elif arg1 == 'edit':
post = Post.get(arg2)
if post:
logging.info(post.message)
em_data = post.embedded_data if post.embedded_data else ''
tmplt = {
'administratorview': True,
'editing_post': True,
'editing_post_id': post.postid,
'editing_name': post.nameblock,
'editing_email': post.email,
'editing_subject': post.subject,
'editing_message': post.message,
'editing_post_has_image': post.image!=None,
'editing_embedded_data': em_data,
'form_action': '/admin/update',
'replythread': str(post.key()),
}
thread = str(postIDToKey(post.parentid)) if post.parentid else str(post.key())
threads = getposts(self, thread, 0)
writepage(self, threads, thread, ex_template_values=tmplt)
return
elif arg1 == 'ban':
post = Post.get(arg2)
if post:
if checkNotBanned(self, post.ip):
ban = Ban()
ban.ip = post.ip
ban.placed = datetime.now()
ban.put()
page_text += 'Ban placed.'
else:
page_text += 'That user is already banned.'
else:
page_text += 'Error: Post not found'
elif arg1 == 'clearcache':
pages = Page.all()
i = 0
for page in pages:
page.delete()
i += 1
page_text += 'Page cache cleared: ' + str(i) + ' pages deleted'
template_values = {
'title': 'kumo management panel',
'page_text': page_text,
'administrator': users.is_current_user_admin(),
}
self.generate('panel_admin.html', template_values)
def post(self,arg1=None,arg2=None,arg3=None):
if not users.is_current_user_admin():
return self.error('You are not authorized to view this page.')
if arg1:
if arg1 == 'update':
editing_post = None
request_parent = self.request.get('parent')
if request_parent:
post_ancestor = Post.get(request_parent)
if post_ancestor:
editing_post = post_ancestor
else:
return self.error('Error: Unable to locate post.')
else:
return self.error('Error: Parent don\'t setted.')
editing_post.nameblock = self.request.get('name').strip()
editing_post.email = self.request.get('email').strip()
editing_post.subject = self.request.get('subject').strip()
editing_post.message = self.request.get('message')
em_data_del_flag = self.request.get('delembeddeddata', None) is not None
if not em_data_del_flag:
em_data = self.request.get('embeddeddata')
if em_data is not None and len(em_data):
editing_post.embedded_data = em_data
else:
editing_post.embedded_data = None
if editing_post.embedded_data is None:
image_del_flag = self.request.get('deleteimage', None) is not None
if not image_del_flag:
thefile = self.request.get('file', None)
image_data = None
image = None
if thefile is not None:
image_data = db.Blob(str(thefile))
imageinfo = getImageInfo(image_data)
if imageinfo[0] in ('image/gif', 'image/png', 'image/jpeg'):
image_origin = cgi.escape(self.request.params.get('file').filename).strip()
if editing_post.parentid:
maxsize = MAX_DIMENSION_FOR_REPLY_IMAGE
else:
maxsize = MAX_DIMENSION_FOR_OP_IMAGE
image = setPostImage(editing_post, image_data, imageinfo, image_origin, maxsize)
if not isinstance(image, Image):
return self.error(image[0], image[1])
elif image is None:
editing_post.image_deleted = False
deletePostImage(editing_post, set_deleted_flag=False, store_post=False)
editing_post.put()
if editing_post.parentid:
threadupdated(self, postIDToKey(editing_post.parentid))
self.redirect_meta('/res/' + str(editing_post.parentid) + '.html?admin=view#' + str(editing_post.postid))
else:
threadupdated(self, editing_post.key())
self.redirect_meta('/res/' + str(editing_post.postid) + '.html?admin=view')
##### ------------------------------------------
def deletePostImage(post, set_deleted_flag=True, store_post=True):
if post and post.image:
image = Image.get(post.image)
if image:
image.delete()
post.image = None
post.image_filename = None
post.image_hex = None
post.image_mime = None
post.image_extension = None
post.image_original = None
post.image_size = None
post.image_size_formatted = None
post.image_width = None
post.image_height = None
post.thumb_filename = None
post.thumb_width = None
post.thumb_height = None
post.thumb_catalog_width = None
post.thumb_catalog_height = None
post.image_deleted = set_deleted_flag
if store_post:
post.put()
def setPostImage(post, image_data, imageinfo, image_origin, maxsize):
"""
image_data = None
if thefile is not None:
image_data = db.Blob(str(thefile))
"""
if image_data:
if len(image_data) > MAX_IMAGE_SIZE_BYTES:
return ('Error: That file is too large.', False)
image = Image(data=image_data)
try:
image.put()
except:
return ('Error: That file is too large.', True)
post.image = str(image.key())
#imageinfo = getImageInfo(image_data)
if imageinfo[0] in ('image/gif', 'image/png', 'image/jpeg'):
if imageinfo[1] > 0 and imageinfo[2] > 0:
is_not_duplicate = checkImageNotDuplicate(image_data)
if is_not_duplicate[0]:
post.image_original = image_origin
post.image_mime = imageinfo[0]
post.image_size = len(image_data)
post.image_size_formatted = str(long(post.image_size / 1024)) + 'KB'
if post.image_mime == 'image/gif':
post.image_extension = '.gif'
else:
if post.image_mime == 'image/png':
post.image_extension = '.png'
else:
if post.image_mime == 'image/jpeg':
post.image_extension = '.jpg'
post.image_width = imageinfo[1]
post.image_height = imageinfo[2]
# Calculate the dimensions for the thumbnail for /thumb/
post.thumb_width, post.thumb_height = getThumbDimensions(post.image_width, post.image_height, maxsize)
# Calculate the dimensions for the thumbnail for /cat/
post.thumb_catalog_width, post.thumb_catalog_height = getThumbDimensions(post.image_width, post.image_height, MAX_DIMENSION_FOR_IMAGE_CATALOG)
post.image_hex = sha224(image_data).hexdigest()
post.image_filename = str(int(time.mktime(post.date.timetuple()))) + str(post.postid)
post.thumb_filename = post.image_filename + 's' + post.image_extension
else:
return ('Error: That image has already been posted <a href="' + threadURL(is_not_duplicate[1]) + '#' + str(is_not_duplicate[2]) + '">here</a>.', False)
else:
return ('Error: Unable to read image dimensions.', False)
else:
return ('Error:Only GIF, JPG, and PNG files are supported.', False)
post.image_deleted = False
return image
def getVideoEmbed(value):
"""
Examples:
- http://youtu.be/SA2iWivDJiE
- http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu
- http://www.youtube.com/embed/SA2iWivDJiE
- http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US
"""
rv = None
query = urlparse(value)
if query.hostname == 'youtu.be':
rv = query.path[1:]
elif query.hostname in ('www.youtube.com', 'youtube.com'):
if query.path == '/watch':
p = parse_qs(query.query)
rv = p['v'][0]
elif query.path[:7] == '/embed/':
rv = query.path.split('/')[2]
elif query.path[:3] == '/v/':
rv = query.path.split('/')[2]
if rv is not None:
#rv = '//www.youtube.com/embed/'+rv
rv = '<iframe width="300" height="200" class="thumb" src="//www.youtube.com/embed/%s" frameborder="0" allowfullscreen=""></iframe>'%rv
else:
if query.hostname == 'vimeo.com':
rv = query.path[1:]
if rv is not None:
rv = '<iframe src="//player.vimeo.com/video/%s" class="thumb" width="300" height="169" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'%rv
return rv
def getUserPrefs(self):
current_user = users.get_current_user()
user_prefs = UserPrefs().all().filter('user = ', current_user)
user_prefs = user_prefs.get()
if not user_prefs:
user_prefs = UserPrefs(user=current_user)
return user_prefs
def getposts(self, thread_op=None,startat=0,special=None):
global total_threads
threads = []
posts = []
add_filter = '' if isAdminView(self) else ' AND deleted = False'
if thread_op:
thread_entity = Post.get(thread_op)
if not thread_entity:
raise
thread = Post.all().ancestor(thread_entity).order('date')
if not isAdminView(self):
thread = thread.filter('deleted = ', False)
firstid = 1
offset = 0
if special and special != '':
if special == 'l50':
replies_total = db.GqlQuery("SELECT * FROM Post WHERE ANCESTOR IS :1" + add_filter, thread_entity)
numposts = replies_total.count()
offset = max(0, (numposts - 50))
thread = thread.fetch(50, offset)
firstid = (offset + 1)
else:
if special == '-100':
thread = thread.fetch(100)
#else:
# raise Exception, 'Invalid operation supplied through URL.'
if offset > 0:
thread_entity.relid = 1
posts.append(thread_entity)
# Iterate through the posts and give them their relative IDs
i = firstid
for post in thread:
post.relid = i
posts.append(post)
i += 1
fullthread = Thread()
fullthread.posts = posts
fullthread.op_postid = thread_entity.postid
fullthread.op_key = thread_entity.key()
threads.append(fullthread)
else:
total_threads = Post.all().filter('parentid = ', None)
total_threads = total_threads.count()
op_posts = Post.all().filter('parentid = ', None).order('-bumped')
op_posts = op_posts.fetch(THREADS_SHOWN_ON_FRONT_PAGE, startat)