A corporation manager and dashboard for EVE Online
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 

170 строки
6.7 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. # ... Ensure IDs are all ints
  84. query = """INSERT OR REPLACE INTO kill (
  85. kill_id, kill_date, kill_system, kill_victim_shipid,
  86. kill_victim_charid, kill_victim_corpid, kill_victim_allianceid,
  87. kill_victim_factionid, kill_value)
  88. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"""
  89. args = (
  90. kill["killID"], kill["killTime"], kill["solarSystemID"],
  91. kill["victim"]["shipTypeID"], kill["victim"]["characterID"],
  92. kill["victim"]["corporationID"], kill["victim"]["allianceID"],
  93. kill["victim"]["factionID"], kill["zkb"]["totalValue"])
  94. with self._conn as conn:
  95. conn.execute(query, args)
  96. def get_kill_associations(self, campaign, kill_id):
  97. """Return a list of operations associated with a campaign and kill."""
  98. query = """SELECT ok_operation FROM oper_kill
  99. WHERE ok_campaign = ? AND ok_killid = ?"""
  100. res = self._conn.execute(query, (campaign, kill_id)).fetchall()
  101. return [row[0] for row in res]
  102. def associate_kill(self, campaign, kill_id, operations):
  103. """Associate a killmail with a set of campaign/operations."""
  104. query = """INSERT OR IGNORE INTO oper_kill
  105. (ok_campaign, ok_operation, ok_killid) VALUES (?, ?, ?)"""
  106. arglist = [(campaign, op, kill_id) for op in operations]
  107. with self._conn as conn:
  108. conn.executemany(query, arglist)
  109. def count_kills(self, campaign, operation):
  110. """Return the number of matching kills and the total kill value."""
  111. query = """SELECT COUNT(*), TOTAL(kill_value)
  112. FROM oper_kill
  113. JOIN kill ON ok_killid = kill_id
  114. WHERE ok_campaign = ? AND ok_operation = ?"""
  115. res = self._conn.execute(query, (campaign, operation)).fetchall()
  116. return tuple(res[0])
  117. def get_associated_kills(self, campaign, operation, limit=5, offset=0):
  118. """Return a list of kills associated with a campaign/operation.
  119. Kills are returned as dictionaries most recent first, up to a limit.
  120. Use -1 for no limit.
  121. """
  122. if not isinstance(limit, int):
  123. raise ValueError(limit)
  124. if not isinstance(offset, int):
  125. raise ValueError(offset)
  126. query = """SELECT kill_id, kill_date, kill_system, kill_victim_shipid,
  127. kill_victim_charid, kill_victim_corpid, kill_victim_allianceid,
  128. kill_victim_factionid, kill_value
  129. FROM oper_kill
  130. JOIN kill ON ok_killid = kill_id
  131. WHERE ok_campaign = ? AND ok_operation = ?
  132. ORDER BY ok_killid DESC LIMIT {} OFFSET {}"""
  133. qform = query.format(limit, offset)
  134. res = self._conn.execute(qform, (campaign, operation)).fetchall()
  135. return [{
  136. "id": row[0],
  137. "date": datetime.strptime(row[1], "%Y-%m-%d %H:%M:%S"),
  138. "system": row[2],
  139. "victim": {
  140. "ship_id": row[3], "char_id": row[4], "corp_id": row[5],
  141. "alliance_id": row[6], "faction_id": row[7]},
  142. "value": row[8]
  143. } for row in res]