Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import sqlite3
- import datetime
- local_db_path = "/home/pi/Scripts/blastardbot/bot.db" # Prod
- # local_db_path = "/home/pi/Scripts/blastardbot/bot-dev.db" # Dev
- class UpdateData():
- def __init__(self, player, slice_date):
- self.player = player
- self.slice_date = slice_date
- self.type = None
- self.incremental = 0
- self.estimated = 0
- self.estimate_rate = None
- self.calculated = 0
- self.kills = 0
- self.elapsed = 0
- # What the columns mean:
- # XPClan: Clan XP direct from the API
- # timeElapsed: seconds online in game for sample.
- # clanXPincremental: amount of XP earned in sample, as calculated
- # clanXPcalculated: total amount of clan XP earned as calculated
- # clanXPestimated: calculated estimated XP for capped members
- # clanXPestimateRate: this is either the rate used for clanXPestimated, or a rate equivalent to the calcuated rate.
- # Queries
- # This query selects the samples that needs updating
- SELECT_FUTURE_SLICES = '''
- SELECT player, date, timeElapsed, XPClan, killsNPC
- FROM stats
- WHERE clanXPtype is NULL and timeElapsed is NOT NULL
- AND (clanXPdataStatus IS NULL or clanXPdataStatus != 'A')
- ORDER BY player, date;
- '''
- # This query selects the previous sample for a sample being processed
- SELECT_PREV_SLICE = '''
- SELECT player, date, XPClan, clanXPtype, clanXPcalculated, timeElapsed, killsNPC
- FROM stats
- WHERE player = :player
- AND date < :slice_date
- AND clanXPtype != "X"
- AND (clanXPdataStatus IS NULL or clanXPdataStatus != 'A')
- ORDER BY date desc
- LIMIT 1;
- '''
- # Used to update the sample in the database
- UPDATE_SLICE = '''
- UPDATE stats
- SET clanXPtype = :type,
- clanXPincremental = :incremental,
- clanXPestimated = :estimated,
- clanXPestimateRate = :estimate_rate,
- clanXPcalculated = :calculated,
- killsIncremental = :kills,
- timeElapsed = :elapsed
- WHERE player = :player
- AND date = :slice_date;
- '''
- # To determine the estimated XP rate for a member
- SELECT_EST_RATE = '''
- SELECT
- sum(clanXPestimateRate)/count(*) as 'estimated_rate'
- FROM
- stats
- WHERE
- player = :player
- AND
- date >
- (
- SELECT
- date(substr(max(date),1,10),'-90 days')
- FROM
- stats
- WHERE
- player=:player
- AND
- clanXPtype = "I"
- AND
- clanXPestimateRate IS NOT NULL
- AND
- date < :sample_date
- )
- AND
- date <= :sample_date
- AND
- clanXPestimateRate IS NOT NULL;
- '''
- ### Config
- # For calcuation estimated rates, we only include samples covering 0:30 - 4:00 of game play
- DURATION_MIN = 60*30 # 30 minutes
- DURATION_MAX = 60*60*4 # 4 hours
- # Discount rates for estimated XP
- NORMAL_DISC_RATE = 0.70 # Use this for elapsed time within MIN and MAX
- ATYPICAL_DISC_RATE = 0.25 # Use this for elapsed time outside of MIN and MAX
- # DB Utiity Functions
- def get_rec(cursor, query, query_opts=None):
- result = None
- if query_opts is not None:
- cursor.execute(query, query_opts)
- else:
- cursor.execute(query)
- row = cursor.fetchone()
- if row is not None:
- result = dict(row)
- return result
- def query_db(cursor, query, query_opts=None):
- if query_opts is not None:
- cursor.execute(query, query_opts)
- else:
- cursor.execute(query)
- def get_next_rec(cursor):
- result = None
- row = cursor.fetchone()
- if row is not None:
- result = dict(row)
- return result
- def update_rec(cursor, query, update_opts=None):
- if update_opts is not None:
- cursor.execute(query, update_opts)
- else:
- cursor.execute(query)
- #########################
- ###
- ### START OF MAIN ROUTINE
- ###
- # Open the database
- db = sqlite3.connect(f"file:{local_db_path}", uri=True)
- db.row_factory = sqlite3.Row
- # Start processing loop
- # Fetch player and date for a single first, oldest NULL clanXPtype row (TARGET_ROW)
- # clanXPtype values:
- # N New
- # C Capped
- # R Reset
- # I Incremental (Normal)
- # X No activity (no time online)
- # Z Zero (no clan XP)
- # B Bugged (no XP earned)
- # First stats are slice 2020-01-29-23
- # Fetch single oldest clanXPtype row earlier than TARGET_ROW matching TARGET_ROW player
- # if none found, update TARGET_ROW with 0 earned, this is a baseline/first entry
- # if found, update TARGET_ROW with difference, if difference is 0 (non earned, check for CAP)
- # Load last on data for players
- found = True
- table_available = True
- cur = db.cursor()
- update_cur = db.cursor()
- prev_row_cur = db.cursor()
- est_cur = db.cursor()
- query_db(cur, SELECT_FUTURE_SLICES)
- while found and table_available:
- result = get_next_rec(cur)
- if result is None:
- found = False
- else:
- player = result['player']
- pending_slice_date = result['date']
- clan_xp = result['XPClan']
- elapsed = result['timeElapsed']
- total_kills = result['killsNPC']
- # These are the values we need to populate
- row_description = None
- row_type = None
- update_data = UpdateData(player, pending_slice_date)
- if elapsed < 0:
- elapsed = 0 # Correct for negative elapsed glitches
- update_data.elapsed = elapsed
- test_start = pending_slice_date
- prev_result = get_rec(prev_row_cur, SELECT_PREV_SLICE, {'player': player, 'slice_date' : pending_slice_date})
- if prev_result is not None:
- prev_calculated = prev_result['clanXPcalculated']
- prev_type = prev_result['clanXPtype']
- if prev_type == "Z":
- prev_xp = prev_result['clanXPcalculated']
- else:
- prev_xp = prev_result['XPClan']
- prev_kills = prev_result['killsNPC']
- session_kills = total_kills - prev_kills
- update_data.kills = session_kills
- # Are we capped? Two ways to find out.
- # If the previous sample was capped and we have the same amount of XP as that, we are capped
- # OR if we have the same XP as the previous row and we've spent time and had some kills (not perfect, but good enough)
- # Also there's a bug where some capped players go to zero and stay that way, and we need to flag
- # them as capped and not just zero (which is otherwise a different bug)
- if (prev_xp == clan_xp or (clan_xp == 0 and prev_type == "C")) and elapsed > 0 and session_kills > 0 :
- if (clan_xp < 2000000000 and clan_xp >0) or elapsed < 0:
- update_data.type = "B"
- row_description = "Bugged"
- update_data.incremental = 0
- update_data.calculated = prev_calculated
- else:
- update_data.type = "C"
- row_description = "Capped"
- # We need to calculate ESTIMATED XP here.
- disc_rate = NORMAL_DISC_RATE
- if elapsed < DURATION_MIN or elapsed > DURATION_MAX:
- disc_rate = ATYPICAL_DISC_RATE
- est_result = get_rec(est_cur, SELECT_EST_RATE, {'sample_date' : update_data.slice_date, 'player': player})
- est_rate = int(est_result['estimated_rate'] * disc_rate)
- est_xp = est_rate * elapsed
- update_data.estimate_rate = est_rate
- update_data.estimated = est_xp
- update_data.incremental = 0
- update_data.calculated = prev_calculated + est_xp
- else:
- # Did someone get reset (leave and rejoin)? We can tell because the clan XP will drop below what it was (probably)
- if prev_xp > clan_xp:
- if clan_xp == 0: # If it's zero, this is just a ZERO row
- update_data.type = "Z"
- row_description = "Zero clan XP"
- update_data.incremental = 0
- update_data.calculated = prev_calculated + update_data.incremental
- else: # Otherwise we have a member who was reset (left/joined)
- update_data.type = "R"
- row_description = "Reset"
- update_data.incremental = clan_xp
- update_data.calculated = prev_calculated + update_data.incremental
- else:
- # Was the player not online at all?
- if (elapsed == 0 or session_kills ==0) and (clan_xp - prev_xp) == 0:
- update_data.type = "X"
- row_description = "No activity"
- update_data.calculated = prev_calculated
- else: # There was some kind of activity for this sample
- update_data.type ="I"
- row_description = "Incremental"
- update_data.incremental = clan_xp - prev_xp
- update_data.calculated = prev_calculated + update_data.incremental
- # If this session is a more typical duration, we can calc the XP rate
- if elapsed >= DURATION_MIN and elapsed <= DURATION_MAX:
- # calculate xp rate
- update_data.estimate_rate = int(update_data.incremental / elapsed)
- else:
- # This member is new (i.e. first sample for the player)
- update_data.type = "N" # New
- row_description = "New"
- session_kills = total_kills
- update_data.incremental = clan_xp
- update_data.calculated = clan_xp
- update_data.kills = session_kills
- prev_xp = 0
- # We do not set an estimate_rate for new players
- display_rate = 0 # Just used for the console display
- if update_data.estimate_rate is not None:
- display_rate = update_data.estimate_rate
- if update_data.estimated > 0:
- xp_type="est"
- xp_value = update_data.estimated
- else:
- xp_type="inc"
- xp_value = update_data.incremental
- if update_data.type != "X":
- # We show samples with no activity without a linefeed on the console, so it's easier to read changes
- print(f" {player:<12}|{update_data.slice_date}|{update_data.type}|cxp: {clan_xp:>12,}|elap: {elapsed:>6,}|kills: {session_kills:>6,}|{xp_type} cxp: {xp_value:>11,}|calc cxp: {update_data.calculated:>12,}|est.rate: {display_rate:>6,}")
- else:
- print(f" {player:<12}|{update_data.slice_date}|{update_data.type}|cxp: {clan_xp:>12,}|elap: {elapsed:>6,}|kills: {session_kills:>6,}|{xp_type} cxp: {xp_value:>11,}|calc cxp: {update_data.calculated:>12,}|est.rate: {display_rate:>6,}", end='\r', flush=True)
- # Save to the database!
- update_rec(update_cur, UPDATE_SLICE, vars(update_data))
- db.commit()
- # We commit after each update so that any contention
- # on the database with a lock will fail immediately
- # We don't want this process locking the database for any duration,
- # since it can resume after failure without issue on a subsequent run
- db.close()
- print("")
- print("Complete.")
Advertisement
Add Comment
Please, Sign In to add comment