Ejemplo n.º 1
0
def browse_list():
    tourney_name = request.args.get('tourney')
    admin        = request.args.get('admin')
    pm = PersistenceManager(myapp.db_connector)
    tourney = pm.get_tourney(tourney_name)
    tourney_lists = tourney.tourney_lists
    return render_template( 'tourney_lists.html', tourney=tourney, tourney_lists=tourney_lists, admin=admin)
Ejemplo n.º 2
0
def get_tourney_data():
    tourney_id        = request.args['tourney_id']
    pm                = PersistenceManager(myapp.db_connector)
    tourney           = pm.get_tourney_by_id(tourney_id)

    de = RankingEditor( pm, tourney )
    return de.get_json()
Ejemplo n.º 3
0
    def put_or_post(self, helper, tourney_id):
        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player get" % ( tourney_id), 403)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        if tourney is None:
            return helper.bail("failed to look up tourney id %d for player get" % ( tourney_id), 403)

        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)
        if json_data is not None:
            bail = helper.check_token(json_data, tourney)
            if bail:
                return bail, None
        if not json_data.has_key(PLAYERS):
            return helper.bail("player put missing player key", 403), None

        bail, tl1, tl2 = helper.extract_players(json_data, tourney)
        if bail:
            return bail
        pm.db_connector.get_session().commit()

        players = []
        for player in tourney.tourney_players:
            players.append({NAME: player.get_player_name(), ID: player.id})
        return None, players
Ejemplo n.º 4
0
def unlock_tourney():
    key = request.args.get('key')
    tourney_id = request.args.get('tourney_id')
    pm = PersistenceManager(myapp.db_connector)
    state = ""
    try:
        tourney = pm.get_tourney_by_id(tourney_id)
        if len(key) and tourney.email == key:
            response = jsonify( result="success")
            if tourney.locked == True: #flip the lock
                tourney.locked = False
                state = "unlocked"
            else:
                tourney.locked = True
                state = "locked"
            event = Event(remote_address=myapp.remote_address(request),
                  event_date=func.now(),
                  event="lock/unlock tourney",
                  event_details="set tourney %s to state %s" % ( tourney.tourney_name, state ))
            pm.db_connector.get_session().add(event)
            pm.db_connector.get_session().commit()
            return response
        else:
            response = jsonify(result="fail")
            return response
    except Exception, e:
        error = "someone tried to unlock tourney_id " + tourney_id + " with email address " + key + " ( expected " + tourney.email + " ) "
        mail_error( error  )
        response = jsonify(message=str(e))
        response.status_code = (500)
        return response
Ejemplo n.º 5
0
 def get(self):
     pm = PersistenceManager(myapp.db_connector)
     leagues = pm.get_leagues()
     ret = []
     for l in leagues:
         ret.append(l.id)
     return jsonify({LEAGUES: ret})
Ejemplo n.º 6
0
def add_squad():
         data         = request.json['data']
         points       = request.json['points']
         faction      = request.json['faction']

         tourney_id = request.args.get('tourney_id')
         tourney_list_id = request.args.get('tourney_list_id')

         pm = PersistenceManager(myapp.db_connector)
         tourney_list = pm.get_tourney_list(tourney_list_id)
         tourney_list.faction = Faction.from_string( faction )
         tourney_list.points  = points

         ships = []
         for squad_member in data:
             ship_pilot = pm.get_ship_pilot( squad_member['ship'], squad_member['pilot'] )
             ship       = Ship( ship_pilot_id=ship_pilot.id, tlist_id=tourney_list.id)
             tourney_list.ships.append( ship )
             for upgrade in squad_member['upgrades']:
                 upgrade = pm.get_upgrade(upgrade['type'], upgrade['name'])
                 ship_upgrade = ShipUpgrade( ship_id=ship.id,
                                             upgrade=upgrade )
                 ship.upgrades.append( ship_upgrade )
             ships.append( ship )

         tourney_list.generate_hash_key()
         pm.db_connector.get_session().add_all( ships )
         pm.db_connector.get_session().commit()

         return jsonify(tourney_id=tourney_id, tourney_list_id=tourney_list.id)
Ejemplo n.º 7
0
 def get(self):
     pm = PersistenceManager(myapp.db_connector)
     ids = pm.get_tourney_ids()
     ret = []
     for id in ids:
         ret.append(id[0])
     return json.dumps({TOURNAMENTS: ret})
Ejemplo n.º 8
0
    def get(self, league_id):
        pm = PersistenceManager(myapp.db_connector)
        league = pm.get_league_by_id(league_id)
        ret = {}
        ret[LEAGUE_NAME] = league.name
        ret[LEAGUE_CHALLONGE_NAME] = league.challonge_name
        tiers = league.tiers
        tiers_data = []
        ret[LEAGUE_TIERS] = tiers_data

        for t in tiers:
            tdata = {
                TIER_NAME: t.name,
                TIER_CHALLONGE_NAME: t.challonge_name,
                TIER_DIVISIONS: [],
                TIER_ID: t.id
            }

            for division in t.divisions:
                division_players = []
                for player in division.players:
                    division_players.append({PLAYER_NAME: player.name, PLAYER_ID: player.id})
                tdata[TIER_DIVISIONS].append({DIVISION_NAME: division.name,
                                              DIVISION_CHALLONGE_NAME: division.name,
                                              DIVISION_ID: division.id,
                                              DIVISION_PLAYERS: division_players
                                              })

            tiers_data.append(tdata)
        return jsonify(ret)
Ejemplo n.º 9
0
 def get(self):
     pm = PersistenceManager(myapp.db_connector)
     ids = pm.get_tourney_ids()
     ret = []
     for id in ids:
         ret.append(id[0])
     return jsonify({TOURNAMENTS: ret})
