@mat1/

colors

Python

No description

fork
loading
Files
  • main.py
  • templates
  • website
  • color.py
  • database.py
  • requirements.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
from aiohttp import web
from jinja2 import Environment, FileSystemLoader, select_autoescape
import color
import json
import colorsys
import random
from datetime import datetime
from database import db
import hashlib
import os
import aiohttp
import asyncio
# import time

jinja_env = Environment(
	loader=FileSystemLoader(searchpath='templates'),
	autoescape=select_autoescape(['html', 'xml']),
	enable_async=True
)

class templates:
	template_dict = {}

async def load_template(filename, **kwargs):
	if filename in templates.template_dict:
		r = await templates.template_dict[filename].render_async(**kwargs)
	else:
		print(f'Loading template {filename} for the first time')
		t = jinja_env.get_template(filename)
		templates.template_dict[filename] = t
		r = await t.render_async(**kwargs)
	return r

routes = web.RouteTableDef()

start_time = datetime.now()

trending_limit = 35

def get_sitemap_date(now=False):
	t = datetime.now() if now else start_time
	return datetime.strftime(t, '%Y-%m-%d')

def open_sitemap(i):
	print(f'opening sitemap #{i}')
	#now = datetime.strftime(datetime.now(), '%Y-%m-%dT%H:%I:%SZ')
	now = get_sitemap_date()
	generated_sitemap = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
	generated_sitemap += ''.join(f'<url><loc>https://colors.matdoes.dev/color/{"{:06X}".format(i)}</loc><lastmod>{now}</lastmod><changefreq>daily</changefreq><priority>0.5</priority></url>' for i in range(i*50000, min((i+1)*50000, 0xFFFFFF+1)))
	generated_sitemap += '</urlset>'
	return generated_sitemap

@routes.get('/')
async def index(request):
	random_hex = color.to_hex((
		random.randint(0, 255),
		random.randint(0, 255),
		random.randint(0, 255)
	))
	trending_colors = await db.get_trending()
	return await load_template('index.html', url=request.url, random_hex=random_hex, trending=trending_colors)


@routes.get('/trending/ws')
async def trending_ws(request):

	ws = web.WebSocketResponse()
	await ws.prepare(request)

	trending_html_before = ''
	while True:
		try:
			trending_colors = await db.get_trending()
			trending_html = await load_template('trending.html', trending=trending_colors)
			if trending_html != trending_html_before:
				await ws.send_str(trending_html)
				trending_html_before = trending_html
		except:
			break
		await asyncio.sleep(0.2)
	try:
		await ws.close()
	except:
		pass



	# async for msg in ws:
	# 	if msg.type == aiohttp.WSMsgType.TEXT:
	# 		if msg.data == 'close':
	# 			await ws.close()
	# 		else:
	# 			await ws.send_str(msg.data + '/answer')
	# 	elif msg.type == aiohttp.WSMsgType.ERROR:
	# 		print('ws connection closed with exception %s' %
	# 			ws.exception())

	# print('websocket connection closed')

	return ws




@routes.get('/api/trending')
async def api_trending(request):
	trending_colors_raw = await db.get_trending(limit=100)
	trending_colors = []
	for c in trending_colors_raw:
		hex_color, upvotes, rgb = c

		trending_colors.append({
			'hex': hex_color,
			'upvotes':upvotes,
			'rgb': rgb
		})
	return web.json_response(trending_colors[:trending_limit])

@routes.get('/api/trending/dark')
async def api_trending_dark(request):
	trending_colors_raw = await db.get_trending(limit=100)
	trending_colors = []
	for c in trending_colors_raw:
		hex_color, upvotes, rgb = c
		is_light = sum(rgb) >= 360
		if is_light:
			continue
		trending_colors.append({
			'hex': hex_color,
			'upvotes':upvotes,
			'rgb': rgb
		})
	return web.json_response(trending_colors[:trending_limit])

@routes.get('/api/trending/light')
async def api_trending_light(request):
	trending_colors_raw = await db.get_trending(limit=100)
	trending_colors = []
	for c in trending_colors_raw:
		hex_color, upvotes, rgb = c
		is_light = sum(rgb) >= 360
		if not is_light:
			continue
		trending_colors.append({
			'hex': hex_color,
			'upvotes':upvotes,
			'rgb': rgb
		})
	return web.json_response(trending_colors[:trending_limit])


