コード例 #1
0
def userPanel(userID, force=False):
    # Connected and restricted check
    userToken = glob.tokens.getTokenFromUserID(userID)
    if userToken is None or ((userToken.restricted) and not force):
        return bytes()

    # Get user data
    username = userToken.username
    timezone = 24 + userToken.timeOffset
    country = userToken.country
    gameRank = userToken.gameRank
    latitude = userToken.getLatitude()
    longitude = userToken.getLongitude()

    # Get username color according to rank
    # Only admins and normal users are currently supported
    userRank = 0
    if username == glob.BOT_NAME:
        userRank |= userRanks.MOD
    elif userUtils.isInPrivilegeGroup(userID, "Owner"):
        userRank |= userRanks.PEPPY
    elif userUtils.isInPrivilegeGroup(
            userID, "Developer") or userUtils.isInPrivilegeGroup(
                userID, "Community Manager"):
        userRank |= userRanks.ADMIN
    elif userUtils.isInPrivilegeGroup(
            userID, "Chat Moderators") or userUtils.isInPrivilegeGroup(
                userID, "Replay moderator"):
        userRank |= userRanks.MOD
    elif userUtils.isInPrivilegeGroup(userID, "BAT"):
        userRank |= userRanks.BAT
    elif (userToken.privileges & privileges.USER_DONOR) > 0:
        userRank |= userRanks.SUPPORTER
    else:
        userRank |= userRanks.NORMAL

    return packetHelper.buildPacket(
        packetIDs.server_userPanel,
        [[userID, dataTypes.SINT32], [username, dataTypes.STRING],
         [timezone, dataTypes.BYTE], [country, dataTypes.BYTE],
         [userRank, dataTypes.BYTE], [longitude, dataTypes.FFLOAT],
         [latitude, dataTypes.FFLOAT], [gameRank, dataTypes.UINT32]])
コード例 #2
0
ファイル: commentHandler.py プロジェクト: osuripple/lets
    def _addComment(self):
        username = self.get_argument("u")
        target = self.get_argument("target", default=None)
        specialFormat = self.get_argument("f", default=None)
        userID = userUtils.getID(username)

        # Technically useless
        if userID < 0:
            return

        # Get beatmap/set/score ids
        try:
            beatmapID = int(self.get_argument("b", default=0))
            beatmapSetID = int(self.get_argument("s", default=0))
            scoreID = int(self.get_argument("r", default=0))
        except ValueError:
            raise exceptions.invalidArgumentsException(self.MODULE_NAME)

        # Add a comment, removing all illegal characters and trimming after 128 characters
        comment = self.get_argument("comment").replace("\r", "").replace(
            "\t", "").replace("\n", "")[:128]
        try:
            time_ = int(self.get_argument("starttime"))
        except ValueError:
            raise exceptions.invalidArgumentsException(self.MODULE_NAME)

        # Type of comment
        who = "normal"
        if target == "replay" and glob.db.fetch(
                "SELECT COUNT(*) AS c FROM scores WHERE id = %s AND userid = %s AND completed = 3",
            (scoreID, userID))["c"] > 0:
            # From player, on their score
            who = "player"
        elif userUtils.isInAnyPrivilegeGroup(
                userID, ("developer", "community manager", "bat")):
            # From BAT/Admin
            who = "admin"
        elif userUtils.isInPrivilegeGroup(userID, "donor"):
            # Supporter
            who = "donor"

        if target == "song":
            # Set comment
            if beatmapSetID <= 0:
                return
            value = beatmapSetID
            column = "beatmapset_id"
        elif target == "map":
            # Beatmap comment
            if beatmapID <= 0:
                return
            value = beatmapID
            column = "beatmap_id"
        elif target == "replay":
            # Score comment
            if scoreID <= 0:
                return
            value = scoreID
            column = "score_id"
        else:
            # Invalid target
            return

        # Make sure the user hasn't submitted another comment on the same map/set/song in a 5 seconds range
        if glob.db.fetch(
                "SELECT COUNT(*) AS c FROM comments WHERE user_id = %s AND {} = %s AND `time` BETWEEN %s AND %s"
                .format(column),
            (userID, value, time_ - 5000, time_ + 5000))["c"] > 0:
            return

        # Store the comment
        glob.db.execute(
            "INSERT INTO comments ({}, user_id, comment, `time`, who, special_format) "
            "VALUES (%s, %s, %s, %s, %s, %s)".format(column),
            (value, userID, comment, time_, who, specialFormat))
        log.info("Submitted {} ({}) comment, user {}: '{}'".format(
            column, value, userID, comment))