Ejemplo n.º 10
0
    def put_or_post(self, helper, tourney_id):
        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player get" % (tourney_id), 403)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        if tourney is None:
            return helper.bail("failed to look up tourney id %d for player get" % (tourney_id), 403)

        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)
        if json_data is not None:
            bail = helper.check_token(json_data, tourney)
            if bail:
                return bail, None
        if not json_data.has_key(PLAYERS):
            return helper.bail("player put missing player key", 403), None

        bail, tl1, tl2 = helper.extract_players(json_data, tourney)
        if bail:
            return bail
        pm.db_connector.get_session().commit()

        players = []
        for player in tourney.tourney_players:
            xws = None
            tourney_list = player.get_first_tourney_list()
            if tourney_list and tourney_list.archtype_list:
                xws = XWSListConverter(tourney_list.archtype_list).data
            players.append({NAME: player.get_player_name(), ID: player.id, XWS: xws})
        return None, players
Ejemplo n.º 11
0
def game():
    id = str(request.args.get('id'))
    pm = PersistenceManager(myapp.db_connector)
    game = pm.get_game(session,id)
    if game == None:
        return redirect(url_for('new'))

    player1 = game.game_players[0]
    player2 = game.game_players[1]

    winning_player = "Unknown"
    if game.game_winner is not None:
        winning_player = game.game_winner.name

    #summary_stats = GameSummaryStats(game)
    game_tape = GameTape(game)
    game_tape.score()

    luck_result = pm.get_luck_score(session, game.id)

    if luck_result is None:

        luck_result = calculate_luck_result(game, game_tape=game_tape)
        if luck_result is not None:
            myapp.db_connector.get_session().add(luck_result)
            myapp.db_connector.get_session().commit()

    return render_template( 'game_summary.html',
                            game=game,
                            player1=player1,
                            player2=player2,
                            winner=winning_player,
                            game_tape=game_tape,
                            colorscale=colorscale() )
Ejemplo n.º 12
0
 def __init__(self,tsvfile):
     if tsvfile is None:
         return
     pm = PersistenceManager( myapp.db_connector )
     league_name = "X-Wing Vassal League Season Two"
     league = pm.get_league(league_name)
     self.tsv_players = {}
     self.divisions = {}
     with open(tsvfile, 'rU') as input:
         reader = csv.reader( input,delimiter='\t' )
         for row in reader:
             person_name = unicode(row[0].strip())
             email_address = row[1].strip()
             challonge_name = unicode(row[2].strip())
             time_zone = row[3].strip()
             reddit_handle = row[4].strip()
             challengeboards_name = row[5].strip()
             tier_name = row[6].strip()
             tier_number = row[7].strip()
             division_name = row[8].strip()
             division_letter = row[9].strip()
             self.tsv_players[challonge_name] = { 'person_name': person_name,
                                             'email_address' : email_address,
                                             'challonge_name' : challonge_name,
                                             'time_zone' : time_zone,
                                             'reddit_handle' : reddit_handle,
                                             'challengeboards_name':challengeboards_name ,
                                             'tier_name' : tier_name,
                                             'tier_number' : tier_number,
                                             'division_name' : division_name,
                                             'division_letter' : division_letter }
             if not self.divisions.has_key( division_name ):
                 self.divisions[division_name] = { 'name': division_name, 'letter':division_letter, 'tier': tier_name}
Ejemplo n.º 13
0
    def processFile(self, start, span, locfile):
        """
        排序、时间范围校验
        :param start:
        :param span:
        :param locfile:
        :return:
        """
        lines = open(locfile).readlines()
        lines = map(string.strip, lines)
        list = map(json.loads, lines)
        mos = []
        for _ in list:
            mo = MovableObject.unmarshall(_)
            if not mo:
                continue
            loc = mo.getLocation()
            if loc.time < start or loc.time > start + span:
                instance.getLogger().warning(
                    'location time is not in (%s,%s)' % (start, start + span))
                continue
            mos.append(mo)

        #根据时间排序
        mos = sorted(
            mos, lambda x, y: cmp(x.getLocation().time,
                                  y.getLocation().time))
        PersistenceManager.instance().write(start, span, mos)
Ejemplo n.º 14
0
def editgames():
    try:
        games = PersistenceManager(myapp.db_connector).get_games(myapp.db_connector.get_session())
        return( render_template('games-edit.html', games=games) )
    except Exception:
        #give it another shot...
        games = PersistenceManager(myapp.db_connector).get_games(myapp.db_connector.get_session())
        return( render_template('games-edit.html', games=games) )
Ejemplo n.º 15
0
def correct_list_points():

    pm                = PersistenceManager(myapp.db_connector)
    lists             = pm.get_all_lists()
    for list in lists:
        if list.points == 0 and len(list.ships) > 0:
            print "list %d is a problem" % list.id
    return redirect(url_for('tourneys') )
Ejemplo n.º 16
0
def list_rank_generate_cache():

    list_ranks = simple_cache.get('list-ranks')
    if list_ranks is None:
        pm = PersistenceManager(myapp.db_connector)
        list_ranks = pm.get_list_ranks()
        simple_cache.set( 'list-ranks', list_ranks, timeout=60*60)
    return render_template("listrank_impl.html", ranks=list_ranks)
Ejemplo n.º 17
0
    def setUp(self):
        self.persistence_manager = PersistenceManager(True)

        #just keep a top level reference to these guys for ease of use
        self.session = db_connector.get_session()

        #and then create the database schema, reference tables
        self.persistence_manager.create_schema()
        self.persistence_manager.populate_reference_tables()
        self.session.commit()
Ejemplo n.º 18
0
def get_summaries():
    try:
        summaries = simple_cache.get('banner-summary-data')
        if summaries is None:
            pm = PersistenceManager(myapp.db_connector)
            summaries = pm.get_summaries()
            simple_cache.set( 'banner-summary-data', summaries, timeout=5*60)
        return json.dumps( summaries  )
    except Exception, e:
        response = jsonify(message=str(e))
        response.status_code = (500)
        return response
