def team_create(): mock = config_setting("TESTING") customNames = config_setting("CUSTOM_PLAYER_NAMES") if not g.user: return redirect('/login') form = TeamForm() # We wish to query this every time, since we can now upload photos. if not mock: form.logo.choices = logos.get_logo_choices() if request.method == 'POST': num_teams = g.user.teams.count() max_teams = config_setting('USER_MAX_TEAMS') if max_teams >= 0 and num_teams >= max_teams and not (util.is_admin( g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of teams ({}) stored'. format(num_teams)) elif form.validate(): data = form.data auths = form.get_auth_list() pref_names = form.get_pref_list() name = data['name'].strip() tag = data['tag'].strip() flag = data['country_flag'] logo = data['logo'] # Update the logo. Passing validation we have the filename in the # list now. if not mock and (util.is_admin(g.user) or util.is_super_admin( g.user)) and form.upload_logo.data: filename = secure_filename(form.upload_logo.data.filename) index_of_dot = filename.index('.') newLogoDetail = filename[:index_of_dot] # Reinit our logos. logos.add_new_logo(newLogoDetail) app.logger.info("Added new logo id {}".format(newLogoDetail)) data['logo'] = newLogoDetail team = Team.create( g.user, name, tag, flag, logo, auths, data['public_team'] and (util.is_admin(g.user) or util.is_super_admin(g.user)), pref_names) db.session.commit() app.logger.info('User {} created team {}'.format( g.user.id, team.id)) return redirect('/teams/{}'.format(team.user_id)) else: flash_errors(form) return render_template('team_create.html', user=g.user, form=form, edit=False, is_admin=(util.is_admin(g.user) or util.is_super_admin(g.user)), MAXPLAYER=Team.MAXPLAYERS, customNames=customNames)
def server_edit(serverid): server = GameServer.query.get_or_404(serverid) is_owner = (g.user and (util.is_server_owner(g.user, server))) is_sadmin = (g.user and util.is_super_admin(g.user)) app.logger.info("Owner: {} Sadmin: {}".format(is_owner, is_sadmin)) if not is_owner: if not is_sadmin: raise BadRequestError('You do not have access to this server.') # Attempt encryption/decryption rconDecrypt = util.decrypt(dbKey, server.rcon_password) form = ServerForm(request.form, display_name=server.display_name, ip_string=server.ip_string, port=server.port, rcon_password=server.rcon_password if rconDecrypt is None else rconDecrypt, public_server=server.public_server) if request.method == 'POST': if form.validate(): mock = app.config['TESTING'] data = form.data if not mock: encRcon = util.encrypt(dbKey, str(data['rcon_password'])) else: encRcon = data['rcon_password'] server.display_name = data['display_name'] server.ip_string = data['ip_string'] server.port = data['port'] server.rcon_password = encRcon server.public_server = (data['public_server'] and util.is_admin(g.user)) if mock or util.check_server_connection(server, dbKey): db.session.commit() return redirect('/myservers') else: db.session.remove() flash('Failed to connect to server') else: flash_errors(form) return render_template('server_create.html', user=g.user, form=form, edit=True, is_admin=util.is_admin(g.user), is_sadmin=util.is_super_admin(g.user))
def main(argv): if not 0x02070000 < sys.hexversion < 0x02080000: sys.stderr.write("Python 2.7 is required. Exiting.\n") return 1 options, arguments = parse_args(argv) if not util.is_admin(): sys.stderr.write("Must be root/admin. Exiting.\n") return 1 system = sysiface.SystemFactory().build() eigrpserv = EIGRP( requested_ifaces=options.interface, import_routes=options.import_routes, port=options.admin_port, kvalues=options.kvalues, hello_interval=options.hello_interval, system=system, logconfig=options.log_config, rid=options.router_id, asn=options.as_number, admin_port=options.admin_port, ) eigrpserv.run()
def season_create(): if not g.user: return redirect('/login') form = SeasonForm(request.form) if request.method == 'POST': num_seasons = g.user.seasons.count() max_seasons = config_setting('USER_MAX_SEASONS') if max_seasons >= 0 and num_seasons >= max_seasons and not (util.is_admin(g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of seasons ({}) created'.format( num_seasons)) elif form.validate(): season = Season.create( g.user, form.data['season_title'], form.data['start_date'], form.data['end_date']) db.session.commit() app.logger.info('User {} created season {}' .format(g.user.id, season.id)) return redirect('/myseasons') else: get5.flash_errors(form) return render_template( 'season_create.html', form=form, user=g.user)
def server_create(): if not g.user: return redirect('/login') form = ServerForm(request.form) if request.method == 'POST': num_servers = g.user.servers.count() max_servers = config_setting('USER_MAX_SERVERS') if max_servers >= 0 and num_servers >= max_servers and not ( util.is_admin(g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of servers ({}) stored'. format(num_servers)) elif form.validate(): mock = config_setting('TESTING') data = form.data if not mock: encRcon = util.encrypt(dbKey, str(data['rcon_password'])) else: encRcon = data['rcon_password'] server = GameServer.create( g.user, data['display_name'], data['ip_string'], data['port'], encRcon, data['public_server'] and util.is_admin(g.user)) if mock or util.check_server_connection(server, dbKey): db.session.commit() app.logger.info('User {} created server {}'.format( g.user.id, server.id)) return redirect('/myservers') else: db.session.remove() flash('Failed to connect to server') else: flash_errors(form) return render_template('server_create.html', user=g.user, form=form, edit=False, is_admin=util.is_admin(g.user))
def check_private_or_public(user, match, team1, team2): if match.is_private_match(): if not user: raise BadRequestError("Please login before viewing this match.") # Get team lists, and check if logged in user is part of match. if (user.id == match.user_id) or (config_setting( 'ADMINS_ACCESS_ALL_MATCHES') and util.is_admin(user)) or util.is_super_admin(user): isPlayer = False playerstats_steam = [r.steam_id for r in PlayerStats.query.filter( PlayerStats.match_id == match.id)] playerList = list( set(team1.auths + team2.auths + playerstats_steam)) app.logger.info("Our list: {}".format(playerList)) if (config_setting('ADMINS_ACCESS_ALL_MATCHES') and util.is_admin(user)) or util.is_super_admin(user): isPlayer = True else: for player in playerList: if user.steam_id == player: isPlayer = True break if not isPlayer: raise BadRequestError( "You cannot view this match as you were not a part of it!")
def admintools_check(user, match): if user is None: raise BadRequestError('You do not have access to this page') grant_admin_access = util.is_admin(user) and get5.config_setting( 'ADMINS_ACCESS_ALL_MATCHES') if user.id != match.user_id and not grant_admin_access: raise BadRequestError('You do not have access to this page') if match.finished(): raise BadRequestError('Match already finished') if match.cancelled: raise BadRequestError('Match is cancelled')
def create(user, name, tag, flag, logo, auths, public_team=False, preferred_names=None): rv = Team() rv.user_id = user.id rv.set_data(name, tag, flag, logo, auths, (public_team and util.is_admin(user)), preferred_names) db.session.add(rv) return rv
def useradd_linux(p_user): print("Creating the user " + p_user) if not util.get_platform() == "Linux": print("ERROR: USERADD is a Linux only command.") return (1) if not util.is_admin(): print("ERROR: Must be ROOT to run USERADD.") return (1) ## make sure the user exists.... util.run_sudo("useradd -m " + p_user) return (0)
def main(argv): if not (0x02070000 < sys.hexversion < 0x02080000): sys.stderr.write("Python 2.7 is required. Exiting.") return 1 options, arguments = parse_args(argv) # Must run as root/admin to manipulate the routing table. if not util.is_admin(): sys.stderr.write( "Must run as a privileged user (root/admin/etc.). Exiting.\n") return 1 RIP(options.rip_port, options.route, options.import_routes, options.interface, options.log_config, options.base_timer, options.admin_port)
def match(matchid): match = Match.query.get_or_404(matchid) # Begin Private/Public Match Implementation vetoes = Veto.query.filter_by(match_id=matchid) if match.server_id: server = GameServer.query.get_or_404(match.server_id) else: server = None team1 = Team.query.get_or_404(match.team1_id) team2 = Team.query.get_or_404(match.team2_id) check_private_or_public(g.user, match, team1, team2) map_stat_list = match.map_stats.all() completed = match.winner try: if server is not None and (completed is None and match.cancelled == 0): password = server.receive_rcon_value('sv_password') connect_string = str("steam://connect/") + str(server.ip_string) + str(":") + \ str(server.port) + str("/") + str(password) gotv_port = server.receive_rcon_value('tv_port') gotv_string = str("steam://connect/") + str(server.ip_string) + str(":") + \ str(gotv_port) else: connect_string = None gotv_string = None except util.RconError as e: connect_string = None gotv_string = None app.logger.info('Attempted to connect to server {}, but it is offline' .format(server.ip_string)) is_match_owner = False is_server_op = False has_admin_access = False has_super_admin_access = False if g.user: is_match_owner = (g.user.id == match.user_id) has_admin_access = (config_setting( 'ADMINS_ACCESS_ALL_MATCHES') and util.is_admin(g.user)) has_super_admin_access = util.is_super_admin(g.user) is_server_op = util.is_server_owner(g.user, server) return render_template( 'match.html', user=g.user, admin_access=has_admin_access, match=match, team1=team1, team2=team2, map_stat_list=map_stat_list, completed=completed, connect_string=connect_string, gotv_string=gotv_string, super_admin_access=has_super_admin_access, vetoes=vetoes, server_owner=is_server_op, match_owner=is_match_owner)
async def reset(ctx): logger('reset',ctx) if is_admin(ctx.message.author): await ctx.send('clearing the cache') if os.path.exists('word_cloud.png'): # delete the last word cloud os.remove('word_cloud.png') if os.path.exists('downloads'): # delete cached google images shutil.rmtree('downloads') if os.path.exists('source.m4a'): # delete the last youtube sound file os.remove('source.m4a') await ctx.send('cache cleared') await ctx.send('restarting the bot') os.execv('turkey-bot/bot.py', sys.argv) # restart the bot else: await ctx.send('you are not authorized to use this command :rage:')
async def friend_message_listener(bot_app: GraiaMiraiApplication, message: MessageChain, friend: Friend): # Interpreter commands. input_msg = message.asDisplay() if util.is_admin(str(friend.id)): logging.info(f"Detected message from admin: {friend.id}") msg_send = factory.exec_bot_command_friend_admin(input_msg) else: logging.info(f"Detected message from friend: {friend.id}") msg_send = factory.exec_bot_command_friend(input_msg) if msg_send is not None: await bot_app.sendFriendMessage(friend, message.create([Plain(msg_send)])) else: logging.warning( "No message will be send. May be there are some errors.")
async def update(ctx): logger('update',ctx) if is_admin(ctx.message.author): await ctx.send('updating the bot') if os.path.exists('bot.py'): # remove the old source file os.remove('bot.py') if os.path.exists('turkey-bot'): # remove old cloned directory shutil.rmtree('turkey-bot') git('clone', 'https://github.com/h4sohail/turkey-bot.git') # Clones repo if os.path.exists('turkey-bot/bot.py'): # move file to working directory os.replace('turkey-bot/bot.py', '../turkey-bot/bot.py') # set execute permissions st = os.stat('bot.py') os.chmod('bot.py', st.st_mode | stat.S_IEXEC) if os.path.exists('turkey-bot'): # cleanup shutil.rmtree('turkey-bot') else: await ctx.send('You are not authorized to use this command.')
def main(args): if not util.is_admin(): print("Must run as root/admin. Exiting.") return 1 try: ip = args[1] user = args[2] logconfig = args[3] except: print("Usage: ./rtpchat.py ip user logconfig") return 1 system = sysiface.SystemFactory().build() rtpchat = RTPChat(user, RTPChat.GTK_UI, ip, system=system, logconfig=logconfig) rtpchat.run()
def main(args): if not util.is_admin(): print("Must run as root/admin. Exiting.") return 1 try: ip = args[1] user = args[2] logconfig = args[3] except: print("Usage: ./rtpchat.py ip user logconfig") return 1 system = sysiface.SystemFactory(0, 0).build() chat = DropPacketsRTPChat(user, DropPacketsRTPChat.GTK_UI, ip, system=system, logconfig=logconfig) rtp_control.make_hooks(chat) chat.run()
def info(p_json, p_home, p_repo, print_flag=True): import os p_user = util.get_user() p_is_admin = util.is_admin() pip_ver = get_pip_ver() this_os = "" this_uname = str(platform.system()) host_ip = util.get_host_ip() wmic_path = os.getenv("SYSTEMROOT", "") + os.sep + "System32" + os.sep + "wbem" + os.sep + "wmic" if this_uname == "Windows": import psutil host_display = os.getenv('LOGONSERVER','') + '\\' + os.getenv('COMPUTERNAME') system_cpu_cores = os.getenv('NUMBER_OF_PROCESSORS','1') os_arch = os.getenv('PROCESSOR_ARCHITECTURE', '') cpu_model = check_output_wmic([wmic_path, "cpu", "get", "name"]) ## system_memory_in_gb ###################################### m = psutil.virtual_memory().total mem_bytes = int(m) system_memory_in_kbytes = mem_bytes / 1024.0 system_memory_in_gb = str(mem_bytes / (1024.0**3)) else: os_arch = util.getoutput("uname -m") host_display = util.get_host_short() ## Check the OS & Resources ######################################## plat = util.get_os() os_major_ver = "" if this_uname == "Darwin": mem_mb = util.get_mem_mb() system_memory_in_kbytes = mem_mb * 1024 system_memory_in_gb = mem_mb / 1024.0 system_cpu_cores = util.get_cpu_cores() cpu_model=util.getoutput("/usr/sbin/sysctl -n machdep.cpu.brand_string") prod_name = util.getoutput("sw_vers -productName") prod_version = util.getoutput("sw_vers -productVersion") this_os = prod_name + " " + prod_version elif this_uname == "Linux": mem_mb = util.get_mem_mb() system_memory_in_kbytes = mem_mb * 1024 system_memory_in_gb = mem_mb / 1024.0 system_cpu_cores = util.get_cpu_cores() cpu_model=util.getoutput("grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2") os_major_ver = util.getoutput("cat /etc/os-release | grep VERSION_ID | cut -d= -f2 | tr -d '\"'") if cpu_model == "": cpu_model="ARM" if os.path.exists("/etc/redhat-release"): this_os = util.getoutput("cat /etc/redhat-release") elif os.path.exists("/etc/system-release"): this_os = util.getoutput("cat /etc/system-release") elif os.path.exists("/etc/lsb-release"): this_os = util.getoutput("cat /etc/lsb-release | grep DISTRIB_DESCRIPTION | cut -d= -f2 | tr -d '\"'") elif os.path.exists("/etc/os-release"): this_os = util.getoutput("cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | tr -d '\"'") elif this_uname == "Windows": caption = check_output_wmic([wmic_path, "os", "get", "caption"]) svcpack = check_output_wmic([wmic_path, "os", "get", "servicepackmajorversion"]) if svcpack == "0": this_os = caption else: this_os = caption + ", SP " + svcpack round_mem = util.pretty_rounder(float(system_memory_in_gb), 1) mem = str(round_mem) + " GB" cores = str(system_cpu_cores) cpu = cpu_model.strip() cpu = cpu.replace("(R)", "") cpu = cpu.replace("(TM)", "") cpu = cpu.replace(" CPU ", " ") os = this_os.replace(" release ", " ") os = os.replace(" (Final)", "") arch = os_arch.replace("x86_64", "AMD") arch = arch.replace("AMD64", "AMD") ver = util.get_version() [last_update_utc, last_update_local, unique_id] = util.read_hosts('localhost') if last_update_local: last_upd_dt = datetime.strptime(last_update_local, "%Y-%m-%d %H:%M:%S") time_diff = int(util.timedelta_total_seconds(datetime.now() - last_upd_dt)) last_update_readable = util.get_readable_time_diff(str(time_diff), precision=2) versions_sql = util.get_versions_sql() perl_ver = util.get_perl_ver() [java_major_ver, java_ver] = util.get_java_ver() os_pkg_mgr = util.get_pkg_mgr() jvm_location = util.get_jvm_location() if p_json: infoJsonArray = [] infoJson = {} infoJson['version'] = ver infoJson['home'] = p_home infoJson['user'] = p_user infoJson['host'] = host_display infoJson['host_short'] = util.get_host_short() infoJson['host_long'] = util.get_host() infoJson['host_ip'] = util.get_host_ip() infoJson['os'] = unicode(str(os),sys.getdefaultencoding(),errors='ignore').strip() infoJson['os_pkg_mgr'] = os_pkg_mgr infoJson['os_major_ver'] = os_major_ver infoJson['platform'] = unicode(str(plat),sys.getdefaultencoding(),errors='ignore').strip() infoJson['arch'] = arch infoJson['mem'] = round_mem infoJson['cores'] = system_cpu_cores infoJson['cpu'] = cpu infoJson['last_update_utc'] = last_update_utc if last_update_local: infoJson['last_update_readable'] = last_update_readable infoJson['unique_id'] = unique_id infoJson['repo'] = p_repo infoJson['versions_sql'] = versions_sql infoJson['system_memory_in_kb'] = system_memory_in_kbytes infoJson['python_ver'] = python_ver infoJson['python_exe'] = python_exe if pip_ver != 'None': infoJson['pip_ver'] = pip_ver infoJson['perl_ver'] = perl_ver infoJson['java_ver'] = java_ver infoJson['java_major_ver'] = java_major_ver infoJson['jvm_location'] = jvm_location infoJsonArray.append(infoJson) if print_flag: print(json.dumps(infoJson)) return else: return infoJson if p_is_admin: admin_display = " (Admin)" else: admin_display = "" langs = "Python v" + python_ver if perl_ver > "": langs = langs + " | Perl v" + perl_ver if java_ver > "": langs = langs + " | Java v" + java_ver util.validate_distutils_click(False) print(style_start + ("#" * 70) + style_end) print(style_start + "# IO: " + style_end + "v" + ver + " " + p_home) print(style_start + "# User & Host: " + style_end + p_user + admin_display + " " + host_display) print(style_start + "# Operating System: " + style_end + os.rstrip() + " - " + str(plat)) print(style_start + "# Machine: " + style_end + mem + ", " + cores + " vCPU, " + cpu) print(style_start + "# Programming Langs: " + style_end + langs) default_repo = "https://openrds-download.s3.amazonaws.com/REPO" if p_repo != default_repo: print(style_start + "# Repo URL: " + style_end + p_repo) if versions_sql == "versions.sql": pass else: print(style_start + "# Versions SQL: " + style_end + versions_sql) if not last_update_local: last_update_local="None" print(style_start + "# Last Update: " + style_end + str(last_update_local)) print(style_start + ("#" * 70) + style_end)
def match_create(): if not g.user: return redirect('/login') form = MatchForm(request.form) form.add_teams(g.user) form.add_servers(g.user) form.add_seasons() if request.method == 'POST': num_matches = g.user.matches.count() max_matches = config_setting('USER_MAX_MATCHES') season_id = None if max_matches >= 0 and num_matches >= max_matches and not (util.is_admin(g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of matches ({}) created'.format( num_matches)) elif form.validate(): mock = config_setting('TESTING') server = GameServer.query.get_or_404(form.data['server_id']) match_on_server = g.user.matches.filter_by( server_id=server.id, end_time=None, cancelled=False).first() server_available = False json_reply = None if g.user.id != server.user_id and not server.public_server: server_available = False message = 'This is not your server!' elif match_on_server is not None: server_available = False message = 'Match {} is already using this server'.format( match_on_server.id) elif mock: server_available = True message = 'Success' else: json_reply, message = util.check_server_avaliability( server, dbKey) server_available = (json_reply is not None) if server_available: skip_veto = 'preset' in form.data['series_type'] try: max_maps = int(form.data['series_type'][2]) except ValueError: max_maps = 1 if form.data['season_selection'] != 0: season_id = form.data['season_selection'] # Series Score Feature. team1_series_score = form.data[ 'team1_series_score'] if not None else 0 team2_series_score = form.data[ 'team2_series_score'] if not None else 0 # End Series Score Feature. # Spectator Feature specList = [] if form.data['spectator_string']: for auth in form.data['spectator_string'].split(): suc, new_auth = steamid.auth_to_steam64(auth) if suc: specList.append(new_auth) if not specList: specList = None # End Spectator Feature match = Match.create( g.user, form.data['team1_id'], form.data['team2_id'], form.data['team1_string'], form.data['team2_string'], max_maps, skip_veto, form.data['match_title'], form.data['veto_mappool'], season_id, form.data['side_type'], form.data['veto_first'], form.data['server_id'], team1_series_score, team2_series_score, specList, form.data['private_match'], form.data['enforce_teams']) # Save plugin version data if we have it if json_reply and 'plugin_version' in json_reply: match.plugin_version = json_reply['plugin_version'] else: match.plugin_version = 'unknown' server.in_use = True db.session.commit() app.logger.info('User {} created match {}, assigned to server {}' .format(g.user.id, match.id, server.id)) if mock or match.send_to_server(): return redirect('/mymatches') else: flash('Failed to load match configs on server') else: flash(message) else: get5.flash_errors(form) return render_template( 'match_create.html', form=form, user=g.user, teams=g.user.teams, match_text_option=config_setting('CREATE_MATCH_TITLE_TEXT'))
def info(p_json, p_home, p_repo, print_flag=True): import os p_user = util.get_user() p_is_admin = util.is_admin() this_os = "" this_uname = str(platform.system()) host_ip = util.get_host_ip() wmic_path = os.getenv( "SYSTEMROOT", "") + os.sep + "System32" + os.sep + "wbem" + os.sep + "wmic" if this_uname == "Windows": import psutil host_display = os.getenv('LOGONSERVER', '') + '\\' + os.getenv('COMPUTERNAME') system_cpu_cores = os.getenv('NUMBER_OF_PROCESSORS', '1') os_arch = os.getenv('PROCESSOR_ARCHITECTURE', '') cpu_model = subprocess.check_output([wmic_path, "cpu", "get", "name"]).strip().split("\n")[1] ## system_memory_in_gb ###################################### m = psutil.virtual_memory().total mem_bytes = int(m) system_memory_in_kbytes = mem_bytes / 1024.0 system_memory_in_gb = mem_bytes / (1024.0**3) else: os_arch = util.getoutput("uname -m") HOST = util.get_host_short() host_display = "{0} {1}".format(HOST, host_ip) ## Check the OS & Resources ######################################## plat = util.get_os() if this_uname == "Darwin": system_memory_in_bytes = int( util.getoutput("/usr/sbin/sysctl hw.memsize | awk '{print $2}'")) system_memory_in_kbytes = system_memory_in_bytes / 1024 system_memory_in_gb = system_memory_in_bytes / 1024 / 1024 / 1024 system_cpu_cores = int( util.getoutput( "/usr/sbin/sysctl hw.physicalcpu | awk '{print $2}'")) cpu_model = util.getoutput( "/usr/sbin/sysctl -n machdep.cpu.brand_string") prod_name = util.getoutput("sw_vers -productName") prod_version = util.getoutput("sw_vers -productVersion") this_os = prod_name + " " + prod_version elif this_uname == "Linux": system_memory_in_kbytes = int( util.getoutput("cat /proc/meminfo | awk '/MemTotal/ {print $2}'")) system_memory_in_gb = system_memory_in_kbytes / 1024.0 / 1024.0 system_cpu_cores = int( util.getoutput( "egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo")) cpu_model = util.getoutput( "grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2") if os.path.exists("/etc/redhat-release"): this_os = util.getoutput("cat /etc/redhat-release") elif os.path.exists("/etc/system-release"): this_os = util.getoutput("cat /etc/system-release") elif os.path.exists("/etc/lsb-release"): this_os = util.getoutput( "cat /etc/lsb-release | grep DISTRIB_DESCRIPTION | cut -d= -f2 | tr -d '\"'" ) elif this_uname == "Windows": caption_result = subprocess.check_output( [wmic_path, "os", "get", "caption"]) try: caption = str(caption_result).strip().split("\n")[1] except UnicodeDecodeError as e: caption = unicode(caption_result, sys.getdefaultencoding(), errors='ignore').strip().split("\n")[1] svcpack_result = subprocess.check_output( [wmic_path, "os", "get", "servicepackmajorversion"]) try: svcpack = str(svcpack_result).strip().split("\n")[1] except UnicodeDecodeError as e: svcpack = unicode(svcpack_result, sys.getdefaultencoding(), errors='ignore').strip().split("\n")[1] if svcpack == "0": this_os = caption else: this_os = caption + ", SP " + svcpack round_mem = util.pretty_rounder(system_memory_in_gb, 1) mem = str(round_mem) + " GB" cores = str(system_cpu_cores) + " x" cpu = cpu_model.strip() cpu = cpu.replace("(R)", "") cpu = cpu.replace("(TM)", "") cpu = cpu.replace(" CPU ", " ") os = this_os.replace(" release ", " ") os = os.replace(" (Final)", "") arch = os_arch.replace("x86_64", "x64") arch = arch.replace("AMD64", "x64") ver = util.get_pgc_version() [ interval, last_update_utc, next_update_utc, last_update_local, next_update_local, unique_id ] = util.read_hosts('localhost') if last_update_local: last_upd_dt = datetime.strptime(last_update_local, "%Y-%m-%d %H:%M:%S") time_diff = int( util.timedelta_total_seconds(datetime.now() - last_upd_dt)) last_update_readable = util.get_readable_time_diff(str(time_diff), precision=2) versions_sql = util.get_versions_sql() if p_json: infoJsonArray = [] infoJson = {} infoJson['version'] = ver infoJson['home'] = p_home infoJson['user'] = p_user infoJson['host'] = host_display infoJson['host_short'] = util.get_host_short() infoJson['host_long'] = util.get_host() infoJson['host_ip'] = util.get_host_ip() infoJson['os'] = unicode(str(os), sys.getdefaultencoding(), errors='ignore').strip() infoJson['platform'] = unicode(str(plat), sys.getdefaultencoding(), errors='ignore').strip() infoJson['arch'] = arch infoJson['mem'] = round_mem infoJson['cores'] = system_cpu_cores infoJson['cpu'] = cpu infoJson['interval'] = interval infoJson['last_update_utc'] = last_update_utc if last_update_local: infoJson['last_update_readable'] = last_update_readable infoJson['next_update_utc'] = next_update_utc infoJson['unique_id'] = unique_id infoJson['repo'] = p_repo infoJson['versions_sql'] = versions_sql infoJson['system_memory_in_kb'] = system_memory_in_kbytes infoJson['python_ver'] = python_ver infoJson['python_exe'] = python_exe if pip_ver != 'None': infoJson['pip_ver'] = pip_ver infoJsonArray.append(infoJson) if print_flag: print(json.dumps(infoJsonArray, sort_keys=True, indent=2)) return else: return infoJson if p_is_admin: admin_display = " (Admin)" else: admin_display = "" print(style_start + ("#" * 70) + style_end) print(style_start + "# PGC: " + style_end + "v" + ver + " " + p_home) print(style_start + "# User & Host: " + style_end + p_user + admin_display + " " + host_display) print(style_start + "# Platform: " + style_end + plat + " | " + os.rstrip()) if pip_ver != "None": print(style_start + "# Python: " + style_end + "pip v" + pip_ver + \ " | v" + python_ver + " | " + python_exe) else: print(style_start + "# Python: " + style_end + "v" + python_ver + " | " + python_exe) print(style_start + "# Hardware: " + style_end + mem + ", " + cores + " " + cpu) default_repo = "https://s3.amazonaws.com/pgcentral" if p_repo != default_repo: print(style_start + "# Repo URL: " + style_end + p_repo) if versions_sql == "versions.sql": pass else: print(style_start + "# Versions SQL: " + style_end + versions_sql) if not last_update_local: last_update_local = "None" print(style_start + "# Last Update: " + style_end + str(last_update_local)) if interval: print(style_start + "# Update Interval: " + style_end + str(interval)) print(style_start + "# Next Update : " + style_end + str(next_update_local)) print(style_start + ("#" * 70) + style_end)
async def on_message(message): # runs on a new message being sent in the server global votes global voters global u_votes global u_voters global echoes_mode message_content = message.content # store message content in a variable author = message.author # grab the author name from the message if author == bot.user: # make sure the message was not sent by the bot return if vote: # check if votemute is active if (message_content == 'yes') and not(author in voters): # check if someone typed 'yes' votes['yes'] = votes['yes'] + 1 # add 1 to votes counter voters.append(author) # add author to voters list print(f'{author} voted yes') elif (message_content == 'no') and not(author in voters): # check if someone typed 'no' votes['no'] = votes['no'] + 1 # add 1 to the no counter voters.append(author) # add author to voters list print(f'{author} voted no') elif u_vote: # check if voteunmute is active if (message_content == 'yes') and not(author in u_voters): u_votes['yes'] = u_votes['yes'] + 1 u_voters.append(author) print(f'{author} voted yes') elif (message_content == 'no') and not(author in u_voters): u_votes['no'] = u_votes['no'] + 1 u_voters.append(author) print(f'{author} voted no') else: pass # TO-DO: To be decided if is_admin(author): if message_content == "!toggle echoes": echoes_mode = not echoes_mode if echoes_mode: await message.channel.send(f":moyai: Echoes Mode: ON :moyai:") else: await message.channel.send(f":moyai: Echoes Mode: OFF :moyai:") if (echoes_mode): if message.author.bot: return await message.add_reaction("🗿") await message.channel.send(f":moyai: {next(echoes_lyrics)} :moyai:") voice_channel = message.guild.get_channel(619595098279378977) try: vc = await voice_channel.connect() except: print(f"something went wrong :)") vc.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source="C:/Users/nullptr/Projects/Personal/justForAK/turkey-bot/sounds/echoes.mp3")) while vc.is_playing(): time.sleep(.1) if not vc.is_playing(): time.sleep(.3) await vc.disconnect() # log all messages sent in the server with a time stamp in the format YYYY:MM:DD HH:MM:SS dir = 'cache\log.txt' with open(dir, 'a') as f: time_stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') f.write(f"<{time_stamp}>{message_content}\n") await bot.process_commands(message) # tells bot to process the custom commands below
def team_edit(teamid): mock = config_setting("TESTING") customNames = config_setting("CUSTOM_PLAYER_NAMES") team = Team.query.get_or_404(teamid) if not team.can_edit(g.user): raise BadRequestError("Not your team.") form = TeamForm() # We wish to query this every time, since we can now upload photos. if not mock: form.logo.choices = logos.get_logo_choices() if request.method == 'GET': # Set values here, as per new FlaskForms. form.name.data = team.name form.tag.data = team.tag form.country_flag.data = team.flag form.logo.data = team.logo for field in form: if "auth" in field.name: try: field.data = team.auths[ int(re.search(r'\d+', field.name).group()) - 1] except: field.data = None if "pref_name" in field.name: try: field.data = team.preferred_names[ int(re.search(r'\d+', field.name).group()) - 1] except: field.data = None form.public_team.data = team.public_team return render_template('team_create.html', user=g.user, form=form, edit=True, is_admin=util.is_admin(g.user), MAXPLAYER=Team.MAXPLAYERS, customNames=customNames) elif request.method == 'POST': if form.validate(): data = form.data public_team = team.public_team if util.is_admin(g.user): public_team = data['public_team'] # Update the logo. Passing validation we have the filename in the # list now. if not mock and util.is_admin(g.user) and form.upload_logo.data: filename = secure_filename(form.upload_logo.data.filename) index_of_dot = filename.index('.') newLogoDetail = filename[:index_of_dot] # Reinit our logos. logos.add_new_logo(newLogoDetail) data['logo'] = newLogoDetail team.set_data(data['name'], data['tag'], data['country_flag'], data['logo'], form.get_auth_list(), public_team, form.get_pref_list()) db.session.commit() return redirect('/teams/{}'.format(team.user_id)) else: flash_errors(form) return render_template('team_create.html', user=g.user, form=form, edit=True, is_admin=util.is_admin(g.user), MAXPLAYER=Team.MAXPLAYERS)
def valid_file(form, field): if not field.data: return mock = config_setting("TESTING") if mock: return elif not util.is_admin(g.user): return filename = secure_filename(field.data.filename) # Safe method. if filename == '': return index_of_dot = filename.index('.') file_name_without_extension = filename[:index_of_dot] extension = filename.rsplit('.', 1)[1].lower() exists = os.path.isfile(app.config['LOGO_FOLDER'] + "/" + secure_filename(filename)) existsSVG = os.path.isfile(app.config['PANO_LOGO_FOLDER'] + "/" + secure_filename(filename)) if '.' not in filename: raise ValidationError('Image MUST be PNG or SVG.') elif extension not in {'svg', 'png'}: raise ValidationError('Image MUST be PNG or SVG.') elif len(filename.rsplit('.', 1)[0]) > 3: raise ValidationError('Image name can only be 3 characters long.') elif exists: raise ValidationError('Image already exists in PNG.') elif existsSVG: raise ValidationError('Image name already exists for SVG.') if extension == 'png': file = request.files['upload_logo'] img = Image.open(file) width, height = img.size out = io.BytesIO() if width != 64 or height != 64: app.logger.info("Resizing image as it is not 64x64.") img = img.resize((64, 64), Image.ANTIALIAS) img.save(out, format=extension) # check once more for size. if out.tell() > 16384: app.logger.info("Size: {}".format(out.tell())) raise ValidationError( 'Image is too large, must be 10kB or less.') img.save(os.path.join(app.config['LOGO_FOLDER'], filename), optimize=True) elif out.tell() > 16384: raise ValidationError('Image is too large, must be 10kB or less.') else: img.save(os.path.join(app.config['LOGO_FOLDER'], filename), optimize=True) else: file = request.files['upload_logo'] # Limited - attempt to find width and height. If nothing then deny # upload. tree = ET.parse(file) root = tree.getroot() try: width = root.attrib['width'] height = root.attrib['height'] except: raise ValidationError('SVG is not properly formatted.') if (width in {'64', '64px'}) and (height in {'64', '64px'}): tree.write(app.config['PANO_LOGO_FOLDER'] + "/" + secure_filename(filename)) else: raise ValidationError("Error in saving SVG to folder.")
os.mkdir(data_root) if args.datadir == "": pg_data = os.path.join(data_root, pgver) else: pg_data = args.datadir if not os.path.isdir(pg_data): os.mkdir(pg_data) ## SVCUSER ########################################### svcuser = "" curr_user = "" svcuser = args.svcuser if util.is_admin(): if svcuser == "": svcuser = "******" ## PASSWD ############################################# is_password = False pgpass_file = pg_home + os.sep + ".pgpass" if args.pwfile: pgpass_file = args.pwfile if not os.path.isfile(pgpass_file): fatal_error("Error: Invalid --pwfile") if os.path.isfile(pgpass_file): is_password = True file = open(pgpass_file, 'r') line = file.readline()
if args.datadir == "": pg_data = os.path.join(data_root, pgver) else: pg_data = args.datadir if not os.path.isdir(pg_data): os.mkdir(pg_data) ## SVCUSER ########################################### svcuser = "" curr_user = "" if util.get_platform() == "Linux": svcuser = args.svcuser if util.is_admin(): if svcuser == "": svcuser = "******" else: if svcuser > "": fatal_error("ERROR: --svcuser cannot be specified if not root") svcuser = util.get_user() curr_user = svcuser ## PASSWD ############################################# is_password = False pgpass_file = pg_home + os.sep + ".pgpass" if args.pwfile: pgpass_file = args.pwfile if not os.path.isfile(pgpass_file): fatal_error("Error: Invalid --pwfile")