def random_gg_image(): random_idol_id = get_random_idol_id_with_photo() c.execute( "SELECT fullname, stagename FROM groupmembers.member WHERE id = %s", (random_idol_id, )) info = c.fetchone() full_name = info[0] stage_name = info[1] c.execute( "SELECT alias FROM groupmembers.aliases WHERE objectid = %s AND isgroup = 0 AND serverid IS NULL", (random_idol_id, )) aliases = c.fetchall() aliases = [alias[0] for alias in aliases] photo_link = ".mp4" # confirm the client does not receive a video. while ".mp4" in photo_link or ".webm" in photo_link: photo_link = get_idol_photo(random_idol_id, redirect_user=False, auth=True, guessing_game=True) idol_info_json = { 'id': random_idol_id, 'full_name': full_name, 'stage_name': stage_name, 'image_url': photo_link, 'aliases': aliases } return idol_info_json
def get_groups(): """Get all group ids to group names.""" c.execute("SELECT groupid, groupname FROM groupmembers.groups") all_groups = {} for group_id, group_name in c.fetchall(): all_groups[group_id] = group_name return all_groups
def get_group(group_id): """Get group name by group id""" c.execute("SELECT groupname FROM groupmembers.groups WHERE groupid=%s", (group_id, )) group = c.fetchone() try: return {group_id: group[0]} except: return {}
def get_all_members(): """Gets all full names and stage names of idols.""" c.execute("SELECT id, fullname, stagename FROM groupmembers.member") all_members = {} for idol_id, full_name, stage_name in c.fetchall(): all_members[idol_id] = { 'full_name': full_name, 'stage_name': stage_name } return all_members
def get_member(idol_id): """Get full name and stage name of an idol by it's id.""" c.execute( "SELECT fullname, stagename FROM groupmembers.member WHERE id=%s", (idol_id, )) all_members = {} for full_name, stage_name in c.fetchall(): all_members[idol_id] = { 'full_name': full_name, 'stage_name': stage_name } return all_members
def get_all_members_with_photos(): """Gets all full names and stage names of idols with photos""" c.execute("""SELECT DISTINCT(m.id), fullname, stagename FROM groupmembers.member as m, groupmembers.imagelinks as i WHERE m.id = i.memberid""") all_members = {} for idol_id, full_name, stage_name in c.fetchall(): all_members[idol_id] = { 'full_name': full_name, 'stage_name': stage_name } return all_members
def get_image(image_id): # check authorization if not check_auth_key(request.headers.get('Authorization')): # Invalid API Key return Response(status=403) try: c.execute("SELECT link FROM groupmembers.imagelinks where id = %s", (image_id, )) link = c.fetchone() if not link: return Response(status=404) return process_image([image_id, link[0]]) except Exception as e: print(e) return Response(status=500)
def get_idol_photo(idol_id): """Download an idol's photo and redirect the user to the image link.""" # check authorization if not check_auth_key(request.headers.get('Authorization')): # Invalid API Key return Response(status=403) # delete files after a certain amount exist in the directory. currently_existing_photos = os.listdir(idol_folder) if len(currently_existing_photos) > 150000: # noinspection PyPep8 try: for file in currently_existing_photos: os.remove(file) except: pass try: allow_group_photos = request.args.get('allow_group_photos') # must be None. 0 is an alternative of allow_group_photos, so do not simplify. if allow_group_photos is None: allow_group_photos = 1 if allow_group_photos: # get all types of photos from the idol. c.execute( "SELECT id, link FROM groupmembers.imagelinks WHERE memberid=%s", (idol_id, )) else: # only get photos that are not a group photo c.execute( "SELECT id, link FROM groupmembers.imagelinks WHERE memberid=%s AND groupphoto=%s", (idol_id, 0)) all_links = c.fetchall() if not all_links: # idol has no photos return Response(status=404) random_link = random.choice(all_links) return process_image(random_link) except Exception as e: print(e) return Response(status=500)
def get_top_gg_vote(): if not check_webhook_key(request.headers.get('Authorization')): # Invalid Webhook Key return Response(status=403) user_id = (request.get_json()).get('user') if not user_id: return Response(status=400) try: c.execute("DELETE FROM general.lastvoted WHERE userid = %s", (user_id, )) c.execute("INSERT INTO general.lastvoted(userid) values(%s)", (user_id, )) db_conn.commit() print(user_id, " has voted.") return Response(status=200) except Exception as e: print(e) return Response(status=500)
def get_groups(): """Get all group ids to group names.""" c.execute("SELECT groupid, groupname FROM groupmembers.groups") groups = c.fetchall() c.execute("SELECT idolid, groupid FROM groupmembers.idoltogroup") all_groups = {} members_in_groups = {} for idol_id, group_id in c.fetchall(): members = members_in_groups.get(group_id) if not members: members_in_groups[group_id] = [idol_id] else: members_in_groups[group_id].append(idol_id) for group_id, group_name in groups: members = members_in_groups.get(group_id) or [] all_groups[group_id] = {"name": group_name, "members": members} return all_groups
def log_info(): """Log minimal request information to know amount of calls along with key usage.""" try: key = request.headers.get('Authorization') or "None" # keys are always appended to the end in order, so we can use the index to differentiate between keys. try: index = private_keys.index(key) except: index = -1 # c.execute("INSERT INTO ") c.execute( "SELECT called FROM stats.apiusage WHERE endpoint = %s AND keyused = %s", (request.base_url, index)) called_amount = c.fetchone() if called_amount: c.execute( "UPDATE stats.apiusage SET called = %s WHERE endpoint = %s AND keyused = %s", (called_amount[0] + 1, request.base_url, index)) else: c.execute( "INSERT INTO stats.apiusage(endpoint, keyused, called) VALUES(%s, %s, %s)", (request.base_url, index, 1)) db_conn.commit() except Exception as e: db_conn.commit( ) # will cause a transaction rollback / abort the current transaction. print(f"{e} - log_info")
def get_bot_info(): """Sends a list of bot information such as Server Count, User Count, Total commands used, Amount of Idol Photos """ c.execute("SELECT totalused FROM stats.sessions ORDER BY totalused DESC") total_commands_used = c.fetchone()[0] c.execute("SELECT COUNT(*) FROM stats.guilds") server_count = c.fetchone()[0] c.execute("SELECT SUM(membercount) FROM stats.guilds") member_count = c.fetchone()[0] c.execute("SELECT COUNT(*) FROM groupmembers.imagelinks") idol_photo_count = c.fetchone()[0] return { 'total_commands_used': total_commands_used, 'server_count': server_count, 'member_count': member_count, 'idol_photo_count': idol_photo_count }, 200
def get_image_ids(idol_id): """Returns all image ids an idol has.""" c.execute("SELECT id FROM groupmembers.imagelinks WHERE memberid=%s", (idol_id, )) all_ids = {'ids': [current_id[0] for current_id in c.fetchall()]} return all_ids
def get_random_idol_id_with_photo(): """Get a random idol id that definitely has a photo.""" c.execute("SELECT DISTINCT(memberid) FROM groupmembers.imagelinks") return random.choice(c.fetchall())[0]
def get_idol_commands_used(): """Get the Amount of Idol Photo Commands Used.""" c.execute( "SELECT SUM(count) FROM stats.commands WHERE commandname LIKE 'Idol %' OR commandname LIKE 'randomidol'" ) return {'idol_commands_used': c.fetchone()[0]}, 200
def get_idol_photo(idol_id, redirect_user=True, auth=True, guessing_game=False, looped=0): """Download an idol's photo and redirect the user to the image link.""" # check authorization if not check_auth_key(request.headers.get('Authorization')) and auth: # Invalid API Key return Response(status=403) # defining the args and kwargs for this method to use recursive strategies. args = {idol_id} kwargs = { "redirect_user": redirect_user, "auth": auth, "guessing_game": guessing_game } try: check_redirect = get_param( "redirect") or 1 # should redirect by default allow_video = get_param( 'video_allowed') or 1 # video allowed by default min_faces = get_param('min_faces') or 1 max_faces = get_param('max_faces') or 999 # confirm the input is not a string check_redirect = int(check_redirect) allow_video = int(allow_video) min_faces = int(min_faces) max_faces = int(max_faces) except: return Response(status=422) if not check_redirect: redirect_user = False if 999 < min_faces < -1: min_faces = 1 if max_faces > 10000: max_faces = 999 if max_faces < min_faces: max_faces = min_faces try: add_sql_query = "" if not allow_video else "OR facecount = -1" sql_query = f"""SELECT id, link FROM groupmembers.imagelinks WHERE memberid=%s AND ( (facecount >= %s AND facecount <= %s) {add_sql_query})""" c.execute(sql_query, (idol_id, min_faces, max_faces)) all_links = c.fetchall() if not all_links: # idol has no photos return Response(status=404) random_link = random.choice(all_links) if guessing_game: image_host_url = process_image(random_link, redirect_user=redirect_user, guessing_game=True) return image_host_url return process_image(random_link, redirect_user=redirect_user) except Exception as e: if "current transaction is aborted" in f"{e}".lower() and looped < 5: # we will attempt this 5 times. kwargs['looped'] = looped + 1 return get_idol_photo(*args, **kwargs) print(f"{e} (Looped {looped} times) - get_idol_photo 2 ") return Response(status=500)