Ejemplo n.º 19
0
def leaderboard():
    bottom_ten_greens = PersistenceManager(myapp.db_connector).get_worst_green_luck_scores(myapp.db_connector.get_session()).all()[0:10]
    bottom_ten_reds   = PersistenceManager(myapp.db_connector).get_worst_red_luck_scores(myapp.db_connector.get_session()).all()[0:10]
    top_ten_greens    = PersistenceManager(myapp.db_connector).get_best_green_luck_scores(myapp.db_connector.get_session()).all()[0:10]
    top_ten_reds      = PersistenceManager(myapp.db_connector).get_best_red_luck_scores(myapp.db_connector.get_session()).all()[0:10]


    return render_template( 'leaderboard.html',
                            bottom_ten_greens=bottom_ten_greens,
                            bottom_ten_reds=bottom_ten_reds,
                            top_ten_greens=top_ten_greens,
                            top_ten_reds=top_ten_reds)
Ejemplo n.º 20
0
def delete_tourney():
    tourney_name = request.args.get('tourney')
    pm = PersistenceManager(myapp.db_connector)
    pm.delete_tourney(tourney_name)

    event = Event(remote_address=myapp.remote_address(request),
                  event_date=func.now(),
                  event="delete tourney",
                  event_details="deleted tourney %s" % ( tourney_name ))
    pm.db_connector.get_session().add(event)
    pm.db_connector.get_session().commit()

    return redirect(url_for('tourneys') )
Ejemplo n.º 21
0
def get_tourney_details():
    tourney_id   = request.args.get('tourney_id')

    pm                = PersistenceManager(myapp.db_connector)
    tourney           = pm.get_tourney_by_id(tourney_id)

    unlocked = True
    if tourney.locked:
        unlocked = False

    return render_template('edit_tourney.html', tourney_id=tourney_id,
                                                tourney=tourney,
                                                unlocked=unlocked )
Ejemplo n.º 22
0
    def get(self, league_id):
        pm = PersistenceManager(myapp.db_connector)
        league = pm.get_league_by_id(league_id)
        ret = {}
        ret[LEAGUE_NAME] = league.name
        ret[LEAGUE_CHALLONGE_NAME] = league.name
        matches = []
        ret[MATCHES] = matches

        for t in league.tiers:
            for m in t.matches:
                c = XWSListConverter(m.player1_list)
                p1_xws = c.data
                c = XWSListConverter(m.player2_list)
                p2_xws = c.data

                p1_pretty_list = None
                p2_pretty_list = None
                if m.player1_list is not None:
                    p1_pretty_list = m.player1_list.pretty_print_list('\n')
                if m.player2_list is not None:
                    p2_pretty_list = m.player2_list.pretty_print_list('\n')

                matches.append({
                    'url': m.get_url(use_markup=False),
                    'tier_name': t.name,
                    'scheduled_datetime': m.scheduled_datetime,
                    'state': m.state,
                    'last_updated_at': m.updated_at,
                    'logfile_url': m.challonge_attachment_url,
                    'player1': {
                        'name': m.player1.name,
                        "division_name": m.player1.division.name,
                        "list": m.player1_list_url,
                        "pretty_print": p1_pretty_list,
                        "xws": p1_xws,
                        'score': m.player1_score,
                        'id': m.player1.id
                    },
                    'player2': {
                        'name': m.player2.name,
                        'division_name': m.player2.division.name,
                        'list': m.player2_list_url,
                        'pretty_print': p2_pretty_list,
                        'xws': p2_xws,
                        'score': m.player2_score,
                        'id': m.player2.id
                    }
                })
        return jsonify(ret)
Ejemplo n.º 23
0
    def search(self):

        ret = []
        seen = {}
        pm = PersistenceManager(myapp.db_connector)

        for rec in self.query:
            list_id = rec[0]
            if not seen.has_key(list_id):
                list = pm.get_tourney_list(list_id)
                seen[list_id] = 1
                ret.append(list)

        return ret
Ejemplo n.º 24
0
def show_results():
    hashkey = request.args.get('hashkey')
    pm   = PersistenceManager(myapp.db_connector)
    lists = pm.get_lists_for_hashkey(hashkey)
    results = []
    ret     = {}
    ret[ 'pretty_print'] = lists[0].pretty_print( manage_list=0, show_results=0)
    ret['hashkey'] = lists[0].hashkey
    for list in lists:
        res = pm.get_round_results_for_list(list.id)
        for r in res:
            results.append(r)
    ret[ "results"] = results
    return render_template("show_results.html", data=ret)
Ejemplo n.º 25
0
def update_tourney_details():
    tourney_id            = request.form['tourney_id']
    name                  = decode( request.form['name'] )
    type                  = request.form['tourney_type']
    print request.form['datepicker']
    mmddyyyy              = request.form['datepicker'].split('/')
    date                  = datetime.date( int(mmddyyyy[2]),int(mmddyyyy[0]), int(mmddyyyy[1])) #YYYY, MM, DD
    round_length  = request.form['round_length_userdef']
    tourney_format_def    = request.form['tourney_format_dropdown']
    tourney_format_custom = request.form['tourney_format_custom']
    participant_count     = int(request.form['participant_count'])
    country               = decode(request.form['country'])
    state                 = decode(request.form['state'])
    city                  = decode(request.form['city'])
    venue                 = decode(request.form['venue'])


    tourney_format = None
    if tourney_format_def is None or len(tourney_format_def) == 0:
        if tourney_format_custom is None or len(tourney_format_custom) == 0:
            tourney_format = xwingmetadata.format_default
        else:
            tourney_format = decode(tourney_format_custom)
    else:
        tourney_format = str(tourney_format_def)


    pm                = PersistenceManager(myapp.db_connector)
    tourney           = pm.get_tourney_by_id(tourney_id)

    tourney.tourney_name = name
    tourney.tourney_type  = type
    tourney.tourney_date = date
    tourney.round_length = round_length
    tourney.format = tourney_format
    tourney.participant_count = participant_count
    tourney.venue.country = country
    tourney.venue.state = state
    tourney.venue.city = city
    tourney.venue.venue = venue

    event = Event(remote_address=myapp.remote_address(request),
                  event_date=func.now(),
                  event="edit tourney information",
                  event_details="edited " + name )

    pm.db_connector.get_session().add(event)
    pm.db_connector.get_session().commit()

    return redirect( url_for( 'get_tourney_details', tourney_id=tourney_id) )
