From b186e977477f63ab6fc13d2c9ef2a1e317591c2c Mon Sep 17 00:00:00 2001 From: A_D Date: Sat, 1 Aug 2020 21:36:50 +0200 Subject: [PATCH 01/19] autoformatted code --- plugins/eddn.py | 118 ++++++++++++++++++++++++++---------------------- 1 file changed, 64 insertions(+), 54 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index b65ac034..68e1dbb7 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -38,19 +38,19 @@ this.commodities = this.outfitting = this.shipyard = None class EDDN(object): - ### SERVER = 'http://localhost:8081' # testing + # SERVER = 'http://localhost:8081' # testing SERVER = 'https://eddn.edcd.io:4430' UPLOAD = '%s/upload/' % SERVER - REPLAYPERIOD = 400 # Roughly two messages per second, accounting for send delays [ms] - REPLAYFLUSH = 20 # Update log on disk roughly every 10 seconds - TIMEOUT= 10 # requests timeout + REPLAYPERIOD = 400 # Roughly two messages per second, accounting for send delays [ms] + REPLAYFLUSH = 20 # Update log on disk roughly every 10 seconds + TIMEOUT = 10 # requests timeout MODULE_RE = re.compile('^Hpt_|^Int_|Armour_', re.IGNORECASE) CANONICALISE_RE = re.compile(r'\$(.+)_name;') def __init__(self, parent): self.parent = parent self.session = requests.Session() - self.replayfile = None # For delayed messages + self.replayfile = None # For delayed messages self.replaylog = [] def load(self): @@ -94,7 +94,7 @@ class EDDN(object): msg = OrderedDict([ ('$schemaRef', msg['$schemaRef']), ('header', OrderedDict([ - ('softwareName', '%s [%s]' % (applongname, sys.platform=='darwin' and "Mac OS" or system())), + ('softwareName', '%s [%s]' % (applongname, sys.platform == 'darwin' and "Mac OS" or system())), ('softwareVersion', appversion), ('uploaderID', uploaderID), ])), @@ -119,7 +119,7 @@ class EDDN(object): if len(self.replaylog) == 1: status['text'] = _('Sending data to EDDN...') else: - status['text'] = '%s [%d]' % (_('Sending data to EDDN...').replace('...',''), len(self.replaylog)) + status['text'] = '%s [%d]' % (_('Sending data to EDDN...').replace('...', ''), len(self.replaylog)) self.parent.update_idletasks() try: cmdr, msg = json.loads(self.replaylog[0], object_pairs_hook=OrderedDict) @@ -166,9 +166,9 @@ class EDDN(object): ])) if commodity['statusFlags']: commodities[-1]['statusFlags'] = commodity['statusFlags'] - commodities.sort(key = lambda c: c['name']) + commodities.sort(key=lambda c: c['name']) - if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it + if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it message = OrderedDict([ ('timestamp', data['timestamp']), ('systemName', data['lastSystem']['name']), @@ -181,24 +181,25 @@ class EDDN(object): if 'prohibited' in data['lastStarport']: message['prohibited'] = sorted(list([x for x in (data['lastStarport']['prohibited'] or {}).values()])) self.send(data['commander']['name'], { - '$schemaRef' : 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), - 'message' : message, + '$schemaRef': 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), + 'message': message, }) this.commodities = commodities def export_outfitting(self, data, is_beta): economies = data['lastStarport'].get('economies') or {} modules = data['lastStarport'].get('modules') or {} - ships = data['lastStarport'].get('ships') or { 'shipyard_list': {}, 'unavailable_list': [] } + ships = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} # Horizons flag - will hit at least Int_PlanetApproachSuite other than at engineer bases ("Colony"), prison or rescue Megaships, or under Pirate Attack etc horizons = (any(economy['name'] == 'Colony' for economy in economies.values()) or any(module.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for module in modules.values()) or any(ship.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for ship in list((ships['shipyard_list'] or {}).values()))) outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['name'].lower()) for module in modules.values() if self.MODULE_RE.search(module['name']) and module.get('sku') in [None, 'ELITE_HORIZONS_V_PLANETARY_LANDINGS'] and module['name'] != 'Int_PlanetApproachSuite']) - if outfitting and this.outfitting != (horizons, outfitting): # Don't send empty modules list - schema won't allow it + # Don't send empty modules list - schema won't allow it + if outfitting and this.outfitting != (horizons, outfitting): self.send(data['commander']['name'], { - '$schemaRef' : 'https://eddn.edcd.io/schemas/outfitting/2' + (is_beta and '/test' or ''), - 'message' : OrderedDict([ + '$schemaRef': 'https://eddn.edcd.io/schemas/outfitting/2' + (is_beta and '/test' or ''), + 'message': OrderedDict([ ('timestamp', data['timestamp']), ('systemName', data['lastSystem']['name']), ('stationName', data['lastStarport']['name']), @@ -212,15 +213,16 @@ class EDDN(object): def export_shipyard(self, data, is_beta): economies = data['lastStarport'].get('economies') or {} modules = data['lastStarport'].get('modules') or {} - ships = data['lastStarport'].get('ships') or { 'shipyard_list': {}, 'unavailable_list': [] } + ships = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} horizons = (any(economy['name'] == 'Colony' for economy in economies.values()) or any(module.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for module in modules.values()) or any(ship.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for ship in list((ships['shipyard_list'] or {}).values()))) shipyard = sorted([ship['name'].lower() for ship in list((ships['shipyard_list'] or {}).values()) + ships['unavailable_list']]) - if shipyard and this.shipyard != (horizons, shipyard): # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. + # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. + if shipyard and this.shipyard != (horizons, shipyard): self.send(data['commander']['name'], { - '$schemaRef' : 'https://eddn.edcd.io/schemas/shipyard/2' + (is_beta and '/test' or ''), - 'message' : OrderedDict([ + '$schemaRef': 'https://eddn.edcd.io/schemas/shipyard/2' + (is_beta and '/test' or ''), + 'message': OrderedDict([ ('timestamp', data['timestamp']), ('systemName', data['lastSystem']['name']), ('stationName', data['lastStarport']['name']), @@ -242,12 +244,12 @@ class EDDN(object): ('sellPrice', commodity['SellPrice']), ('demand', commodity['Demand']), ('demandBracket', commodity['DemandBracket']), - ]) for commodity in items], key = lambda c: c['name']) + ]) for commodity in items], key=lambda c: c['name']) - if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it + if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it self.send(cmdr, { - '$schemaRef' : 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), - 'message' : OrderedDict([ + '$schemaRef': 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), + 'message': OrderedDict([ ('timestamp', entry['timestamp']), ('systemName', entry['StarSystem']), ('stationName', entry['StationName']), @@ -261,10 +263,11 @@ class EDDN(object): modules = entry.get('Items') or [] horizons = entry.get('Horizons', False) outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) for module in modules if module['Name'] != 'int_planetapproachsuite']) - if outfitting and this.outfitting != (horizons, outfitting): # Don't send empty modules list - schema won't allow it + # Don't send empty modules list - schema won't allow it + if outfitting and this.outfitting != (horizons, outfitting): self.send(cmdr, { - '$schemaRef' : 'https://eddn.edcd.io/schemas/outfitting/2' + (is_beta and '/test' or ''), - 'message' : OrderedDict([ + '$schemaRef': 'https://eddn.edcd.io/schemas/outfitting/2' + (is_beta and '/test' or ''), + 'message': OrderedDict([ ('timestamp', entry['timestamp']), ('systemName', entry['StarSystem']), ('stationName', entry['StationName']), @@ -279,10 +282,11 @@ class EDDN(object): ships = entry.get('PriceList') or [] horizons = entry.get('Horizons', False) shipyard = sorted([ship['ShipType'] for ship in ships]) - if shipyard and this.shipyard != (horizons, shipyard): # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. + # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. + if shipyard and this.shipyard != (horizons, shipyard): self.send(cmdr, { - '$schemaRef' : 'https://eddn.edcd.io/schemas/shipyard/2' + (is_beta and '/test' or ''), - 'message' : OrderedDict([ + '$schemaRef': 'https://eddn.edcd.io/schemas/shipyard/2' + (is_beta and '/test' or ''), + 'message': OrderedDict([ ('timestamp', entry['timestamp']), ('systemName', entry['StarSystem']), ('stationName', entry['StationName']), @@ -295,8 +299,8 @@ class EDDN(object): def export_journal_entry(self, cmdr, is_beta, entry): msg = { - '$schemaRef' : 'https://eddn.edcd.io/schemas/journal/1' + (is_beta and '/test' or ''), - 'message' : entry + '$schemaRef': 'https://eddn.edcd.io/schemas/journal/1' + (is_beta and '/test' or ''), + 'message': entry } if self.replayfile or self.load(): # Store the entry @@ -304,9 +308,8 @@ class EDDN(object): self.replayfile.write('%s\n' % self.replaylog[-1]) if (entry['event'] == 'Docked' or - (entry['event'] == 'Location' and entry['Docked']) or - not (config.getint('output') & config.OUT_SYS_DELAY)): - self.parent.after(self.REPLAYPERIOD, self.sendreplay) # Try to send this and previous entries + (entry['event'] == 'Location' and entry['Docked']) or not (config.getint('output') & config.OUT_SYS_DELAY)): + self.parent.after(self.REPLAYPERIOD, self.sendreplay) # Try to send this and previous entries else: # Can't access replay file! Send immediately. status = self.parent.children['status'] @@ -325,54 +328,61 @@ class EDDN(object): def plugin_start3(plugin_dir): return 'EDDN' + def plugin_app(parent): this.parent = parent this.eddn = EDDN(parent) # Try to obtain exclusive lock on journal cache, even if we don't need it yet if not this.eddn.load(): - this.status['text'] = 'Error: Is another copy of this app already running?' # Shouldn't happen - don't bother localizing + # Shouldn't happen - don't bother localizing + this.status['text'] = 'Error: Is another copy of this app already running?' + def plugin_prefs(parent, cmdr, is_beta): PADX = 10 - BUTTONX = 12 # indent Checkbuttons and Radiobuttons + BUTTONX = 12 # indent Checkbuttons and Radiobuttons PADY = 2 # close spacing if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.getint('output'))): - output = (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN) # default settings + output = (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN) # default settings else: output = config.getint('output') eddnframe = nb.Frame(parent) - HyperlinkLabel(eddnframe, text='Elite Dangerous Data Network', background=nb.Label().cget('background'), url='https://github.com/EDSM-NET/EDDN/wiki', underline=True).grid(padx=PADX, sticky=tk.W) # Don't translate - this.eddn_station= tk.IntVar(value = (output & config.OUT_MKT_EDDN) and 1) - this.eddn_station_button = nb.Checkbutton(eddnframe, text=_('Send station data to the Elite Dangerous Data Network'), variable=this.eddn_station, command=prefsvarchanged) # Output setting - this.eddn_station_button.grid(padx=BUTTONX, pady=(5,0), sticky=tk.W) - this.eddn_system = tk.IntVar(value = (output & config.OUT_SYS_EDDN) and 1) - this.eddn_system_button = nb.Checkbutton(eddnframe, text=_('Send system and scan data to the Elite Dangerous Data Network'), variable=this.eddn_system, command=prefsvarchanged) # Output setting new in E:D 2.2 - this.eddn_system_button.grid(padx=BUTTONX, pady=(5,0), sticky=tk.W) - this.eddn_delay= tk.IntVar(value = (output & config.OUT_SYS_DELAY) and 1) - this.eddn_delay_button = nb.Checkbutton(eddnframe, text=_('Delay sending until docked'), variable=this.eddn_delay) # Output setting under 'Send system and scan data to the Elite Dangerous Data Network' new in E:D 2.2 - this.eddn_delay_button.grid(padx=BUTTONX, sticky=tk.W) + HyperlinkLabel(eddnframe, text='Elite Dangerous Data Network', background=nb.Label().cget('background'), url='https://github.com/EDSM-NET/EDDN/wiki', underline=True).grid(padx=PADX, sticky=tk.W) # Don't translate + this.eddn_station = tk.IntVar(value=(output & config.OUT_MKT_EDDN) and 1) + this.eddn_station_button = nb.Checkbutton(eddnframe, text=_('Send station data to the Elite Dangerous Data Network'), variable=this.eddn_station, command=prefsvarchanged) # Output setting + this.eddn_station_button.grid(padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.eddn_system = tk.IntVar(value=(output & config.OUT_SYS_EDDN) and 1) + this.eddn_system_button = nb.Checkbutton(eddnframe, text=_('Send system and scan data to the Elite Dangerous Data Network'), variable=this.eddn_system, command=prefsvarchanged) # Output setting new in E:D 2.2 + this.eddn_system_button.grid(padx=BUTTONX, pady=(5, 0), sticky=tk.W) + this.eddn_delay = tk.IntVar(value=(output & config.OUT_SYS_DELAY) and 1) + # Output setting under 'Send system and scan data to the Elite Dangerous Data Network' new in E:D 2.2 + this.eddn_delay_button = nb.Checkbutton(eddnframe, text=_('Delay sending until docked'), variable=this.eddn_delay) this.eddn_delay_button.grid(padx=BUTTONX, sticky=tk.W) return eddnframe + def prefsvarchanged(event=None): this.eddn_station_button['state'] = tk.NORMAL - this.eddn_system_button['state']= tk.NORMAL + this.eddn_system_button['state'] = tk.NORMAL this.eddn_delay_button['state'] = this.eddn.replayfile and this.eddn_system.get() and tk.NORMAL or tk.DISABLED + def prefs_changed(cmdr, is_beta): config.set('output', - (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP |config.OUT_MKT_MANUAL)) + + (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + (this.eddn_station.get() and config.OUT_MKT_EDDN) + (this.eddn_system.get() and config.OUT_SYS_EDDN) + (this.eddn_delay.get() and config.OUT_SYS_DELAY)) + def plugin_stop(): this.eddn.close() + def journal_entry(cmdr, is_beta, system, station, entry, state): # Recursively filter '*_Localised' keys from dict @@ -381,9 +391,9 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): for k, v in d.items(): if k.endswith('_Localised'): pass - elif hasattr(v, 'items'): # dict -> recurse + elif hasattr(v, 'items'): # dict -> recurse filtered[k] = filter_localised(v) - elif isinstance(v, list): # list of dicts -> recurse + elif isinstance(v, list): # list of dicts -> recurse filtered[k] = [filter_localised(x) if hasattr(x, 'items') else x for x in v] else: filtered[k] = v @@ -398,7 +408,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): if 'StarPos' in entry: this.coordinates = tuple(entry['StarPos']) elif this.systemaddress != entry.get('SystemAddress'): - this.coordinates = None # Docked event doesn't include coordinates + this.coordinates = None # Docked event doesn't include coordinates this.systemaddress = entry.get('SystemAddress') elif entry['event'] == 'ApproachBody': this.planet = entry['Body'] @@ -408,13 +418,13 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): # Send interesting events to EDDN, but not when on a crew if (config.getint('output') & config.OUT_SYS_EDDN and not state['Captain'] and (entry['event'] in ('Location', 'FSDJump', 'Docked', 'Scan', 'SAASignalsFound', 'CarrierJump')) and - ('StarPos' in entry or this.coordinates)): + ('StarPos' in entry or this.coordinates)): # strip out properties disallowed by the schema for thing in ['ActiveFine', 'CockpitBreach', 'BoostUsed', 'FuelLevel', 'FuelUsed', 'JumpDist', 'Latitude', 'Longitude', 'Wanted']: entry.pop(thing, None) if 'Factions' in entry: # Filter faction state. `entry` is a shallow copy so replace 'Factions' value rather than modify in-place. - entry['Factions'] = [ {k: v for k, v in f.items() if k not in ['HappiestSystem', 'HomeSystem', 'MyReputation', 'SquadronFaction']} for f in entry['Factions']] + entry['Factions'] = [{k: v for k, v in f.items() if k not in ['HappiestSystem', 'HomeSystem', 'MyReputation', 'SquadronFaction']} for f in entry['Factions']] # add planet to Docked event for planetary stations if known if entry['event'] == 'Docked' and this.planet: From 4d0cf4e335231fccfe7bb9b34300ed6713821bda Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 02:24:37 +0200 Subject: [PATCH 02/19] Added scope change newlines --- plugins/eddn.py | 65 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 6 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 68e1dbb7..fced18e7 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -6,6 +6,7 @@ from os import SEEK_SET, SEEK_CUR, SEEK_END from os.path import exists, join from platform import system import re +from typing import Any import requests import sys import logging @@ -24,7 +25,7 @@ from companion import category_map logger = logging.getLogger(appname) -this = sys.modules[__name__] # For holding module globals +this: Any = sys.modules[__name__] # For holding module globals # Track location to add to Journal events this.systemaddress = None @@ -60,19 +61,25 @@ class EDDN(object): try: # Try to open existing file self.replayfile = open(filename, 'r+', buffering=1) + except Exception: if exists(filename): raise # Couldn't open existing file + else: self.replayfile = open(filename, 'w+', buffering=1) # Create file + if sys.platform != 'win32': # open for writing is automatically exclusive on Windows lockf(self.replayfile, LOCK_EX | LOCK_NB) + except Exception as e: logger.debug('Failed opening "replay.jsonl"', exc_info=e) if self.replayfile: self.replayfile.close() + self.replayfile = None return False + self.replaylog = [line.strip() for line in self.replayfile] return True @@ -104,6 +111,7 @@ class EDDN(object): r = self.session.post(self.UPLOAD, data=json.dumps(msg), timeout=self.TIMEOUT) if r.status_code != requests.codes.ok: logger.debug(f':\nStatus\t{r.status_code}URL\t{r.url}Headers\t{r.headers}Content:\n{r.text}') + r.raise_for_status() def sendreplay(self): @@ -118,9 +126,12 @@ class EDDN(object): if len(self.replaylog) == 1: status['text'] = _('Sending data to EDDN...') + else: status['text'] = '%s [%d]' % (_('Sending data to EDDN...').replace('...', ''), len(self.replaylog)) + self.parent.update_idletasks() + try: cmdr, msg = json.loads(self.replaylog[0], object_pairs_hook=OrderedDict) except json.JSONDecodeError as e: @@ -128,19 +139,23 @@ class EDDN(object): logger.debug(f'\n{self.replaylog[0]}\n', exc_info=e) # Discard and continue self.replaylog.pop(0) + else: # Rewrite old schema name if msg['$schemaRef'].startswith('http://schemas.elite-markets.net/eddn/'): msg['$schemaRef'] = 'https://eddn.edcd.io/schemas/' + msg['$schemaRef'][38:] + try: self.send(cmdr, msg) self.replaylog.pop(0) if not len(self.replaylog) % self.REPLAYFLUSH: self.flush() + except requests.exceptions.RequestException as e: logger.debug('Failed sending', exc_info=e) status['text'] = _("Error: Can't connect to EDDN") return # stop sending + except Exception as e: logger.debug('Failed sending', exc_info=e) status['text'] = str(e) @@ -164,8 +179,10 @@ class EDDN(object): ('demand', int(commodity['demand'])), ('demandBracket', commodity['demandBracket']), ])) + if commodity['statusFlags']: commodities[-1]['statusFlags'] = commodity['statusFlags'] + commodities.sort(key=lambda c: c['name']) if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it @@ -176,14 +193,18 @@ class EDDN(object): ('marketId', data['lastStarport']['id']), ('commodities', commodities), ]) + if 'economies' in data['lastStarport']: message['economies'] = sorted(list([x for x in (data['lastStarport']['economies'] or {}).values()]), key=lambda x: x['name']) + if 'prohibited' in data['lastStarport']: message['prohibited'] = sorted(list([x for x in (data['lastStarport']['prohibited'] or {}).values()])) + self.send(data['commander']['name'], { '$schemaRef': 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), 'message': message, }) + this.commodities = commodities def export_outfitting(self, data, is_beta): @@ -194,6 +215,7 @@ class EDDN(object): horizons = (any(economy['name'] == 'Colony' for economy in economies.values()) or any(module.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for module in modules.values()) or any(ship.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for ship in list((ships['shipyard_list'] or {}).values()))) + outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['name'].lower()) for module in modules.values() if self.MODULE_RE.search(module['name']) and module.get('sku') in [None, 'ELITE_HORIZONS_V_PLANETARY_LANDINGS'] and module['name'] != 'Int_PlanetApproachSuite']) # Don't send empty modules list - schema won't allow it if outfitting and this.outfitting != (horizons, outfitting): @@ -208,6 +230,7 @@ class EDDN(object): ('modules', outfitting), ]), }) + this.outfitting = (horizons, outfitting) def export_shipyard(self, data, is_beta): @@ -217,6 +240,7 @@ class EDDN(object): horizons = (any(economy['name'] == 'Colony' for economy in economies.values()) or any(module.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for module in modules.values()) or any(ship.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for ship in list((ships['shipyard_list'] or {}).values()))) + shipyard = sorted([ship['name'].lower() for ship in list((ships['shipyard_list'] or {}).values()) + ships['unavailable_list']]) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. if shipyard and this.shipyard != (horizons, shipyard): @@ -231,6 +255,7 @@ class EDDN(object): ('ships', shipyard), ]), }) + this.shipyard = (horizons, shipyard) def export_journal_commodities(self, cmdr, is_beta, entry): @@ -257,6 +282,7 @@ class EDDN(object): ('commodities', commodities), ]), }) + this.commodities = commodities def export_journal_outfitting(self, cmdr, is_beta, entry): @@ -276,6 +302,7 @@ class EDDN(object): ('modules', outfitting), ]), }) + this.outfitting = (horizons, outfitting) def export_journal_shipyard(self, cmdr, is_beta, entry): @@ -295,6 +322,7 @@ class EDDN(object): ('ships', shipyard), ]), }) + this.shipyard = (horizons, shipyard) def export_journal_entry(self, cmdr, is_beta, entry): @@ -302,14 +330,16 @@ class EDDN(object): '$schemaRef': 'https://eddn.edcd.io/schemas/journal/1' + (is_beta and '/test' or ''), 'message': entry } + if self.replayfile or self.load(): # Store the entry self.replaylog.append(json.dumps([cmdr, msg])) self.replayfile.write('%s\n' % self.replaylog[-1]) - if (entry['event'] == 'Docked' or - (entry['event'] == 'Location' and entry['Docked']) or not (config.getint('output') & config.OUT_SYS_DELAY)): + if (entry['event'] == 'Docked' or (entry['event'] == 'Location' and entry['Docked']) or not (config.getint('output') & config.OUT_SYS_DELAY)): + self.parent.after(self.REPLAYPERIOD, self.sendreplay) # Try to send this and previous entries + else: # Can't access replay file! Send immediately. status = self.parent.children['status'] @@ -339,13 +369,13 @@ def plugin_app(parent): def plugin_prefs(parent, cmdr, is_beta): - PADX = 10 BUTTONX = 12 # indent Checkbuttons and Radiobuttons PADY = 2 # close spacing if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.getint('output'))): output = (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN) # default settings + else: output = config.getint('output') @@ -384,34 +414,43 @@ def plugin_stop(): def journal_entry(cmdr, is_beta, system, station, entry, state): - # Recursively filter '*_Localised' keys from dict def filter_localised(d): filtered = OrderedDict() for k, v in d.items(): if k.endswith('_Localised'): pass + elif hasattr(v, 'items'): # dict -> recurse filtered[k] = filter_localised(v) + elif isinstance(v, list): # list of dicts -> recurse filtered[k] = [filter_localised(x) if hasattr(x, 'items') else x for x in v] + else: filtered[k] = v + return filtered # Track location if entry['event'] in ['Location', 'FSDJump', 'Docked', 'CarrierJump']: if entry['event'] in ('Location', 'CarrierJump'): this.planet = entry.get('Body') if entry.get('BodyType') == 'Planet' else None + elif entry['event'] == 'FSDJump': this.planet = None + if 'StarPos' in entry: this.coordinates = tuple(entry['StarPos']) + elif this.systemaddress != entry.get('SystemAddress'): this.coordinates = None # Docked event doesn't include coordinates + this.systemaddress = entry.get('SystemAddress') + elif entry['event'] == 'ApproachBody': this.planet = entry['Body'] + elif entry['event'] in ['LeaveBody', 'SupercruiseEntry']: this.planet = None @@ -419,9 +458,11 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): if (config.getint('output') & config.OUT_SYS_EDDN and not state['Captain'] and (entry['event'] in ('Location', 'FSDJump', 'Docked', 'Scan', 'SAASignalsFound', 'CarrierJump')) and ('StarPos' in entry or this.coordinates)): + # strip out properties disallowed by the schema for thing in ['ActiveFine', 'CockpitBreach', 'BoostUsed', 'FuelLevel', 'FuelUsed', 'JumpDist', 'Latitude', 'Longitude', 'Wanted']: entry.pop(thing, None) + if 'Factions' in entry: # Filter faction state. `entry` is a shallow copy so replace 'Factions' value rather than modify in-place. entry['Factions'] = [{k: v for k, v in f.items() if k not in ['HappiestSystem', 'HomeSystem', 'MyReputation', 'SquadronFaction']} for f in entry['Factions']] @@ -435,27 +476,35 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): if 'StarSystem' not in entry: if not system: return("system is None, can't add StarSystem") + entry['StarSystem'] = system + if 'StarPos' not in entry: if not this.coordinates: return("this.coordinates is None, can't add StarPos") + entry['StarPos'] = list(this.coordinates) + if 'SystemAddress' not in entry: if not this.systemaddress: return("this.systemaddress is None, can't add SystemAddress") + entry['SystemAddress'] = this.systemaddress try: this.eddn.export_journal_entry(cmdr, is_beta, filter_localised(entry)) + except requests.exceptions.RequestException as e: logger.debug('Failed in export_journal_entry', exc_info=e) return _("Error: Can't connect to EDDN") + except Exception as e: logger.debug('Failed in export_journal_entry', exc_info=e) return str(e) elif (config.getint('output') & config.OUT_MKT_EDDN and not state['Captain'] and - entry['event'] in ['Market', 'Outfitting', 'Shipyard']): + entry['event'] in ['Market', 'Outfitting', 'Shipyard']): + try: if this.marketId != entry['MarketID']: this.commodities = this.outfitting = this.shipyard = None @@ -465,14 +514,17 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): entry = json.load(h) if entry['event'] == 'Market': this.eddn.export_journal_commodities(cmdr, is_beta, entry) + elif entry['event'] == 'Outfitting': this.eddn.export_journal_outfitting(cmdr, is_beta, entry) + elif entry['event'] == 'Shipyard': this.eddn.export_journal_shipyard(cmdr, is_beta, entry) except requests.exceptions.RequestException as e: logger.debug(f'Failed exporting {entry["event"]}', exc_info=e) return _("Error: Can't connect to EDDN") + except Exception as e: logger.debug(f'Failed exporting {entry["event"]}', exc_info=e) return str(e) @@ -490,6 +542,7 @@ def cmdr_data(data, is_beta): if not old_status: status['text'] = _('Sending data to EDDN...') status.update_idletasks() + this.eddn.export_commodities(data, is_beta) this.eddn.export_outfitting(data, is_beta) this.eddn.export_shipyard(data, is_beta) From 4105662fb572c5f14748880c75db5992c514f041 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:23:40 +0200 Subject: [PATCH 03/19] Cleaned up logic and removed overlong lines Generally for the logic cleanups it was replacing giant list comprehensions with slightly smaller filter calls. filter() is just plain cleaner when all you're doing in a list comp is [x for x in y if somecondition]. --- plugins/eddn.py | 142 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 115 insertions(+), 27 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index fced18e7..9f0b08f2 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -1,12 +1,13 @@ # Export to EDDN from collections import OrderedDict +import itertools import json from os import SEEK_SET, SEEK_CUR, SEEK_END from os.path import exists, join from platform import system import re -from typing import Any +from typing import Any, Mapping, TYPE_CHECKING import requests import sys import logging @@ -23,6 +24,9 @@ if sys.platform != 'win32': from config import appname, applongname, appversion, config from companion import category_map +if TYPE_CHECKING: + def _(x): return x + logger = logging.getLogger(appname) this: Any = sys.modules[__name__] # For holding module globals @@ -36,6 +40,15 @@ this.planet = None this.marketId = None this.commodities = this.outfitting = this.shipyard = None +HORIZ_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' + + +# TODO: +# 1, this does a bunch of magic checks for whether or not the given commander has horizons. We can get that directly +# from CAPI via commander.capabilities.Horizons -- Should this be changed to use that? did such a thing exist when +# this was written? +# +# 2, a good few of these methods are static or could be classmethods. they should be created as such. class EDDN(object): @@ -88,11 +101,13 @@ class EDDN(object): self.replayfile.truncate() for line in self.replaylog: self.replayfile.write('%s\n' % line) + self.replayfile.flush() def close(self): if self.replayfile: self.replayfile.close() + self.replayfile = None def send(self, cmdr, msg): @@ -195,7 +210,9 @@ class EDDN(object): ]) if 'economies' in data['lastStarport']: - message['economies'] = sorted(list([x for x in (data['lastStarport']['economies'] or {}).values()]), key=lambda x: x['name']) + message['economies'] = sorted( + list([x for x in (data['lastStarport']['economies'] or {}).values()]), key=lambda x: x['name'] + ) if 'prohibited' in data['lastStarport']: message['prohibited'] = sorted(list([x for x in (data['lastStarport']['prohibited'] or {}).values()])) @@ -209,14 +226,25 @@ class EDDN(object): def export_outfitting(self, data, is_beta): economies = data['lastStarport'].get('economies') or {} - modules = data['lastStarport'].get('modules') or {} + modules: Mapping[str, Any] = data['lastStarport'].get('modules') or {} ships = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} - # Horizons flag - will hit at least Int_PlanetApproachSuite other than at engineer bases ("Colony"), prison or rescue Megaships, or under Pirate Attack etc - horizons = (any(economy['name'] == 'Colony' for economy in economies.values()) or - any(module.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for module in modules.values()) or - any(ship.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for ship in list((ships['shipyard_list'] or {}).values()))) + # Horizons flag - will hit at least Int_PlanetApproachSuite other than at engineer bases ("Colony"), + # prison or rescue Megaships, or under Pirate Attack etc + horizons = ( + any(economy['name'] == 'Colony' for economy in economies.values()) or + any(module.get('sku') == HORIZ_SKU for module in modules.values()) or + any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) + ) - outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['name'].lower()) for module in modules.values() if self.MODULE_RE.search(module['name']) and module.get('sku') in [None, 'ELITE_HORIZONS_V_PLANETARY_LANDINGS'] and module['name'] != 'Int_PlanetApproachSuite']) + to_search = filter( + lambda m: self.MODULE_RE.search(m['name']) and m.get('sku') in (None, HORIZ_SKU) and + m['name'] != 'Int_PlanetApproachSuite', + modules.values() + ) + + outfitting = sorted( + self.MODULE_RE.sub(lambda match: match.group(0).capitalize(), mod['name'].lower()) for mod in to_search + ) # Don't send empty modules list - schema won't allow it if outfitting and this.outfitting != (horizons, outfitting): self.send(data['commander']['name'], { @@ -237,11 +265,18 @@ class EDDN(object): economies = data['lastStarport'].get('economies') or {} modules = data['lastStarport'].get('modules') or {} ships = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} - horizons = (any(economy['name'] == 'Colony' for economy in economies.values()) or - any(module.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for module in modules.values()) or - any(ship.get('sku') == 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' for ship in list((ships['shipyard_list'] or {}).values()))) + horizons = ( + any(economy['name'] == 'Colony' for economy in economies.values()) or + any(module.get('sku') == HORIZ_SKU for module in modules.values()) or + any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) + ) - shipyard = sorted([ship['name'].lower() for ship in list((ships['shipyard_list'] or {}).values()) + ships['unavailable_list']]) + shipyard = sorted( + itertools.chain( + (ship['name'].lower() for ship in (ships['shipyard_list'] or {}).values()), + ships['unavailable_list'] + ) + ) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. if shipyard and this.shipyard != (horizons, shipyard): self.send(data['commander']['name'], { @@ -288,7 +323,12 @@ class EDDN(object): def export_journal_outfitting(self, cmdr, is_beta, entry): modules = entry.get('Items') or [] horizons = entry.get('Horizons', False) - outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) for module in modules if module['Name'] != 'int_planetapproachsuite']) + # outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) + # for module in modules if module['Name'] != 'int_planetapproachsuite']) + outfitting = sorted( + self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), mod['Name']) for mod in + filter(lambda m: m['Name'] != 'int_planetapproachsuite', modules) + ) # Don't send empty modules list - schema won't allow it if outfitting and this.outfitting != (horizons, outfitting): self.send(cmdr, { @@ -336,8 +376,10 @@ class EDDN(object): self.replaylog.append(json.dumps([cmdr, msg])) self.replayfile.write('%s\n' % self.replaylog[-1]) - if (entry['event'] == 'Docked' or (entry['event'] == 'Location' and entry['Docked']) or not (config.getint('output') & config.OUT_SYS_DELAY)): - + if ( + entry['event'] == 'Docked' or (entry['event'] == 'Location' and entry['Docked']) or not + (config.getint('output') & config.OUT_SYS_DELAY) + ): self.parent.after(self.REPLAYPERIOD, self.sendreplay) # Try to send this and previous entries else: @@ -381,16 +423,41 @@ def plugin_prefs(parent, cmdr, is_beta): eddnframe = nb.Frame(parent) - HyperlinkLabel(eddnframe, text='Elite Dangerous Data Network', background=nb.Label().cget('background'), url='https://github.com/EDSM-NET/EDDN/wiki', underline=True).grid(padx=PADX, sticky=tk.W) # Don't translate + HyperlinkLabel( + eddnframe, + text='Elite Dangerous Data Network', + background=nb.Label().cget('background'), + url='https://github.com/EDSM-NET/EDDN/wiki', + underline=True + ).grid(padx=PADX, sticky=tk.W) # Don't translate + this.eddn_station = tk.IntVar(value=(output & config.OUT_MKT_EDDN) and 1) - this.eddn_station_button = nb.Checkbutton(eddnframe, text=_('Send station data to the Elite Dangerous Data Network'), variable=this.eddn_station, command=prefsvarchanged) # Output setting + this.eddn_station_button = nb.Checkbutton( + eddnframe, + text=_('Send station data to the Elite Dangerous Data Network'), + variable=this.eddn_station, + command=prefsvarchanged + ) # Output setting + this.eddn_station_button.grid(padx=BUTTONX, pady=(5, 0), sticky=tk.W) this.eddn_system = tk.IntVar(value=(output & config.OUT_SYS_EDDN) and 1) - this.eddn_system_button = nb.Checkbutton(eddnframe, text=_('Send system and scan data to the Elite Dangerous Data Network'), variable=this.eddn_system, command=prefsvarchanged) # Output setting new in E:D 2.2 + # Output setting new in E:D 2.2 + this.eddn_system_button = nb.Checkbutton( + eddnframe, + text=_('Send system and scan data to the Elite Dangerous Data Network'), + variable=this.eddn_system, + command=prefsvarchanged + ) + this.eddn_system_button.grid(padx=BUTTONX, pady=(5, 0), sticky=tk.W) this.eddn_delay = tk.IntVar(value=(output & config.OUT_SYS_DELAY) and 1) # Output setting under 'Send system and scan data to the Elite Dangerous Data Network' new in E:D 2.2 - this.eddn_delay_button = nb.Checkbutton(eddnframe, text=_('Delay sending until docked'), variable=this.eddn_delay) this.eddn_delay_button.grid(padx=BUTTONX, sticky=tk.W) + this.eddn_delay_button = nb.Checkbutton( + eddnframe, + text=_('Delay sending until docked'), + variable=this.eddn_delay + ) + this.eddn_delay_button.grid(padx=BUTTONX, sticky=tk.W) return eddnframe @@ -402,11 +469,13 @@ def prefsvarchanged(event=None): def prefs_changed(cmdr, is_beta): - config.set('output', - (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + - (this.eddn_station.get() and config.OUT_MKT_EDDN) + - (this.eddn_system.get() and config.OUT_SYS_EDDN) + - (this.eddn_delay.get() and config.OUT_SYS_DELAY)) + config.set( + 'output', + (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + + (this.eddn_station.get() and config.OUT_MKT_EDDN) + + (this.eddn_system.get() and config.OUT_SYS_EDDN) + + (this.eddn_delay.get() and config.OUT_SYS_DELAY) + ) def plugin_stop(): @@ -460,12 +529,29 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): ('StarPos' in entry or this.coordinates)): # strip out properties disallowed by the schema - for thing in ['ActiveFine', 'CockpitBreach', 'BoostUsed', 'FuelLevel', 'FuelUsed', 'JumpDist', 'Latitude', 'Longitude', 'Wanted']: + for thing in [ + 'ActiveFine', + 'CockpitBreach', + 'BoostUsed', + 'FuelLevel', + 'FuelUsed', + 'JumpDist', + 'Latitude', + 'Longitude', + 'Wanted' + ]: entry.pop(thing, None) if 'Factions' in entry: # Filter faction state. `entry` is a shallow copy so replace 'Factions' value rather than modify in-place. - entry['Factions'] = [{k: v for k, v in f.items() if k not in ['HappiestSystem', 'HomeSystem', 'MyReputation', 'SquadronFaction']} for f in entry['Factions']] + entry['Factions'] = [ + { + k: v for k, v in f.items() if k not in [ + 'HappiestSystem', 'HomeSystem', 'MyReputation', 'SquadronFaction' + ] + } + for f in entry['Factions'] + ] # add planet to Docked event for planetary stations if known if entry['event'] == 'Docked' and this.planet: @@ -510,7 +596,9 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): this.commodities = this.outfitting = this.shipyard = None this.marketId = entry['MarketID'] - with open(join(config.get('journaldir') or config.default_journal_dir, '%s.json' % entry['event']), 'rb') as h: + with open( + join(config.get('journaldir') or config.default_journal_dir, '%s.json' % entry['event']), 'rb' + ) as h: entry = json.load(h) if entry['event'] == 'Market': this.eddn.export_journal_commodities(cmdr, is_beta, entry) From c012ebc54e6573ee6d5f87ed89893e8399c6cce2 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:35:51 +0200 Subject: [PATCH 04/19] Replaced modulo-formatting with fstrings Specifically did not replace `somefile.write('%s\n' % some_data)` as print may change the line endings on some OSes which may not be wanted --- plugins/eddn.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 9f0b08f2..5f679f2a 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -54,7 +54,7 @@ class EDDN(object): # SERVER = 'http://localhost:8081' # testing SERVER = 'https://eddn.edcd.io:4430' - UPLOAD = '%s/upload/' % SERVER + UPLOAD = f'{SERVER}/upload/' REPLAYPERIOD = 400 # Roughly two messages per second, accounting for send delays [ms] REPLAYFLUSH = 20 # Update log on disk roughly every 10 seconds TIMEOUT = 10 # requests timeout @@ -100,7 +100,7 @@ class EDDN(object): self.replayfile.seek(0, SEEK_SET) self.replayfile.truncate() for line in self.replaylog: - self.replayfile.write('%s\n' % line) + self.replayfile.write(f'{line}\n') self.replayfile.flush() @@ -115,12 +115,12 @@ class EDDN(object): msg = OrderedDict([ ('$schemaRef', msg['$schemaRef']), - ('header', OrderedDict([ - ('softwareName', '%s [%s]' % (applongname, sys.platform == 'darwin' and "Mac OS" or system())), + ('header', OrderedDict([ + ('softwareName', f'{applongname} [{system() if sys.platform != "darwin" else "Mac OS"}]'), ('softwareVersion', appversion), ('uploaderID', uploaderID), ])), - ('message', msg['message']), + ('message', msg['message']), ]) r = self.session.post(self.UPLOAD, data=json.dumps(msg), timeout=self.TIMEOUT) @@ -138,12 +138,12 @@ class EDDN(object): if not self.replaylog: status['text'] = '' return - + localized = _('Sending data to EDDN...') if len(self.replaylog) == 1: - status['text'] = _('Sending data to EDDN...') + status['text'] = localized else: - status['text'] = '%s [%d]' % (_('Sending data to EDDN...').replace('...', ''), len(self.replaylog)) + status['text'] = f'{localized.replace("...", "")} [{len(self.replaylog)}]' self.parent.update_idletasks() @@ -374,12 +374,12 @@ class EDDN(object): if self.replayfile or self.load(): # Store the entry self.replaylog.append(json.dumps([cmdr, msg])) - self.replayfile.write('%s\n' % self.replaylog[-1]) + self.replayfile.write(f'{self.replaylog[-1]}\n') if ( entry['event'] == 'Docked' or (entry['event'] == 'Location' and entry['Docked']) or not (config.getint('output') & config.OUT_SYS_DELAY) - ): + ): self.parent.after(self.REPLAYPERIOD, self.sendreplay) # Try to send this and previous entries else: @@ -597,7 +597,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): this.marketId = entry['MarketID'] with open( - join(config.get('journaldir') or config.default_journal_dir, '%s.json' % entry['event']), 'rb' + join(config.get('journaldir') or config.default_journal_dir, f'{entry["event"]}.json'), 'rb' ) as h: entry = json.load(h) if entry['event'] == 'Market': From c0026cea617b42c5be7653d1eebbb59fd19f0551 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:39:21 +0200 Subject: [PATCH 05/19] replaced list comps with generators --- plugins/eddn.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 5f679f2a..b58b39fe 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -211,11 +211,11 @@ class EDDN(object): if 'economies' in data['lastStarport']: message['economies'] = sorted( - list([x for x in (data['lastStarport']['economies'] or {}).values()]), key=lambda x: x['name'] + (x for x in (data['lastStarport']['economies'] or {}).values()), key=lambda x: x['name'] ) if 'prohibited' in data['lastStarport']: - message['prohibited'] = sorted(list([x for x in (data['lastStarport']['prohibited'] or {}).values()])) + message['prohibited'] = sorted(x for x in (data['lastStarport']['prohibited'] or {}).values()) self.send(data['commander']['name'], { '$schemaRef': 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), @@ -295,7 +295,7 @@ class EDDN(object): def export_journal_commodities(self, cmdr, is_beta, entry): items = entry.get('Items') or [] - commodities = sorted([OrderedDict([ + commodities = sorted((OrderedDict([ ('name', self.canonicalise(commodity['Name'])), ('meanPrice', commodity['MeanPrice']), ('buyPrice', commodity['BuyPrice']), @@ -304,7 +304,7 @@ class EDDN(object): ('sellPrice', commodity['SellPrice']), ('demand', commodity['Demand']), ('demandBracket', commodity['DemandBracket']), - ]) for commodity in items], key=lambda c: c['name']) + ]) for commodity in items), key=lambda c: c['name']) if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it self.send(cmdr, { @@ -348,7 +348,7 @@ class EDDN(object): def export_journal_shipyard(self, cmdr, is_beta, entry): ships = entry.get('PriceList') or [] horizons = entry.get('Horizons', False) - shipyard = sorted([ship['ShipType'] for ship in ships]) + shipyard = sorted(ship['ShipType'] for ship in ships) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. if shipyard and this.shipyard != (horizons, shipyard): self.send(cmdr, { From 6772c84a5fc9828f2f6648c9c6a191cb9da9c18d Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:41:43 +0200 Subject: [PATCH 06/19] fixed names where possible --- plugins/eddn.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index b58b39fe..ea13ddad 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -14,7 +14,7 @@ import logging import tkinter as tk from ttkHyperlinkLabel import HyperlinkLabel -import myNotebook as nb +import myNotebook as nb # noqa: N813 from prefs import prefsVersion @@ -111,14 +111,14 @@ class EDDN(object): self.replayfile = None def send(self, cmdr, msg): - uploaderID = cmdr + uploader_id = cmdr msg = OrderedDict([ ('$schemaRef', msg['$schemaRef']), ('header', OrderedDict([ ('softwareName', f'{applongname} [{system() if sys.platform != "darwin" else "Mac OS"}]'), ('softwareVersion', appversion), - ('uploaderID', uploaderID), + ('uploaderID', uploader_id), ])), ('message', msg['message']), ]) From 3c66ab7246ceac23e71f552a8a3313e072f0be85 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:42:19 +0200 Subject: [PATCH 07/19] removed unused imports --- plugins/eddn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index ea13ddad..75a4714d 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -3,7 +3,7 @@ from collections import OrderedDict import itertools import json -from os import SEEK_SET, SEEK_CUR, SEEK_END +from os import SEEK_SET from os.path import exists, join from platform import system import re From e477f896640fea4dad8352055000c5547a1af530 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:42:44 +0200 Subject: [PATCH 08/19] removed un-needed object subclass --- plugins/eddn.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 75a4714d..c6a109a8 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -50,8 +50,7 @@ HORIZ_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' # # 2, a good few of these methods are static or could be classmethods. they should be created as such. -class EDDN(object): - +class EDDN: # SERVER = 'http://localhost:8081' # testing SERVER = 'https://eddn.edcd.io:4430' UPLOAD = f'{SERVER}/upload/' From cea8ac49caa5418aa960da6b3616efef37fa0751 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 13:43:20 +0200 Subject: [PATCH 09/19] Ensured that regexps are raw strings Ensures that there are no weird excaping issues --- plugins/eddn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index c6a109a8..0875c007 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -57,7 +57,7 @@ class EDDN: REPLAYPERIOD = 400 # Roughly two messages per second, accounting for send delays [ms] REPLAYFLUSH = 20 # Update log on disk roughly every 10 seconds TIMEOUT = 10 # requests timeout - MODULE_RE = re.compile('^Hpt_|^Int_|Armour_', re.IGNORECASE) + MODULE_RE = re.compile(r'^Hpt_|^Int_|Armour_', re.IGNORECASE) CANONICALISE_RE = re.compile(r'\$(.+)_name;') def __init__(self, parent): From 94c4a7b7d0154e185493128aa171ca55b56e112f Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 14:54:56 +0200 Subject: [PATCH 10/19] Replaced static lists with tuples --- plugins/eddn.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 0875c007..52a08e61 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -528,7 +528,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): ('StarPos' in entry or this.coordinates)): # strip out properties disallowed by the schema - for thing in [ + for thing in ( 'ActiveFine', 'CockpitBreach', 'BoostUsed', @@ -538,16 +538,16 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): 'Latitude', 'Longitude', 'Wanted' - ]: + ): entry.pop(thing, None) if 'Factions' in entry: # Filter faction state. `entry` is a shallow copy so replace 'Factions' value rather than modify in-place. entry['Factions'] = [ { - k: v for k, v in f.items() if k not in [ + k: v for k, v in f.items() if k not in ( 'HappiestSystem', 'HomeSystem', 'MyReputation', 'SquadronFaction' - ] + ) } for f in entry['Factions'] ] @@ -588,7 +588,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): return str(e) elif (config.getint('output') & config.OUT_MKT_EDDN and not state['Captain'] and - entry['event'] in ['Market', 'Outfitting', 'Shipyard']): + entry['event'] in ('Market', 'Outfitting', 'Shipyard')): try: if this.marketId != entry['MarketID']: From 5aa67957739a6fb65960ae1ac80261de40775042 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 2 Aug 2020 14:56:43 +0200 Subject: [PATCH 11/19] Type annotate all the things! --- plugins/eddn.py | 156 ++++++++++++++++++++++++++---------------------- 1 file changed, 84 insertions(+), 72 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 52a08e61..ecbabe1f 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -7,12 +7,17 @@ from os import SEEK_SET from os.path import exists, join from platform import system import re -from typing import Any, Mapping, TYPE_CHECKING +from typing import ( + Any, AnyStr, Dict, Iterator, List, Mapping, MutableMapping, Optional, + Sequence, TYPE_CHECKING, OrderedDict as OrderedDictT, TextIO, Tuple, Union +) + import requests import sys import logging import tkinter as tk +from myNotebook import Frame from ttkHyperlinkLabel import HyperlinkLabel import myNotebook as nb # noqa: N813 @@ -25,7 +30,8 @@ from config import appname, applongname, appversion, config from companion import category_map if TYPE_CHECKING: - def _(x): return x + def _(x: str) -> str: + return x logger = logging.getLogger(appname) @@ -60,13 +66,13 @@ class EDDN: MODULE_RE = re.compile(r'^Hpt_|^Int_|Armour_', re.IGNORECASE) CANONICALISE_RE = re.compile(r'\$(.+)_name;') - def __init__(self, parent): - self.parent = parent + def __init__(self, parent: tk.Tk): + self.parent: tk.Tk = parent self.session = requests.Session() - self.replayfile = None # For delayed messages - self.replaylog = [] + self.replayfile: Optional[TextIO] = None # For delayed messages + self.replaylog: List[str] = [] - def load(self): + def load(self) -> bool: # Try to obtain exclusive access to the journal cache filename = join(config.app_dir, 'replay.jsonl') try: @@ -109,10 +115,10 @@ class EDDN: self.replayfile = None - def send(self, cmdr, msg): + def send(self, cmdr: str, msg: Mapping[str, Any]): uploader_id = cmdr - msg = OrderedDict([ + to_send: OrderedDictT[str, str] = OrderedDict([ ('$schemaRef', msg['$schemaRef']), ('header', OrderedDict([ ('softwareName', f'{applongname} [{system() if sys.platform != "darwin" else "Mac OS"}]'), @@ -122,7 +128,7 @@ class EDDN: ('message', msg['message']), ]) - r = self.session.post(self.UPLOAD, data=json.dumps(msg), timeout=self.TIMEOUT) + r = self.session.post(self.UPLOAD, data=json.dumps(to_send), timeout=self.TIMEOUT) if r.status_code != requests.codes.ok: logger.debug(f':\nStatus\t{r.status_code}URL\t{r.url}Headers\t{r.headers}Content:\n{r.text}') @@ -132,12 +138,13 @@ class EDDN: if not self.replayfile: return # Probably closing app - status = self.parent.children['status'] + status: Dict[str, Any] = self.parent.children['status'] if not self.replaylog: status['text'] = '' return - localized = _('Sending data to EDDN...') + + localized: str = _('Sending data to EDDN...') if len(self.replaylog) == 1: status['text'] = localized @@ -148,6 +155,7 @@ class EDDN: try: cmdr, msg = json.loads(self.replaylog[0], object_pairs_hook=OrderedDict) + except json.JSONDecodeError as e: # Couldn't decode - shouldn't happen! logger.debug(f'\n{self.replaylog[0]}\n', exc_info=e) @@ -157,7 +165,7 @@ class EDDN: else: # Rewrite old schema name if msg['$schemaRef'].startswith('http://schemas.elite-markets.net/eddn/'): - msg['$schemaRef'] = 'https://eddn.edcd.io/schemas/' + msg['$schemaRef'][38:] + msg['$schemaRef'] = 'https://eddn.edcd.io/schemas/' + msg['$schemaRef'][38:] # TODO: 38?! try: self.send(cmdr, msg) @@ -177,8 +185,8 @@ class EDDN: self.parent.after(self.REPLAYPERIOD, self.sendreplay) - def export_commodities(self, data, is_beta): - commodities = [] + def export_commodities(self, data: Mapping[str, Any], is_beta: bool): + commodities: List[OrderedDictT[str, Any]] = [] for commodity in data['lastStarport'].get('commodities') or []: # Check 'marketable' and 'not prohibited' if (category_map.get(commodity['categoryname'], True) @@ -200,7 +208,7 @@ class EDDN: commodities.sort(key=lambda c: c['name']) if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it - message = OrderedDict([ + message: OrderedDictT[str, Any] = OrderedDict([ ('timestamp', data['timestamp']), ('systemName', data['lastSystem']['name']), ('stationName', data['lastStarport']['name']), @@ -217,16 +225,19 @@ class EDDN: message['prohibited'] = sorted(x for x in (data['lastStarport']['prohibited'] or {}).values()) self.send(data['commander']['name'], { - '$schemaRef': 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/commodity/3{"/test" if is_beta else ""}', 'message': message, }) this.commodities = commodities - def export_outfitting(self, data, is_beta): - economies = data['lastStarport'].get('economies') or {} - modules: Mapping[str, Any] = data['lastStarport'].get('modules') or {} - ships = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} + def export_outfitting(self, data: Mapping[str, Any], is_beta: bool): + economies: Dict[str, Any] = data['lastStarport'].get('economies') or {} + modules: Dict[str, Any] = data['lastStarport'].get('modules') or {} + ships: Dict[str, Union[Dict[str, Any], List]] = data['lastStarport'].get('ships') or { + 'shipyard_list': {}, 'unavailable_list': [] + } + # Horizons flag - will hit at least Int_PlanetApproachSuite other than at engineer bases ("Colony"), # prison or rescue Megaships, or under Pirate Attack etc horizons = ( @@ -235,19 +246,19 @@ class EDDN: any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) ) - to_search = filter( + to_search: Iterator[Mapping[str, Any]] = filter( lambda m: self.MODULE_RE.search(m['name']) and m.get('sku') in (None, HORIZ_SKU) and m['name'] != 'Int_PlanetApproachSuite', modules.values() ) - outfitting = sorted( + outfitting: List[str] = sorted( self.MODULE_RE.sub(lambda match: match.group(0).capitalize(), mod['name'].lower()) for mod in to_search ) # Don't send empty modules list - schema won't allow it if outfitting and this.outfitting != (horizons, outfitting): self.send(data['commander']['name'], { - '$schemaRef': 'https://eddn.edcd.io/schemas/outfitting/2' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/outfitting/2{"/test" if is_beta else ""}', 'message': OrderedDict([ ('timestamp', data['timestamp']), ('systemName', data['lastSystem']['name']), @@ -260,17 +271,17 @@ class EDDN: this.outfitting = (horizons, outfitting) - def export_shipyard(self, data, is_beta): - economies = data['lastStarport'].get('economies') or {} - modules = data['lastStarport'].get('modules') or {} - ships = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} - horizons = ( + def export_shipyard(self, data: Dict[str, Any], is_beta: bool): + economies: Dict[str, Any] = data['lastStarport'].get('economies') or {} + modules: Dict[str, Any] = data['lastStarport'].get('modules') or {} + ships: Dict[str, Any] = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} + horizons: bool = ( any(economy['name'] == 'Colony' for economy in economies.values()) or any(module.get('sku') == HORIZ_SKU for module in modules.values()) or any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) ) - shipyard = sorted( + shipyard: List[Mapping[str, Any]] = sorted( itertools.chain( (ship['name'].lower() for ship in (ships['shipyard_list'] or {}).values()), ships['unavailable_list'] @@ -279,7 +290,7 @@ class EDDN: # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. if shipyard and this.shipyard != (horizons, shipyard): self.send(data['commander']['name'], { - '$schemaRef': 'https://eddn.edcd.io/schemas/shipyard/2' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/shipyard/2{"/test" if is_beta else ""}', 'message': OrderedDict([ ('timestamp', data['timestamp']), ('systemName', data['lastSystem']['name']), @@ -292,9 +303,9 @@ class EDDN: this.shipyard = (horizons, shipyard) - def export_journal_commodities(self, cmdr, is_beta, entry): - items = entry.get('Items') or [] - commodities = sorted((OrderedDict([ + def export_journal_commodities(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + items: List[Mapping[str, Any]] = entry.get('Items') or [] + commodities: Sequence[OrderedDictT[AnyStr, Any]] = sorted((OrderedDict([ ('name', self.canonicalise(commodity['Name'])), ('meanPrice', commodity['MeanPrice']), ('buyPrice', commodity['BuyPrice']), @@ -307,7 +318,7 @@ class EDDN: if commodities and this.commodities != commodities: # Don't send empty commodities list - schema won't allow it self.send(cmdr, { - '$schemaRef': 'https://eddn.edcd.io/schemas/commodity/3' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/commodity/3{"/test" if is_beta else ""}', 'message': OrderedDict([ ('timestamp', entry['timestamp']), ('systemName', entry['StarSystem']), @@ -317,21 +328,21 @@ class EDDN: ]), }) - this.commodities = commodities + this.commodities: OrderedDictT[str, Any] = commodities - def export_journal_outfitting(self, cmdr, is_beta, entry): - modules = entry.get('Items') or [] - horizons = entry.get('Horizons', False) + def export_journal_outfitting(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + modules: List[Mapping[str, Any]] = entry.get('Items', []) + horizons: bool = entry.get('Horizons', False) # outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) # for module in modules if module['Name'] != 'int_planetapproachsuite']) - outfitting = sorted( + outfitting: List[str] = sorted( self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), mod['Name']) for mod in filter(lambda m: m['Name'] != 'int_planetapproachsuite', modules) ) # Don't send empty modules list - schema won't allow it if outfitting and this.outfitting != (horizons, outfitting): self.send(cmdr, { - '$schemaRef': 'https://eddn.edcd.io/schemas/outfitting/2' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/outfitting/2{"/test" if is_beta else ""}', 'message': OrderedDict([ ('timestamp', entry['timestamp']), ('systemName', entry['StarSystem']), @@ -344,14 +355,14 @@ class EDDN: this.outfitting = (horizons, outfitting) - def export_journal_shipyard(self, cmdr, is_beta, entry): - ships = entry.get('PriceList') or [] - horizons = entry.get('Horizons', False) + def export_journal_shipyard(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + ships: List[Mapping[str, Any]] = entry.get('PriceList') or [] + horizons: bool = entry.get('Horizons', False) shipyard = sorted(ship['ShipType'] for ship in ships) # Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard. if shipyard and this.shipyard != (horizons, shipyard): self.send(cmdr, { - '$schemaRef': 'https://eddn.edcd.io/schemas/shipyard/2' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/shipyard/2{"/test" if is_beta else ""}', 'message': OrderedDict([ ('timestamp', entry['timestamp']), ('systemName', entry['StarSystem']), @@ -364,9 +375,9 @@ class EDDN: this.shipyard = (horizons, shipyard) - def export_journal_entry(self, cmdr, is_beta, entry): + def export_journal_entry(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): msg = { - '$schemaRef': 'https://eddn.edcd.io/schemas/journal/1' + (is_beta and '/test' or ''), + '$schemaRef': f'https://eddn.edcd.io/schemas/journal/1{"/test" if is_beta else ""}', 'message': entry } @@ -383,13 +394,13 @@ class EDDN: else: # Can't access replay file! Send immediately. - status = self.parent.children['status'] + status: MutableMapping[str, str] = self.parent.children['status'] status['text'] = _('Sending data to EDDN...') self.parent.update_idletasks() self.send(cmdr, msg) status['text'] = '' - def canonicalise(self, item): + def canonicalise(self, item: str) -> str: match = self.CANONICALISE_RE.match(item) return match and match.group(1) or item @@ -400,7 +411,7 @@ def plugin_start3(plugin_dir): return 'EDDN' -def plugin_app(parent): +def plugin_app(parent: tk.Tk): this.parent = parent this.eddn = EDDN(parent) # Try to obtain exclusive lock on journal cache, even if we don't need it yet @@ -409,16 +420,15 @@ def plugin_app(parent): this.status['text'] = 'Error: Is another copy of this app already running?' -def plugin_prefs(parent, cmdr, is_beta): - PADX = 10 - BUTTONX = 12 # indent Checkbuttons and Radiobuttons - PADY = 2 # close spacing +def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: + PADX = 10 # noqa: N806 + BUTTONX = 12 # noqa: N806 # indent Checkbuttons and Radiobuttons if prefsVersion.shouldSetDefaults('0.0.0.0', not bool(config.getint('output'))): - output = (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN) # default settings + output: int = (config.OUT_MKT_EDDN | config.OUT_SYS_EDDN) # default settings else: - output = config.getint('output') + output: int = config.getint('output') eddnframe = nb.Frame(parent) @@ -467,7 +477,7 @@ def prefsvarchanged(event=None): this.eddn_delay_button['state'] = this.eddn.replayfile and this.eddn_system.get() and tk.NORMAL or tk.DISABLED -def prefs_changed(cmdr, is_beta): +def prefs_changed(cmdr: str, is_beta: bool): config.set( 'output', (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + @@ -481,10 +491,12 @@ def plugin_stop(): this.eddn.close() -def journal_entry(cmdr, is_beta, system, station, entry, state): +def journal_entry( + cmdr: str, is_beta: bool, system: str, station: str, entry: MutableMapping[str, Any], state: Mapping[str, Any] +) -> Optional[str]: # Recursively filter '*_Localised' keys from dict - def filter_localised(d): - filtered = OrderedDict() + def filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]: + filtered: OrderedDictT[str, Any] = OrderedDict() for k, v in d.items(): if k.endswith('_Localised'): pass @@ -501,25 +513,25 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): return filtered # Track location - if entry['event'] in ['Location', 'FSDJump', 'Docked', 'CarrierJump']: + if entry['event'] in ('Location', 'FSDJump', 'Docked', 'CarrierJump'): if entry['event'] in ('Location', 'CarrierJump'): - this.planet = entry.get('Body') if entry.get('BodyType') == 'Planet' else None + this.planet: Optional[str] = entry.get('Body') if entry.get('BodyType') == 'Planet' else None elif entry['event'] == 'FSDJump': - this.planet = None + this.planet: Optional[str] = None if 'StarPos' in entry: - this.coordinates = tuple(entry['StarPos']) + this.coordinates: Optional[Tuple[int, int, int]] = tuple(entry['StarPos']) elif this.systemaddress != entry.get('SystemAddress'): - this.coordinates = None # Docked event doesn't include coordinates + this.coordinates: Optional[Tuple[int, int, int]] = None # Docked event doesn't include coordinates - this.systemaddress = entry.get('SystemAddress') + this.systemaddress: Optional[str] = entry.get('SystemAddress') elif entry['event'] == 'ApproachBody': this.planet = entry['Body'] - elif entry['event'] in ['LeaveBody', 'SupercruiseEntry']: + elif entry['event'] in ('LeaveBody', 'SupercruiseEntry'): this.planet = None # Send interesting events to EDDN, but not when on a crew @@ -560,19 +572,19 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): # add mandatory StarSystem, StarPos and SystemAddress properties to Scan events if 'StarSystem' not in entry: if not system: - return("system is None, can't add StarSystem") + return "system is None, can't add StarSystem" entry['StarSystem'] = system if 'StarPos' not in entry: if not this.coordinates: - return("this.coordinates is None, can't add StarPos") + return "this.coordinates is None, can't add StarPos" entry['StarPos'] = list(this.coordinates) if 'SystemAddress' not in entry: if not this.systemaddress: - return("this.systemaddress is None, can't add SystemAddress") + return "this.systemaddress is None, can't add SystemAddress" entry['SystemAddress'] = this.systemaddress @@ -596,7 +608,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): this.marketId = entry['MarketID'] with open( - join(config.get('journaldir') or config.default_journal_dir, f'{entry["event"]}.json'), 'rb' + join(str(config.get('journaldir') or config.default_journal_dir), f'{entry["event"]}.json'), 'rb' ) as h: entry = json.load(h) if entry['event'] == 'Market': @@ -617,7 +629,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state): return str(e) -def cmdr_data(data, is_beta): +def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> str: if data['commander'].get('docked') and config.getint('output') & config.OUT_MKT_EDDN: try: if this.marketId != data['lastStarport']['id']: From a21280ed3b4fb8880ce297edec32d0d8512e99f4 Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 13:32:01 +0200 Subject: [PATCH 12/19] reordered imports --- plugins/eddn.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index ecbabe1f..e3392dc4 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -1,33 +1,31 @@ # Export to EDDN -from collections import OrderedDict import itertools import json +import logging +import re +import sys +import tkinter as tk +from collections import OrderedDict from os import SEEK_SET from os.path import exists, join from platform import system -import re -from typing import ( - Any, AnyStr, Dict, Iterator, List, Mapping, MutableMapping, Optional, - Sequence, TYPE_CHECKING, OrderedDict as OrderedDictT, TextIO, Tuple, Union -) +from typing import TYPE_CHECKING, Any, AnyStr, Dict, Iterator, List, Mapping, MutableMapping, Optional +from typing import OrderedDict as OrderedDictT +from typing import Sequence, TextIO, Tuple, Union import requests -import sys -import logging -import tkinter as tk -from myNotebook import Frame -from ttkHyperlinkLabel import HyperlinkLabel import myNotebook as nb # noqa: N813 - +from companion import category_map +from config import applongname, appname, appversion, config +from myNotebook import Frame from prefs import prefsVersion +from ttkHyperlinkLabel import HyperlinkLabel if sys.platform != 'win32': from fcntl import lockf, LOCK_EX, LOCK_NB -from config import appname, applongname, appversion, config -from companion import category_map if TYPE_CHECKING: def _(x: str) -> str: From b5d3b89a3cbf44ab05416d1fa34b2b9b2c571fe2 Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 14:39:12 +0200 Subject: [PATCH 13/19] Added docstrings and further type annotations --- plugins/eddn.py | 111 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 93 insertions(+), 18 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index e3392dc4..ecc90d5f 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -42,7 +42,9 @@ this.planet = None # Avoid duplicates this.marketId = None -this.commodities = this.outfitting = this.shipyard = None +this.commodities = None +this.outfitting: Optional[Tuple[bool, MutableMapping[str, Any]]] = None +this.shipyard = None HORIZ_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' @@ -70,7 +72,12 @@ class EDDN: self.replayfile: Optional[TextIO] = None # For delayed messages self.replaylog: List[str] = [] - def load(self) -> bool: + def load_journal_replay(self) -> bool: + """ + Load cached journal entries from disk + + :return: a bool indicating success + """ # Try to obtain exclusive access to the journal cache filename = join(config.app_dir, 'replay.jsonl') try: @@ -100,6 +107,9 @@ class EDDN: return True def flush(self): + """ + flush flushes the replay file, clearing any data currently there that is not in the replaylog list + """ self.replayfile.seek(0, SEEK_SET) self.replayfile.truncate() for line in self.replaylog: @@ -108,12 +118,21 @@ class EDDN: self.replayfile.flush() def close(self): + """ + close closes the replay file + """ if self.replayfile: self.replayfile.close() self.replayfile = None - def send(self, cmdr: str, msg: Mapping[str, Any]): + def send(self, cmdr: str, msg: Mapping[str, Any]) -> None: + """ + Send sends an update to EDDN + + :param cmdr: the CMDR to use as the uploader ID + :param msg: the payload to send + """ uploader_id = cmdr to_send: OrderedDictT[str, str] = OrderedDict([ @@ -132,7 +151,10 @@ class EDDN: r.raise_for_status() - def sendreplay(self): + def sendreplay(self) -> None: + """ + sendreplay updates EDDN with cached journal lines + """ if not self.replayfile: return # Probably closing app @@ -183,7 +205,14 @@ class EDDN: self.parent.after(self.REPLAYPERIOD, self.sendreplay) - def export_commodities(self, data: Mapping[str, Any], is_beta: bool): + def export_commodities(self, data: Mapping[str, Any], is_beta: bool) -> None: + """ + export_commodities updates EDDN with the commodities on the current (lastStarport) station. + Once the send is complete, this.commodities is updated with the new data. + + :param data: a dict containing the starport data + :param is_beta: whether or not we're currently in beta mode + """ commodities: List[OrderedDictT[str, Any]] = [] for commodity in data['lastStarport'].get('commodities') or []: # Check 'marketable' and 'not prohibited' @@ -229,7 +258,14 @@ class EDDN: this.commodities = commodities - def export_outfitting(self, data: Mapping[str, Any], is_beta: bool): + def export_outfitting(self, data: Mapping[str, Any], is_beta: bool) -> None: + """ + export_outfitting updates EDDN with the current (lastStarport) station's outfitting options, if any. + Once the send is complete, this.outfitting is updated with the given data. + + :param data: dict containing the outfitting data + :param is_beta: whether or not we're currently in beta mode + """ economies: Dict[str, Any] = data['lastStarport'].get('economies') or {} modules: Dict[str, Any] = data['lastStarport'].get('modules') or {} ships: Dict[str, Union[Dict[str, Any], List]] = data['lastStarport'].get('ships') or { @@ -269,7 +305,14 @@ class EDDN: this.outfitting = (horizons, outfitting) - def export_shipyard(self, data: Dict[str, Any], is_beta: bool): + def export_shipyard(self, data: Dict[str, Any], is_beta: bool) -> None: + """ + export_shipyard updates EDDN with the current (lastStarport) station's outfitting options, if any. + once the send is complete, this.shipyard is updated to the new data. + + :param data: dict containing the shipyard data + :param is_beta: whether or not we are in beta mode + """ economies: Dict[str, Any] = data['lastStarport'].get('economies') or {} modules: Dict[str, Any] = data['lastStarport'].get('modules') or {} ships: Dict[str, Any] = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} @@ -301,7 +344,15 @@ class EDDN: this.shipyard = (horizons, shipyard) - def export_journal_commodities(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + def export_journal_commodities(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: + """ + export_journal_commodities updates EDDN with the commodities list on the current station (lastStarport) from + data in the journal. As a side effect, it also updates this.commodities with the data + + :param cmdr: The commander to send data under + :param is_beta: whether or not we're in beta mode + :param entry: the journal entry containing the commodities data + """ items: List[Mapping[str, Any]] = entry.get('Items') or [] commodities: Sequence[OrderedDictT[AnyStr, Any]] = sorted((OrderedDict([ ('name', self.canonicalise(commodity['Name'])), @@ -328,7 +379,15 @@ class EDDN: this.commodities: OrderedDictT[str, Any] = commodities - def export_journal_outfitting(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + def export_journal_outfitting(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: + """ + export_journal_outfitting updates EDDN with station outfitting based on a journal entry. As a side effect, + it also updates this.outfitting with the data + + :param cmdr: The commander to send data under + :param is_beta: Whether or not we're in beta mode + :param entry: The relevant journal entry + """ modules: List[Mapping[str, Any]] = entry.get('Items', []) horizons: bool = entry.get('Horizons', False) # outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name']) @@ -353,7 +412,15 @@ class EDDN: this.outfitting = (horizons, outfitting) - def export_journal_shipyard(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + def export_journal_shipyard(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: + """ + export_journal_shipyard updates EDDN with station shipyard data based on a journal entry. As a side effect, + this.shipyard is updated with the data. + + :param cmdr: the commander to send this update under + :param is_beta: Whether or not we're in beta mode + :param entry: the relevant journal entry + """ ships: List[Mapping[str, Any]] = entry.get('PriceList') or [] horizons: bool = entry.get('Horizons', False) shipyard = sorted(ship['ShipType'] for ship in ships) @@ -373,13 +440,21 @@ class EDDN: this.shipyard = (horizons, shipyard) - def export_journal_entry(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]): + def export_journal_entry(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None: + """ + export_journal_entry updates EDDN with a line from the journal. Additionally if additional lines are cached, + it may send those as well. + + :param cmdr: the commander under which this upload is made + :param is_beta: whether or not we are in beta mode + :param entry: the journal entry to send + """ msg = { '$schemaRef': f'https://eddn.edcd.io/schemas/journal/1{"/test" if is_beta else ""}', 'message': entry } - if self.replayfile or self.load(): + if self.replayfile or self.load_journal_replay(): # Store the entry self.replaylog.append(json.dumps([cmdr, msg])) self.replayfile.write(f'{self.replaylog[-1]}\n') @@ -405,15 +480,15 @@ class EDDN: # Plugin callbacks -def plugin_start3(plugin_dir): +def plugin_start3(plugin_dir: str) -> str: return 'EDDN' -def plugin_app(parent: tk.Tk): +def plugin_app(parent: tk.Tk) -> None: this.parent = parent this.eddn = EDDN(parent) # Try to obtain exclusive lock on journal cache, even if we don't need it yet - if not this.eddn.load(): + if not this.eddn.load_journal_replay(): # Shouldn't happen - don't bother localizing this.status['text'] = 'Error: Is another copy of this app already running?' @@ -469,13 +544,13 @@ def plugin_prefs(parent, cmdr: str, is_beta: bool) -> Frame: return eddnframe -def prefsvarchanged(event=None): +def prefsvarchanged(event=None) -> None: this.eddn_station_button['state'] = tk.NORMAL this.eddn_system_button['state'] = tk.NORMAL this.eddn_delay_button['state'] = this.eddn.replayfile and this.eddn_system.get() and tk.NORMAL or tk.DISABLED -def prefs_changed(cmdr: str, is_beta: bool): +def prefs_changed(cmdr: str, is_beta: bool) -> None: config.set( 'output', (config.getint('output') & (config.OUT_MKT_TD | config.OUT_MKT_CSV | config.OUT_SHIP | config.OUT_MKT_MANUAL)) + @@ -485,7 +560,7 @@ def prefs_changed(cmdr: str, is_beta: bool): ) -def plugin_stop(): +def plugin_stop() -> None: this.eddn.close() From 237e5ce52d2e5df890ab367d4d83d6e146d11a2f Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 14:43:53 +0200 Subject: [PATCH 14/19] Replaced subscript and concat with replace() call --- plugins/eddn.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index ecc90d5f..7d1fc698 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -185,7 +185,10 @@ class EDDN: else: # Rewrite old schema name if msg['$schemaRef'].startswith('http://schemas.elite-markets.net/eddn/'): - msg['$schemaRef'] = 'https://eddn.edcd.io/schemas/' + msg['$schemaRef'][38:] # TODO: 38?! + msg['$schemaRef'] = str(msg['$schemaRef']).replace( + 'http://schemas.elite-markets.net/eddn/', + 'https://eddn.edcd.io/schemas/' + ) try: self.send(cmdr, msg) From 17f8433a6a7a498126590509d95fde5c3a1d7280 Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 14:45:48 +0200 Subject: [PATCH 15/19] clarify comment --- plugins/eddn.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 7d1fc698..8786d5a7 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -630,7 +630,8 @@ def journal_entry( entry.pop(thing, None) if 'Factions' in entry: - # Filter faction state. `entry` is a shallow copy so replace 'Factions' value rather than modify in-place. + # Filter faction state to comply with schema restrictions regarding personal data. `entry` is a shallow copy + # so replace 'Factions' value rather than modify in-place. entry['Factions'] = [ { k: v for k, v in f.items() if k not in ( From 94418dc4fa319aeaa53936c93bef62fb92ab748f Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 14:54:04 +0200 Subject: [PATCH 16/19] Switched to using pathlib --- plugins/eddn.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index 8786d5a7..db648a31 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -3,6 +3,7 @@ import itertools import json import logging +import pathlib import re import sys import tkinter as tk @@ -684,10 +685,9 @@ def journal_entry( this.commodities = this.outfitting = this.shipyard = None this.marketId = entry['MarketID'] - with open( - join(str(config.get('journaldir') or config.default_journal_dir), f'{entry["event"]}.json'), 'rb' - ) as h: - entry = json.load(h) + path = pathlib.Path(str(config.get('journaldir') or config.default_journal_dir)) / f'{entry["event"]}.json' + with path.open('rb') as f: + entry = json.load(f) if entry['event'] == 'Market': this.eddn.export_journal_commodities(cmdr, is_beta, entry) From a88cb454da9c0dddb695673f67c4369caf9f3222 Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 14:54:43 +0200 Subject: [PATCH 17/19] Removed todo related to Horizons --- plugins/eddn.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index db648a31..cdd64c45 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -50,12 +50,7 @@ this.shipyard = None HORIZ_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS' -# TODO: -# 1, this does a bunch of magic checks for whether or not the given commander has horizons. We can get that directly -# from CAPI via commander.capabilities.Horizons -- Should this be changed to use that? did such a thing exist when -# this was written? -# -# 2, a good few of these methods are static or could be classmethods. they should be created as such. +# TODO: a good few of these methods are static or could be classmethods. they should be created as such. class EDDN: # SERVER = 'http://localhost:8081' # testing From 7adf522de9d8b5a332f674fbc2b2a498fe1d4e14 Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 15:18:33 +0200 Subject: [PATCH 18/19] Replaced repeated code with helper function --- plugins/eddn.py | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/plugins/eddn.py b/plugins/eddn.py index cdd64c45..877573e2 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -265,19 +265,15 @@ class EDDN: :param data: dict containing the outfitting data :param is_beta: whether or not we're currently in beta mode """ - economies: Dict[str, Any] = data['lastStarport'].get('economies') or {} modules: Dict[str, Any] = data['lastStarport'].get('modules') or {} - ships: Dict[str, Union[Dict[str, Any], List]] = data['lastStarport'].get('ships') or { - 'shipyard_list': {}, 'unavailable_list': [] - } # Horizons flag - will hit at least Int_PlanetApproachSuite other than at engineer bases ("Colony"), # prison or rescue Megaships, or under Pirate Attack etc - horizons = ( - any(economy['name'] == 'Colony' for economy in economies.values()) or - any(module.get('sku') == HORIZ_SKU for module in modules.values()) or - any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) - ) + horizons: bool = is_horizons( + data['lastStarport'].get('economies', {}), + modules, + data['lastStarport'].get('ships', {'shipyard_list': {}, 'unavailable_list': []}) + ) to_search: Iterator[Mapping[str, Any]] = filter( lambda m: self.MODULE_RE.search(m['name']) and m.get('sku') in (None, HORIZ_SKU) and @@ -312,14 +308,12 @@ class EDDN: :param data: dict containing the shipyard data :param is_beta: whether or not we are in beta mode """ - economies: Dict[str, Any] = data['lastStarport'].get('economies') or {} - modules: Dict[str, Any] = data['lastStarport'].get('modules') or {} - ships: Dict[str, Any] = data['lastStarport'].get('ships') or {'shipyard_list': {}, 'unavailable_list': []} - horizons: bool = ( - any(economy['name'] == 'Colony' for economy in economies.values()) or - any(module.get('sku') == HORIZ_SKU for module in modules.values()) or - any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) - ) + ships: Dict[str, Any] = data['lastStarport'].get('ships', {'shipyard_list': {}, 'unavailable_list': []}) + horizons: bool = is_horizons( + data['lastStarport'].get('economies', {}), + data['lastStarport'].get('modules', {}), + ships + ) shipyard: List[Mapping[str, Any]] = sorted( itertools.chain( @@ -728,3 +722,14 @@ def cmdr_data(data: Mapping[str, Any], is_beta: bool) -> str: except Exception as e: logger.debug('Failed exporting data', exc_info=e) return str(e) + + +MAP_STR_ANY = Mapping[str, Any] + + +def is_horizons(economies: MAP_STR_ANY, modules: MAP_STR_ANY, ships: MAP_STR_ANY) -> bool: + return ( + any(economy['name'] == 'Colony' for economy in economies.values()) or + any(module.get('sku') == HORIZ_SKU for module in modules.values()) or + any(ship.get('sku') == HORIZ_SKU for ship in (ships['shipyard_list'] or {}).values()) + ) From de872cdfa665b21b4683430956ed17cb441edb0a Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 7 Aug 2020 15:46:46 +0200 Subject: [PATCH 19/19] Added warning log messages --- plugins/eddn.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/plugins/eddn.py b/plugins/eddn.py index 877573e2..b16fc98b 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -639,18 +639,21 @@ def journal_entry( # add mandatory StarSystem, StarPos and SystemAddress properties to Scan events if 'StarSystem' not in entry: if not system: + logger.warn("system is None, can't add StarSystem") return "system is None, can't add StarSystem" entry['StarSystem'] = system if 'StarPos' not in entry: if not this.coordinates: + logger.warn("this.coordinates is None, can't add StarPos") return "this.coordinates is None, can't add StarPos" entry['StarPos'] = list(this.coordinates) if 'SystemAddress' not in entry: if not this.systemaddress: + logger.warn("this.systemaddress is None, can't add SystemAddress") return "this.systemaddress is None, can't add SystemAddress" entry['SystemAddress'] = this.systemaddress