A corporation manager and dashboard for EVE Online
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

251 lines
10 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. import sqlite3
  4. from flask import g
  5. from werkzeug.local import LocalProxy
  6. __all__ = ["CampaignDB"]
  7. class CampaignDB:
  8. """Database manager for internal storage for the Campaigns module."""
  9. path = None
  10. def __init__(self):
  11. if self.path is None:
  12. raise RuntimeError("CampaignDB.path not set")
  13. self._conn = sqlite3.connect(self.path)
  14. @classmethod
  15. def _get(cls):
  16. """Return the current database, or allocate a new one if necessary."""
  17. if not hasattr(g, "_campaign_db"):
  18. g._campaign_db = cls()
  19. return g._campaign_db
  20. @classmethod
  21. def pre_hook(cls):
  22. """Hook to be called before a request context.
  23. Sets up the g.campaign_db proxy.
  24. """
  25. g.campaign_db = LocalProxy(cls._get)
  26. @classmethod
  27. def post_hook(cls, exc):
  28. """Hook to be called when tearing down an application context.
  29. Closes the database if necessary.
  30. """
  31. if hasattr(g, "_campaign_db"):
  32. g._campaign_db.close()
  33. def close(self):
  34. """Close the database connection."""
  35. return self._conn.close()
  36. def check_operation(self, campaign, operation):
  37. """Return the last updated timestamp and key for the given operation.
  38. Return (None, None) if the given operation was never updated.
  39. """
  40. query = """SELECT lu_date, lu_key FROM last_updated
  41. WHERE lu_campaign = ? AND lu_operation = ?"""
  42. res = self._conn.execute(query, (campaign, operation)).fetchall()
  43. if not res:
  44. return None, None
  45. return datetime.strptime(res[0][0], "%Y-%m-%d %H:%M:%S"), res[0][1]
  46. def touch_operation(self, campaign, operation, key=None):
  47. """Mark the given operation as just updated, or add it."""
  48. with self._conn as conn:
  49. cur = conn.execute("BEGIN TRANSACTION")
  50. cur.execute("""UPDATE last_updated
  51. SET lu_date = CURRENT_TIMESTAMP, lu_key = ?
  52. WHERE lu_campaign = ? AND lu_operation = ?""", (
  53. key, campaign, operation))
  54. if cur.rowcount == 0:
  55. cur.execute("""INSERT INTO last_updated
  56. (lu_campaign, lu_operation, lu_key) VALUES (?, ?, ?)""", (
  57. campaign, operation, key))
  58. def set_overview(self, campaign, operation, primary, secondary=None):
  59. """Set overview information for this operation."""
  60. with self._conn as conn:
  61. conn.execute("""INSERT OR REPLACE INTO overview
  62. (ov_campaign, ov_operation, ov_primary, ov_secondary)
  63. VALUES (?, ?, ?, ?)""", (
  64. campaign, operation, primary, secondary))
  65. def get_overview(self, campaign, operation):
  66. """Return a 2-tuple of overview information for this operation."""
  67. query = """SELECT ov_primary, ov_secondary FROM overview
  68. WHERE ov_campaign = ? AND ov_operation = ?"""
  69. res = self._conn.execute(query, (campaign, operation)).fetchall()
  70. return tuple(res[0]) if res else (0, None)
  71. def has_kill(self, kill_id):
  72. """Return whether the database has a killmail with the given ID."""
  73. query = "SELECT 1 FROM kill WHERE kill_id = ?"
  74. res = self._conn.execute(query, (kill_id,)).fetchall()
  75. return bool(res)
  76. def add_kill(self, kill):
  77. """Insert a killmail into the database."""
  78. try:
  79. datetime.strptime(kill["killmail_time"], "%Y-%m-%d %H:%M:%S")
  80. except ValueError:
  81. raise RuntimeError("Invalid kill_date=%s for kill_id=%d" % (
  82. kill["killmail_time"], kill["killmail_id"]))
  83. query = """INSERT OR REPLACE INTO kill (
  84. kill_id, kill_date, kill_system, kill_victim_shipid,
  85. kill_victim_charid, kill_victim_charname, kill_victim_corpid,
  86. kill_victim_corpname, kill_victim_allianceid,
  87. kill_victim_alliancename, kill_victim_factionid,
  88. kill_victim_factionname, kill_value)
  89. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
  90. victim = kill["victim"]
  91. args = (
  92. int(kill["killmail_id"]), kill["killmail_time"],
  93. int(kill["solar_system_id"]), int(victim["ship_type_id"]),
  94. int(victim["character_id"]), victim["character_name"],
  95. int(victim["corporation_id"]), victim["corporation_name"],
  96. int(victim["alliance_id"]), victim["alliance_name"],
  97. int(victim["faction_id"]), victim["faction_name"],
  98. float(kill["zkb"]["totalValue"]))
  99. with self._conn as conn:
  100. conn.execute(query, args)
  101. def get_kill_associations(self, campaign, kill_id):
  102. """Return a list of operations associated with a campaign and kill."""
  103. query = """SELECT ok_operation FROM oper_kill
  104. WHERE ok_campaign = ? AND ok_killid = ?"""
  105. res = self._conn.execute(query, (campaign, kill_id)).fetchall()
  106. return [row[0] for row in res]
  107. def associate_kill(self, campaign, kill_id, operations):
  108. """Associate a killmail with a set of campaign/operations."""
  109. query = """INSERT OR IGNORE INTO oper_kill
  110. (ok_campaign, ok_operation, ok_killid) VALUES (?, ?, ?)"""
  111. arglist = [(campaign, op, kill_id) for op in operations]
  112. with self._conn as conn:
  113. conn.executemany(query, arglist)
  114. def count_kills(self, campaign, operation):
  115. """Return the number of matching kills and the total kill value."""
  116. query = """SELECT COUNT(*), TOTAL(kill_value)
  117. FROM oper_kill
  118. JOIN kill ON ok_killid = kill_id
  119. WHERE ok_campaign = ? AND ok_operation = ?"""
  120. res = self._conn.execute(query, (campaign, operation)).fetchall()
  121. return tuple(res[0])
  122. def get_associated_kills(self, campaign, operation, sort="new", limit=-1,
  123. offset=0):
  124. """Return a list of kills associated with a campaign/operation.
  125. Kills are returned as dictionaries, up to a limit. Use -1 for no limit.
  126. The sort should be "new" for most recent first, "old" for most recent
  127. last, or "value" for most valuable first.
  128. """
  129. sortkeys = {
  130. "new": "ok_killid DESC",
  131. "old": "ok_killid ASC",
  132. "value": "kill_value DESC, ok_killid DESC"
  133. }
  134. if sort in sortkeys:
  135. sortkey = sortkeys[sort]
  136. else:
  137. raise ValueError(sort)
  138. if not isinstance(limit, int):
  139. raise ValueError(limit)
  140. if not isinstance(offset, int):
  141. raise ValueError(offset)
  142. query = """SELECT kill_id, kill_date, kill_system, kill_victim_shipid,
  143. kill_victim_charid, kill_victim_charname, kill_victim_corpid,
  144. kill_victim_corpname, kill_victim_allianceid,
  145. kill_victim_alliancename, kill_victim_factionid,
  146. kill_victim_factionname, kill_value
  147. FROM oper_kill
  148. JOIN kill ON ok_killid = kill_id
  149. WHERE ok_campaign = ? AND ok_operation = ?
  150. ORDER BY {} LIMIT {} OFFSET {}"""
  151. qform = query.format(sortkey, limit, offset)
  152. res = self._conn.execute(qform, (campaign, operation)).fetchall()
  153. return [{
  154. "id": row[0],
  155. "date": datetime.strptime(row[1], "%Y-%m-%d %H:%M:%S"),
  156. "system": row[2],
  157. "victim": {
  158. "ship_id": row[3],
  159. "char_id": row[4],
  160. "char_name": row[5],
  161. "corp_id": row[6],
  162. "corp_name": row[7],
  163. "alliance_id": row[8],
  164. "alliance_name": row[9],
  165. "faction_id": row[10],
  166. "faction_name": row[11]
  167. },
  168. "value": row[12]
  169. } for row in res]
  170. def update_items(self, campaign, data):
  171. """Update all item details in the database for the given campaign.
  172. The data should be a multi-layered dictionary. It maps operation names
  173. to a dict that maps character IDs to a dict that maps type IDs to
  174. tuples of integer counts and float values.
  175. """
  176. with self._conn as conn:
  177. cur = conn.execute("BEGIN TRANSACTION")
  178. query = "DELETE FROM oper_item WHERE oi_campaign = ?"
  179. cur.execute(query, (campaign,))
  180. query = """INSERT INTO oper_item (
  181. oi_campaign, oi_operation, oi_character, oi_type, oi_count,
  182. oi_value)
  183. VALUES (?, ?, ?, ?, ?, ?)"""
  184. cur.executemany(query, [
  185. (campaign, operation, int(char_id), int(type_id), int(count),
  186. float(value))
  187. for operation, chars in data.items()
  188. for char_id, types in chars.items()
  189. for type_id, (count, value) in types.items()])
  190. def get_associated_items(self, campaign, operation, sort="value", limit=-1,
  191. offset=0):
  192. """Return a list of items associated with a campaign/operation.
  193. Items are returned as 2-tuples of (item_type, item_count), up to a
  194. limit. Use -1 for no limit. The sort should be "value" for most
  195. valuable first (individual item value * quantity), "quantity" for
  196. greatest quantity first, "price" for most valuable items first.
  197. """
  198. sortkeys = {
  199. "value": "total_value DESC",
  200. "quantity": "total_count DESC",
  201. "price": "(total_value / total_count) DESC"
  202. }
  203. if sort in sortkeys:
  204. sortkey = sortkeys[sort]
  205. else:
  206. raise ValueError(sort)
  207. if not isinstance(limit, int):
  208. raise ValueError(limit)
  209. if not isinstance(offset, int):
  210. raise ValueError(offset)
  211. query = """SELECT oi_type, SUM(oi_count) AS total_count,
  212. TOTAL(oi_value) as total_value
  213. FROM oper_item
  214. WHERE oi_campaign = ? AND oi_operation = ?
  215. GROUP BY oi_type ORDER BY {} LIMIT {} OFFSET {}"""
  216. qform = query.format(sortkey, limit, offset)
  217. res = self._conn.execute(qform, (campaign, operation)).fetchall()
  218. return [(type_id, count or 0, value) for type_id, count, value in res]