def swapCodeForTokens(response): # takes dict of response parameters as input, like {'error':'blah blah'} or {'code':'blah blah','state':'blah blah'} db = app.connect_db() c=db.cursor() state = json.loads(response['state']) user_identifier = state['id'] redir = state['redir'] if 'error' in response: c.execute('UPDATE users SET imgur_json=NULL WHERE imgur_id='+app.app.sqlesc,(user_identifier,)) db.commit() return {'success':False} # called at the server redirect when imgur returns the code client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) credentials = client.authorize(response['code'],'authorization_code') # print credentials if 'access_token' in credentials.keys() and 'refresh_token' in credentials.keys(): db = app.connect_db() c = db.cursor() c.execute('UPDATE users SET imgur_json='+app.app.sqlesc+' WHERE imgur_id='+app.app.sqlesc,(json.dumps(credentials),user_identifier)) db.commit() db.close() return {'success':True,'redir':redir} else: c.execute('UPDATE users SET imgur_json=NULL WHERE imgur_id='+app.app.sqlesc,(user_identifier,)) db.commit() return {'success':False}
def process_email(): start_time = time.time() records_handled = 0 db = app.connect_db() cur = db.cursor() while True: cur.execute('UPDATE todo SET currently_processing='+app.app.sqlesc+' WHERE id=(SELECT id FROM todo WHERE task=ANY('+app.app.sqlesc+') AND currently_processing IS NOT TRUE LIMIT 1) RETURNING *',(True,['email_confirmation','old_email_confirmation','email_passwordreset'],)) tasks = cur.fetchall() db.commit() # print tasks if len(tasks) != 0: for task in tasks: if task[1] in ['email_confirmation','old_email_confirmation']: cur.execute('UPDATE users SET email_conf_token=(CASE WHEN email_conf_token IS NULL THEN '+app.app.sqlesc+' WHEN email_conf_token IS NOT NULL THEN email_conf_token END) WHERE id='+app.app.sqlesc+' RETURNING email, id, email_conf_token',(str(uuid.uuid4()),task[2])) email_data = cur.fetchall()[0] if task[1] == 'email_confirmation': email_confirmation(*email_data) elif task[1] == 'old_email_confirmation': old_email_confirmation(*email_data) elif task[1] in ['email_passwordreset']: cur.execute('UPDATE users SET pw_reset_token='+app.app.sqlesc+' WHERE id='+app.app.sqlesc+' RETURNING email, id, pw_reset_token',(str(uuid.uuid4()),task[2])) email_data = cur.fetchall()[0] email_passwordreset(*email_data) cur.execute('DELETE FROM todo WHERE id=('+app.app.sqlesc+')',(task[0],)) db.commit() records_handled += 1 else: db.close() return time.time()-start_time, records_handled
def uploadToImgur(userid,url): db = app.connect_db() c = db.cursor() c.execute('SELECT map_url,name,farmname,date,imgur_json FROM playerinfo WHERE url='+app.app.sqlesc,(url,)) result = c.fetchone() if result[4] != None: previous_upload_properties = json.loads(result[4]) if time.time() < previous_upload_properties['upload_time']+(2*3600): return {'error':'too_soon','link':previous_upload_properties['imgur_url']} map_url = result[0] titlestring = u"{} Farm, {} by {}".format(result[2],result[3],result[1]) descriptionstring = u"Stardew Valley game progress, full summary at http://upload.farm/{}".format(url) # try: c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,)) r = json.loads(c.fetchone()[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token,refresh_token) # file = url_for('home',filename=map_url,_external=True) # print 'uploaded to',file # client.upload_from_url(file,config={'title':'uploaded from','description':'upload.farm'},anon=False) if app.app.config['IMGUR_DIRECT_UPLOAD'] == True: result = client.upload_from_path(map_url,config={'title':titlestring,'description':descriptionstring},anon=False) else: map_url = u"http://upload.farm/{}".format(map_url) result = client.upload_from_url(map_url,config={'title':titlestring,'description':descriptionstring},anon=False) print(result) imgur_json = json.dumps({'imgur_url':'http://imgur.com/'+result['id'],'upload_time':time.time()}) c.execute('UPDATE playerinfo SET imgur_json='+app.app.sqlesc+' WHERE url='+app.app.sqlesc,(imgur_json,url)) db.commit() try: return {'success':None,'link':result['link']} except: return {'error':'upload_issue','link':None}
def checkApiAccess(userid): # something that checks whether we have api keys and whether they work; # if not, return False db = app.connect_db() c = db.cursor() c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,)) r = c.fetchone() if len(r) > 0: try: r = json.loads(r[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] except TypeError: return False else: return False client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token,refresh_token) try: client.get_account('me').url credits = client.credits # print(credits) if credits['ClientRemaining'] > 10 and credits['UserRemaining'] > 10: return True else: return None except ImgurClientError: return False
def processFile(filename,old_md5,rowid,url): # with open(filename,'rb') as f: # md5_info = md5(f) # replaced by zipuploads method zfile = zopen(filename) memfile = io.BytesIO() memfile.write(zfile.read()) zfile.close() md5_info = md5(memfile) save = savefile(memfile.getvalue(), True) player_info = playerInfo(save) farm_info = getFarmInfo(save) try: print(md5_info,old_md5) assert md5_info == old_md5 except AssertionError: return False print(filename,'failed md5') columns = [] values = [] for key in player_info.keys(): if type(player_info[key]) == list: for i,item in enumerate(player_info[key]): columns.append(key.replace(' ','_') + unicode(i)) values.append(unicode(item)) elif type(player_info[key]) == dict: for subkey in player_info[key]: if type(player_info[key][subkey]) == dict: for subsubkey in player_info[key][subkey]: columns.append((key+subkey+subsubkey).replace(' ','_')) values.append((player_info[key][subkey][subsubkey])) else: columns.append((key + subkey).replace(' ','_')) values.append(unicode(player_info[key][subkey])) else: columns.append(key) values.append(unicode(player_info[key])) columns.append('farm_info') values.append(json.dumps(farm_info)) columns.append('failed_processing') values.append(None) colstring = '' for c in columns: colstring += c+', ' colstring = colstring[:-2] questionmarks = ((sqlesc+',')*len(values))[:-1] try: connection = connect_db() cur = connection.cursor() cur.execute('UPDATE playerinfo SET ('+colstring+') = ('+questionmarks+') WHERE id='+sqlesc,(tuple(values+[rowid]))) cur.execute('INSERT INTO todo (task, playerid) VALUES ('+sqlesc+','+sqlesc+')',('process_image',rowid)) connection.commit() connection.close() return True except (sqlite3.OperationalError, psycopg2.ProgrammingError) as e: cur.execute('INSERT INTO errors (ip, time, notes) VALUES ('+sqlesc+','+sqlesc+','+sqlesc+')',('reprocessEntry.py', time.time(),unicode(e)+' '+unicode([columns,values]))) connection.commit() return False
def process_queue(): start_time = time.time() records_handled = 0 db = __init__.connect_db() cur = db.cursor() while True: #cur.execute('SELECT * FROM todo WHERE task='+__init__.app.sqlesc+' AND currently_processing NOT TRUE',('process_image',)) cur.execute('UPDATE todo SET currently_processing='+__init__.app.sqlesc+' WHERE id=(SELECT id FROM todo WHERE task='+__init__.app.sqlesc+' AND currently_processing IS NOT TRUE LIMIT 1) RETURNING *',(True,'process_image',)) tasks = cur.fetchall() db.commit() # print tasks if len(tasks) != 0: for task in tasks: cur.execute('SELECT '+database_fields+' FROM playerinfo WHERE id=('+__init__.app.sqlesc+')',(task[2],)) result = cur.fetchone() data = {} for i, item in enumerate(result): data[sorted(database_structure_dict.keys())[i]] = item data['pantsColor'] = [data['pantsColor0'],data['pantsColor1'],data['pantsColor2'],data['pantsColor3']] data['newEyeColor'] = [data['newEyeColor0'],data['newEyeColor1'],data['newEyeColor2'],data['newEyeColor3']] data['hairstyleColor'] = [data['hairstyleColor0'],data['hairstyleColor1'],data['hairstyleColor2'],data['hairstyleColor3']] base_path = os.path.join(__init__.app.config.get('IMAGE_FOLDER'), data['url']) try: os.mkdir(base_path) except OSError: pass avatar_path = os.path.join(base_path, data['url']+'-a.png') avatar = generateAvatar(data) pi = json.loads(data['portrait_info']) portrait_path = os.path.join(base_path, data['url']+'-p.png') generateFamilyPortrait(avatar, pi).save(portrait_path, compress_level=9) avatar.resize((avatar.width*4, avatar.height*4)).save(avatar_path, compress_level=9) farm_data = regenerateFarmInfo(json.loads(data['farm_info'])) farm_path = os.path.join(base_path, data['url']+'-f.png') generateMinimap(farm_data).save(farm_path, compress_level=9) map_path = os.path.join(base_path, data['url']+'-m.png') thumb_path = os.path.join(base_path, data['url']+'-t.png') farm = generateFarm(data['currentSeason'], farm_data) th = farm.resize((int(farm.width/4), int(farm.height/4)), Image.ANTIALIAS) th.save(thumb_path) farm.save(map_path, compress_level=9) cur.execute('UPDATE playerinfo SET farm_url='+__init__.app.sqlesc+', avatar_url='+__init__.app.sqlesc+', portrait_url='+__init__.app.sqlesc+', map_url='+__init__.app.sqlesc+', thumb_url='+__init__.app.sqlesc+', base_path='+__init__.app.sqlesc+' WHERE id='+__init__.app.sqlesc+'',(farm_path,avatar_path,portrait_path,map_path,thumb_path,base_path,data['id'])) db.commit() # except: # cur.execute('UPDATE playerinfo SET failed_processing='+__init__.app.sqlesc+' WHERE id='+__init__.app.,(True,data['id'])) # db.commit() cur.execute('DELETE FROM todo WHERE id=('+__init__.app.sqlesc+')',(task[0],)) db.commit() records_handled += 1 else: db.close() return time.time()-start_time, records_handled
def check_voting_base(): db = connect_db() cur = db.cursor() cur.execute("SELECT id FROM playerinfo WHERE (positive_votes IS NULL OR positive_votes = 0) AND (negative_votes IS NULL OR negative_votes = 0)") player_ids = cur.fetchall() cur.executemany('UPDATE playerinfo SET positive_votes=1, negative_votes=1 WHERE id='+app.sqlesc,player_ids) db.commit() return len(player_ids)
def getEntries(where=None): connection = connect_db() c = connection.cursor() if where == None: where = "" c.execute("SELECT id,md5,url,savefileLocation FROM playerinfo " + where) entries = c.fetchall() connection.close() return entries
def check_email_verification(): db = connect_db() cur = db.cursor() cur.execute('SELECT users.id FROM users WHERE users.email_confirmed IS NULL AND users.email_conf_token IS NULL AND NOT EXISTS (SELECT todo.id FROM todo WHERE todo.playerid=CAST(users.id AS text))') # cur.execute("SELECT users.id FROM (users INNER JOIN todo ON CAST(users.id AS text) != todo.playerid AND todo.task = 'email_confirmation') WHERE users.email_confirmed IS NULL AND users.email_conf_token IS NULL") user_ids = cur.fetchall() cur.executemany('INSERT INTO todo (task, playerid) VALUES ('+app.sqlesc+','+app.sqlesc+')',[('old_email_confirmation',user_id[0]) for user_id in user_ids]) db.commit() return len(user_ids)
def getAuthUrl(userid,target=None): db = app.connect_db() c = db.cursor() iuid = unicode(uuid.uuid4()) imgur_id = json.dumps({'id':iuid,'redir':target}) c.execute('UPDATE users SET imgur_id='+app.app.sqlesc+' WHERE id='+app.app.sqlesc,(iuid,userid)) db.commit() db.close() client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) authorization_url = client.get_auth_url('code')+'&state='+unicode(imgur_id) return authorization_url
def check_voting_base(): db = connect_db() cur = db.cursor() cur.execute( "SELECT id FROM playerinfo WHERE (positive_votes IS NULL OR positive_votes = 0) AND (negative_votes IS NULL OR negative_votes = 0)" ) player_ids = cur.fetchall() cur.executemany( 'UPDATE playerinfo SET positive_votes=1, negative_votes=1 WHERE id=' + app.sqlesc, player_ids) db.commit() return len(player_ids)
def check_email_verification(): db = connect_db() cur = db.cursor() cur.execute( 'SELECT users.id FROM users WHERE users.email_confirmed IS NULL AND users.email_conf_token IS NULL AND NOT EXISTS (SELECT todo.id FROM todo WHERE todo.playerid=CAST(users.id AS text))' ) # cur.execute("SELECT users.id FROM (users INNER JOIN todo ON CAST(users.id AS text) != todo.playerid AND todo.task = 'email_confirmation') WHERE users.email_confirmed IS NULL AND users.email_conf_token IS NULL") user_ids = cur.fetchall() cur.executemany( 'INSERT INTO todo (task, playerid) VALUES (' + app.sqlesc + ',' + app.sqlesc + ')', [('old_email_confirmation', user_id[0]) for user_id in user_ids]) db.commit() return len(user_ids)
WSGI config for supportcenter project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "supportcenter.settings") from __init__ import setup_paths, connect_db setup_paths() # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application connect_db() application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)