@routes.get('/api/color/{color}')
async def api_get_color(request):
	trending_colors_raw = await db.get_trending(limit=100)
	trending_colors = []
	for c in trending_colors_raw:
		hex_color, upvotes, rgb = c
		is_light = sum(rgb) >= 360
		if not is_light:
			continue
		trending_colors.append({
			'hex': hex_color,
			'upvotes':upvotes,
			'rgb': rgb
		})
	return web.json_response(trending_colors[:trending_limit])


@routes.get('/color')
async def redirect_trending(request):
	trending_colors_raw = await db.get_trending()
	trending_hex = trending_colors_raw[0][0]
	return web.HTTPFound(location=f'/color/{trending_hex}')

@routes.get('/c')
async def redirect_trending_im(request):
	trending_colors_raw = await db.get_trending()
	trending_hex = trending_colors_raw[0][0]
	return web.HTTPFound(location=f'/c/{trending_hex}')



@routes.get('/color/random')
async def random_color(request):
	return web.HTTPFound('/color/' + color.to_hex((
		random.randint(0, 255),
		random.randint(0, 255),
		random.randint(0, 255)
	)))


@routes.get('/c/random')
async def random_color_c(request):
	return web.HTTPFound('/c/' + color.to_hex((
		random.randint(0, 255),
		random.randint(0, 255),
		random.randint(0, 255)
	)))

@routes.get('/c/{color}')
async def get_color_png(request):
	try:
		r, g, b = color.to_rgb(request.match_info
		['color'])
	except:
		return web.HTTPNotFound()
	color_bytes = color.to_png((r, g, b), (200, 200), filename=None, compression_level=9)
	return web.Response(body=color_bytes, content_type='image/png')

@routes.get('/sitemap_{i}.xml')
async def get_sitemap_id(request):
	return web.Response(
		text=open_sitemap(int(request.match_info
		['i'])),
		content_type='text/xml'
	)

@routes.get('/public_sitemap.xml')
async def get_public_sitemap(request):
	now = get_sitemap_date(True)
	return web.Response(
		text=open('templates/sitemap_public.xml').read().replace('{now}', now),
		content_type='text/xml'
	)

@routes.get('/now.txt')
async def get_sitemap_time(request):
	now = get_sitemap_date(True)
	return web.Response(
		text=now
	)


@routes.get('/csscolors_sitemap.xml')
async def csscolors_sitemap(request):
	now = get_sitemap_date(True)
	generated_sitemap = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
	for c in color.color_names:
		generated_sitemap += ''.join(f'<url><loc>https://colors.matdoes.dev/color/{c}</loc><lastmod>{now}</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>')
	generated_sitemap += '</urlset>'


	return web.Response(
		text=generated_sitemap,
		content_type='text/xml'
	)


@routes.get('/sitemap.xml')
async def get_sitemap(request):
	generated_sitemap = '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.84">'
	for i in range(round((16777216/50000)+0.5)):
		generated_sitemap += f'<sitemap><loc>https://colors.matdoes.dev/sitemap_{i}.xml</loc></sitemap>'
	extra_sitemaps = ('public_sitemap.xml', 'csscolors_sitemap.xml')
	for s in extra_sitemaps:
		generated_sitemap += f'<sitemap><loc>https://colors.matdoes.dev/{s}</loc></sitemap>'

	generated_sitemap += '</sitemapindex>'

	return web.Response(
		text=generated_sitemap,
		content_type='text/xml'
	)
	

@routes.post('/upvote')
async def upvote_color(request):
	post_data = json.loads(await request.content.read())
	token = post_data['token']
	async with aiohttp.ClientSession() as s:
		# print('verifying captcha')
		# captcha_start = time.time()
		r = await s.post('https://www.google.com/recaptcha/api/siteverify', data={
			'secret': os.getenv('recaptcha'),
			'response': token,
			'remoteip': request.headers.get('Cf-Connecting-Ip')
		})
		# captcha_end = time.time()
		recaptcha_resp = await r.json()
		# print('Captcha took',captcha_end-captcha_start,'seconds')
	if 'score' not in recaptcha_resp:
		return web.HTTPBadRequest(text='no')
	if recaptcha_resp['score'] <= 0.2 or recaptcha_resp['action'] != 'upvote':
		print('bot detected:', recaptcha_resp['score'])
		print(request.headers)
		return web.HTTPBadRequest(text='no')

	color_id = post_data['color'].lower()
	bad_color = False
	if len(color_id) != 6:
		bad_color = True
	try:
		int(color_id, 16)
	except ValueError:
		bad_color = True
	if bad_color:
		return web.HTTPBadRequest(text='no')

	hashed_ip = hashlib.md5(request.headers.get('Cf-Connecting-Ip').encode()).hexdigest()

	await db.upvote_color(color_id, hashed_ip)
	print('upvoted', color_id)
	# print(request.headers)
	print(recaptcha_resp['score'])
	return web.Response(
		text='ok',
		content_type='text/plain'
	)
	
