def post(self):
     username = self.get_current_user()
     
     if username is None:
         self.result("error", "Access denied.")
         return
         
     user = User.get_user(username)
             
     if user.permission_level < constants.PERMISSION_LEVEL_ADMIN:
         self.result("error", "Access denied.")
         return
     
     try:
         username = self.get_argument("username")
         displayname = self.get_argument("displayname")
         email = self.get_argument("email", None) or None
     except:
         self.result("error", "Invalid arguments. Check that all fields are filled out correctly.")
         return
     
     session = SessionFactory()
     try:
         create_user(session, username, displayname, email)
         session.commit()
         
         self.result("success", "User added successfully.")
         
     finally:
         session.close()
 def query(self, socket_connection, message, count, start, dojo_sort, dojo_query):
     session = SessionFactory()
     try:
         query = session.query(User.id, User.username, User.permission_level)
     
         column_map = {u'id': User.id, u'username': User.username, u'permissions': User.permission_level}
     
         if dojo_query:
             dojo_query_obj = DojoQuery(dojo_query)
             query = dojo_query_obj.apply_to_sqla_query(query, column_map)
             
         if dojo_sort is not None:
             dojo_sort_obj = DojoSort(dojo_sort)
             query = dojo_sort_obj.apply_to_sqla_query(query, column_map)
         
         user_count = query.count()
         user_list = query.offset(start).limit(count).all()
         user_list = [{'id': uid, 'username': username, 'permissions': permission_level} for uid, username, permission_level in user_list]
         
         result_message = {'type': self.message_type,
                           'response': user_list,
                           'total': user_count,
                           'deferredId': message['deferredId'],
                          }
     finally:
         session.close()
     
     socket_connection.write_message(json.dumps(result_message))
 def put(self, socket_connection, message, object_data):
     target_id = object_data[u'id']
     target_username = object_data[u'username']
     target_permission_level = int(object_data[u'permissions'])
         
     session = SessionFactory()
     try:
         if target_id is not None:
             user = session.query(User).filter(User.id==int(target_id)).one()
             user.username = target_username
             user.permission_level = target_permission_level
         else:
             user = User(target_username, target_permission_level)
         
         session.add(user)
         session.commit()
         
         self.on_update(user)
     finally:
         session.close()
         
     result_message = {'type': self.message_type,
                       'response': self.object_to_json(user),
                       'deferredId': message['deferredId'],
                      }
     
     socket_connection.write_message(json.dumps(result_message))