Ejemplo n.º 26
0
    def search(self):

        ret = []
        seen = {}
        pm = PersistenceManager( myapp.db_connector )

        for rec in self.query:
             list_id = rec[0]
             if not seen.has_key( list_id ):
                 list    = pm.get_tourney_list( list_id )
                 seen[list_id] = 1
                 ret.append( list )

        return ret
Ejemplo n.º 27
0
def populate_luck_scores():
    pm = PersistenceManager(myapp.db_connector)
    pm.delete_all_luck_results(myapp.db_connector.get_session())
    games = PersistenceManager(myapp.db_connector).get_games(myapp.db_connector.get_session())
    i = 0
    print "populating " + str(len(games)) + " luck results "
    for game in games:
        if i % 100 == 0:
            print "calculating luck result for " + str(i) + "th game"
        i += 1
        luck_result = calculate_luck_result(game, game_tape=None)
        if luck_result is not None:
            myapp.db_connector.get_session().add( luck_result )
    myapp.db_connector.get_session().commit()
    return redirect(url_for('leaderboard'))
Ejemplo n.º 28
0
def edit_tourney_details():
    tourney_id   = request.args.get('tourney_id')

    pm                = PersistenceManager(myapp.db_connector)
    tourney           = pm.get_tourney_by_id(tourney_id)

    tourney_date      = tourney.tourney_date
    date_str          = "%d/%d/%d" % ( tourney_date.month, tourney_date.day, tourney_date.year)
    print "tourney date is " + date_str

    return render_template('edit_tourney_details.html', tourney_id=tourney_id,
                                                tourney=tourney,
                                                tourney_formats = xwingmetadata.formats,
                                                tourney_date = date_str,
                                                unlocked=False )
Ejemplo n.º 29
0
def export_tourney_lists():
    tourney_id = request.args.get('tourney_id')
    pm         = PersistenceManager(myapp.db_connector)
    tourney    = pm.get_tourney_by_id(tourney_id)

    ret = get_tourney_lists_as_text(tourney)

    event = Event(remote_address=myapp.remote_address(request),
                  event_date=func.now(),
                  event="export tourney lists",
                  event_details="exported tourney %s" % ( tourney.tourney_name ))
    pm.db_connector.get_session().add(event)
    pm.db_connector.get_session().commit()

    return csv_response( ret, "tourney_list_download.csv")
Ejemplo n.º 30
0
def export_all_lists():
    pm          = PersistenceManager(myapp.db_connector)
    tourneys    = pm.get_tourneys();
    make_header = True
    rows        = []
    for tourney in tourneys:
        ret = get_tourney_lists_as_text(tourney, make_header)
        make_header = False
        rows.extend( ret )

    event = Event(remote_address=myapp.remote_address(request),
                  event_date=func.now(),
                  event="export all tourney lists")
    pm.db_connector.get_session().add(event)
    pm.db_connector.get_session().commit()
    return csv_response( rows, "all_lists_download.csv")
Ejemplo n.º 31
0
    def get(self, tourney_id):
        helper = TournamentApiHelper()
        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player get" % ( tourney_id), 403)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        if tourney is None:
            return helper.bail("failed to look up tourney id %d for player get" % ( tourney_id), 403)

        players = []
        for player in tourney.tourney_players:
            players.append({NAME: player.get_player_name(), ID: player.id})

        response = jsonify({PLAYERS: players})
        response.status_code = 200
        return response
Ejemplo n.º 32
0
    def post(self):
        try:
            query = request.form['query']
        except KeyError:
            json_data = request.get_json(force=True)
            query = json_data['query']

        try:
            query = query.decode('utf-8')
        except (UnicodeEncodeError, UnicodeDecodeError):
            abort(400)

        pm = PersistenceManager(myapp.db_connector)
        tourneys = pm.db_connector.get_session().query(Tourney) \
            .join(TourneyVenue) \
            .filter(
            or_(
                Tourney.tourney_name.like('%{}%'.format(query)),
                TourneyVenue.venue.like('%{}%'.format(query))
            )
        )

        response = {
            t.id: {
                'name': t.tourney_name,
                'venue': t.venue.venue,
                'date': t.tourney_date.strftime('%Y-%m-%d'),  # no timezone was kept :(
            }
            for t in tourneys}

        return jsonify(response)
Ejemplo n.º 33
0
    def post(self, tourney_id, player_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)
        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)

        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player post" % ( tourney_id), 400)
        if not helper.isint(player_id):
            return helper.bail("invalid player  %d passed to player post" % ( player_id), 400)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        bail = helper.check_token(json_data, tourney)
        if bail:
            return bail
        player = tourney.get_player_by_id(player_id)
        if player is None:
            return helper.bail("couldn't find player %d, bailing out" % ( player_id), 400)

        dirty = False

        # add list via XWS
        if XWS in json_data:
            dirty = True
            try:
                tourney_list = player.tourney_lists[-1]
                XWSToJuggler(json_data[XWS]).convert(pm, tourney_list)
            except:
                pm.db_connector.get_session().rollback()
                return helper.bail('Could not add list via XWS', 400)

        # other potential edits

        if dirty:
            pm.db_connector.get_session().commit()

        return jsonify({
            'player': {
                'id': player.id,
                'tourney_id': tourney.id,
                'name': player.get_player_name(),
            }
        })
Ejemplo n.º 34
0
    def get(self, tourney_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)
        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player get" % ( tourney_id), 403)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        if tourney is None:
            return helper.bail("failed to look up tourney id %d for player get" % ( tourney_id), 403)

        players = []
        for player in tourney.tourney_players:
            players.append({NAME: player.get_player_name(), ID: player.id})

        response = jsonify({PLAYERS: players})
        response.status_code = 200
        return response
