def mpMake(): if len(message) < 2: raise exceptions.invalidArgumentsException("Wrong syntax: !mp make <name>") matchName = " ".join(message[1:]).strip() if not matchName: raise exceptions.invalidArgumentsException("Match name must not be empty!") matchID = glob.matches.createMatch(matchName, generalUtils.stringMd5(generalUtils.randomString(32)), 0, "Tournament", "", 0, -1, isTourney=True) glob.matches.matches[matchID].sendUpdates() return "Tourney match #{} created!".format(matchID)
def asyncPost(self): try: if glob.conf["DEBUG"]: requestsManager.printArguments(self) # Make sure screenshot file was passed if "ss" not in self.request.files: raise exceptions.invalidArgumentsException(MODULE_NAME) # Check user auth because of sneaky people if not requestsManager.checkArguments(self.request.arguments, ["u", "p"]): raise exceptions.invalidArgumentsException(MODULE_NAME) username = self.get_argument("u") password = self.get_argument("p") ip = self.getRequestIP() userID = userUtils.getID(username) if not userUtils.checkLogin(userID, password): raise exceptions.loginFailedException(MODULE_NAME, username) if userUtils.check2FA(userID, ip): raise exceptions.need2FAException(MODULE_NAME, username, ip) # Rate limit if glob.redis.get("lets:screenshot:{}".format(userID)) is not None: self.write("no") return glob.redis.set("lets:screenshot:{}".format(userID), 1, 60) # Get a random screenshot id found = False screenshotID = "" while not found: screenshotID = generalUtils.randomString(8) if not os.path.isfile("{}/{}.jpg".format( glob.conf["SCREENSHOTS_FOLDER"], screenshotID)): found = True # Write screenshot file to .data folder with open( "{}/{}.jpg".format(glob.conf["SCREENSHOTS_FOLDER"], screenshotID), "wb") as f: f.write(self.request.files["ss"][0]["body"]) # Output log.info("New screenshot ({})".format(screenshotID)) # Return screenshot link self.write("{}/ss/{}.jpg".format(glob.conf["SERVER_URL"], screenshotID)) except exceptions.need2FAException: pass except exceptions.invalidArgumentsException: pass except exceptions.loginFailedException: pass
def mpHost(): if len(message) < 2: raise exceptions.invalidArgumentsException("Wrong syntax: !mp host <username>") username = message[1].strip() if not username: raise exceptions.invalidArgumentsException("Please provide a username") userID = userUtils.getIDSafe(username) if userID is None: raise exceptions.userNotFoundException("No such user") _match = glob.matches.matches[getMatchIDFromChannel(chan)] success = _match.setHost(userID) return "{} is now the host".format(username) if success else "Couldn't give host to {}".format(username)
def asyncGet(self): statusCode = 400 response = {'message': "invalid parameters"} try: # Check args if not requestsManager.checkArguments( self.request.arguments, ['k', 'matchName', 'gameMode', 'isTourney']): raise exceptions.invalidArgumentsException() # Check ci key key = self.get_argument('k') if key is None or key != glob.conf.config["server"]["cikey"]: response[ 'message'] = 'Bad secret key. You are not allowed to access to this api.' raise exceptions.invalidArgumentsException() matchName = self.get_argument('matchName') gameMode = getGameModeForMatchAPI(self.get_argument('gameMode')) isTourney = self.get_argument('isTourney') if isTourney == 'True': isTourney = True elif isTourney == 'False': isTourney = False else: response[ 'message'] = 'isTourney is requirement not optional. Only accepts True or False' raise exceptions.invalidArgumentsException() if gameMode is None: response[ 'message'] = 'Oh my we only accepts gameMode std, taiko, ctb and mania' raise exceptions.invalidArgumentsException() matchID = glob.matches.createMatch( matchName, generalUtils.stringMd5(generalUtils.randomString(32)), 0, "Tournament", "", gameMode, -1, isTourney=isTourney) glob.matches.matches[matchID].sendUpdates() response = {"matchID": matchID} statusCode = 200 except exceptions.invalidArgumentsException: statusCode = 400 self.write(json.dumps(response)) self.set_status(statusCode)
def removeReferee(response, token, sender, channel, message): if len(message) < 1: raise exceptions.invalidArgumentsException( "Wrong syntax: !mp rmref <user>") _match = getCurrentMatch(channel) username = message[0].strip() if not username: raise exceptions.invalidArgumentsException( "Please provide a username") userID = lookupUser(username) _match.removeReferee(userID) response.setContent(token, "Removed {} to referees".format(username))
def asyncPost(self): try: if glob.debug: requestsManager.printArguments(self) # Make sure screenshot file was passed if "ss" not in self.request.files: raise exceptions.invalidArgumentsException(MODULE_NAME) # Check user auth because of sneaky people if not requestsManager.checkArguments(self.request.arguments, ["u", "p"]): raise exceptions.invalidArgumentsException(MODULE_NAME) username = self.get_argument("u") password = self.get_argument("p") ip = self.getRequestIP() userID = userUtils.getID(username) if not userUtils.checkLogin(userID, password): raise exceptions.loginFailedException(MODULE_NAME, username) if userUtils.check2FA(userID, ip): raise exceptions.need2FAException(MODULE_NAME, username, ip) # Rate limit if glob.redis.get("lets:screenshot:{}".format(userID)) is not None: self.write("no") return glob.redis.set("lets:screenshot:{}".format(userID), 1, 60) # Get a random screenshot id found = False screenshotID = "" while not found: screenshotID = generalUtils.randomString(8) if not os.path.isfile(".data/screenshots/{}.png".format(screenshotID)): found = True glob.db.execute("INSERT INTO screenshots (userid, ssid, sstime) VALUES (%s, %s, %s)", [userID, screenshotID, int(time.time())]); # Write screenshot file to .data folder with open(".data/screenshots/{}.png".format(screenshotID), "wb") as f: f.write(self.request.files["ss"][0]["body"]) # Output log.info("New screenshot ({})".format(screenshotID)) # Return screenshot link self.write("{}/ss/{}.png".format(glob.conf.config["server"]["serverurl"], screenshotID)) except exceptions.need2FAException: pass except exceptions.invalidArgumentsException: pass except exceptions.loginFailedException: pass
def mpJoin(): if len(message) < 2 or not message[1].isdigit(): raise exceptions.invalidArgumentsException("Wrong syntax: !mp join <id>") matchID = int(message[1]) userToken = glob.tokens.getTokenFromUsername(fro, ignoreIRC=True) if userToken is None: raise exceptions.invalidArgumentsException( "No game clients found for {}, can't join the match. " "If you're a referee and you want to join the chat " "channel from IRC, use /join #multi_{} instead.".format(fro, matchID) ) userToken.joinMatch(matchID) return "Attempting to join match #{}!".format(matchID)
def asyncGet(self): try: args = {} try: # Check user auth because of sneaky people if not requestsManager.checkArguments(self.request.arguments, ["u", "h"]): raise exceptions.invalidArgumentsException(MODULE_NAME) username = self.get_argument("u") password = self.get_argument("h") ip = self.getRequestIP() userID = userUtils.getID(username) if not userUtils.checkLogin(userID, password): raise exceptions.loginFailedException(MODULE_NAME, username) if userUtils.check2FA(userID, ip): raise exceptions.need2FAException(MODULE_NAME, username, ip) # Get arguments gameMode = self.get_argument("m", None) if gameMode is not None: gameMode = int(gameMode) try: if gameMode < 0 or gameMode > 3: gameMode = None except: gameMode = None rankedStatus = self.get_argument("r", None) if rankedStatus is not None: rankedStatus = int(rankedStatus) query = self.get_argument("q", "") page = int(self.get_argument("p", "0")) if query.lower() in ["newest", "top rated", "most played"]: query = "" except ValueError: raise exceptions.invalidArgumentsException(MODULE_NAME) # Pass all arguments otherwise it doesn't work for key, _ in self.request.arguments.items(): args[key] = self.get_argument(key) # Get data from cheesegull API log.info("{} has requested osu!direct search: {}".format(username, query if query != "" else "index")) response = requests.get("http://ripple.moe/web/osu-search.php?{}".format(urlencode(args))) self.write(response.text) except Exception as e: log.error("search failed: {}".format(e)) self.write("")
def mpTeam(): if len(message) < 3: raise exceptions.invalidArgumentsException("Wrong syntax: !mp team <username> <colour>") username = message[1].strip() if not username: raise exceptions.invalidArgumentsException("Please provide a username") colour = message[2].lower().strip() if colour not in ["red", "blue"]: raise exceptions.invalidArgumentsException("Team colour must be red or blue") userID = userUtils.getIDSafe(username) if userID is None: raise exceptions.userNotFoundException("No such user") _match = glob.matches.matches[getMatchIDFromChannel(chan)] _match.changeTeam(userID, matchTeams.BLUE if colour == "blue" else matchTeams.RED) return "{} is now in {} team".format(username, colour)
def asyncPost(self): statusCode = 400 data = {"message": "unknown error"} try: # Check arguments if not requestsManager.checkArguments(self.request.arguments, ["sid", "refresh"]): raise exceptions.invalidArgumentsException(MODULE_NAME) # Get beatmap set data from osu api beatmapSetID = self.get_argument("sid") refresh = int(self.get_argument("refresh")) if refresh == 1: log.debug("Forced refresh") apiResponse = osuapiHelper.osuApiRequest( "get_beatmaps", "s={}".format(beatmapSetID), False) if len(apiResponse) == 0: raise exceptions.invalidBeatmapException # Loop through all beatmaps in this set and save them in db data["maps"] = [] for i in apiResponse: log.debug("Saving beatmap {} in db".format(i["file_md5"])) bmap = beatmap.beatmap(i["file_md5"], int(i["beatmapset_id"]), refresh=refresh) pp = glob.db.fetch( "SELECT pp_100 FROM beatmaps WHERE beatmap_id = %s LIMIT 1", [bmap.beatmapID]) if pp is None: pp = 0 else: pp = pp["pp_100"] data["maps"].append({ "id": bmap.beatmapID, "name": bmap.songName, "status": bmap.rankedStatus, "frozen": bmap.rankedStatusFrozen, "pp": pp, }) # Set status code and message statusCode = 200 data["message"] = "ok" except exceptions.invalidArgumentsException: # Set error and message statusCode = 400 data["message"] = "missing required arguments" except exceptions.invalidBeatmapException: statusCode = 400 data["message"] = "beatmap not found from osu!api." finally: # Add status code to data data["status"] = statusCode # Send response self.write(json.dumps(data)) self.set_header("Content-Type", "application/json") #self.add_header("Access-Control-Allow-Origin", "*") self.set_status(statusCode)
def asyncGet(self): try: # Argument check if not requestsManager.checkArguments(self.request.arguments, ["u", "h"]): raise exceptions.invalidArgumentsException(MODULE_NAME) username = self.get_argument("u") password = self.get_argument("h")
def asyncPost(self): try: # Required arguments check if not requestsManager.checkArguments(self.request.arguments, ("u", "p", "a")): raise exceptions.invalidArgumentsException(MODULE_NAME) # Get arguments username = self.get_argument("u") password = self.get_argument("p") action = self.get_argument("a").strip().lower() # IP for session check ip = self.getRequestIP() # Login and ban check userID = userUtils.getID(username) if userID == 0: raise exceptions.loginFailedException(MODULE_NAME, userID) if not userUtils.checkLogin(userID, password, ip): raise exceptions.loginFailedException(MODULE_NAME, username) if userUtils.check2FA(userID, ip): raise exceptions.need2FAException(MODULE_NAME, userID, ip) if userUtils.isBanned(userID): raise exceptions.userBannedException(MODULE_NAME, username) # Action (depends on 'action' parameter, not on HTTP method) if action == "get": self.write(self._getComments()) elif action == "post": self._addComment() except (exceptions.loginFailedException, exceptions.need2FAException, exceptions.userBannedException): self.write("error: no")
def mpMods(): if len(message) < 2: raise exceptions.invalidArgumentsException( "Wrong syntax: !mp <mod1> [<mod2>] ...") _match = glob.matches.matches[getMatchIDFromChannel(chan)] newMods = 0 freeMod = False for _mod in message[1:]: if _mod.lower().strip() == "hd": newMods |= mods.HIDDEN elif _mod.lower().strip() == "hr": newMods |= mods.HARDROCK elif _mod.lower().strip() == "dt": newMods |= mods.DOUBLETIME elif _mod.lower().strip() == "fl": newMods |= mods.FLASHLIGHT elif _mod.lower().strip() == "fi": newMods |= mods.FADEIN if _mod.lower().strip() == "none": newMods = 0 if _mod.lower().strip() == "freemod": freeMod = True _match.matchModMode = matchModModes.FREE_MOD if freeMod else matchModModes.NORMAL _match.resetReady() if _match.matchModMode == matchModModes.FREE_MOD: _match.resetMods() _match.changeMods(newMods) return "Match mods have been updated!"
def host(response, token, sender, channel, message): if len(message) < 1: raise exceptions.invalidArgumentsException( "Wrong syntax: !mp host <username>") username = message[0].strip() if not username: raise exceptions.invalidArgumentsException( "Please provide a username") userID = lookupUser(username) _match = getCurrentMatch(channel) success = _match.setHost(userID) result = "{} is now the host".format( username) if success else "Couldn't give host to {}".format( username) response.setContent(token, result) response.listen_in = [token.token]
def mpSize(): if len(message) < 2 or not message[1].isdigit() or int(message[1]) < 2 or int(message[1]) > 16: raise exceptions.invalidArgumentsException("Wrong syntax: !mp size <slots(2-16)>") matchSize = int(message[1]) _match = glob.matches.matches[getMatchIDFromChannel(chan)] _match.forceSize(matchSize) return "Match size changed to {}".format(matchSize)
def mpScoreV(): if len(message) < 2 or message[1] not in ("1", "2"): raise exceptions.invalidArgumentsException("Wrong syntax: !mp scorev <1|2>") _match = glob.matches.matches[getMatchIDFromChannel(chan)] _match.matchScoringType = matchScoringTypes.SCORE_V2 if message[1] == "2" else matchScoringTypes.SCORE _match.sendUpdates() return "Match scoring type set to scorev{}".format(message[1])
def mpKick(): if len(message) < 2: raise exceptions.invalidArgumentsException("Wrong syntax: !mp kick <username>") username = message[1].strip() if not username: raise exceptions.invalidArgumentsException("Please provide a username") userID = userUtils.getIDSafe(username) if userID is None: raise exceptions.userNotFoundException("No such user") _match = glob.matches.matches[getMatchIDFromChannel(chan)] slotID = _match.getUserSlotID(userID) if slotID is None: raise exceptions.userNotFoundException("The specified user is not in this match") for i in range(0, 2): _match.toggleSlotLocked(slotID) return "{} has been kicked from the match.".format(username)
def mp_mods(): userID = userUtils.getID(fro) if not can_user_touch_lobby(get_match_id_from_channel(chan), userID, True): return False if len(message) < 2: raise exceptions.invalidArgumentsException( "Wrong syntax: !mp mods <mod1> [<mod2>] ...") _match = glob.matches.matches[get_match_id_from_channel(chan)] newMods = 0 freeMod = False for _mod in message[1:]: if _mod.lower().strip() == "hd": newMods |= mods.HIDDEN elif _mod.lower().strip() == "hr": newMods |= mods.HARDROCK elif _mod.lower().strip() == "dt": newMods |= mods.DOUBLETIME elif _mod.lower().strip() == "fl": newMods |= mods.FLASHLIGHT elif _mod.lower().strip() == "fi": newMods |= mods.FADEIN if _mod.lower().strip() == "none" or _mod.lower().strip( ) == "nomod": newMods = 0 if _mod.lower().strip() == "freemod": freeMod = True _match.matchModMode = matchModModes.FREE_MOD if freeMod else matchModModes.NORMAL _match.resetReady() if _match.matchModMode == matchModModes.FREE_MOD: _match.resetMods() _match.changeMods(newMods) return "Match mods have been updated!"
def asyncGet(self): try: # Get request ip ip = self.getRequestIP() # Check arguments if not requestsManager.checkArguments(self.request.arguments, ["c", "u", "h"]): raise exceptions.invalidArgumentsException(MODULE_NAME) # Get arguments username = self.get_argument("u") password = self.get_argument("h") replayID = self.get_argument("c") # Login check userID = userUtils.getID(username) if userID == 0: raise exceptions.loginFailedException(MODULE_NAME, userID) if not userUtils.checkLogin(userID, password, ip): raise exceptions.loginFailedException(MODULE_NAME, username) if userUtils.check2FA(userID, ip): raise exceptions.need2FAException(MODULE_NAME, username, ip) # Get user ID replayData = glob.db.fetch( "SELECT scores.*, users.username AS uname FROM scores LEFT JOIN users ON scores.userid = users.id WHERE scores.id = %s", [replayID]) if replayData == None: replayData = glob.db.fetch( "SELECT scores_relax.*, users.username AS uname FROM scores_relax LEFT JOIN users ON scores_relax.userid = users.id WHERE scores_relax.id = %s", [replayID]) fileName = "{}_relax/replay_{}.osr".format( glob.conf.config["server"]["replayspath"], replayID) else: fileName = "{}/replay_{}.osr".format( glob.conf.config["server"]["replayspath"], replayID) # Increment 'replays watched by others' if needed if replayData is not None: if username != replayData["uname"]: userUtils.incrementReplaysWatched(replayData["userid"], replayData["play_mode"]) # Serve replay log.info("Serving replay_{}.osr".format(replayID)) if os.path.isfile(fileName): with open(fileName, "rb") as f: fileContent = f.read() self.write(fileContent) else: log.warning("Replay {} doesn't exist".format(replayID)) self.write("") except exceptions.invalidArgumentsException: pass except exceptions.need2FAException: pass except exceptions.loginFailedException: pass
def asyncGet(self): try: requestsManager.printArguments(self) # Check user auth because of sneaky people if not requestsManager.checkArguments(self.request.arguments, ["u", "h"]): raise exceptions.invalidArgumentsException(MODULE_NAME) username = self.get_argument("u") password = self.get_argument("h") userID = userUtils.getID(username) if not userUtils.checkLogin(userID, password): raise exceptions.loginFailedException(MODULE_NAME, username) beatmapSetId = int(self.get_argument("s")) beatmapIds = self.get_argument("b").split(',') oldOsz2Hash = self.get_argument("z") if userID != 1000: return self.write( return_errorcode(5, "f**k you, you are NOT Xxdstem")) glob.db.execute( "DELETE FROM gatari_beatmapsets WHERE user_id = {} AND active = -1" .format(userID)) bmInfo = fetch_info(beatmapSetId, False) if beatmapSetId > 0 and bmInfo is not None: if authenticate_creator(userID, bmInfo["user_id"], username) == False: return self.write(return_errorcode(1, "")) if (bmInfo["ranked"] > 0 and has_special_permissions(username) == False): return self.write(return_errorcode(3, "")) else: uploadcap = check_remaining_uploadcap(userID) if (uploadcap == 0): return self.write( return_errorcode( 6, "You have exceeded your submission cap")) if (uploadcap == -1): return self.write( return_errorcode(6, "Only druzhbans can submit beatmaps")) beatmapSetId = create_beatmapset(userID, username) newSubmit = True serverHash = get_osz2_file_hash(beatmapSetId) fullSubmit = newSubmit or oldOsz2Hash == "0" or serverHash is None or serverHash != oldOsz2Hash self.write("0\n\ {}\n\ {}\n\ {}\n\ {}\n\ 0\n\ {}".format(beatmapSetId, self.get_argument("b"), "1" if fullSubmit == True else "2", int(uploadcap), 0)) except exceptions.invalidArgumentsException: pass except exceptions.loginFailedException: pass
def asyncGet(self): output = "" try: # Get data by beatmap id or beatmapset id if "b" in self.request.arguments: id = self.get_argument("b") data = cheesegull.getBeatmap(id) elif "s" in self.request.arguments: id = self.get_argument("s") data = cheesegull.getBeatmapSet(id) else: raise exceptions.invalidArgumentsException(MODULE_NAME) log.info("Requested osu!direct np: {}/{}".format("b" if "b" in self.request.arguments else "s", id)) # Make sure cheesegull returned some valid data if data is None or len(data) == 0: raise exceptions.osuApiFailException(MODULE_NAME) # Write the response output = cheesegull.toDirectNp(data) + "\r\n" except (exceptions.invalidArgumentsException, exceptions.osuApiFailException, KeyError): output = "" finally: self.write(output)
def join(response, token, sender, channel, message): # FIXME: what the f**k? mp join? isn't this bypass?? if len(message) < 1 or not message[0].isdigit(): raise exceptions.invalidArgumentsException( "Wrong syntax: !mp join <id>") matchID = int(message[1]) if not token.irc: raise exceptions.invalidArgumentsException( "No game clients found for {}, can't join the match. " "If you're a referee and you want to join the chat " "channel from IRC, use /join #multi_{} instead.".format( sender, matchID)) token.joinMatch(matchID) response.target = sender response.setContent(token, "Attempting to join match #{}!".format(matchID))
def mpInvite(): if len(message) < 2: raise exceptions.invalidArgumentsException("Wrong syntax: !mp invite <username>") username = message[1].strip() if not username: raise exceptions.invalidArgumentsException("Please provide a username") userID = userUtils.getIDSafe(username) if userID is None: raise exceptions.userNotFoundException("No such user") token = glob.tokens.getTokenFromUserID(userID, ignoreIRC=True) if token is None: raise exceptions.invalidUserException("That user is not connected to bancho right now.") _match = glob.matches.matches[getMatchIDFromChannel(chan)] _match.invite(999, userID) token.enqueue(serverPackets.notification("Please accept the invite you've just received from FokaBot to " "enter your tourney match.")) return "An invite to this match has been sent to {}".format(username)
def mpJoin(): if len(message) < 2 or not message[1].isdigit(): raise exceptions.invalidArgumentsException( "Wrong syntax: !mp join <id>") matchID = int(message[1]) userToken = glob.tokens.getTokenFromUsername(fro, ignoreIRC=True) userToken.joinMatch(matchID) return "Attempting to join match #{}!".format(matchID)
def asyncGet(self): output = "" try: try: # Get arguments gameMode = self.get_argument("m", None) if gameMode is not None: gameMode = int(gameMode) if gameMode < 0 or gameMode > 3: gameMode = None rankedStatus = self.get_argument("r", None) if rankedStatus is not None: rankedStatus = int(rankedStatus) query = self.get_argument("q", "") page = int(self.get_argument("p", "0")) if query.lower() in ["newest", "top rated", "most played"]: query = "" except ValueError: raise exceptions.invalidArgumentsException(MODULE_NAME) # Get data from cheesegull API log.info("Requested osu!direct search: {}".format( query if query != "" else "index")) searchData = cheesegull.getListing( rankedStatus=cheesegull.directToApiStatus(rankedStatus), page=page * 100, gameMode=gameMode, query=query) if searchData is None or searchData is None: raise exceptions.noAPIDataError() args_data = [str(set['SetID']) for set in searchData] data = glob.db.fetchAll( "SELECT beatmapset_id, MAX(rating) AS rate FROM beatmaps WHERE beatmapset_id IN ({seq}) GROUP by beatmapset_id" .format(seq=','.join(['%s'] * len(args_data))), args_data) convert = {} for x in data: convert[x['beatmapset_id']] = x['rate'] # Write output output += "999" if len(searchData) == 100 else str(len(searchData)) output += "\n" for beatmapSet in searchData: rating = 0.00 if beatmapSet['SetID'] in convert: rating = float('{:.2f}'.format( convert[beatmapSet['SetID']])) output += cheesegull.toDirect(beatmapSet, rating) + "\r\n" except (exceptions.noAPIDataError, exceptions.invalidArgumentsException): output = "0\n" finally: self.write(output)
def asyncGet(self): try: # Get request ip ip = self.getRequestIP() # Argument check if not requestsManager.checkArguments(self.request.arguments, ["u", "h"]): raise exceptions.invalidArgumentsException(self.MODULE_NAME) # Get user ID username = self.get_argument("u") userID = userUtils.getID(username) if userID is None: raise exceptions.loginFailedException(self.MODULE_NAME, username) # Check login log.info("{} ({}) wants to connect".format(username, userID)) if not userUtils.checkLogin(userID, self.get_argument("h"), ip): raise exceptions.loginFailedException(self.MODULE_NAME, username) # Ban check if userUtils.isBanned(userID): raise exceptions.userBannedException(self.MODULE_NAME, username) # Lock check if userUtils.isLocked(userID): raise exceptions.userLockedException(self.MODULE_NAME, username) # 2FA check if userUtils.check2FA(userID, ip): raise exceptions.need2FAException(self.MODULE_NAME, username, ip) # Update latest activity userUtils.updateLatestActivity(userID) # Get country and output it country = glob.db.fetch( "SELECT country FROM users_stats WHERE id = %s", [userID])["country"] self.write(country) except exceptions.invalidArgumentsException: pass except exceptions.loginFailedException: self.write("error: pass\n") except exceptions.userBannedException: pass except exceptions.userLockedException: pass except exceptions.need2FAException: self.write("error: verify\n")
def asyncGet(self): statusCode = 400 data = {"message": "unknown error"} try: # Check arguments if "u" not in self.request.arguments and "id" not in self.request.arguments: raise exceptions.invalidArgumentsException() # Get online staus username = None userID = None if "u" in self.request.arguments: #username = self.get_argument("u").lower().replace(" ", "_") username = userUtils.safeUsername(self.get_argument("u")) else: try: userID = int(self.get_argument("id")) except: raise exceptions.invalidArgumentsException() if username is None and userID is None: data["result"] = False else: if username is not None: data["result"] = True if glob.tokens.getTokenFromUsername( username, safe=True) is not None else False else: data["result"] = True if glob.tokens.getTokenFromUserID( userID) is not None else False # Status code and message statusCode = 200 data["message"] = "ok" except exceptions.invalidArgumentsException: statusCode = 400 data["message"] = "missing required arguments" finally: # Add status code to data data["status"] = statusCode # Send response self.write(json.dumps(data)) self.set_status(statusCode)
def kick(response, token, sender, channel, message): if len(message) < 1: raise exceptions.invalidArgumentsException( "Wrong syntax: !mp kick <username>") ensureMatchIdle(channel) username = message[0].strip() if not username: raise exceptions.invalidArgumentsException( "Please provide a username") userID = lookupUser(username) _match = getCurrentMatch(channel) slotID = _match.getUserSlotID(userID) if slotID is None: raise exceptions.userNotFoundException( "The specified user is not in this match") for i in range(2): _match.toggleSlotLocked(slotID) response.setContent( token, "{} has been kicked from the match.".format(username))
def asyncGet(self): try: # Get request ip ip = self.getRequestIP() # Check arguments if not requestsManager.checkArguments(self.request.arguments, ["c", "k"]): raise exceptions.invalidArgumentsException(MODULE_NAME) # Get arguments key = self.get_argument("k") targetID = self.get_argument("c") if key is None or key != generalUtils.stringMd5( glob.conf.config["server"]["apikey"]): raise exceptions.invalidArgumentsException(MODULE_NAME) targetUsername = userUtils.getUsername(targetID) if (targetUsername is None): raise exceptions.invalidArgumentsException(MODULE_NAME) # Serve replay log.info("Serving {}.txt".format(targetUsername)) fileName = ".data/pl/{}.txt".format(targetUsername) if os.path.isfile(fileName): with open(fileName, "rb") as f: fileContent = f.read() self.write(fileContent) self.set_header("Content-length", len(fileContent)) self.set_header("Content-Description", "File Transfer") self.set_header( "Content-Disposition", "attachment; filename=\"{}_trace.txt\"".format( targetUsername)) else: log.warning("Trace {} doesn't exist".format(targetUsername)) self.write("") except exceptions.invalidArgumentsException: pass except exceptions.loginFailedException: pass
def mpMap(): if len(message) < 2 or not message[1].isdigit() or (len(message) == 3 and not message[2].isdigit()): raise exceptions.invalidArgumentsException("Wrong syntax: !mp map <beatmapid> [<gamemode>]") beatmapID = int(message[1]) gameMode = int(message[2]) if len(message) == 3 else 0 if gameMode < 0 or gameMode > 3: raise exceptions.invalidArgumentsException("Gamemode must be 0, 1, 2 or 3") beatmapData = glob.db.fetch("SELECT * FROM beatmaps WHERE beatmap_id = %s LIMIT 1", [beatmapID]) if beatmapData is None: raise exceptions.invalidArgumentsException("The beatmap you've selected couldn't be found in the database." "If the beatmap id is valid, please load the scoreboard first in " "order to cache it, then try again.") _match = glob.matches.matches[getMatchIDFromChannel(chan)] _match.beatmapID = beatmapID _match.beatmapName = beatmapData["song_name"] _match.beatmapMD5 = beatmapData["beatmap_md5"] _match.gameMode = gameMode _match.resetReady() _match.sendUpdates() return "Match map has been updated"