def get_most_recent_ratings(user_id):
    from sqlalchemy.orm.exc import NoResultFound
    session = SessionFactory()
    try:
        participation_matches = session.query( Match.id.label("match_id"), 
                                               Match.date_recorded.label("date") ).\
                                filter( Participation.user_id == user_id ).\
                                filter( Participation.match_id == Match.id ).subquery()
                                
        most_recent_match_date = session.query( participation_matches.c.match_id.label("match_id"),
                                                func.max(participation_matches.c.date).label("date") ).\
                                subquery()
                                
        most_recent_match = session.query( participation_matches.c.match_id.label("match_id") ).\
                                filter( participation_matches.c.date == most_recent_match_date.c.date ).\
                                subquery()

        most_recent_ratings = session.query( TrueSkillCache.sigma.label("sigma"),
                                             TrueSkillCache.mu.label("mu"),
                                            TrueSkillCache.exposure.label("exposure")).\
                                filter( TrueSkillCache.user_id == user_id ).\
                                filter( most_recent_match.c.match_id == TrueSkillCache.match_id ).one()
        
        return resultdict(most_recent_ratings)
    except NoResultFound:
        return {'mu': trueskill.MU, 'sigma': trueskill.SIGMA, 'exposure': 0}
    finally:
        session.close()
 def post(self):
     username = self.get_current_user()
     
     if username is None:
         self.result("error", "Access denied.")
         return
         
     user = User.get_user(username)
             
     if user.permission_level < constants.PERMISSION_LEVEL_USER:
         self.result("error", "Access denied.")
         return
     
     try:
         displayname = strip_tags(self.get_argument("displayname"))
         email = strip_tags(self.get_argument("email"))
         showemail = bool(self.get_argument("showemail", False))
     except:
         self.result("error", "Invalid arguments. Check that all fields are filled out correctly.")
         return
     
     session = SessionFactory()
     try:
         user.displayname = displayname
         user.email = email
         user.showemail = showemail
         session.add(user)
         session.commit()
         self.result("success", "Settings saved successfully.", user)
     finally:
         session.close()
    def post(self):
        username = self.get_current_user()
        
        if username is None:
            self.result("error", "Access denied.")
            return
            
        user = User.get_user(username)
                
        if user.permission_level < constants.PERMISSION_LEVEL_USER:
            self.result("error", "Access denied.")
            return
        
        try:
            user1_id = int(self.get_argument("userSelect1"))
            user2_id = int(self.get_argument("userSelect2"))
            # date_time = self.get_argument("date") + " " + self.get_argument("time")
            
            games = []
            for gnum in range(1):
                game = (int(self.get_argument("score_g{}_p0".format(gnum))), int(self.get_argument("score_g{}_p1".format(gnum))))
                games.append(game)
        except:
            self.result("error", "Invalid arguments. Check that all fields are filled out correctly.")
            return
        
        if user1_id == user2_id:
            self.result("error", "Opponents must be different users.")
            return
        
        session = SessionFactory()
        try:
            user1 = session.query(User).filter(User.id == user1_id).one()
            user2 = session.query(User).filter(User.id == user2_id).one()
            
            # d = datetime.datetime.strptime(date_time, "%Y-%m-%d T%H:%M:%S")
            seconds = int(time.time()) #int(d.strftime('%s'))

            # filter out any games which have negative or all-zero scores
            games = filter(lambda g: all(map(lambda s: s >= 0, g)) and any(map(lambda s: s > 0, g)), games)
            
            if len(games) < 1:
                self.result("error", "A match consists of one or more games.")
                return
            current_score = (get_most_recent_ratings(user1.id).get('exposure',0), get_most_recent_ratings(user2.id).get('exposure',0))
            match = create_match(session, user1, user2, seconds, games)
            session.commit()
            new_score = (get_most_recent_ratings(user1.id).get('exposure',0), get_most_recent_ratings(user2.id).get('exposure',0))

            msg = "Match recorded successfully.<br><br>"\
            "Points Changes:<br>" \
            '%s: %0.3f<br>' \
            '%s: %0.3f' % (user1.displayname, new_score[0]-current_score[0], user2.displayname, new_score[1]-current_score[1])

            self.result("success", msg)
            
        finally:
            session.close()
 def delete(self, socket_connection, message, object_id):
     session = SessionFactory()
     try:
         assignment = session.query(User).filter(User.id==object_id).delete()
         session.commit()
     finally:
         session.close()
         
     self.on_delete(object_id)
 def get(self, mid=None):
     username = self.get_current_user()
     
     if username is None:
         self.validate_user()
         return
         
     user = User.get_user(username)
             
     if user.permission_level < constants.PERMISSION_LEVEL_USER:
         self.render("denied.html", user=user)
         return
     
     if mid is None:
         self.render("match-history.html", user=user)
     else:
         session = SessionFactory()
         try:
             target_match = session.query(Match).filter(Match.id==str(mid)).one()
             self.render("match-details.html", user=user, target_match=target_match)
         except NoResultFound:
             return None
         finally:
             session.close()
 def post(self):
     username = self.get_current_user()
     
     if username is None:
         self.result("error", "Access denied.")
         return
         
     user = User.get_user(username)
             
     if user.permission_level < constants.PERMISSION_LEVEL_USER:
         self.result("error", "Access denied.")
         return
     
     try:
         user1_id = int(self.get_argument("userSelect1"))
         user2_id = int(self.get_argument("userSelect2"))
         date_time = self.get_argument("date") + " " + self.get_argument("time")
         
         games = []
         for gnum in range(3):
             game = (int(self.get_argument("score_g{}_p0".format(gnum))), int(self.get_argument("score_g{}_p1".format(gnum))))
             games.append(game)
     except:
         self.result("error", "Invalid arguments. Check that all fields are filled out correctly.")
         return
     
     if user1_id == user2_id:
         self.result("error", "Opponents must be different users.")
         return
     
     session = SessionFactory()
     try:
         user1 = session.query(User).filter(User.id == user1_id).one()
         user2 = session.query(User).filter(User.id == user2_id).one()
         
         d = datetime.datetime.strptime(date_time, "%Y-%m-%d T%H:%M:%S")
         seconds = int(d.strftime('%s'))
         
         # filter out any games which have negative or all-zero scores
         games = filter(lambda g: all(map(lambda s: s >= 0, g)) and any(map(lambda s: s > 0, g)), games)
         
         if len(games) < 2:
             self.result("error", "A match consists of two or more games.")
             return
             
         match = create_match(session, user1, user2, seconds, games)
         session.commit()
         
         self.result("success", "Match recorded successfully.")
         
     finally:
         session.close()
    def get(self, user_id):
        username = self.get_current_user()
        
        if username is None:
            self.validate_user()
            return
            
        user = User.get_user(username)
                
        if user.permission_level < constants.PERMISSION_LEVEL_USER:
            self.render("denied.html", user=user)
            return
    
    
        if user_id is not None and user_id != "":
            # single item
            user_id = int(user_id)
            
            session = SessionFactory()
            try:
                result = get_leaderboard_query(session).filter(User.id == user_id).one()
                        
                result = resultdict(result)
                
                data = "{}&& "+json.dumps(result)
                self.set_header('Content-length', len(data))
                self.set_header('Content-type', 'application/json')
                self.write(data)
            finally:
                session.close()
        else:
            # query items
            
            raw_range = self.request.headers.get('Range', '')
            m = range_expression.match(raw_range)

            if m is not None:
                start = int(m.group('lower'))
                stop = int(m.group('upper')) + 1
            else:
                start = 0
                stop = -1

            raw_query = self.request.query
            m = sorting_expression.match(raw_query)
            
            if m is not None:
                    direction = m.group('direction')
                    column = m.group('column')
            else:
                    direction = '-'
                    column = "rating"
                    
            if column not in ["id", "displayname", "games", "wins", "win_percentage", "rating", "form", "streak",
                              'rank_change', 'order']:
                column = "rating"

            if direction == '-':
                    direction = 'desc'
            else:
                    direction = 'asc'
            
            session = SessionFactory()
            try:
                query = get_leaderboard_query(session)
                        
                total = query.count()
            
                # query = query.order_by(direction(column))
                        
                query = query.slice(start, stop)
                        
                result = query.all()

                result = resultdict(result)

                trophy_holder = session.query(FloatingTrophyCache).order_by(FloatingTrophyCache.id.desc()).first()

                today = datetime.now().date()
                today = datetime(today.year, today.month, today.day)
                today = int(today.strftime('%s'))

                previous_board = get_leaderboard_query(session, at_date = today).order_by(desc('rating')).all()
                previous_ranking = {}
                for pos, item in enumerate(previous_board,1):
                    previous_ranking[item.id] = (pos, item.rating)

                result = sorted(result, key= lambda k:k['rating'])[::-1]
                for i,res in enumerate(result,1):
                    res['order']= i
                    s1 = aliased(Score)
                    game_history = session.query(Score.score.label('player_score'), Score.game_id, s1.score.label('opponent_score') ).\
                        join(s1, sqlalchemy.and_(s1.game_id==Score.game_id, s1.user_id!=Score.user_id)).filter(Score.user_id==res['id']).\
                        order_by(Score.game_id.desc())
                    res['form'] = ''
                    game_history = ['W' if game.player_score>game.opponent_score else 'L' for game in game_history]
                    last_game = game_history[0]
                    opposite = 'W' if last_game == 'L' else 'L'
                    res['form'] = ''.join(reversed(game_history[0:5]))
                    res['streak'] = '%s%s' % (last_game, game_history.index(opposite) if  opposite in game_history else len(game_history))
                    res['rank_change'] = (previous_ranking[res['id']][0]- i) if previous_ranking.has_key(res['id']) else 0
                    res['rating_change'] = (res['rating']-previous_ranking[res['id']][1]) if previous_ranking.has_key(res['id']) else 0
                    res['hot_streak'] = False
                    res['trophy_holder'] = trophy_holder is not None and trophy_holder.user_id==res['id']

                result = sorted(result, key= sort_dict.get(column,lambda k:k[column]))
                if direction == 'desc':
                    result = result[::-1]

                best_streak = None

                for res in sorted(result, key= sort_dict.get('streak'))[::-1]:
                    if (best_streak is None and int(res['streak'][1:])>3) or res['streak'] == best_streak:
                        res['hot_streak'] = True
                        best_streak = res['streak']
                    else:
                        break

                data = "{}&& "+json.dumps(result)
                self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total))
                self.set_header('Content-length', len(data))
                self.set_header('Content-type', 'application/json')
                self.write(data)
                
            finally:
                session.close()