Ejemplo n.º 35
0
    def post(self, tourney_id, player_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)
        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)

        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player post" % (tourney_id), 400)
        if not helper.isint(player_id):
            return helper.bail("invalid player  %d passed to player post" % (player_id), 400)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        bail = helper.check_token(json_data, tourney)
        if bail:
            return bail
        player = tourney.get_player_by_id(player_id)
        if player is None:
            return helper.bail("couldn't find player %d, bailing out" % (player_id), 400)

        dirty = False

        # add list via XWS
        if XWS in json_data:
            dirty = True
            try:
                tourney_list = player.tourney_lists[-1]
                XWSToJuggler(json_data[XWS]).convert(pm, tourney_list)
            except:
                pm.db_connector.get_session().rollback()
                return helper.bail('Could not add list via XWS', 400)

        # other potential edits

        if dirty:
            pm.db_connector.get_session().commit()

        return jsonify({
            'player': {
                'id': player.id,
                'tourney_id': tourney.id,
                'name': player.get_player_name(),
            }
        })
Ejemplo n.º 36
0
def delete_list_and_retry():
    tourney_list_id = request.args.get('tourney_list_id')
    print("calling delete list and retry on tourney id " + tourney_list_id)

    pm = PersistenceManager(myapp.db_connector)
    tourney_list = pm.get_tourney_list(tourney_list_id)
    pm.delete_tourney_list_details( tourney_list )

    event = Event(remote_address=myapp.remote_address(request),
                  event_date=func.now(),
                  event="delete list",
                  event_details="deleted list id %d from tourney %s" % ( tourney_list.id, tourney_list.tourney.tourney_name ))
    pm = PersistenceManager(myapp.db_connector)
    pm.db_connector.get_session().add(event)
    pm.db_connector.get_session().commit()

    return redirect( url_for('enter_list', tourney=tourney_list.tourney.id, tourney_list_id=tourney_list.id ) )
Ejemplo n.º 37
0
    def get(self, tourney_id):
        pm = PersistenceManager(myapp.db_connector)
        t = pm.get_tourney_by_id(tourney_id)
        if t is None:
            response = jsonify(message="tourney %d not found" % ( tourney_id ))
            response.status_code = 404
            return response

        # and log it
        event = Event(remote_address=myapp.remote_address(request),
                      event_date=func.now(),
                      event="API",
                      event_details="tournament API: tourney GET")
        pm.db_connector.get_session().add(event)

        pm.db_connector.get_session().commit()

        return jsonify(TourneyToJsonConverter().convert(t))
Ejemplo n.º 38
0
     def get(self, tourney_id):
        pm = PersistenceManager(myapp.db_connector)
        t = pm.get_tourney_by_id(tourney_id)
        if t is None:
            response = jsonify(message="tourney %d not found" % (tourney_id))
            response.status_code = 404
            return response

        # and log it
        event = Event(remote_address=myapp.remote_address(request),
                      event_date=func.now(),
                      event="API",
                      event_details="tournament API: tourney GET")
        pm.db_connector.get_session().add(event)
        pm.db_connector.get_session().commit()

        json = TourneyToJsonConverter().convert(t,provide_points=True)
        return jsonify(json)
Ejemplo n.º 39
0
def luck_graph():
    id = str(request.args.get('game_id'))
    game = PersistenceManager().get_game(session,id)

    player_id = long(request.args.get('player'))
    dice_type = request.args.get('dice_type')

    lp = LuckPlot( game, player_id, dice_type)
    return lp.plot()
Ejemplo n.º 40
0
    def __init__(self, config=None, **kwargs):
        self.config = config
        self.user_login = self.config.get("login").lower()
        self.user_password = self.config.get("password")
        self.persistence = PersistenceManager(self.config.get("database"))
        self.session_file = self.config.get("session_file")
        
        self.s = requests.Session()
        self.c = requests.Session()
        
        self.proxies = self.config.get('proxies')
        if self.proxies:
            self.s.proxies.update(self.proxies)
            self.s.proxies.update(self.proxies)
        
#         to do: check what is user agent
        self.user_agent = random.sample(self.config.get("list_of_ua"), 1)[0]
        self.login()
Ejemplo n.º 41
0
    def get(self, tourney_id, player_id):
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)

        xws = None
        tourney_player = tourney.get_player_by_id(player_id)
        tourney_list = tourney_player.get_first_tourney_list()
        if tourney_list and tourney_list.archtype_list:
            xws = XWSListConverter(tourney_list.archtype_list).data


        payload = {NAME: tourney_player.get_player_name(),
                    ID: tourney_player.id,
                    XWS: xws}

        response = jsonify({'player': payload} )
        response.status_code = 200
        return response
Ejemplo n.º 42
0
def advantage():
    id = str(request.args.get('game_id'))
    use_initial = int(request.args.get('initial'))
    game = PersistenceManager().get_game(session,id)

    ap = AdvantagePlot( game, use_initial )
    output = ap.plot()
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Ejemplo n.º 43
0
def get_from_fab():
    try:
        fab = request.args.get('fab')
        tourney_id = request.args.get('tourney_id')
        tourney_list_id = request.args.get('tourney_list_id')
        pm = PersistenceManager(myapp.db_connector)
        tourney_list = pm.get_tourney_list(tourney_list_id)

        fetcher = FabFetcher()
        xws     = fetcher.fetch( fab )
        converter = XWSToJuggler(xws)
        converter.convert( pm, tourney_list )
        pm.db_connector.get_session().commit()
        return jsonify(tourney_id=tourney_id, tourney_list_id=tourney_list_id)
    except Exception, e:
         mail_error( "Unable to fetch from fab for url " + fab + ", reason: " + str(e))
         response = jsonify(message=str(e))
         response.status_code = (500)
         return response
