From 1a11202aea5e040a7a0b3c79c794c949c4c4806c Mon Sep 17 00:00:00 2001
From: Athanasius <github@miggy.org>
Date: Sat, 27 Jun 2020 03:54:00 +0100
Subject: [PATCH] Implement tracking station MarketID, and use in eddb plugin

 * Adds monitor.station_marketid, tracked at the same points as
   monitor.station (name).
 * Changes EDDB plugin to also track its own this.station_marketid so
   that it can be used in /market-id/ EDDB URL.
   This removes a use case for stations.p file.
---
 monitor.py      | 11 ++++++++++-
 plugins/eddb.py | 26 ++++++++++++++++++++------
 2 files changed, 30 insertions(+), 7 deletions(-)

diff --git a/monitor.py b/monitor.py
index b408f2b3..e88d37de 100644
--- a/monitor.py
+++ b/monitor.py
@@ -82,6 +82,7 @@ class EDLogs(FileSystemEventHandler):
         self.planet = None
         self.system = None
         self.station = None
+        self.station_marketid = None
         self.stationtype = None
         self.coordinates = None
         self.systemaddress = None
@@ -166,7 +167,7 @@ class EDLogs(FileSystemEventHandler):
         if __debug__:
             print('Stopping monitoring Journal')
         self.currentdir = None
-        self.version = self.mode = self.group = self.cmdr = self.planet = self.system = self.station = self.stationtype = self.stationservices = self.coordinates = self.systemaddress = None
+        self.version = self.mode = self.group = self.cmdr = self.planet = self.system = self.station = self.station_marketid = self.stationtype = self.stationservices = self.coordinates = self.systemaddress = None
         self.is_beta = False
         if self.observed:
             self.observed = None
@@ -229,6 +230,7 @@ class EDLogs(FileSystemEventHandler):
                 if self.station:
                     entry['StationName'] = self.station
                     entry['StationType'] = self.stationtype
+                    entry['MarketID'] = self.station_marketid
                 self.event_queue.append(json.dumps(entry, separators=(', ', ':')))
             else:
                 self.event_queue.append(None)	# Generate null event to update the display (with possibly out-of-date info)
@@ -305,6 +307,7 @@ class EDLogs(FileSystemEventHandler):
                 self.planet = None
                 self.system = None
                 self.station = None
+                self.station_marketid = None
                 self.stationtype = None
                 self.stationservices = None
                 self.coordinates = None
@@ -344,6 +347,7 @@ class EDLogs(FileSystemEventHandler):
                 self.planet = None
                 self.system = None
                 self.station = None
+                self.station_marketid = None
                 self.stationtype = None
                 self.stationservices = None
                 self.coordinates = None
@@ -429,6 +433,7 @@ class EDLogs(FileSystemEventHandler):
                     self.state['Modules'].pop(entry['FromSlot'], None)
             elif entry['event'] in ['Undocked']:
                 self.station = None
+                self.station_marketid = None
                 self.stationtype = None
                 self.stationservices = None
             elif entry['event'] in ['Location', 'FSDJump', 'Docked', 'CarrierJump']:
@@ -443,6 +448,7 @@ class EDLogs(FileSystemEventHandler):
                 self.systemaddress = entry.get('SystemAddress')
                 (self.system, self.station) = (entry['StarSystem'] == 'ProvingGround' and 'CQC' or entry['StarSystem'],
                                                entry.get('StationName'))	# May be None
+                self.station_marketid = entry.get('MarketID') # May be None
                 self.stationtype = entry.get('StationType')	# May be None
                 self.stationservices = entry.get('StationServices')	# None under E:D < 2.4
             elif entry['event'] == 'ApproachBody':
@@ -595,6 +601,7 @@ class EDLogs(FileSystemEventHandler):
                 self.planet = None
                 self.system = None
                 self.station = None
+                self.station_marketid = None
                 self.stationtype = None
                 self.stationservices = None
                 self.coordinates = None
@@ -607,6 +614,7 @@ class EDLogs(FileSystemEventHandler):
                 self.planet = None
                 self.system = None
                 self.station = None
+                self.station_marketid = None
                 self.stationtype = None
                 self.stationservices = None
                 self.coordinates = None
@@ -651,6 +659,7 @@ class EDLogs(FileSystemEventHandler):
                         ('timestamp', strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())),
                         ('event', 'StartUp'),
                         ('Docked', True),
+                        ('MarketID', self.station_marketid),
                         ('StationName', self.station),
                         ('StationType', self.stationtype),
                         ('StarSystem', self.system),
diff --git a/plugins/eddb.py b/plugins/eddb.py
index 67d292b2..82a294c2 100644
--- a/plugins/eddb.py
+++ b/plugins/eddb.py
@@ -29,12 +29,14 @@ with open(join(config.respath, 'stations.p'), 'rb') as h:
 def system_url(system_name):
     return 'https://eddb.io/system/name/%s' % system_name
 
+
 def station_url(system_name, station_name):
-    if station_id(system_name, station_name):
-        return 'https://eddb.io/station/%d' % station_id(system_name, station_name)
+    if this.station_marketid:
+        return 'https://eddb.io/station/market-id/{}'.format(this.station_marketid)
     else:
         return system_url(system_name)
 
+
 # system_name -> system_id or 0
 def system_id(system_name):
     return this.system_ids.get(system_name, [0, False])[0]
@@ -53,6 +55,7 @@ def plugin_start3(plugin_dir):
 
 def plugin_app(parent):
     this.system_link  = parent.children['system']	# system label in main window
+    this.station_marketid = None                        # Frontier MarketID
     this.station_link = parent.children['station']	# station label in main window
     this.station_link.configure(popup_copy = lambda x: x != STATION_UNDOCKED)
 
@@ -60,14 +63,25 @@ def prefs_changed(cmdr, is_beta):
     if config.get('system_provider') == 'eddb':
         this.system_link['url'] = system_url(system_link['text'])	# Override standard URL function
 
+
 def journal_entry(cmdr, is_beta, system, station, entry, state):
     if config.get('system_provider') == 'eddb':
         this.system_link['url'] = system_url(system)	# Override standard URL function
-    this.station_link['text'] = station or (system_populated(system) and STATION_UNDOCKED or '')
-    this.station_link.update_idletasks()
+
+    if config.get('station_provider') == 'eddb':
+        if entry['event'] in ['Location', 'Docked', 'StartUp']:
+            this.station_marketid = entry.get('MarketID')
+        elif entry['event'] in ['Undocked']:
+            this.station_marketid = None
+        this.station_link['text'] = station or (system_populated(system) and STATION_UNDOCKED or '')
+        this.station_link.update_idletasks()
+
 
 def cmdr_data(data, is_beta):
     if config.get('system_provider') == 'eddb':
         this.system_link['url'] = system_url(data['lastSystem']['name'])	# Override standard URL function
-    this.station_link['text'] = data['commander']['docked'] and data['lastStarport']['name'] or (system_populated(data['lastSystem']['name']) and STATION_UNDOCKED or '')
-    this.station_link.update_idletasks()
+
+    if config.get('station_provider') == 'eddb':
+        this.station_marketid = data['commander']['docked'] and data['lastStarport']['id']
+        this.station_link['text'] = data['commander']['docked'] and data['lastStarport']['name'] or (system_populated(data['lastSystem']['name']) and STATION_UNDOCKED or '')
+        this.station_link.update_idletasks()