Ejemplo n.º 1
0
def changeElo(player_id, elo_change, frame_id, opp_elo):
    # update player elo
    db.query("""
                UPDATE tplayer
                SET elo = elo + $change
                WHERE player_id=$player_id
            """,
             vars={
                 'player_id': player_id,
                 'change': elo_change
             })

    # add elo jrnl entry
    try:
        db.query("""
                INSERT INTO telojrnl (player_id, frame_id, elo_change, opp_elo, new_elo)
                VALUES ($player_id, $frame_id, $elo_change, $opp_elo, (SELECT elo FROM tplayer WHERE player_id=$player_id) )
            """,
                 vars={
                     'player_id': player_id,
                     'frame_id': frame_id,
                     'elo_change': elo_change,
                     'opp_elo': opp_elo
                 })
    except sqlite3.IntegrityError, e:
        log.error('SQL error while inserting entry into tEloJrnl')
Ejemplo n.º 2
0
def send_json():
    to = ''
    message = ''
    if request.method != 'POST':
        return ErrorMethodNotAllowed('This route serve only POST method')

    log.debug('Content-Type: {}'.format(request.content_type))

    json = request.get_json(force=True, silent=True)
    if not json:
        return ErrorBadRequest('Failed to parce JSON input')

    try:
        if 'to' in json:
            to = json['to']
        if 'message' in json:
            message = json['message']
    except Exception as e:
        log.error('{}'.format(e))
        return ErrorBadRequest(e)

    if isBase64(message):
        message = base64.b64decode(message).decode('utf-8')

    return send_message(to, message)
Ejemplo n.º 3
0
def read_json_file(path):
    try:
        log.info('Reading ' + path + ' file ...')
        with open(path, 'r') as f:
            log.info(path + ' file opened.')
            return json.load(f)
    except IOError as err:  # whatever reader errors you care about
        log.error('|IOError| - File not found or couldn\'t be open')
Ejemplo n.º 4
0
def write_json_file(path, content):
    try:
        log.info('Opening ' + path + ' file ...')
        with open(path, 'w') as outfile:
            json.dump(content, outfile, ensure_ascii=False)
            log.info(path + ' file writed.')
    except IOError as err:  # whatever reader errors you care about
        log.error('|IOError| - File not found or couldn\'t be open to write')
Ejemplo n.º 5
0
def commitMatch(match_id):
    try:
        rowcount = db.update('tmatch',
                                where='match_id=$match_id',
                                vars={'match_id':match_id},
                                confirmed="Y")

        if rowcount != 1:
            error = "Bad number of rows deleted: "
            raise
    except:
        log.error('Failed to commit match '+str(match_id))
Ejemplo n.º 6
0
def send_message(to, message):
    if not to:
        return ErrorBadRequest('Missing parameter To')
    if not message:
        return ErrorBadRequest('Missing parameter message')

    log.debug('Sending message to {}: {}'.format(to, message))
    msglog.info('Sending message to {}: {}'.format(to, message))

    try:
        client.send_message(to, message)
    except Exception as e:
        log.error('{}'.format(e))
        return ErrorInternalError('{}'.format(e))

    return ErrorGeneralOK('Send succesfull')
Ejemplo n.º 7
0
def ping():
    try:
        user = client.get_me()
        log.debug('{}'.format(user))

    except Exception as e:
        log.error('{}'.format(e))
        log.error('Trying to reconnect telegram')

        try:
            client.connect()
        except Exception as e:
            log.error('Reconnect failed: {}'.format(e))
            return ErrorInternalError('{}'.format(e))

        try:
            user = client.get_me()
            log.debug('Reconnect successed: {}'.format(user))
            client.is_connected()
        except Exception as e:
            return ErrorInternalError('{}'.format(e))

    return ErrorGeneralOK('{}'.format('Pong'))
Ejemplo n.º 8
0
def parseCsvMatch(csv_content, date=''):
    func = "match.parseCsvMatch()"
    error = ""

    data = csv.reader(StringIO.StringIO(csv_content), delimiter=',')

    column_headers = []

    player_ids = {} # dictionary of names mapping to id

    shots = []

    # First pass to create array of shot dictionaries
    row_no = 0
    for shotrow in data:
        col_no = 0
        shot = {}

        # Check number of columns
        if len(shotrow) != len(MATCH_COLUMNS):
            error = "bad number of csv columns"
            return error, 0

        for colval in shotrow:
            if row_no == 0:
                # Reverse lookup column header code to create dictionaries with keys from MATCH_COLUMNS
                try:
                    column_header = (key for key,value in MATCH_COLUMNS.items() if value==colval).next()
                    column_headers.append(column_header)
                except StopIteration:
                    error = "invalid csv header: "+colval
                    return error, 0
            else:
                # Find which column we're looking at based on headers
                col_type = column_headers[col_no]

                # Add value to shot dictionary
                shot[col_type] = colval

                # Set player names if not known, create players if they don't exist, trim spaces from player names
                if col_type == "PLAYER":
                    colval = colval.replace(" ", "")
                    if colval not in player_ids:
                        if len(player_ids) < 2:
                            player_ids[colval] = tplayer.getOrCreatePlayer(colval)
                        else:
                            error = "More than two players detected"
                            return error, 0

            col_no += 1

        # Add shot dictionary to list of shots
        if shot != {}:
            shots.append(shot)

        row_no += 1

    # Errors from first pass - Known issue: Won't work if one player doesn't pot
    if len(player_ids) != 2:
        error = "Invalid number of players: "+str(len(player_ids))
        return error, 0

    # Check if match might already exist
    # select m.match_id, count(distinct p.name), count(*)
    # from tmatch m, tframe f, tbreak b, tbreakpot bp, tmatchscore ms, tplayer p 
    # where m.match_id=f.match_id and f.frame_id=b.frame_id and b.break_id=bp.break_id and 
    #           m.match_id=ms.match_id and ms.player_id=p.player_id and p.name in ("David", "Jimmy")
    #  group by 1 having count(distinct p.name)=2;

    # Second pass to populate database
    # FIXME BEGIN TRANSACTION
    match_id = 0
    t = db.transaction()
    try:
        match_id = createMatch(date)
        cur_player_id = 0
        cur_frame_id = 0
        cur_frame = 0
        cur_break_id = 0
        cur_break = 0

        for shot in shots:
            cur_player_id = player_ids[shot['PLAYER']]

            if shot['FRAME'] != cur_frame: # New frame
                if cur_break_id > 0:
                    breakpot.closeBreak(cur_break_id)
                    cur_break_id = 0
                if cur_frame_id > 0:
                    tframe.closeFrame(cur_frame_id)
                cur_frame = shot['FRAME']
                cur_frame_id = tframe.createFrame(match_id, cur_frame)


            if shot['BREAK'] != cur_break or shot['BREAK'] == '': # New break
                if cur_break_id > 0:
                    breakpot.closeBreak(cur_break_id)
                if shot['BREAK'] != '':
                    cur_break = shot['BREAK']
                cur_break_id = breakpot.createBreak(cur_frame_id, cur_break, cur_player_id)

            # Register shot
            breakpot.pot(cur_break_id, shot['BALL'], shot['POINTS'], shot['TYPE'])

        if cur_break_id > 0:
            breakpot.closeBreak(cur_break_id)

        if cur_frame_id > 0:
            tframe.closeFrame(cur_frame_id)

        closeMatch(match_id)
        commitMatch(match_id)
    except Exception, e:
        log.error('Failed to create match - '+str(e))
        error = 'Failed to create match'
        log.error('rollback()')
        t.rollback()