@routes.post('/unupvote')
async def unupvote_color(request):
	color_id = await request.content.read()
	color_id = color_id.decode().lower()
	bad_color = False
	if len(color_id) != 6:
		bad_color = True
	try:
		int(color_id, 16)
	except ValueError:
		bad_color = True
	if bad_color:
		return web.HTTPBadRequest(text='no')

	hashed_ip = hashlib.md5(request.headers.get('Cf-Connecting-Ip').encode()).hexdigest()

	await db.unupvote_color(color_id, hashed_ip)
	print('unupvoted', color_id)
	return web.Response(
		text='ok',
		content_type='text/plain'
	)
	

@routes.post('/upvoted')
async def has_upvoted(request):
	post_data = json.loads(await request.content.read())
	print(post_data)
	color_id = post_data['color'].decode().lower()
	bad_color = False
	if len(color_id) != 6:
		bad_color = True
	try:
		int(color_id, 16)
	except ValueError:
		bad_color = True
	if bad_color:
		return web.HTTPBadRequest(text='no')

	hashed_ip = hashlib.md5(request.headers.get('Cf-Connecting-Ip').encode()).hexdigest()

	upvoted = await db.has_upvoted(color_id, hashed_ip)
	return web.Response(
		text='true' if upvoted else 'false',
		content_type='text/plain'
	)
	

class Color():
	def __init__(self, original_color):
		color_hex = color.to_hex(original_color)
		color_rgb = color.to_rgb(original_color)
		r, g, b = color_rgb[0]/255, color_rgb[1]/255, color_rgb[2]/255
		color_hsv = colorsys.rgb_to_hsv(r, g, b)
		color_hls = colorsys.rgb_to_hls(r, g, b)
		shades = []
		saturations = []
		hues = []
		lightness = color_hls[1]
		lightness_offset = .25
		if lightness < .25:
			lightness_offset = lightness + 0.05
		if lightness > .75:
			lightness_offset = lightness - 0.55

		for i in range(1, 10):
			hls_tmp = list(color_hls)
			hls_tmp[1] = (hls_tmp[1] + i*0.05 - lightness_offset)
			if hls_tmp[1] < 0:
				hls_tmp[1] = 0.0
			elif hls_tmp[1] > 1:
				hls_tmp[1] = 1.0
			shades.append(
				color.to_hex(
					colorsys.hls_to_rgb(*hls_tmp)
				)
			)

			hls_tmp = list(color_hls)
			hls_tmp[2] = (i+1)*0.1
			saturations.append(
				color.to_hex(
					colorsys.hls_to_rgb(*hls_tmp)
				)
			)
			hsv_tmp = list(color_hsv)
			hsv_tmp[0] = ((hsv_tmp[0] + i*0.05) - 0.24) % 1
			hues.append(
				color.to_hex(
					colorsys.hsv_to_rgb(*hsv_tmp)
				)
			)

		self.color = color_hex
		self.rgb = color_rgb
		self.hsv = color_hsv
		self.hls = color_hls
		self.shades = shades
		self.saturations = saturations
		self.hues = hues
	def __repr__(self):
		return f'#{self.color}'
	