#!/usr/bin/python

import os
import sys

system_directory = os.path.dirname(os.path.abspath(__file__))

sys.path.append(system_directory + "/imports")

username = sys.argv[1]
permission_level = int(sys.argv[2])

from database.User import User
from database.SessionFactory import SessionFactory

session = SessionFactory()
try:
    user = User.get_user(username)
    user.permission_level = permission_level
    session.add(user)
    session.commit()
    print "Successfully set permission level for user '{}' to {}.".format(user.username, user.permission_level)
finally:
    session.close()

    def get(self, target_user_id):
        username = self.get_current_user()
        
        if username is None:
            self.validate_user()
            return
            
        user = User.get_user(username)
                
        if user.permission_level < constants.PERMISSION_LEVEL_USER:
            self.render("denied.html", user=user)
            return
        
        
        if not target_user_id:
            raise ValueError("User required")
        # query items
        
        raw_range = self.request.headers.get('Range', '')
        m = range_expression.match(raw_range)

        if m is not None:
            start = int(m.group('lower'))
            stop = int(m.group('upper')) + 1
        else:
            start = 0
            stop = -1

        raw_query = self.request.query
        m = sorting_expression.match(raw_query)
        
        if m is not None:
                direction = m.group('direction')
                column = m.group('column')
        else:
                direction = '-'
                column = "date"
                
        if column not in ["id", "date", "winner_id", "winner_score", "winner_displayname", "opponent_id", "opponent_score", "opponent_displayname"]:
            column = "date"

        if direction == '-':
                direction = desc
        else:
                direction = asc
        
        session = SessionFactory()
        try:
            query = get_match_history_query(session, target_user_id)
                    
            total = query.count()
        
            query = query.order_by(direction(column))
                    
            query = query.slice(start, stop)
                    
            result = query.all()
                    
            result = resultdict(result)
            
            data = "{}&& "+json.dumps(result)
            self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total))
            self.set_header('Content-length', len(data))
            self.set_header('Content-type', 'application/json')
            self.write(data)
            
        finally:
            session.close()
    def get(self, user1, user2, summary=False):
        username = self.get_current_user()

        if username is None:
            self.validate_user()
            return

        user = User.get_user(username)

        if user.permission_level < constants.PERMISSION_LEVEL_USER:
            self.render("denied.html", user=user)
            return


        if not (user1 and user2):
            raise ValueError("Two users are required")

        user1 = User.by_id(user1)
        user2 = User.by_id(user2)
        # query items

        raw_range = self.request.headers.get('Range', '')
        m = range_expression.match(raw_range)

        if m is not None:
            start = int(m.group('lower'))
            stop = int(m.group('upper')) + 1
        else:
            start = 0
            stop = -1

        raw_query = self.request.query
        m = sorting_expression.match(raw_query)

        if m is not None:
                direction = m.group('direction')
                column = m.group('column')
        else:
                direction = '-'
                column = "date"

        if column not in ["id", "date", "winner_id", "winner_score", "winner_displayname", "opponent_id", "opponent_score", "opponent_displayname"]:
            column = "date"

        if direction == '-':
                direction = desc
        else:
                direction = asc

        session = SessionFactory()
        try:
            query = get_match_history_query(session, [user1.id, user2.id])

            total = query.count()

            query = query.order_by(direction(column))
            if not summary:
                query = query.slice(start, stop)

            result = query.all()

            if summary:
                score_dict = {'won': 0, 'lost': 0, 'points_scored': 0, 'difference': 0, 'form': ''}
                sum_dict = { user1.id: score_dict.copy(), user2.id: score_dict.copy() }

                for res in result:
                    sum_dict[res.winner_id]['won'] += 1
                    sum_dict[res.winner_id]['points_scored'] += res.winner_score
                    sum_dict[res.winner_id]['difference'] += res.winner_score-res.opponent_score
                    sum_dict[res.winner_id]['form'] = 'W' + sum_dict[res.winner_id]['form']
                    sum_dict[res.opponent_id]['lost'] += 1
                    sum_dict[res.opponent_id]['points_scored'] += res.opponent_score
                    sum_dict[res.opponent_id]['difference'] += res.opponent_score-res.winner_score
                    sum_dict[res.opponent_id]['form'] = 'L' + sum_dict[res.opponent_id]['form']

                result = []
                for player in sum_dict:
                    user = user1 if player==user1.id else user2
                    player_dict = sum_dict[player]
                    player_dict['form'] = player_dict['form'][-5:]
                    player_dict.update({'id': player, 'displayname': user.displayname})
                    result.append(player_dict)
                start = 0
                stop = 1
                total = 2
            else:
                result = resultdict(result)

            data = "{}&& "+json.dumps(result)
            self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total))
            self.set_header('Content-length', len(data))
            self.set_header('Content-type', 'application/json')
            self.write(data)

        finally:
            session.close()
