This repository has been archived by the owner on May 27, 2022. It is now read-only.
forked from e1ven/Robohash
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webfront.py
executable file
·439 lines (378 loc) · 16.7 KB
/
webfront.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
#!/usr/bin/env python
#
# Copyright 2011 Pluric
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.escape
import socket
import re
import os
import md5
import pprint
import Image
import hashlib
import urllib
import random
import urllib2
from tornado.options import define, options
try:
from hashlib import md5 as md5_func
except ImportError:
from md5 import new as md5_func
import cStringIO
define("port", default=80, help="run on the given port", type=int)
class Robohash(object):
def __init__(self,string):
hash = hashlib.sha512()
hash.update(string)
self.hexdigest = hash.hexdigest()
self.hasharray = []
#Start this at 3, so earlier is reserved
#0 = Color
#1 = Set
#2 = bgset
#3 = BG
self.iter = 4
def createHashes(self,count):
#Create and store a series of hash-values
#Basically, split up a hash (SHA/md5/etc) into X parts
for i in range(0,count):
#Get 1/numblocks of the hash
blocksize = (len(self.hexdigest) / count)
currentstart = (1 + i) * blocksize - blocksize
currentend = (1 +i) * blocksize
self.hasharray.append(int(self.hexdigest[currentstart:currentend],16))
def dirCount(self,path):
#return the count of just the directories beneath me.
return sum([len(dirs) for (root, dirs, files) in os.walk(path)])
def getHashList(self,path):
#Each iteration, if we hit a directory, recurse
#If not, choose the appropriate file, given the hashes, stored above
completelist = []
locallist = []
listdir = os.listdir(path)
listdir.sort()
for ls in listdir:
if not ls.startswith("."):
if os.path.isdir(path + "/" + ls):
subfiles = self.getHashList(path + "/" + ls)
if subfiles is not None:
completelist = completelist + subfiles
else:
locallist.append( path + "/" + ls)
if len(locallist) > 0:
elementchoice = self.hasharray[self.iter] % len(locallist)
luckyelement = locallist[elementchoice]
locallist = []
locallist.append(luckyelement)
self.iter += 1
completelist = completelist + locallist
return completelist
class MainHandler(tornado.web.RequestHandler):
def get(self):
ip = self.request.remote_ip
robo = [
"""
, ,
(\\____/)
(_oo_)
(O)
__||__ \\)
[]/______\\[] /
/ \\______/ \\/
/ /__\\
(\\ /____\\ """,
"""
_______
_/ \\_
/ | | \\
/ |__ __| \\
|__/((o| |o))\\__|
| | | |
|\\ |_| /|
| \\ / |
\\| / ___ \\ |/
\\ | / _ \\ | /
\\_________/
_|_____|_
____|_________|____
/ \\ -- Mark Moir
""",
""" .andAHHAbnn.
.aAHHHAAUUAAHHHAn.
dHP^~" "~^THb.
. .AHF YHA. .
| .AHHb. .dHHA. |
| HHAUAAHAbn adAHAAUAHA |
I HF~"_____ ____ ]HHH I
HHI HAPK""~^YUHb dAHHHHHHHHHH IHH
HHI HHHD> .andHH HHUUP^~YHHHH IHH
YUI ]HHP "~Y P~" THH[ IUP
" `HK ]HH' "
THAn. .d.aAAn.b. .dHHP
]HHHHAAUP" ~~ "YUAAHHHH[
`HHP^~" .annn. "~^YHH'
YHb ~" "" "~ dHF
"YAb..abdHHbndbndAP"
THHAAb. .adAHHF
"UHHHHHHHHHHU"
]HHUUHHHHHH[
.adHHb "HHHHHbn.
..andAAHHHHHHb.AHHHHHHHAAbnn..
.ndAAHHHHHHUUHHHHHHHHHHUP^~"~^YUHHHAAbn.
"~^YUHHP" "~^YUHHUP" "^YUP^"
"" "~~"
""",
""" /~@@~\\,
_______ . _\\_\\___/\\ __ /\\___|_|_ . _______
/ ____ |=| \\ <_+> / |=| ____ \\
~| |\\|=|======\\\\______//======|=|/| |~
|_ | \\ | | / | |
\\==-| \\ | 2D | / |----|~~)
| | | | | | |____/~/
| | \\____\\____/____/ / / /
| | {----------} /____/ /
|___| /~~~~~~~~~~~~\\ |_/~|_|/
\\_/ [/~~~~~||~~~~~\\] /__|\\
| | | |||| | (/|[[\\)
[_] | | | |
|_____| |_____|
(_____) (_____)
| | | |
| | | |
|/~~~\\| |/~~~\\|
/|___|\\ /|___|\\
<_______><_______>""",
""" _____
/_____\\
____[\\`---'/]____
/\\ #\\ \\_____/ /# /\\
/ \\# \\_.---._/ #/ \\
/ /|\\ | | /|\\ \\
/___/ | | | | | | \\___\\
| | | | |---| | | | |
|__| \\_| |_#_| |_/ |__|
//\\\\ <\\ _//^\\\\_ /> //\\\\
\\||/ |\\//// \\\\\\\\/| \\||/
| | | |
|---| |---|
|---| |---|
| | | |
|___| |___|
/ \\ / \\
|_____| |_____|
|HHHHH| |HHHHH|
""",
""" () ()
\\ /
__\\___________/__
/ \\
/ ___ ___ \\
| / \\ / \\ |
| | H || H | |
| \\___/ \\___/ |
| |
| \\ / |
| \\___________/ |
\\ /
\\_________________/
_________|__|_______
_| |_
/ | | \\
/ | O O O | \\
| | | |
| | O O O | |
| | | |
/ | | \\
| /| |\\ |
\\| | | |/
|____________________|
| | | |
|__| |__|
/ __ \\ / __ \\
OO OO OO OO
"""]
self.write(self.render_string('templates/root.html',ip=ip,robo=random.choice(robo)))
class ImgHandler(tornado.web.RequestHandler):
def get(self,string=None):
# gravatar is picky, it hates quers strings, allow us to fake them by using a uri
# /abc.png/s_100x100/set_any = /abc.png?set=any&s=100x100
#
# we use underscore as a replacement for = and / as a replacement for [&?]
args = self.request.arguments.copy()
for k in args.keys():
v = args[k]
if type(v) is list:
if len(v) > 0:
args[k] = args[k][0]
else:
args[k] = ""
# IF, and Only IF, there is an arg in the list, should we interpret slashes as params
split = string.split('/')
if len(split) > 1:
for st in split:
b = st.encode('ascii','ignore').split('_')
if len(b) == 2:
if b[0] in ['gravatar','ignoreext','size','set','bgset','color']:
args[b[0]] = b[1]
string = split[len(split)-1]
colors = ['blue','brown','green','grey','orange','pink','purple','red','white','yellow']
sets = ['set1','set2','set3']
bgsets = ['bg1','bg2']
#Create a hash for the string as given
if string is None:
string = self.request.remote_ip
# string = urllib.quote_plus(string)
if "ignoreext" in args:
client_ignoreext = tornado.escape.xhtml_escape(args["ignoreext"])
else:
client_ignoreext = None
#Change to a usuable format
if string.endswith(('.png','.gif','.jpg','.bmp','.jpeg','.ppm','.datauri')):
ext = string[string.rfind('.') +1 :len(string)]
if ext.lower() == 'jpg':
ext = 'jpeg'
else:
ext = "png"
if client_ignoreext != "false":
if string.endswith(('.png','.gif','.jpg','.bmp','.jpeg','.ppm','.datauri')):
string = string[0:string.rfind('.')]
r = Robohash(string)
#Create 10 hashes. This should be long enough for the current crop of variables.
#This is probably not insecure, sicne we'd be modding anyway. This just spreads it out more.
r.createHashes(11)
#Now, customize the request if possible.
client_color = ""
client_set = ""
client_bgset = ""
sizex = 300
sizey = 300
if "size" in args:
sizelist = args["size"].split(tornado.escape.xhtml_escape("x"),3)
if ((int(sizelist[0]) > 0) and (int(sizelist[0]) < 4096)):
sizex = int(sizelist[0])
if ((int(sizelist[0]) > 0) and (int(sizelist[0]) < 4096)):
sizey = int(sizelist[1])
if "gravatar" in args:
if tornado.escape.xhtml_escape(args["gravatar"]) == 'yes':
default = "404"
# construct the url
gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(string.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'default':default, 'size':str(sizey)})
if tornado.escape.xhtml_escape(args["gravatar"]) == 'hashed':
string = urllib.quote(string)
default = "404"
# construct the url
gravatar_url = "https://secure.gravatar.com/avatar/" + string + "?"
gravatar_url += urllib.urlencode({'default':default, 'size':str(sizey)})
try:
f = urllib2.urlopen(urllib2.Request(gravatar_url))
self.redirect(gravatar_url, permanent=False)
return 0
except:
badGravatar = True
if "set" in args:
if tornado.escape.xhtml_escape(args["set"]) == 'any':
client_set = sets[r.hasharray[1] % len(sets) ]
if args["set"] in sets:
client_set = tornado.escape.xhtml_escape(args["set"])
else:
#If no set specified, you get set 1
client_set = "set1"
##Let people define multiple sets, so I can add more.
if "sets" in args:
newsets = tornado.escape.xhtml_escape(args["sets"]).split(",");
replaceset = []
for s in newsets:
if s in sets:
replaceset.append(s)
client_set = replaceset[r.hasharray[1] % len(replaceset) ]
if client_set == 'set1':
client_set = colors[r.hasharray[0] % len(colors) ]
if "color" in args:
if args["color"] in colors:
client_set = tornado.escape.xhtml_escape(args["color"])
if "bgset" in args:
if args["bgset"] in bgsets:
client_bgset = tornado.escape.xhtml_escape(args["bgset"])
else:
client_bgset = bgsets[r.hasharray[2] % len(bgsets) ]
#If they don't specify a color, use hashvalue
if ((client_color == "") and (client_set == "")):
client_set = colors[r.hasharray[0] % len(colors) ]
self.set_header("Content-Type", "image/" + ext)
hashlist = r.getHashList(client_set)
#OK, here's where we do some creative sorting.
#Basically, we have two integers before every file
#The first one ensure FS order, which is necessary to match the RH.org server
#The second one ensures build order.
#The FS order is only necessary during picking elements. Now, we want the second sort
#So create a new list, ordered by the second integer
hlcopy = []
for element in hashlist:
element = element[0:element.find("/",element.find("#") -4) +1] + element[element.find("#") +1:len(element)]
hlcopy.append(element)
#Now, combine them into tuples, and sort. A tuples list always sorts by the FIRST element.
duality = zip(hlcopy,hashlist)
duality.sort()
pprint.pprint(duality)
hlcopy,hashlist = zip(*duality)
pprint.pprint(hlcopy)
print "------"
pprint.pprint(hashlist)
robohash = Image.open(hashlist[0])
robohash = robohash.resize((1024,1024))
for png in hashlist:
img = Image.open(png)
img = img.resize((1024,1024))
robohash.paste(img,(0,0),img)
if ext == 'bmp':
#Flatten bmps
r, g, b, a = robohash.split()
robohash = Image.merge("RGB", (r, g, b))
if client_bgset is not "":
bglist = []
backgrounds = os.listdir(client_bgset)
backgrounds.sort()
for ls in backgrounds:
if not ls.startswith("."):
bglist.append(client_bgset + "/" + ls)
bg = Image.open(bglist[r.hasharray[3] % len(bglist)])
bg = bg.resize((1024,1024))
bg.paste(robohash,(0,0),robohash)
robohash = bg
robohash = robohash.resize((sizex,sizey),Image.ANTIALIAS)
if ext != 'datauri':
robohash.save(self,format=ext)
else:
fakefile = cStringIO.StringIO()
robohash.save(fakefile,format='jpeg')
fakefile.seek(0)
data_uri = fakefile.read().encode("base64").replace("\n", "")
self.write("data:image/jpeg;base64," + data_uri)
def main():
tornado.options.parse_command_line()
# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"cookie_secret": "9b90a85cfe46cad5ec136ee44a3fa332",
"login_url": "/login",
"xsrf_cookies": True,
}
application = tornado.web.Application([
(r'/(crossdomain\.xml)', tornado.web.StaticFileHandler, {"path": os.path.join(os.path.dirname(__file__),
"static/")}),
(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(os.path.dirname(__file__),
"static/")}),
(r"/", MainHandler),
(r"/(.*)", ImgHandler),
], **settings)
http_server = tornado.httpserver.HTTPServer(application,xheaders=True)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()