@routes.get('/color/{color}')
async def view_color(request):
	original_color = request.match_info['color']
	c = Color(original_color)
	# try:
	# 	color_hex = color.to_hex(original_color)
	# except:
	# 	raise web.HTTPNotFound()
	# color_rgb = color.to_rgb(original_color)
	# r, g, b = color_rgb[0]/255, color_rgb[1]/255, color_rgb[2]/255
	# color_hsv = colorsys.rgb_to_hsv(r, g, b)
	# color_hls = colorsys.rgb_to_hls(r, g, b)
	# shades = []
	# saturations = []
	# hues = []
	# lightness = color_hls[1]
	# lightness_offset = .25
	# if lightness < .25:
	# 	lightness_offset = lightness + 0.05
	# if lightness > .75:
	# 	lightness_offset = lightness - 0.55

	# for i in range(1, 10):
	# 	hls_tmp = list(color_hls)
	# 	hls_tmp[1] = (hls_tmp[1] + i*0.05 - lightness_offset)
	# 	if hls_tmp[1] < 0:
	# 		hls_tmp[1] = 0.0
	# 	elif hls_tmp[1] > 1:
	# 		hls_tmp[1] = 1.0
	# 	shades.append(
	# 		color.to_hex(
	# 			colorsys.hls_to_rgb(*hls_tmp)
	# 		)
	# 	)

	# 	hls_tmp = list(color_hls)
	# 	hls_tmp[2] = (i+1)*0.1
	# 	saturations.append(
	# 		color.to_hex(
	# 			colorsys.hls_to_rgb(*hls_tmp)
	# 		)
	# 	)
	# 	hsv_tmp = list(color_hsv)
	# 	hsv_tmp[0] = ((hsv_tmp[0] + i*0.05) - 0.24) % 1
	# 	hues.append(
	# 		color.to_hex(
	# 			colorsys.hsv_to_rgb(*hsv_tmp)
	# 		)
	# 	)


	color_id = c.color.lower()
	bad_color = False
	if len(color_id) != 6:
		bad_color = True
	try:
		int(color_id, 16)
	except ValueError:
		bad_color = True
	if bad_color:
		return web.HTTPBadRequest(text='no')

	hashed_ip = hashlib.md5(request.headers.get('Cf-Connecting-Ip').encode()).hexdigest()

	# color_data = await db.get_color(color_id)
	# if color_data is None:
	# 	has_upvoted = False
	# 	upvotes = 0
	# else:
	has_upvoted = await db.has_upvoted(color_id, hashed_ip)
	upvoters = await db.get_upvoters(color_id)
	upvotes = len(upvoters)

	return await load_template(
		'color.html',
		color=c.color,
		rgb=c.rgb,
		hsv=c.hsv,
		hls=c.hls,
		shades=c.shades,
		saturations=c.saturations,
		hues=c.hues,
		url=request.url,
		upvotes=upvotes,
		has_upvoted=has_upvoted
	)

@routes.get('/{color}/oembed.json')
async def get_oembed(request):
	image_hex = request.match_info['color']
	oembed_data = {
		'version': '1.0',
		'type': 'photo',
		'width': 200,
		'height': 200,
		'title': '#' + image_hex,
		'url': 'https://colors.matdoes.dev/c/' + image_hex
	}
	return web.Response(text=json.dumps(oembed_data, indent=2))

async def resp_404():
	content = await load_template('404.html')
	return web.Response(
		text=content,
		status=404,
		content_type='text/html'
	)

@web.middleware
async def middleware(request, handler):
	if 'Cf-Connecting-Ip' not in request.headers:
		raise web.HTTPNotAcceptable()
	if request.url.path[-1] == '/' and request.url.path != '/':
		return web.HTTPMovedPermanently(location=request.url.path[:-1])
	try:
		r = await handler(request)
	except web.HTTPException as e:
		r = e
	except color.BadColor:
		return await resp_404()
	except ValueError:
		return await resp_404()

	# hashed_ip = hashlib.md5(request.headers.get('Cf-Connecting-Ip').encode()).hexdigest()
	# user_agent = request.headers.get('User-Agent')
	# print(hashed_ip[:4], user_agent, request.url)
	
	if isinstance(r, str):
		r = web.Response(
			text=r,
			headers={
				'content-type': 'text/html'
			}
		)
	content_types = {
		'css': 'text/css',
		'js': 'text/javascript',
		'html': 'text/html',
		'json': 'application/json',
		'xml': 'text/xml'
	}
	if r.content_type == 'application/octet-stream':
		parts = request.url.parts
		last_path = parts[-1]
		ext = last_path.rsplit('.', 1)[-1]
		if ext in content_types:
			r.content_type = content_types[ext]
		else:
			r.content_type = 'text/plain'
	if r.status == 404:
		return await resp_404()
	return r

app = web.Application(middlewares=[middleware])
app.add_routes(routes)
app.add_routes([web.static('/', 'website')])
web.run_app(app)