| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 |
- #!/usr/bin/python3
- import sqlite3
- import json
- import sys
- import os
- import math
- """
- Reads the API KEY, that must be passed as first command line argument.
- :returns: Recovered API KEY.
- :raises Exception: Th KEY couldn't be red.
- """
- def readKey():
- try:
- key = sys.argv[1]
- return key
- except Exception as e:
- print("Error parsing API KEY: " + str(e))
- raise
- """
- Reads the JSON data, that must be passed as second command line argument.
- :param: index 2 for start data, 3 for result data
- :returns: Recovered data, in JSON format.
- :raises Exception: The data couldn't be red or converted to JSON.
- """
- def readData(index):
- try:
- data = json.loads(sys.argv[index])
- return data
- except Exception as e:
- print("Error parsing data: " + str(e))
- raise
- """
- Verifies that the API key matches the player data and that it exists in th DB.
- :param db: Connection to the database.
- :returns: Connection to the database.
- :param data: Data in json format.
- :param key: API KEY.
- :returns: True if key and player match, False otherwise.
- :raises IntegrityError: The queryes couldn't bre executed.
- """
- def verifyKey(db, data, key):
- print('Verifying KEY...')
- status = False
- try:
- uid = data["wizard_info"]["wizard_id"]
- cursor = db.cursor()
- cursor.execute('SELECT count(uid) AS c FROM player WHERE uid = ? AND api_key = ?;', (uid, key))
- if cursor.fetchone()[0] == 1:
- status = True
- cursor.close()
- except sqlite3.IntegrityError as e:
- print("Error executing statement: " + str(e))
- raise
- return status
- """
- Opens the database file and deletes from the user tables
- :param name: The path to the sqlite database.
- :returns: Connection to the database.
- :raises IntegrityError: The queryes couldn't bre executed.
- :raises IOError: The sqlite file couldn't be created.
- """
- def openDatabase():
- kdb = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../../../sw.sqlite'
- udb = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../../../../data/sw.sqlite'
- print('Configuring database...')
- try:
- db = sqlite3.connect(kdb)
- cursor = db.cursor()
- cursor.execute('attach "' + udb + '" as data;')
- cursor.close()
- return db
- except sqlite3.IntegrityError as e:
- print("Error executing statement: " + str(e))
- raise
- except IOError as e:
- print("I/O Error opening database " + name + ": " + str(e))
- raise
- """
- Inserts a row into the database.
- :param db: Connection to the database.
- :param table: Name of the table to insert into.
- :param values: List of values to insert.
- :raises IntegrityError: The insert query was unsuccesfull.
- """
- def insert(db, table, values):
- cursor = db.cursor()
- placeholders = ''
- for x in range(0, len(values)):
- placeholders = placeholders + '?, '
- placeholders = placeholders[:len(placeholders) - 2]
- query = 'INSERT INTO ' + table + ' VALUES (' + placeholders + ')'
- try:
- cursor.execute(query, values)
- except sqlite3.IntegrityError as e:
- print('Error Inserting into ' + table + ' with values (' + str(values) + '): ' + str(e))
- raise
- cursor.close;
- """
- Parses run data (tables run, run_party, run_drop_rune, run_drop_runecraft,
- run_drop_item, run_drop_unit, run_drop_sd, run_drop_unit_pieces,
- run_drop_shapeshifting).
- :param db: Sqlite database connection.
- :param data_start: JSON data of the run start.
- :param data_result: JSON data of the run result.
- """
- def parseRun(db, data_request, data_response):
- print("Parsing run...")
- cursor = db.cursor()
- # Read basic data
- uid = data_request["wizard_id"]
- dtime = data_response["tvaluelocal"]
- # Check if run has already been inserted.
- cursor.execute("SELECT count(id) AS c FROM run WHERE uid = ? AND dtime = ?;", (uid, dtime))
- if (cursor.fetchone()[0] > 0):
- print(" Run already in database. Stopping....")
- return 409;
- # We are inserting, get aditional info
- area_type = 10 # TOA
- area = 10 # TOA
- stage = data_request["floor_id"]
- difficulty = data_request["difficulty"]
- win = data_response["win_lose"]
- time = data_request["clear_time"]
- helper = 0
- # Get the new ID and insert
- cursor.execute("SELECT max(id) + 1 AS id FROM run;")
- id = cursor.fetchone()[0]
- if id == None:
- id = 1
- # Calculate rewards
- mana = 0
- energy = 0
- crystal = 0
- if stage == 10:
- energy = 50
- elif stage == 20:
- # Rainbowmon 3* MAX
- insert(db, "run_drop_item", (id, 143140325, 1))
- elif stage == 30:
- # Mystical Scroll
- insert(db, "run_drop_item", (id, 3, 1))
- elif stage == 40:
- crystal = 100
- elif stage == 50:
- # Mystical Scroll
- insert(db, "run_drop_item", (id, 3, 2))
- elif stage == 60:
- # Rainbowmon 4* MAX
- insert(db, "run_drop_item", (id, 143140430, 1))
- elif stage == 70:
- # Devilmon
- insert(db, "run_drop_item", (id, 151050101, 1))
- elif stage == 80:
- crystal = 300
- elif stage == 90:
- # Light and Dark Scroll
- insert(db, "run_drop_item", (id, 11, 1))
- elif stage == 100:
- # Legendary Scroll
- insert(db, "run_drop_item", (id, 10, 1))
- elif stage / 5 == 0:
- crystal = 10 * int(math.ceil((stage / 2) / 10) + 1)
- else:
- # Summon stone
- insert(db, "run_drop_item", (id, 8, 1))
- # Insert
- insert(db, "run", (uid, id, dtime, area_type, area, stage, difficulty, win, time, mana, energy, crystal, helper))
- # Parse units
- i = 0
- for unit in data_request["unit_id_list"]:
- unit_id = unit["unit_id"]
- cursor.execute("SELECT unit FROM unit WHERE uid = ? AND id = ?;", (uid, unit_id))
- unit_master_id = cursor.fetchone()[0]
- for k_unit in data_response["unit_list"]:
- if k_unit["unit_id"] == unit["unit_id"]:
- unit_master_id = k_unit["unit_master_id"];
- break;
- if i == 0:
- leader = 1 # TODO UNKNOWABLE? Check event start
- else:
- leader = 0
- front = 0
- insert(db, "run_party", (id, unit_master_id, unit_id, leader, front))
- i += 1
- db.commit()
- """
- Begin script
- """
- data_request = readData(2)
- data_response = readData(3)
- key = readKey()
- db = openDatabase()
- if verifyKey(db, data_response, key) == False:
- print("Invalid API KEY...")
- sys.exit(401)
- else:
- try:
- parseRun(db, data_request, data_response)
- except Exception as e:
- print("Error parsing TOA run: " + str(e))
- sys.exit(400)
- sys.exit(201)
|