Example #14
0
    def get(self, user_id, timestamp):
        user_id = int(user_id)
        username = self.get_current_user()
        
        if username is None:
            self.validate_user()
            return
            
        user = User.get_user(username)
                
        if user.permission_level < constants.PERMISSION_LEVEL_USER:
            self.render("denied.html", user=user)
            return
    
    
        if timestamp is not None and timestamp != "":
            # single item
            timestamp = int(timestamp)
            
            session = SessionFactory()
            try:
                result = get_rankstore_query(session, user_id).filter_by(timestamp=timestamp).one()
                        
                result = resultdict(result)
                
                data = "{}&& "+json.dumps(result)
                self.set_header('Content-length', len(data))
                self.set_header('Content-type', 'application/json')
                self.write(data)
            finally:
                session.close()
        else:
            # query items
            
            raw_range = self.request.headers.get('Range', '')
            m = range_expression.match(raw_range)

            if m is not None:
                start = int(m.group('lower'))
                stop = int(m.group('upper')) + 1
            else:
                start = 0
                stop = -1

            raw_query = self.request.query
            m = sorting_expression.match(raw_query)
            
            if m is not None:
                    direction = m.group('direction')
                    column = m.group('column')
            else:
                    direction = '-'
                    column = "timestamp"
                    
            if column not in ["timestamp", "rank"]:
                column = "timestamp"

            if direction == '-':
                    direction = desc
            else:
                    direction = asc
            
            session = SessionFactory()
            try:
                query = get_rankstore_query(session, user_id)
                        
                total = query.count()
            
                query = query.order_by(direction(column))
                        
                query = query.slice(start, stop)
                        
                result = query.all()
                        
                result = resultdict(result)
                
                data = "{}&& "+json.dumps(result)
                self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total))
                self.set_header('Content-length', len(data))
                self.set_header('Content-type', 'application/json')
                self.write(data)
                
            finally:
                session.close()
 def post(self):
     session = SessionFactory()
     try:
         max_match_id = session.query(sqlalchemy.func.max(Match.id)).one()[0]
         match = session.query(Match).filter(Match.id==max_match_id).all()
         games = session.query(Game).filter(Game.match_id==max_match_id).all()
         partipations = session.query(Participation).filter(Participation.match_id==max_match_id).all()
         true_skill = session.query(TrueSkillCache).filter(TrueSkillCache.match_id==max_match_id).all()
         scores = []
         for game in games:
             scores += session.query(Score).filter(Score.game_id==game.id).all()
         for row in match + games + partipations + true_skill + scores:
             session.delete(row)
         session.commit()
         self.result("success", "Match #%s removed." % max_match_id)
     finally:
         session.close()
    def get(self, user_id):
        username = self.get_current_user()
        
        if username is None:
            self.validate_user()
            return
            
        user = User.get_user(username)
                
        if user.permission_level < constants.PERMISSION_LEVEL_USER:
            self.render("denied.html", user=user)
            return
    
    
        if user_id is not None and user_id != "":
            # single item
            user_id = int(user_id)
            
            session = SessionFactory()
            try:
                result = get_leaderboard_query(session).filter(User.id == user_id).one()
                        
                result = resultdict(result)
                
                data = "{}&& "+json.dumps(result)
                self.set_header('Content-length', len(data))
                self.set_header('Content-type', 'application/json')
                self.write(data)
            finally:
                session.close()
        else:
            # query items
            
            raw_range = self.request.headers.get('Range', '')
            m = range_expression.match(raw_range)

            if m is not None:
                start = int(m.group('lower'))
                stop = int(m.group('upper')) + 1
            else:
                start = 0
                stop = -1

            raw_query = self.request.query
            m = sorting_expression.match(raw_query)
            
            if m is not None:
                    direction = m.group('direction')
                    column = m.group('column')
            else:
                    direction = '-'
                    column = "displayname"
                    
            if column not in ["id", "displayname"]:
                column = "displayname"

            if direction == '-':
                    direction = desc
            else:
                    direction = asc
            
            session = SessionFactory()
            try:
                query = get_leaderboard_query(session)
                
                filterable_columns = {'displayname': User.displayname}
                
                for col, val in self.request.arguments.iteritems():
                    if col in filterable_columns.keys():
                        val = val[0].replace('*', '%')
                        query = query.filter(filterable_columns[col].like(val))
                        
                query = query.order_by(direction(column))
                        
                query = query.slice(start, stop)
                        
                result = query.all()
                        
                result = resultdict(result)
                
                total = len(result)
            
                data = "{}&& "+json.dumps(result)
                self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total))
                self.set_header('Content-length', len(data))
                self.set_header('Content-type', 'application/json')
                self.write(data)
                
            finally:
                session.close()