Example #1
0
 def checkUsername(self, username):
     '''
     Returns True or False, depending on whether the given username is
     already in use.
     '''
     try:
         TrosnothUser.fromUser(username=username)
     except User.DoesNotExist:
         return False
     return True
Example #2
0
 def setPassword(self, password):
     # Don't put DB write in a queue as user will expect it to take place
     # immediately.
     user = User.objects.get(username=self.username)
     user.set_password(password)
     user.save()
     trosnothUser = TrosnothUser.fromUser(pk=user.pk)
     trosnothUser.oldPasswordHash = b''
     trosnothUser.save()
Example #3
0
 def getAchievementRecord(self, achievementId):
     user = TrosnothUser.fromUser(username=self.username)
     try:
         achievement = AchievementProgress.objects.get(
             user=user, achievementId=achievementId)
     except AchievementProgress.DoesNotExist:
         achievement = AchievementProgress(user=user,
                                           achievementId=achievementId)
         achievement.save()
     return achievement
Example #4
0
 def writeUnlockedAchievementToDB():
     user = TrosnothUser.fromUser(username=self.username)
     try:
         achievement = AchievementProgress.objects.get(
             user=user, achievementId=achievementId)
     except AchievementProgress.DoesNotExist:
         achievement = AchievementProgress(user=user,
                                           achievementId=achievementId)
     if not achievement.unlocked:
         achievement.unlocked = True
         achievement.save()
Example #5
0
    def noteClientUsername(self, username):
        '''
        Do nothing, unless the "Trust client usernames" setting is switched on.
        Returns a Trosnoth user, or None.
        '''
        settings = TrosnothServerSettings.get()
        if not settings.trustClientUsernames:
            return None

        username = username.lower()
        try:
            trosnothUser = TrosnothUser.fromUser(username=username)
        except User.DoesNotExist:
            user = self.createUser(username, None)
        else:
            if not trosnothUser.user.is_active:
                return None
            user = AuthenticatedUser(self, username)

        user.seen()
        return user
Example #6
0
    def authenticateUser(self, username, password):
        '''
        If a username exists with the given password, returns the user,
        otherwise returns None.
        '''
        username = username.lower()
        try:
            trosnothUser = TrosnothUser.fromUser(username=username)
        except User.DoesNotExist:
            return defer.fail()

        if not trosnothUser.oldPasswordHash:
            # Just use Django auth
            djangoUser = authenticate(username=username, password=password)
            if djangoUser is None:
                return defer.fail(ValueError('Authentication failed'))
            if not djangoUser.is_active:
                return defer.fail(ValueError('User deactivated'))
            user = AuthenticatedUser(self, username)
        else:
            # Old Trosnoth auth, only exists for backward compatibility
            hash1 = sha1(SALT + password.encode('utf-8')).digest()
            hash2 = bytes(trosnothUser.oldPasswordHash)
            if hash1 != hash2:
                return defer.fail(ValueError('Incorrect password'))

            # Put the password into Django
            trosnothUser.user.set_password(password)
            trosnothUser.user.save()
            trosnothUser.oldPasswordHash = b''
            trosnothUser.save()

            user = AuthenticatedUser(self, username)

        user.seen()
        return defer.succeed(user)
Example #7
0
    def stopAndSave(self):
        '''
        Saves the game stats to the server database.
        '''
        from trosnoth.djangoapp.models import (
            TrosnothUser, GamePlayer, PlayerKills, UpgradesUsedInGameRecord,
        )

        self.statKeeper.stop()
        for playerStat in self.statKeeper.playerStatList.values():
            playerStat._updateStreaks(not playerStat.player.dead)

        self.gameRecord.finished = datetime.datetime.now()
        self.gameRecord.gameSeconds = (
            self.world.getMonotonicTime() - self.startGameTime)

        winner = self.world.level.getWinner()
        winnerId = winner.id if winner is not None else ''
        self.gameRecord.winningTeam = winnerId
        dbqueue.add(self.gameRecord.save)

        playerRecords = {}
        for playerStat in self.statKeeper.allPlayerStatLists.itervalues():
            player = playerStat.player
            if player.user:
                user = TrosnothUser.fromUser(
                    username=player.user.username)
                bot = False
                botName = ''
            else:
                user = None
                bot = player.bot
                botName = player.nick

            record = GamePlayer(
                game=self.gameRecord,
                user=user, bot=bot, botName=botName,
                team=player.team.id if player.team else '',

                coinsEarned=playerStat.coinsEarned,
                coinsWasted=playerStat.coinsLost - playerStat.coinsUsed,
                coinsUsed=playerStat.coinsUsed,
                kills=playerStat.kills,
                deaths=playerStat.deaths,
                zoneTags=playerStat.zoneTags,
                zoneAssists=playerStat.zoneAssists,
                shotsFired=playerStat.shotsFired,
                shotsHit=playerStat.shotsHit,
                timeAlive=playerStat.timeAlive,
                timeDead=playerStat.timeDead,
                killStreak=playerStat.killStreak,
                tagStreak=playerStat.tagStreak,
                aliveStreak=playerStat.aliveStreak,
            )
            self.queueSaveWithAttrs(record, ['game'])
            playerRecords[player.identifyingName] = record

            for upgradeType, count in playerStat.upgradesUsed.iteritems():
                upgradeRecord = UpgradesUsedInGameRecord(
                    gamePlayer=record,
                    upgrade=upgradeType,
                    count=count,
                )
                self.queueSaveWithAttrs(upgradeRecord, ['gamePlayer'])

        for playerStat in self.statKeeper.allPlayerStatLists.itervalues():
            killeeRecord = playerRecords[playerStat.player.identifyingName]
            killEntries = {}
            for killer, count in playerStat.playerDeaths.iteritems():
                if killer:
                    killerRecord = playerRecords[killer.identifyingName]
                else:
                    killerRecord = None

                if killer in killEntries:
                    # Same killer after disconnect / reconnect
                    killRecord = killEntries[killer]
                else:
                    killRecord = PlayerKills(
                        killer=killerRecord,
                        killee=killeeRecord,
                    )
                    killEntries[killer] = killRecord

                killRecord.count += count

            for killRecord in killEntries.itervalues():
                self.queueSaveWithAttrs(killRecord, ['killee', 'killer'])
