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.
 
 
 
 
 

138 lines
5.4 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["killTime"], "%Y-%m-%d %H:%M:%S")
  80. except ValueError:
  81. raise RuntimeError("Invalid kill_date=%s for kill_id=%d" % (
  82. kill["killTime"], kill["killID"]))
  83. query = """INSERT OR REPLACE INTO kill (
  84. kill_id, kill_date, kill_system, kill_victim_shipid,
  85. kill_victim_charid, kill_victim_corpid, kill_victim_allianceid,
  86. kill_victim_factionid, kill_value)
  87. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"""
  88. args = (
  89. kill["killID"], kill["killTime"], kill["solarSystemID"],
  90. kill["victim"]["shipTypeID"], kill["victim"]["characterID"],
  91. kill["victim"]["corporationID"], kill["victim"]["allianceID"],
  92. kill["victim"]["factionID"], kill["zkb"]["totalValue"])
  93. with self._conn as conn:
  94. conn.execute(query, args)
  95. def get_kill_associations(self, campaign, kill_id):
  96. """Return a list of operations associated with a campaign and kill."""
  97. query = """SELECT ok_operation FROM oper_kill
  98. WHERE ok_campaign = ? AND ok_killid = ?"""
  99. res = self._conn.execute(query, (campaign, kill_id)).fetchall()
  100. return [row[0] for row in res]
  101. def associate_kill(self, campaign, kill_id, operations):
  102. """Associate a killmail with a set of campaign/operations."""
  103. query = """INSERT OR IGNORE INTO oper_kill
  104. (ok_campaign, ok_operation, ok_killid) VALUES (?, ?, ?)"""
  105. arglist = [(campaign, op, kill_id) for op in operations]
  106. with self._conn as conn:
  107. conn.executemany(query, arglist)
  108. def count_kills(self, campaign, operation):
  109. """Return the number of matching kills and the total kill value."""
  110. query = """SELECT COUNT(*), TOTAL(kill_value)
  111. FROM oper_kill
  112. JOIN kill ON ok_killid = kill_id
  113. WHERE ok_campaign = ? AND ok_operation = ?"""
  114. res = self._conn.execute(query, (campaign, operation)).fetchall()
  115. return tuple(res[0])