Ejemplo n.º 44
0
    def get(self, league_id, tier_id):
        pm = PersistenceManager(myapp.db_connector)
        tier = pm.get_tier_by_id(tier_id)
        ret = {}
        if tier is None:
            return jsonify(ret)

        division_rankings = []
        tier_rankings = []
        ret[DIVISION_RANKING] = division_rankings
        ret[TIER_RANKING] = tier_rankings

        for d in tier.divisions:
            dr = {'division_name': d.name,
                  'division_id': d.id,
                  'division_letter' : d.division_letter,
                  'rankings': []
                  }
            division_rankings.append(dr)
            for r in d.get_ranking(ignore_defaults=False, ignore_interdivisional=False):
                dr['rankings'].append(
                    {
                        'rank': r['rank'],
                        'wins': r['wins'],
                        'loses': r['losses'],
                        'draws': r['draws'],
                        'mov': r['mov'],
                        'id': r['player'].id,
                        'name': r['player'].name,
                    })

        for r in tier.get_ranking(ignore_defaults=False, ignore_interdivisional=False):
            tier_rankings.append({
                'rank': r['rank'],
                'wins': r['wins'],
                'losses': r['losses'],
                'draws': r['draws'],
                'mov': r['mov'],
                'id': r['player'].id,
                'name': r['player'].name,
            })

        return jsonify(ret)
Ejemplo n.º 45
0
def api_games():
    try:
        games = PersistenceManager(myapp.db_connector).get_games(
            myapp.db_connector.get_session())
        # transforming into JSON-serializable objects
        schema = GameSchema(many=True)
        games_json = schema.dump(games)
        return jsonify(games_json)
    except Exception as e:
        print("It is busted returned {}" + e)
        return {}
Ejemplo n.º 46
0
def delete_game():
    id = str(request.args.get('id'))
    game = PersistenceManager(myapp.db_connector).get_game(session,id)
    if game == None:
        return redirect(url_for('new'))
    #doing this manually as I banged my head against the wall trying to get it to work using the sql alchemy cascade logic...
    luck_results = PersistenceManager(myapp.db_connector).get_luck_score(session, game.id)
    if luck_results is not None:
        for lr in luck_results:
            myapp.db_connector.get_session().delete(lr)

    for throw in game.game_throws:
        for result in throw.results:
            for adjustment in result.adjustments:
                myapp.db_connector.get_session().delete(adjustment)
            myapp.db_connector.get_session().delete(result)
        myapp.db_connector.get_session().delete(throw)

    myapp.db_connector.get_session().delete(game)
    myapp.db_connector.get_session().commit()
    return redirect(url_for('editgames'))
Ejemplo n.º 47
0
def versus():
    id = str(request.args.get('game_id'))
    game = PersistenceManager().get_game(session,id)

    attacker_id = long(request.args.get('attacker'))
    defender_id = long(request.args.get('defender'))

    vp = VersusPlot( game, attacker_id, defender_id)
    output = vp.plot()
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Ejemplo n.º 48
0
    def extract_players(self, t, tourney):
        pm = PersistenceManager(myapp.db_connector)
        tlists_by_id = {}
        tlists_by_name = {}

        if t.has_key(PLAYERS):
            players = t[PLAYERS]
            i = 1
            for p in players:
                player = None
                ranking = None

                # first see if the tourney already has a player and player list matching this player's name
                #if so, update it rather than creating a new one
                if p.has_key(PLAYER_ID):
                    player = tourney.get_player_by_id(p[PLAYER_ID])
                    if player is None:
                        return self.bail(
                            "couldn't find player with id %d, giving up" % ( p[PLAYER_ID], 403)), None, None
                else:
                    if not p.has_key(PLAYER_NAME):
                        return self.bail("neither an id or a name was provided, giving up ", 403), None, None
                    player = tourney.get_player_by_name(p[PLAYER_NAME])

                if player is None:
                    player = TourneyPlayer(player_name="Player %d" % ( i ))
                    ranking = TourneyRanking(player=player)
                    player.result = ranking
                    tourney_list = TourneyList(tourney=tourney, player=player)
                    tlists_by_id[player.id] = tourney_list  # stash it away for later use
                    if p.has_key(PLAYER_NAME):
                        tlists_by_name[p[PLAYER_NAME]] = tourney_list
                    tourney.tourney_players.append(player)
                    tourney.tourney_lists.append(tourney_list)
                    tourney.rankings.append(ranking)
                    player.tourney_lists.append(tourney_list)
                    i = i + 1
                else:
                    ranking = player.result
                    tlists_by_id[player.id] = player.get_first_tourney_list()
                    if p.has_key(PLAYER_NAME):
                        tlists_by_name[p[PLAYER_NAME]] = tlists_by_id[player.id]

                # add list via XWS
                if XWS in p:
                    try:
                        XWSToJuggler(p[XWS]).convert(pm, tourney_list)
                    except Exception as e:
                        print "Could not convert XWS: {} (XWS was {!r})".format(e, p[XWS])

                self.extract_player(p, player, ranking)

        return None, tlists_by_id, tlists_by_name
Ejemplo n.º 49
0
    def setUp(self):

        user = os.environ['USER']
        password = os.environ['PASSWORD']
        sqlfile = "./dbs/prod.sql"
        cmd = "/usr/local/mysql/bin/mysql -u %s -p%s 'sozin$lists' < %s" % (
            user, password, sqlfile)

        print os.system(cmd)

        self.pm = PersistenceManager(db_connector)
        self.session = db_connector.get_session()
Ejemplo n.º 50
0
def damage():
    id = str(request.args.get('game_id'))
    game = PersistenceManager().get_game(session, id)

    if game.game_tape is None:
        game_tape = GameTape(game)
        game_tape.score()

    dp = DamagePlot( game )
    output = dp.plot()
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Ejemplo n.º 51
0
    def delete(self, tourney_id, player_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)
        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)

        if not helper.isint(tourney_id):
            return helper.bail("invalid tourney_id  %d passed to player delete" % ( tourney_id), 403)
        if not helper.isint(player_id):
            return helper.bail("invalid player  %d passed to player delete" % ( player_id), 403)
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        bail = helper.check_token(json_data, tourney)
        if bail:
            return bail
        player = tourney.get_player_by_id(player_id)
        if player is None:
            return helper.bail("couldn't find player %d, bailing out" % ( player_id), 403)
        pm.db_connector.get_session().delete(player)
        pm.db_connector.get_session().commit()
