<commit_before>"""
The admin-related URI request handlers used by Tweb.
"""

import datetime
import random
import re

from bson.objectid import ObjectId
import tornado.web
import tornado.gen

import motor

import tweblib.handlers
import twcommon.misc

class AdminBaseHandler(tweblib.handlers.MyRequestHandler):
    """Base class for the handlers for admin pages. This has some common
    functionality.
    """
    @tornado.gen.coroutine
    def prepare(self):
        """
        Called before every get/post invocation for this handler. We use
        the opportunity to look up the session status, and then make sure
        the player is an administrator.
        """
        yield self.find_current_session()
        if self.twsessionstatus != 'auth':
            raise tornado.web.HTTPError(403, 'You are not signed in.')
        res = yield motor.Op(self.application.mongodb.players.find_one,
                             { '_id':self.twsession['uid'] })
        if not res or not res.get('admin', False):
            raise tornado.web.HTTPError(403, 'You do not have admin access.')

class AdminMainHandler(AdminBaseHandler):
    """Handler for the Admin page, which is rudimentary and not worth much
    right now.
    """
    @tornado.gen.coroutine
    def get(self):
        uptime = (twcommon.misc.now() - self.application.twlaunchtime)
        uptime = datetime.timedelta(seconds=int(uptime.total_seconds()))
        self.render('admin.html',
                    uptime=uptime,
                    mongoavailable=(self.application.mongodb is not None),
                    tworldavailable=(self.application.twservermgr.tworldavailable),
                    conntable=self.application.twconntable.as_dict())

    @tornado.gen.coroutine
    def post(self):
        if (self.get_argument('playerconntable', None)):
            msg = { 'cmd':'logplayerconntable' }
            self.application.twservermgr.tworld_write(0, msg)
        self.redirect('/admin')

class AdminSessionsHandler(AdminBaseHandler):
    """Handler for the Admin page which displays recent sessions.
    """
    @tornado.gen.coroutine
    def get(self):
        now = twcommon.misc.now()
        PER_PAGE = 16
        page = 0
        sessions = []
        cursor = self.application.mongodb.sessions.find(
            {},
            sort=[('starttime', motor.pymongo.DESCENDING)],
            skip=page*PER_PAGE,
            limit=PER_PAGE)
        while (yield cursor.fetch_next):
            prop = cursor.next_object()
            sessions.append(prop)
            try:
                delta = now - prop['starttime']
                prop['sincestarttime'] = datetime.timedelta(seconds=int(delta.total_seconds()))
            except:
                pass
        # cursor autoclose
        self.render('admin_sessions.html',
                    sessions=sessions)

class AdminPlayersHandler(AdminBaseHandler):
    """Handler for the Admin page which displays the players list.
    """
    @tornado.gen.coroutine
    def get(self):
        now = twcommon.misc.now()
        PER_PAGE = 5 ###16
        try:
            page = int(self.get_argument('page', 0))
            page = max(0, page)
        except:
            page = 0
        players = []
        cursor = self.application.mongodb.players.find(
            {},
            sort=[('createtime', motor.pymongo.DESCENDING)],
            skip=page*PER_PAGE,
            limit=PER_PAGE)
        while (yield cursor.fetch_next):
            prop = cursor.next_object()
            players.append(prop)
        # cursor autoclose
        self.render('admin_players.html',
                    page=page,
                    hasnext=int(len(players) == PER_PAGE), hasprev=int(page > 0),
                    players=players)<commit_msg>Bump up the players-per-page count.<commit_after>"""
The admin-related URI request handlers used by Tweb.
"""

import datetime
import random
import re

from bson.objectid import ObjectId
import tornado.web
import tornado.gen

import motor

import tweblib.handlers
import twcommon.misc

class AdminBaseHandler(tweblib.handlers.MyRequestHandler):
    """Base class for the handlers for admin pages. This has some common
    functionality.
    """
    @tornado.gen.coroutine
    def prepare(self):
        """
        Called before every get/post invocation for this handler. We use
        the opportunity to look up the session status, and then make sure
        the player is an administrator.
        """
        yield self.find_current_session()
        if self.twsessionstatus != 'auth':
            raise tornado.web.HTTPError(403, 'You are not signed in.')
        res = yield motor.Op(self.application.mongodb.players.find_one,
                             { '_id':self.twsession['uid'] })
        if not res or not res.get('admin', False):
            raise tornado.web.HTTPError(403, 'You do not have admin access.')

class AdminMainHandler(AdminBaseHandler):
    """Handler for the Admin page, which is rudimentary and not worth much
    right now.
    """
    @tornado.gen.coroutine
    def get(self):
        uptime = (twcommon.misc.now() - self.application.twlaunchtime)
        uptime = datetime.timedelta(seconds=int(uptime.total_seconds()))
        self.render('admin.html',
                    uptime=uptime,
                    mongoavailable=(self.application.mongodb is not None),
                    tworldavailable=(self.application.twservermgr.tworldavailable),
                    conntable=self.application.twconntable.as_dict())

    @tornado.gen.coroutine
    def post(self):
        if (self.get_argument('playerconntable', None)):
            msg = { 'cmd':'logplayerconntable' }
            self.application.twservermgr.tworld_write(0, msg)
        self.redirect('/admin')

class AdminSessionsHandler(AdminBaseHandler):
    """Handler for the Admin page which displays recent sessions.
    """
    @tornado.gen.coroutine
    def get(self):
        now = twcommon.misc.now()
        PER_PAGE = 16
        page = 0
        sessions = []
        cursor = self.application.mongodb.sessions.find(
            {},
            sort=[('starttime', motor.pymongo.DESCENDING)],
            skip=page*PER_PAGE,
            limit=PER_PAGE)
        while (yield cursor.fetch_next):
            prop = cursor.next_object()
            sessions.append(prop)
            try:
                delta = now - prop['starttime']
                prop['sincestarttime'] = datetime.timedelta(seconds=int(delta.total_seconds()))
            except:
                pass
        # cursor autoclose
        self.render('admin_sessions.html',
                    sessions=sessions)

class AdminPlayersHandler(AdminBaseHandler):
    """Handler for the Admin page which displays the players list.
    """
    @tornado.gen.coroutine
    def get(self):
        now = twcommon.misc.now()
        PER_PAGE = 16
        try:
            page = int(self.get_argument('page', 0))
            page = max(0, page)
        except:
            page = 0
        players = []
        cursor = self.application.mongodb.players.find(
            {},
            sort=[('createtime', motor.pymongo.DESCENDING)],
            skip=page*PER_PAGE,
            limit=PER_PAGE)
        while (yield cursor.fetch_next):
            prop = cursor.next_object()
            players.append(prop)
        # cursor autoclose
        self.render('admin_players.html',
                    page=page,
                    hasnext=int(len(players) == PER_PAGE), hasprev=int(page > 0),
                    players=players)
{'fraction_non_alphanumeric': 0.10400952759031362, 'fraction_numerical': 0.004366812227074236, 'mean_word_length': 2.1218504750103264, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '90207', 'n_tokens_mistral': 2174, 'n_tokens_neox': 2095, 'n_words': 492}