upload_run_scenario.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #!/usr/bin/python3
  2. import sqlite3
  3. import json
  4. import sys
  5. import os
  6. """
  7. Reads the API KEY, that must be passed as first command line argument.
  8. :returns: Recovered API KEY.
  9. :raises Exception: Th KEY couldn't be red.
  10. """
  11. def readKey():
  12. try:
  13. #print(sys.argv[0])
  14. key = sys.argv[1]
  15. return key
  16. except Exception as e:
  17. print("Error parsing API KEY: " + str(e))
  18. raise
  19. """
  20. Reads the JSON data, that must be passed as second command line argument.
  21. :returns: Recovered data, in JSON format.
  22. :raises Exception: The data couldn't be red or converted to JSON.
  23. """
  24. def readData():
  25. try:
  26. data = json.loads(sys.argv[2])
  27. return data
  28. except Exception as e:
  29. print("Error parsing data: " + str(e))
  30. raise
  31. """
  32. Verifies that the API key matches the player data and that it exists in th DB.
  33. :param db: Connection to the database.
  34. :returns: Connection to the database.
  35. :param data: Data in json format.
  36. :param key: API KEY.
  37. :returns: True if key and player match, False otherwise.
  38. :raises IntegrityError: The queryes couldn't bre executed.
  39. """
  40. def verifyKey(db, data, key):
  41. print('Verifying KEY...')
  42. status = False
  43. try:
  44. uid = data["wizard_info"]["wizard_id"]
  45. cursor = db.cursor()
  46. cursor.execute('SELECT count(uid) AS c FROM player WHERE uid = ? AND api_key = ?;', (uid, key))
  47. if cursor.fetchone()[0] == 1:
  48. status = True
  49. cursor.close()
  50. except sqlite3.IntegrityError as e:
  51. print("Error executing statement: " + str(e))
  52. raise
  53. return status
  54. """
  55. Opens the database file and deletes from the user tables
  56. :param name: The path to the sqlite database.
  57. :returns: Connection to the database.
  58. :raises IntegrityError: The queryes couldn't bre executed.
  59. :raises IOError: The sqlite file couldn't be created.
  60. """
  61. def openDatabase():
  62. kdb = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../../../sw.sqlite'
  63. udb = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../../../../data/sw.sqlite'
  64. print('Configuring database...')
  65. try:
  66. db = sqlite3.connect(kdb)
  67. cursor = db.cursor()
  68. cursor.execute('attach "' + udb + '" as data;')
  69. cursor.close()
  70. return db
  71. except sqlite3.IntegrityError as e:
  72. print("Error executing statement: " + str(e))
  73. raise
  74. except IOError as e:
  75. print("I/O Error creating database " + name + ": " + str(e))
  76. raise
  77. """
  78. Inserts a row into the database.
  79. :param db: Connection to the database.
  80. :param table: Name of the table to insert into.
  81. :param values: List of values to insert.
  82. :raises IntegrityError: The insert query was unsuccesfull.
  83. """
  84. def insert(db, table, values):
  85. cursor = db.cursor()
  86. placeholders = ''
  87. for x in range(0, len(values)):
  88. placeholders = placeholders + '?, '
  89. placeholders = placeholders[:len(placeholders) - 2]
  90. query = 'INSERT INTO ' + table + ' VALUES (' + placeholders + ')'
  91. try:
  92. cursor.execute(query, values)
  93. except sqlite3.IntegrityError as e:
  94. print('Error Inserting into ' + table + ' with values (' + str(values) + '): ' + str(e))
  95. raise
  96. cursor.close;
  97. """
  98. Parses run data (tables run, run_party, run_drop_rune, run_drop_runecraft,
  99. run_drop_item, run_drop_unit, run_drop_sd, run_drop_unit_pieces,
  100. run_drop_shapeshifting).
  101. :param db: Sqlite database connection.
  102. :param data: JSON data.
  103. """
  104. def parseRun(db, data):
  105. print("Parsing run...")
  106. cursor = db.cursor()
  107. uid = data["wizard_info"]["wizard_id"]
  108. dtime = data["tvaluelocal"]
  109. # Check if run has already been inserted.
  110. cursor.execute("SELECT count(id) AS c FROM run WHERE uid = ? AND dtime = ?;", (uid, dtime))
  111. if (cursor.fetchone()[0] > 0):
  112. print(" Run already in database. Stopping....")
  113. return;
  114. area_type = 1 #scenario
  115. area = data["scenario_info"]["region_id"]
  116. stage = data["scenario_info"]["stage_no"]
  117. difficulty = data["scenario_info"]["difficulty"]
  118. win = data["win_lose"]
  119. time = data["clear_time"]["current_time"]
  120. if ("mana" in data["reward"]):
  121. mana = data["reward"]["mana"]
  122. else:
  123. mana = 0
  124. if ("energy" in data["reward"]):
  125. energy = mana = data["reward"]["energy"]
  126. else:
  127. energy = 0
  128. if ("crystal" in data["reward"]):
  129. crystal = mana = data["reward"]["crystal"]
  130. else:
  131. crystal = 0
  132. helper = data["helper"]
  133. cursor.execute("SELECT max(id) + 1 AS id FROM run;")
  134. id = cursor.fetchone()[0]
  135. if id == None:
  136. id = 1
  137. insert(db, "run", (uid, id, dtime, area, stage, difficulty, win, time, mana, energy, crystal, helper))
  138. if data["shapeshifting"] > 0:
  139. insert(db, "run_drop_shapeshifting", (id, data["shapeshifting"]))
  140. if data["sd"] > 0:
  141. insert(db, "run_drop_sd", (id, data["sd"]))
  142. if data["sd"] > 0:
  143. insert(db, "run_drop_unit", (id, data["unit"]))
  144. for rune in data["rune"]:
  145. rune_id = rune["id"]
  146. rune_type = rune["type"]
  147. slot = rune["slot"]
  148. stars = rune["stars"]
  149. ancient = rune["ancient"]
  150. quality = rune["quality"]
  151. value = rune["value"]
  152. efficiency = rune["efficiency"]
  153. main_stat = rune["main_stat"]
  154. main_stat_value = rune["main_stat_value"]
  155. innate_stat = rune["innate_stat"]
  156. innate_stat_value = rune["innate_stat_value"]
  157. substat_1 = rune["substat_1"]
  158. substat_1_value = rune["substat_1_value"]
  159. substat_2 = rune["substat_2"]
  160. substat_2_value = rune["substat_2_value"]
  161. substat_3 = rune["substat_3"]
  162. substat_3_value = rune["substat_3_value"]
  163. substat_4 = rune["substat_4"]
  164. substat_4_value = rune["substat_4_value"]
  165. insert(db, "run_drop_rune", (id, rune_id, rune_type, slot, stars, ancient, quality, value, efficiency, main_stat, main_stat_value, innate_stat, innate_stat_value, substat_1, substat_1_value, substat_2, substat_2_value, substat_3, substat_3_value, substat_4, substat_4_value))
  166. for item in data["item"]:
  167. item_id = item["id"]
  168. quantity = item["quantity"]
  169. insert(db, "run_drop_item", (id, item_id, quantity))
  170. for pieces in data["unit_pieces"]:
  171. pieces_id = pieces["id"]
  172. quantity = pieces["quantity"]
  173. insert(db, "run_drop_unit_pieces", (id, pieces_id, quantity))
  174. for party in data["party"]:
  175. unit_id = party["unit_id"]
  176. unit_master_id = party["unit_master_id"]
  177. insert(db, "run_party", (id, unit_master_id, unit_id))
  178. db.commit()
  179. """
  180. Begin script
  181. """
  182. data = readData()
  183. key = readKey()
  184. db = openDatabase()
  185. if verifyKey(db, data, key) == False:
  186. print("Invalid API KEY...")
  187. sys.exit(-1)
  188. else:
  189. parseRun(db, data)
  190. sys.exit(0)