Ejemplo n.º 52
0
def download_game():
    games = PersistenceManager(myapp.db_connector).get_games(myapp.db_connector.get_session())

    rows = []
    make_header = True
    for g in games:
        ret = get_game_tape_text(g, make_header)
        for r in ret:
            rows.append(r)
        if make_header is True:
            make_header = False

    disposition = "attachment; filename=all_dice.csv"
    return Response(generate(rows), mimetype='text/csv', headers={'Content-Disposition': disposition} )
Ejemplo n.º 53
0
    def post(self, tourney_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)

        try:
            email = request.form['email']
        except KeyError:
            json_data = request.get_json(force=True)
            email = json_data['email']

        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        if tourney is None:
            return helper.bail("tourney %d not found" % ( tourney_id ), 404)

        if email != tourney.email:
            return helper.bail("incorrect email for tourney {}".format(tourney_id), 404)

        if tourney.api_token is None:
            tourney.api_token = str(uuid.uuid4())
            pm.db_connector.get_session().commit()

        return jsonify({"api_token": tourney.api_token})
Ejemplo n.º 54
0
    def delete(self, tourney_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)
        self.helper = helper
        t = pm.get_tourney_by_id(tourney_id)
        if t is None:
            return helper.bail("tourney %d not found" % ( tourney_id ), 403)

        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)
        if json_data is None:
            return helper.bail("delete call for tourney_id %d missing json payload, giving up " % (tourney_id), 403)

        bail = helper.check_token(json_data, t)
        if bail:
            return bail

        # whew. aaaaalmost there...
        try:
            pm.delete_tourney_by_id(tourney_id)
        except Exception:
            return helper.bail("unable to delete tourney %d, bailing out " % ( tourney_id ), 403)

            #and log it
        event = Event(remote_address=myapp.remote_address(request),
                      event_date=func.now(),
                      event="API",
                      event_details="tournament API: tourney delete %d" % ( tourney_id ))
        pm.db_connector.get_session().add(event)
        pm.db_connector.get_session().commit()

        response = jsonify(message="deleted tourney id %d" % ( tourney_id ))
        response.status_code = 204
        return response
Ejemplo n.º 55
0
    def post(self, tourney_id):
        pm = PersistenceManager(myapp.db_connector)
        helper = TournamentApiHelper(pm)
        bail, players = self.put_or_post(helper, tourney_id)
        if bail:
            return bail
        # only return the players that the caller created
        json_data = None
        try:
            json_data = request.get_json(force=True)
        except Exception:
            return helper.bail("bad json received!", 403)
        new_players = json_data[PLAYERS]
        ret = []
        for p in players:
            for np in new_players:
                if p[NAME] == np[PLAYER_NAME]:
                    ret.append(p)

        response = jsonify({PLAYERS: ret})
        response.status_code = 201
        return response
Ejemplo n.º 56
0
class DatabaseTestCase(unittest.TestCase):

    def setUp(self):
        self.persistence_manager = PersistenceManager(True)

        #just keep a top level reference to these guys for ease of use
        self.session = db_connector.get_session()

        #and then create the database schema, reference tables
        self.persistence_manager.create_schema()
        self.persistence_manager.populate_reference_tables()
        self.session.commit()

    def tearDown(self):

#        self.session.flush()
        self.session.close_all()
        self.persistence_manager.drop_schema()
