#!/bin/python3.4
# -*- coding: utf-8 -*-

__author__ = '1mr'

#### Simple avatar web server 
####
#### avatar format request: http://localhost:5000/0c2a020ce344c96fc11e5cfdc817bbd3?s=48
####  

import os
import glob

from PIL import Image
from flask import Flask
from flask import request
from flask import send_file

img_path = 'img'   #### folder with img files. file names are hashe's (md5(<email>))
img_def = 'kobe-bryant'   ##### default image. 

def findFile(name, path, size):
	for name in glob.glob(path + '/' + size + '/' + name+'.*'):
		name = name
	if os.path.isfile(name):
		return name
	else:
		try:
			os.mkdir(path + '/' + size)
		except OSError:
    	# if pic_folder is already present, use it.
			pass
		##### resize image
		fname = name
		for name in glob.glob(path + '/' + name+'.*'):
			img = Image.open(name)
			fname = path + '/' + size + '/' + fname + '.' + name.rsplit('.', 1)[1]
			img.resize((int(size),int(size)), Image.ANTIALIAS).save(fname, quality=95)
		return fname

app = Flask(__name__)

@app.route('/<hash>')
def index(hash):
	s = request.args.get('s')
	redirect = request.args.get('redirect')
	d = request.args.get('d')
	try:
		filename = findFile(hash,img_path,s)
		return send_file(filename, mimetype='image/jpeg')
	except FileNotFoundError:
		filename =  findFile(img_def,img_path,s)	
		return send_file(filename, mimetype='image/jpeg')


if __name__ == '__main__':
    app.run(debug=False)