コード例 #3
0
ファイル: osuToken.py プロジェクト: osushibui/pep.py
    def __init__(self,
                 userID,
                 token_=None,
                 ip="",
                 irc=False,
                 timeOffset=0,
                 tournament=False):
        """
		Create a token object and set userID and token

		:param userID: user associated to this token
		:param token_: 	if passed, set token to that value
						if not passed, token will be generated
		:param ip: client ip. optional.
		:param irc: if True, set this token as IRC client. Default: False.
		:param timeOffset: the time offset from UTC for this user. Default: 0.
		:param tournament: if True, flag this client as a tournement client. Default: True.
		"""
        # Set stuff
        self.userID = userID
        self.username = userUtils.getUsername(self.userID)
        self.safeUsername = userUtils.getSafeUsername(self.userID)
        self.privileges = userUtils.getPrivileges(self.userID)
        self.admin = userUtils.isInPrivilegeGroup(self.userID, "developer")\
            or userUtils.isInPrivilegeGroup(self.userID, "community manager")\
            or userUtils.isInPrivilegeGroup(self.userID, "chat mod")
        self.irc = irc
        self.kicked = False
        self.restricted = userUtils.isRestricted(self.userID)
        self.loginTime = int(time.time())
        self.pingTime = self.loginTime
        self.timeOffset = timeOffset
        self.streams = []
        self.tournament = tournament
        self.messagesBuffer = []

        # Default variables
        self.spectators = []

        # TODO: Move those two vars to a class
        self.spectating = None
        self.spectatingUserID = 0  # we need this in case we the host gets DCed

        self.location = [0, 0]
        self.joinedChannels = []
        self.ip = ip
        self.country = 0
        self.location = [0, 0]
        self.awayMessage = ""
        self.sentAway = []
        self.matchID = -1
        self.tillerino = [0, 0, -1.0]  # beatmap, mods, acc
        self.silenceEndTime = 0
        self.queue = bytes()

        # Spam protection
        self.spamRate = 0

        # Stats cache
        if userID == 1000:
            self.actionID = actions.WATCHING
        else:
            self.actionID = actions.IDLE
        if userID == 1000:
            self.actionText = "HentaiHaven"
        else:
            self.actionText = ""
        self.actionMd5 = ""
        self.actionMods = 0
        self.gameMode = gameModes.STD
        self.beatmapID = 0
        self.rankedScore = 0
        self.accuracy = 0.0
        self.playcount = 0
        self.totalScore = 0
        self.gameRank = 0
        self.pp = 0

        # Relax
        self.relaxing = False
        self.relaxAnnounce = False

        # Generate/set token
        if token_ is not None:
            self.token = token_
        else:
            self.token = str(uuid.uuid4())

        # Locks
        self.processingLock = threading.Lock(
        )  # Acquired while there's an incoming packet from this user
        self._bufferLock = threading.Lock(
        )  # Acquired while writing to packets buffer
        self._spectLock = threading.RLock()

        # Set stats
        self.updateCachedStats()

        # If we have a valid ip, save bancho session in DB so we can cache LETS logins
        if ip != "":
            userUtils.saveBanchoSession(self.userID, self.ip)

        # Join main stream
        self.joinStream("main")
コード例 #4
0
ファイル: osuToken.py プロジェクト: osu-datenshi/pep.py
    def __init__(self,
                 userID,
                 token_=None,
                 ip="",
                 irc=False,
                 timeOffset=0,
                 tournament=False,
                 ignoreDM=False):
        """
		Create a token object and set userID and token

		:param userID: user associated to this token
		:param token_: 	if passed, set token to that value
						if not passed, token will be generated
		:param ip: client ip. optional.
		:param irc: if True, set this token as IRC client. Default: False.
		:param timeOffset: the time offset from UTC for this user. Default: 0.
		:param tournament: if True, flag this client as a tournement client. Default: True.
		"""
        # Set stuff
        self.userID = userID
        self.username = userUtils.getUsername(self.userID)
        self.safeUsername = userUtils.getSafeUsername(self.userID)
        self.privileges = userUtils.getPrivileges(self.userID)
        self.admin = userUtils.isInPrivilegeGroup(self.userID, "Developer")\
            or userUtils.isInPrivilegeGroup(self.userID, "Community Manager")\
            or userUtils.isInPrivilegeGroup(self.userID, "Chat Moderators")
        self.irc = irc
        self.kicked = False
        self.restricted = userUtils.isRestricted(self.userID)
        self.loginTime = int(time.time())
        self.pingTime = self.loginTime
        self.timeOffset = timeOffset
        self.streams = []
        self.tournament = tournament
        self.messagesBuffer = []

        # Default variables
        self.spectators = []

        # TODO: Move those two vars to a class
        self.spectating = None
        self.spectatingUserID = 0  # we need this in case we the host gets DCed

        self.location = [0, 0]
        self.joinedChannels = []
        self.ip = ip
        self.country = 0
        self.location = [0, 0]
        self.awayMessage = ""
        self.sentAway = []
        self.matchID = -1
        self.tillerino = [0, 0, -1.0]  # beatmap, mods, acc
        self.silenceEndTime = 0
        self.queue = bytes()

        # Spam protection
        self.spamRate = 0

        # Stats cache
        def check_hax_initial():
            stmt = [
                "SELECT initial_status_type as aid, initial_status_text as atxt",
                "FROM bancho_status_hax", "WHERE user_id = %s AND NOT",
                "(initial_status_type IS NULL OR initial_status_text IS NULL OR length(initial_status_text) < 1)"
            ]
            result = glob.db.fetch(" ".join(stmt), [userID])
            if result is None:
                self.actionID, self.actionText = actions.IDLE, ""
            else:
                self.actionID, self.actionText = result['aid'], result['atxt']
            pass

        check_hax_initial()
        self.actionMd5 = ""
        self.actionMods = 0
        self.gameMode = gameModes.STD
        self.beatmapID = 0
        self.rankedScore = 0
        self.accuracy = 0.0
        self.playcount = 0
        self.totalScore = 0
        self.gameRank = 0

        self.noticeFlags = []

        self.pp = 0
        self._ignoreDM = ignoreDM

        self.specialMode = 0

        # Generate/set token
        if token_ is not None:
            self.token = token_
        else:
            self.token = str(uuid.uuid4())

        # Locks
        self.processingLock = threading.Lock(
        )  # Acquired while there's an incoming packet from this user
        self._bufferLock = threading.Lock(
        )  # Acquired while writing to packets buffer
        self._spectLock = threading.RLock()

        # Set stats
        self.updateCachedStats()

        # If we have a valid ip, save bancho session in DB so we can cache LETS logins
        if ip != "":
            userUtils.saveBanchoSession(self.userID, self.ip)

        # Join main stream
        self.joinStream("main")