Ejemplo n.º 57
0
    def testPlayerAPI(self):

        t = {
            "tournament": {
                "name": "playertests",
                "date": "2015-05-25",
                "type": "Store Championship",
                "round_length": 60,
                "participant_count": 30,
                "players": [{
                    "name": "bob"
                }, {
                    "name": "bill"
                }]
            }
        }
        resp = post(dev_url, data=json.dumps(t))
        self.assertEqual(201, resp.status_code)
        tjson = resp.json()
        self.assertTrue(tjson is not None)
        tjson = tjson['tournament']
        tourney_id = tjson["id"]
        api_token = tjson['api_token']
        self.assertTrue(api_token is not None and len(api_token) > 0)

        self.assertTrue(tourney_id is not None)
        players = tjson['players']
        self.assertTrue(len(players) == 2)
        bob = players[0]
        self.assertTrue(bob['name'] == 'bob')
        self.assertTrue(bob.has_key("id"))
        self.assertTrue(self.isint(bob['id']))
        self.assertTrue(int(bob['id'] > 0))

        bill = players[1]
        self.assertTrue(bill['name'] == 'bill')
        self.assertTrue(bill.has_key("id"))
        self.assertTrue(self.isint(bill['id']))
        self.assertTrue(int(bill['id'] > 0))

        #ok, get works just fine.
        #ty out player get
        player_get_url = dev_endpoint + 'tournament/' + str(
            tourney_id) + "/players"
        print player_get_url
        resp = get(player_get_url)
        print resp.text
        self.assertEqual(200, resp.status_code)
        pjson = resp.json()

        self.assertTrue(pjson.has_key('players'))
        players = pjson['players']
        bob = players[0]
        self.assertTrue(bob['name'] == 'bob')
        self.assertTrue(bob.has_key("id"))
        self.assertTrue(self.isint(bob['id']))
        self.assertTrue(int(bob['id'] > 0))

        bill = players[1]
        self.assertTrue(bill['name'] == 'bill')
        self.assertTrue(bill.has_key("id"))
        self.assertTrue(self.isint(bill['id']))
        self.assertTrue(int(bill['id'] > 0))

        #and now the player put
        p = {
            "api_token":
            api_token,
            "players": [{
                'player_id': bob['id'],
                'name': 'bob2'
            }, {
                'player_id': bill['id'],
                'name': 'bill2'
            }]
        }

        resp = put(player_get_url, data=json.dumps(p))
        print resp.text
        self.assertEqual(200, resp.status_code)

        #look it up in the database and verify that the names were changed properly
        myapp.db_connector.close()
        myapp.db_connector.connect()
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        self.assertTrue(tourney is not None)

        p1 = tourney.get_player_by_name("bob2")
        self.assertTrue(p1 is not None)
        self.assertTrue(p1.player_name == "bob2")
        self.assertTrue(p1.id == bob['id'])

        p2 = tourney.get_player_by_name("bill2")
        self.assertTrue(p2 is not None)
        self.assertTrue(p2.player_name == "bill2")
        self.assertTrue(p2.id == bill['id'])

        #add some new names via post
        p = {
            "api_token": api_token,
            "players": [{
                'name': "joe"
            }, {
                "name": "jenny"
            }]
        }

        resp = post(player_get_url, data=json.dumps(p))
        print resp.text
        self.assertEqual(201, resp.status_code)
        tjson = resp.json()
        self.assertTrue(tjson is not None)
        tjson = tjson['players']
        print tjson
        p1 = tjson[0]
        self.assertTrue(p1 is not None)
        self.assertTrue(p1['name'] == 'joe')
        self.assertTrue(p1['id'] is not None)
        p2 = tjson[1]
        self.assertTrue(p2 is not None)
        self.assertTrue(p2['name'] == 'jenny')
        self.assertTrue(p2['id'] is not None)

        #look it up in the database and verify that it stuck
        myapp.db_connector.close()
        myapp.db_connector.connect()
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        self.assertTrue(tourney is not None)

        dp1 = tourney.get_player_by_name("joe")
        self.assertTrue(dp1 is not None)
        self.assertTrue(dp1.player_name == "joe")
        self.assertTrue(dp1.id == p1['id'])

        dp2 = tourney.get_player_by_name("jenny")
        self.assertTrue(dp2 is not None)
        self.assertTrue(dp2.player_name == "jenny")
        self.assertTrue(dp2.id == p2['id'])

        #ok, now try to delete!
        #try to take out jenny

        d = {"api_token": api_token}
        delete_url = dev_endpoint + 'tournament/' + str(
            tourney_id) + "/player/" + str(p2['id'])
        resp = delete(delete_url, data=json.dumps(d))
        print resp.text
        self.assertEqual(200, resp.status_code)

        myapp.db_connector.close()
        myapp.db_connector.connect()
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        self.assertTrue(tourney is not None)

        dp1 = tourney.get_player_by_name("joe")
        self.assertTrue(dp1 is not None)
        self.assertTrue(dp1.player_name == "joe")
        self.assertTrue(dp1.id == p1['id'])

        dp2 = tourney.get_player_by_name("jenny")
        self.assertTrue(dp2 is None)
Ejemplo n.º 58
0
    def testAxelCase(self):
        t = {
            "tournament": {
                "name": "playertests",
                "date": "2015-05-25",
                "type": "Store Championship",
                "round_length": 60,
                "participant_count": 30
            }
        }
        resp = post(dev_url, data=json.dumps(t))
        self.assertEqual(201, resp.status_code)
        tjson = resp.json()
        self.assertTrue(tjson is not None)
        tjson = tjson['tournament']
        tourney_id = tjson["id"]
        api_token = tjson['api_token']
        self.assertTrue(api_token is not None and len(api_token) > 0)

        #add the players
        p = [{"name": "bob"}, {"name": "bill"}]
        t = {'api_token': api_token, 'players': p}

        player_get_url = dev_endpoint + 'tournament/' + str(
            tourney_id) + "/players"
        resp = post(player_get_url, data=json.dumps(t))
        print resp.text
        self.assertEqual(201, resp.status_code)
        pjson = resp.json()

        self.assertTrue(pjson.has_key('players'))
        players = pjson['players']
        bob = players[0]
        self.assertTrue(bob['name'] == 'bob')
        self.assertTrue(bob.has_key("id"))
        self.assertTrue(self.isint(bob['id']))
        self.assertTrue(int(bob['id'] > 0))

        bill = players[1]
        self.assertTrue(bill['name'] == 'bill')
        self.assertTrue(bill.has_key("id"))
        self.assertTrue(self.isint(bill['id']))
        self.assertTrue(int(bill['id'] > 0))

        p = [{
            "player_id": bob['id'],
            "mov": 622,
            "score": 20,
            "sos": 1.00,
            'dropped': False,
            "rank": {
                "swiss": 1,
                "elimination": 2
            }
        }, {
            'player_id': bill['id'],
            "mov": 647,
            "score": 15,
            "sos": 0.00,
            'dropped': True,
            "rank": {
                "swiss": 2,
                "elimination": 4
            }
        }]

        #ok, now enter the rest of the data
        t = {
            'api_token': api_token,
            'tournament': {
                'format':
                'Standard - 100 Point Dogfight',
                'players':
                p,
                "rounds": [{
                    "round-type":
                    "swiss",
                    "round-number":
                    1,
                    "matches": [
                        {
                            "player1_id": bob['id'],
                            "player1points": 100,
                            "player2_id": bill['id'],
                            "player2points": 48,
                            "result": "win"
                        },
                    ]
                }]
            }
        }
        url = dev_endpoint + 'tournament/' + str(tourney_id)

        resp = put(url, data=json.dumps(t))
        self.assertEqual(200, resp.status_code)
        tjson = resp.json()
        self.assertTrue(tjson is not None)

        myapp.db_connector.close()
        myapp.db_connector.connect()
        pm = PersistenceManager(myapp.db_connector)
        tourney = pm.get_tourney_by_id(tourney_id)
        self.assertTrue(tourney is not None)
        self.assertTrue(len(tourney.tourney_players) == 2)