Example #8
0
 def writeSeenTimeToDB():
     user = TrosnothUser.fromUser(username=self.username)
     user.lastSeen = now
     user.save()
Example #9
0
 def writeNickToDB():
     user = TrosnothUser.fromUser(username=self.username)
     if nick != user.nick:
         user.nick = nick
         user.save()
Example #10
0
 def getNick(self):
     return TrosnothUser.fromUser(username=self.username).nick
Example #11
0
    def stopAndSave(self):
        '''
        Saves the game stats to the server database.
        '''
        from trosnoth.djangoapp.models import (
            TrosnothUser,
            GamePlayer,
            PlayerKills,
            UpgradesUsedInGameRecord,
            TrosnothArena,
        )

        self.statKeeper.stop()
        for playerStat in list(self.statKeeper.playerStatList.values()):
            playerStat._updateStreaks(not playerStat.player.dead)

        self.gameRecord.finished = datetime.datetime.now()
        self.gameRecord.gameSeconds = (self.world.getMonotonicTime() -
                                       self.startGameTime)
        scoreboard = self.world.scoreboard
        self.gameRecord.teamScoresEnabled = scoreboard.teamScoresEnabled
        self.gameRecord.playerScoresEnabled = scoreboard.playerScoresEnabled
        self.gameRecord.blueTeamName = self.world.teams[0].teamName
        self.gameRecord.redTeamName = self.world.teams[1].teamName
        self.gameRecord.blueTeamScore = scoreboard.teamScores[
            self.world.teams[0]]
        self.gameRecord.blueTeamScore = scoreboard.teamScores[
            self.world.teams[1]]

        winner = self.world.scenarioManager.level.getWinner()
        winnerId = winner.id if winner is not None else b''
        self.gameRecord.winningTeam = winnerId.decode('ascii')
        dbqueue.add(self.gameRecord.save)

        playerRecords = {}
        for playerStat in self.statKeeper.allPlayerStatLists.values():
            player = playerStat.player
            if player.user:
                user = TrosnothUser.fromUser(username=player.user.username)
                bot = False
                botName = ''
            else:
                user = None
                bot = player.bot
                botName = player.nick

            record = GamePlayer(
                game=self.gameRecord,
                user=user,
                bot=bot,
                botName=botName,
                team=player.team.id.decode('ascii') if player.team else '',
                coinsEarned=playerStat.coinsEarned,
                coinsWasted=playerStat.coinsLost - playerStat.coinsUsed,
                coinsUsed=playerStat.coinsUsed,
                kills=playerStat.kills,
                deaths=playerStat.deaths,
                zoneTags=playerStat.zoneTags,
                zoneAssists=playerStat.zoneAssists,
                zoneScore=playerStat.zoneScore,
                shotsFired=playerStat.shotsFired,
                shotsHit=playerStat.shotsHit,
                timeAlive=playerStat.timeAlive,
                timeDead=playerStat.timeDead,
                killStreak=playerStat.killStreak,
                tagStreak=playerStat.tagStreak,
                aliveStreak=playerStat.aliveStreak,
                boardScore=scoreboard.playerScores.get(player, 0),
            )
            self.queueSaveWithAttrs(record, ['game'])
            playerRecords[player.identifyingName] = record

            for upgradeType, count in playerStat.upgradesUsed.items():
                upgradeRecord = UpgradesUsedInGameRecord(
                    gamePlayer=record,
                    upgrade=upgradeType.decode('utf-8'),
                    count=count,
                )
                self.queueSaveWithAttrs(upgradeRecord, ['gamePlayer'])

        for playerStat in self.statKeeper.allPlayerStatLists.values():
            killeeRecord = playerRecords[playerStat.player.identifyingName]
            killEntries = {}
            for killer, count in playerStat.playerDeaths.items():
                if killer:
                    killerRecord = playerRecords[killer.identifyingName]
                else:
                    killerRecord = None

                if killer in killEntries:
                    # Same killer after disconnect / reconnect
                    killRecord = killEntries[killer]
                else:
                    killRecord = PlayerKills(
                        killer=killerRecord,
                        killee=killeeRecord,
                    )
                    killEntries[killer] = killRecord

                killRecord.count += count

            for killRecord in killEntries.values():
                self.queueSaveWithAttrs(killRecord, ['killee', 'killer'])

        try:
            arena = TrosnothArena.objects.get(id=self.arenaId)
            if arena.currentTournament:

                @dbqueue.add
                def addGameRecordToTournament():
                    arena.currentTournament.matches.add(self.gameRecord)
        except TrosnothArena.DoesNotExist:
            pass