1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-06-10 20:32:12 +03:00

Clean up flake8 output for this branch

This commit is contained in:
Athanasius 2020-07-27 09:37:10 +01:00
parent 3653a1342f
commit f9a23cc831
7 changed files with 122 additions and 108 deletions

View File

@ -9,7 +9,7 @@ import sys
import logging import logging
from typing import Tuple from typing import Tuple
class logger(): class Logger:
""" """
Wrapper class for all logging configuration and code. Wrapper class for all logging configuration and code.
@ -20,7 +20,7 @@ class logger():
Users of this class should then call getLogger() to get the Users of this class should then call getLogger() to get the
logging.Logger instance. logging.Logger instance.
""" """
def __init__(self, logger_name: str, loglevel: int=logging.DEBUG): def __init__(self, logger_name: str, loglevel: int = logging.DEBUG):
""" """
Set up a `logging.Logger` with our preferred configuration. Set up a `logging.Logger` with our preferred configuration.
This includes using an EDMCContextFilter to add 'class' and 'qualname' This includes using an EDMCContextFilter to add 'class' and 'qualname'
@ -37,7 +37,7 @@ class logger():
self.logger_channel = logging.StreamHandler() self.logger_channel = logging.StreamHandler()
self.logger_channel.setLevel(loglevel) self.logger_channel.setLevel(loglevel)
self.logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s.%(qualname)s:%(lineno)d: %(class)s: %(message)s') self.logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s.%(qualname)s:%(lineno)d: %(class)s: %(message)s') # noqa: E501
self.logger_formatter.default_time_format = '%Y-%m-%d %H:%M:%S' self.logger_formatter.default_time_format = '%Y-%m-%d %H:%M:%S'
self.logger_formatter.default_msec_format = '%s.%03d' self.logger_formatter.default_msec_format = '%s.%03d'

View File

@ -15,7 +15,6 @@ import html
import requests import requests
from time import gmtime, time, localtime, strftime, strptime from time import gmtime, time, localtime, strftime, strptime
import _strptime # Workaround for http://bugs.python.org/issue7980 import _strptime # Workaround for http://bugs.python.org/issue7980
from calendar import timegm
import webbrowser import webbrowser
import EDMCLogging import EDMCLogging
@ -207,7 +206,7 @@ class AppWindow(object):
self.help_menu.add_command(command=self.help_general) self.help_menu.add_command(command=self.help_general)
self.help_menu.add_command(command=self.help_privacy) self.help_menu.add_command(command=self.help_privacy)
self.help_menu.add_command(command=self.help_releases) self.help_menu.add_command(command=self.help_releases)
self.help_menu.add_command(command=lambda:self.updater.checkForUpdates()) self.help_menu.add_command(command=lambda: self.updater.checkForUpdates())
self.help_menu.add_command(command=lambda: not self.HelpAbout.showing and self.HelpAbout(self.w)) self.help_menu.add_command(command=lambda: not self.HelpAbout.showing and self.HelpAbout(self.w))
self.menubar.add_cascade(menu=self.help_menu) self.menubar.add_cascade(menu=self.help_menu)
@ -528,7 +527,7 @@ class AppWindow(object):
self.status['text'] = str(e) self.status['text'] = str(e)
play_bad = True play_bad = True
if not self.status['text']: # no errors if not self.status['text']: # no errors
self.status['text'] = strftime(_('Last updated at {HH}:{MM}:{SS}').format(HH='%H', MM='%M', SS='%S'), localtime(querytime)) self.status['text'] = strftime(_('Last updated at {HH}:{MM}:{SS}').format(HH='%H', MM='%M', SS='%S'), localtime(querytime))
if play_sound and play_bad: if play_sound and play_bad:
hotkeymgr.play_bad() hotkeymgr.play_bad()
@ -543,12 +542,13 @@ class AppWindow(object):
if data.get('lastStarport', {}).get('ships'): if data.get('lastStarport', {}).get('ships'):
report = 'Success' report = 'Success'
else: else:
report ='Failure' report = 'Failure'
else: else:
report = 'Undocked!' report = 'Undocked!'
logger.debug(f'{__class__}: Retry for shipyard - {report}') logger.debug(f'{__class__}: Retry for shipyard - {report}')
if not data['commander'].get('docked'): if not data['commander'].get('docked'):
pass # might have undocked while we were waiting for retry in which case station data is unreliable # might have un-docked while we were waiting for retry in which case station data is unreliable
pass
elif (data.get('lastSystem', {}).get('name') == monitor.system and elif (data.get('lastSystem', {}).get('name') == monitor.system and
data.get('lastStarport', {}).get('name') == monitor.station and data.get('lastStarport', {}).get('name') == monitor.station and
data.get('lastStarport', {}).get('ships', {}).get('shipyard_list')): data.get('lastStarport', {}).get('ships', {}).get('shipyard_list')):
@ -620,7 +620,9 @@ class AppWindow(object):
logger.info(f"{__class__}: Can't start Status monitoring") logger.info(f"{__class__}: Can't start Status monitoring")
# Export loadout # Export loadout
if entry['event'] == 'Loadout' and not monitor.state['Captain'] and config.getint('output') & config.OUT_SHIP: if entry['event'] == 'Loadout'\
and not monitor.state['Captain']\
and config.getint('output') & config.OUT_SHIP:
monitor.export_ship() monitor.export_ship()
# Plugins # Plugins
@ -649,8 +651,8 @@ class AppWindow(object):
self.view_menu.entryconfigure(0, state=tk.NORMAL) # Status self.view_menu.entryconfigure(0, state=tk.NORMAL) # Status
self.file_menu.entryconfigure(0, state=tk.NORMAL) # Save Raw Data self.file_menu.entryconfigure(0, state=tk.NORMAL) # Save Raw Data
else: else:
self.file_menu.entryconfigure(0, state=tk.NORMAL) # Status self.file_menu.entryconfigure(0, state=tk.NORMAL) # Status
self.file_menu.entryconfigure(1, state=tk.NORMAL) # Save Raw Data self.file_menu.entryconfigure(1, state=tk.NORMAL) # Save Raw Data
except companion.ServerError as e: except companion.ServerError as e:
self.status['text'] = str(e) self.status['text'] = str(e)
except Exception as e: except Exception as e:
@ -805,7 +807,7 @@ class AppWindow(object):
row += 1 row += 1
button = ttk.Button(frame, text=_('OK'), command=self.apply) button = ttk.Button(frame, text=_('OK'), command=self.apply)
button.grid(row=row, column=2, sticky=tk.E) button.grid(row=row, column=2, sticky=tk.E)
button.bind("<Return>", lambda event:self.apply()) button.bind("<Return>", lambda event: self.apply())
self.protocol("WM_DELETE_WINDOW", self._destroy) self.protocol("WM_DELETE_WINDOW", self._destroy)
############################################################ ############################################################
@ -833,7 +835,11 @@ class AppWindow(object):
initialfile = '%s%s.%s.json' % (data.get('lastSystem', {}).get('name', 'Unknown'), data['commander'].get('docked') and '.'+data.get('lastStarport', {}).get('name', 'Unknown') or '', strftime('%Y-%m-%dT%H.%M.%S', localtime()))) initialfile = '%s%s.%s.json' % (data.get('lastSystem', {}).get('name', 'Unknown'), data['commander'].get('docked') and '.'+data.get('lastStarport', {}).get('name', 'Unknown') or '', strftime('%Y-%m-%dT%H.%M.%S', localtime())))
if f: if f:
with open(f, 'wb') as h: with open(f, 'wb') as h:
h.write(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True, separators=(',', ': ')).encode('utf-8')) h.write(json.dumps(data,
ensure_ascii=False,
indent=2,
sort_keys=True,
separators=(',', ': ')).encode('utf-8'))
except companion.ServerError as e: except companion.ServerError as e:
self.status['text'] = str(e) self.status['text'] = str(e)
except Exception as e: except Exception as e:
@ -841,7 +847,8 @@ class AppWindow(object):
self.status['text'] = str(e) self.status['text'] = str(e)
def onexit(self, event=None): def onexit(self, event=None):
if platform!='darwin' or self.w.winfo_rooty()>0: # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7 # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
if platform != 'darwin' or self.w.winfo_rooty() > 0:
config.set('geometry', '+{1}+{2}'.format(*self.w.geometry().split('+'))) config.set('geometry', '+{1}+{2}'.format(*self.w.geometry().split('+')))
self.w.withdraw() # Following items can take a few seconds, so hide the main window while they happen self.w.withdraw() # Following items can take a few seconds, so hide the main window while they happen
protocolhandler.close() protocolhandler.close()
@ -882,7 +889,7 @@ class AppWindow(object):
self.theme_menubar.grid(row=0, columnspan=2, sticky=tk.NSEW) self.theme_menubar.grid(row=0, columnspan=2, sticky=tk.NSEW)
def onleave(self, event=None): def onleave(self, event=None):
if config.getint('theme') > 1 and event.widget==self.w: if config.getint('theme') > 1 and event.widget == self.w:
self.w.attributes("-transparentcolor", 'grey4') self.w.attributes("-transparentcolor", 'grey4')
self.theme_menubar.grid_remove() self.theme_menubar.grid_remove()
self.blank_menubar.grid(row=0, columnspan=2, sticky=tk.NSEW) self.blank_menubar.grid(row=0, columnspan=2, sticky=tk.NSEW)
@ -931,7 +938,7 @@ def enforce_single_instance() -> None:
if len(sys.argv) > 1 and sys.argv[1].startswith(protocolhandler.redirect): if len(sys.argv) > 1 and sys.argv[1].startswith(protocolhandler.redirect):
# Browser invoked us directly with auth response. Forward the response to the other app instance. # Browser invoked us directly with auth response. Forward the response to the other app instance.
CoInitializeEx(0, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) CoInitializeEx(0, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
ShowWindow(hWnd, SW_RESTORE) # Wait for it to be responsive to avoid ShellExecute recursing ShowWindow(hWnd, SW_RESTORE) # Wait for it to be responsive to avoid ShellExecute recursing
ShellExecute(0, None, sys.argv[1], None, None, SW_RESTORE) ShellExecute(0, None, sys.argv[1], None, None, SW_RESTORE)
else: else:
ShowWindowAsync(hWnd, SW_RESTORE) ShowWindowAsync(hWnd, SW_RESTORE)
@ -949,9 +956,10 @@ if __name__ == "__main__":
if getattr(sys, 'frozen', False): if getattr(sys, 'frozen', False):
# By default py2exe tries to write log to dirname(sys.executable) which fails when installed # By default py2exe tries to write log to dirname(sys.executable) which fails when installed
import tempfile import tempfile
sys.stdout = sys.stderr = open(join(tempfile.gettempdir(), '%s.log' % appname), 'wt', 1) # unbuffered not allowed for text in python3, so use line buffering # unbuffered not allowed for text in python3, so use line buffering
sys.stdout = sys.stderr = open(join(tempfile.gettempdir(), f'{appname}.log'), 'wt', 1)
logger = EDMCLogging.logger(appname).get_logger() logger = EDMCLogging.Logger(appname).get_logger()
# Plain, not via `logger` # Plain, not via `logger`
print(f'{applongname} {appversion}') print(f'{applongname} {appversion}')

View File

@ -4,6 +4,7 @@ from builtins import object
import base64 import base64
import csv import csv
import requests import requests
from typing import TYPE_CHECKING
# TODO: see https://github.com/EDCD/EDMarketConnector/issues/569 # TODO: see https://github.com/EDCD/EDMarketConnector/issues/569
from http.cookiejar import LWPCookieJar # No longer needed but retained in case plugins use it from http.cookiejar import LWPCookieJar # No longer needed but retained in case plugins use it
@ -23,7 +24,6 @@ import logging
logger = logging.getLogger(appname) logger = logging.getLogger(appname)
from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
_ = lambda x: x # noqa # to make flake8 stop complaining that the hacked in _ method doesnt exist _ = lambda x: x # noqa # to make flake8 stop complaining that the hacked in _ method doesnt exist
@ -205,21 +205,21 @@ class Auth(object):
logger.error(f"Frontier CAPI Auth: Can't refresh token for \"{self.cmdr}\"", exc_info=e) logger.error(f"Frontier CAPI Auth: Can't refresh token for \"{self.cmdr}\"", exc_info=e)
else: else:
logger.error(f"Frontier CAPI Auth: No token for \"{self.cmdr}\"", exc_info=e) logger.error(f"Frontier CAPI Auth: No token for \"{self.cmdr}\"")
# New request # New request
logger.info(f'Frontier CAPI Auth: New authorization request') logger.info('Frontier CAPI Auth: New authorization request')
v = random.SystemRandom().getrandbits(8 * 32) v = random.SystemRandom().getrandbits(8 * 32)
self.verifier = self.base64URLEncode(v.to_bytes(32, byteorder='big')).encode('utf-8') self.verifier = self.base64_url_encode(v.to_bytes(32, byteorder='big')).encode('utf-8')
s = random.SystemRandom().getrandbits(8 * 32) s = random.SystemRandom().getrandbits(8 * 32)
self.state = self.base64URLEncode(s.to_bytes(32, byteorder='big')) self.state = self.base64_url_encode(s.to_bytes(32, byteorder='big'))
# Won't work under IE: https://blogs.msdn.microsoft.com/ieinternals/2011/07/13/understanding-protocols/ # Won't work under IE: https://blogs.msdn.microsoft.com/ieinternals/2011/07/13/understanding-protocols/
webbrowser.open( webbrowser.open(
'{server_auth}{url_auth}?response_type=code&audience=frontier&scope=capi&client_id={client_id}&code_challenge={challenge}&code_challenge_method=S256&state={state}&redirect_uri={redirect}'.format( # noqa: E501 # I cant make this any shorter '{server_auth}{url_auth}?response_type=code&audience=frontier&scope=capi&client_id={client_id}&code_challenge={challenge}&code_challenge_method=S256&state={state}&redirect_uri={redirect}'.format( # noqa: E501 # I cant make this any shorter
server_auth=SERVER_AUTH, server_auth=SERVER_AUTH,
url_auth=URL_AUTH, url_auth=URL_AUTH,
client_id=CLIENT_ID, client_id=CLIENT_ID,
challenge=self.base64URLEncode(hashlib.sha256(self.verifier).digest()), challenge=self.base64_url_encode(hashlib.sha256(self.verifier).digest()),
state=self.state, state=self.state,
redirect=protocolhandler.redirect redirect=protocolhandler.redirect
) )
@ -294,7 +294,7 @@ class Auth(object):
def dump(self, r): def dump(self, r):
logger.debug(f'Frontier CAPI Auth: {r.url} {r.status_code} {r.reason if r.reason else "None"} {r.text}') logger.debug(f'Frontier CAPI Auth: {r.url} {r.status_code} {r.reason if r.reason else "None"} {r.text}')
def base64URLEncode(self, text): def base64_url_encode(self, text):
return base64.urlsafe_b64encode(text).decode().replace('=', '') return base64.urlsafe_b64encode(text).decode().replace('=', '')
@ -379,8 +379,8 @@ class Session(object):
r = self.session.get(self.server + endpoint, timeout=timeout) r = self.session.get(self.server + endpoint, timeout=timeout)
except Exception as e: except Exception as e:
logger.debug(f'Attempting GET', exc_info=e) logger.debug('Attempting GET', exc_info=e)
raise ServerError('unable to get endpoint {}'.format(endpoint)) from e raise ServerError(f'unable to get endpoint {endpoint}') from e
if r.url.startswith(SERVER_AUTH): if r.url.startswith(SERVER_AUTH):
# Redirected back to Auth server - force full re-authentication # Redirected back to Auth server - force full re-authentication
@ -400,7 +400,7 @@ class Session(object):
data = r.json() # May also fail here if token expired since response is empty data = r.json() # May also fail here if token expired since response is empty
except (requests.HTTPError, ValueError) as e: except (requests.HTTPError, ValueError) as e:
logger.error(f'Frontier CAPI Auth: GET ', exc_info=e) logger.error('Frontier CAPI Auth: GET ', exc_info=e)
self.dump(r) self.dump(r)
self.close() self.close()
@ -408,7 +408,7 @@ class Session(object):
self.invalidate() self.invalidate()
self.retrying = False self.retrying = False
self.login() self.login()
logger.error(f'Frontier CAPI Auth: query failed after refresh') logger.error('Frontier CAPI Auth: query failed after refresh')
raise CredentialsError('query failed after refresh') from e raise CredentialsError('query failed after refresh') from e
elif self.login(): # Maybe our token expired. Re-authorize in any case elif self.login(): # Maybe our token expired. Re-authorize in any case
@ -417,7 +417,7 @@ class Session(object):
else: else:
self.retrying = False self.retrying = False
logger.error(f'Frontier CAPI Auth: HTTP error or invalid JSON') logger.error('Frontier CAPI Auth: HTTP error or invalid JSON')
raise CredentialsError('HTTP error or invalid JSON') from e raise CredentialsError('HTTP error or invalid JSON') from e
self.retrying = False self.retrying = False
@ -462,7 +462,7 @@ class Session(object):
self.session.close() self.session.close()
except Exception as e: except Exception as e:
logger.debug(f'Frontier CAPI Auth: closing', exc_info=e) logger.debug('Frontier CAPI Auth: closing', exc_info=e)
self.session = None self.session = None
@ -496,7 +496,7 @@ def fixup(data):
# But also see https://github.com/Marginal/EDMarketConnector/issues/32 # But also see https://github.com/Marginal/EDMarketConnector/issues/32
for thing in ('buyPrice', 'sellPrice', 'demand', 'demandBracket', 'stock', 'stockBracket'): for thing in ('buyPrice', 'sellPrice', 'demand', 'demandBracket', 'stock', 'stockBracket'):
if not isinstance(commodity.get(thing), numbers.Number): if not isinstance(commodity.get(thing), numbers.Number):
logger.debug(f'Invalid {thing}:{commodity.get(thing)} ({type(commodity.get(thing))}) for {commodity.get("name", "")}') logger.debug(f'Invalid {thing}:{commodity.get(thing)} ({type(commodity.get(thing))}) for {commodity.get("name", "")}') # noqa: E501
break break
else: else:

83
plug.py
View File

@ -7,50 +7,49 @@ import os
import importlib import importlib
import sys import sys
import operator import operator
import threading # We don't use it, but plugins might import threading # noqa: F401 - We don't use it, but plugins might
import logging import logging
import tkinter as tk import tkinter as tk
import myNotebook as nb import myNotebook as nb
from config import config, appname from config import config, appname
from time import time as time
logger = logging.getLogger(appname) logger = logging.getLogger(appname)
# Dashboard Flags constants # Dashboard Flags constants
FlagsDocked = 1<<0 # on a landing pad FlagsDocked = 1 << 0 # on a landing pad
FlagsLanded = 1<<1 # on planet surface FlagsLanded = 1 << 1 # on planet surface
FlagsLandingGearDown = 1<<2 FlagsLandingGearDown = 1 << 2
FlagsShieldsUp = 1<<3 FlagsShieldsUp = 1 << 3
FlagsSupercruise = 1<<4 FlagsSupercruise = 1 << 4
FlagsFlightAssistOff = 1<<5 FlagsFlightAssistOff = 1 << 5
FlagsHardpointsDeployed = 1<<6 FlagsHardpointsDeployed = 1 << 6
FlagsInWing = 1<<7 FlagsInWing = 1 << 7
FlagsLightsOn = 1<<8 FlagsLightsOn = 1 << 8
FlagsCargoScoopDeployed = 1<<9 FlagsCargoScoopDeployed = 1 << 9
FlagsSilentRunning = 1<<10 FlagsSilentRunning = 1 << 10
FlagsScoopingFuel = 1<<11 FlagsScoopingFuel = 1 << 11
FlagsSrvHandbrake = 1<<12 FlagsSrvHandbrake = 1 << 12
FlagsSrvTurret = 1<<13 # using turret view FlagsSrvTurret = 1 << 13 # using turret view
FlagsSrvUnderShip = 1<<14 # turret retracted FlagsSrvUnderShip = 1 << 14 # turret retracted
FlagsSrvDriveAssist = 1<<15 FlagsSrvDriveAssist = 1 << 15
FlagsFsdMassLocked = 1<<16 FlagsFsdMassLocked = 1 << 16
FlagsFsdCharging = 1<<17 FlagsFsdCharging = 1 << 17
FlagsFsdCooldown = 1<<18 FlagsFsdCooldown = 1 << 18
FlagsLowFuel = 1<<19 # <25% FlagsLowFuel = 1 << 19 # <25%
FlagsOverHeating = 1<<20 # > 100% FlagsOverHeating = 1 << 20 # > 100%
FlagsHasLatLong = 1<<21 FlagsHasLatLong = 1 << 21
FlagsIsInDanger = 1<<22 FlagsIsInDanger = 1 << 22
FlagsBeingInterdicted = 1<<23 FlagsBeingInterdicted = 1 << 23
FlagsInMainShip = 1<<24 FlagsInMainShip = 1 << 24
FlagsInFighter = 1<<25 FlagsInFighter = 1 << 25
FlagsInSRV = 1<<26 FlagsInSRV = 1 << 26
FlagsAnalysisMode = 1<<27 # Hud in Analysis mode FlagsAnalysisMode = 1 << 27 # Hud in Analysis mode
FlagsNightVision = 1<<28 FlagsNightVision = 1 << 28
FlagsAverageAltitude = 1<<29 # Altitude from Average radius FlagsAverageAltitude = 1 << 29 # Altitude from Average radius
FlagsFsdJump = 1<<30 FlagsFsdJump = 1 << 30
FlagsSrvHighBeam = 1<<31 FlagsSrvHighBeam = 1 << 31
# Dashboard GuiFocus constants # Dashboard GuiFocus constants
GuiFocusNoFocus = 0 GuiFocusNoFocus = 0
@ -88,14 +87,16 @@ class Plugin(object):
:raises Exception: Typically ImportError or OSError :raises Exception: Typically ImportError or OSError
""" """
self.name = name # Display name. self.name = name # Display name.
self.folder = name # basename of plugin folder. None for internal plugins. self.folder = name # basename of plugin folder. None for internal plugins.
self.module = None # None for disabled plugins. self.module = None # None for disabled plugins.
if loadfile: if loadfile:
logger.info(f'loading plugin "{name.replace(".", "_")}" from "{loadfile}"') logger.info(f'loading plugin "{name.replace(".", "_")}" from "{loadfile}"')
try: try:
module = importlib.machinery.SourceFileLoader('plugin_{}'.format(name.encode(encoding='ascii', errors='replace').decode('utf-8').replace('.', '_')), loadfile).load_module() module = importlib.machinery.SourceFileLoader('plugin_{}'.format(
name.encode(encoding='ascii', errors='replace').decode('utf-8').replace('.', '_')),
loadfile).load_module()
if getattr(module, 'plugin_start3', None): if getattr(module, 'plugin_start3', None):
newname = module.plugin_start3(os.path.dirname(loadfile)) newname = module.plugin_start3(os.path.dirname(loadfile))
self.name = newname and str(newname) or name self.name = newname and str(newname) or name
@ -173,11 +174,11 @@ def load_plugins(master):
if name.endswith('.py') and not name[0] in ['.', '_']: if name.endswith('.py') and not name[0] in ['.', '_']:
try: try:
plugin = Plugin(name[:-3], os.path.join(config.internal_plugin_dir, name)) plugin = Plugin(name[:-3], os.path.join(config.internal_plugin_dir, name))
plugin.folder = None # Suppress listing in Plugins prefs tab plugin.folder = None # Suppress listing in Plugins prefs tab
internal.append(plugin) internal.append(plugin)
except Exception as e: except Exception as e:
logger.error(f'Failure loading internal Plugin "{name}"', exc_info=e) logger.error(f'Failure loading internal Plugin "{name}"', exc_info=e)
PLUGINS.extend(sorted(internal, key = lambda p: operator.attrgetter('name')(p).lower())) PLUGINS.extend(sorted(internal, key=lambda p: operator.attrgetter('name')(p).lower()))
# Add plugin folder to load path so packages can be loaded from plugin folder # Add plugin folder to load path so packages can be loaded from plugin folder
sys.path.append(config.plugin_dir) sys.path.append(config.plugin_dir)
@ -199,7 +200,7 @@ def load_plugins(master):
except Exception as e: except Exception as e:
logger.error(f'Failure loading found Plugin "{name}"', exc_info=e) logger.error(f'Failure loading found Plugin "{name}"', exc_info=e)
pass pass
PLUGINS.extend(sorted(found, key = lambda p: operator.attrgetter('name')(p).lower())) PLUGINS.extend(sorted(found, key=lambda p: operator.attrgetter('name')(p).lower()))
def provides(fn_name): def provides(fn_name):
""" """

View File

@ -8,7 +8,6 @@ from platform import system
import re import re
import requests import requests
import sys import sys
import uuid
import logging import logging
import tkinter as tk import tkinter as tk
@ -25,7 +24,7 @@ from companion import category_map
logger = logging.getLogger(appname) logger = logging.getLogger(appname)
this = sys.modules[__name__] # For holding module globals this = sys.modules[__name__] # For holding module globals
# Track location to add to Journal events # Track location to add to Journal events
this.systemaddress = None this.systemaddress = None
@ -61,15 +60,15 @@ class EDDN(object):
try: try:
# Try to open existing file # Try to open existing file
self.replayfile = open(filename, 'r+', buffering=1) self.replayfile = open(filename, 'r+', buffering=1)
except Exception as e: except Exception:
if exists(filename): if exists(filename):
raise # Couldn't open existing file raise # Couldn't open existing file
else: else:
self.replayfile = open(filename, 'w+', buffering=1) # Create file self.replayfile = open(filename, 'w+', buffering=1) # Create file
if sys.platform != 'win32': # open for writing is automatically exclusive on Windows if sys.platform != 'win32': # open for writing is automatically exclusive on Windows
lockf(self.replayfile, LOCK_EX|LOCK_NB) lockf(self.replayfile, LOCK_EX | LOCK_NB)
except Exception as e: except Exception as e:
logger.debug(f'Failed opening "replay.jsonl"', exc_info=e) logger.debug('Failed opening "replay.jsonl"', exc_info=e)
if self.replayfile: if self.replayfile:
self.replayfile.close() self.replayfile.close()
self.replayfile = None self.replayfile = None
@ -104,18 +103,12 @@ class EDDN(object):
r = self.session.post(self.UPLOAD, data=json.dumps(msg), timeout=self.TIMEOUT) r = self.session.post(self.UPLOAD, data=json.dumps(msg), timeout=self.TIMEOUT)
if r.status_code != requests.codes.ok: if r.status_code != requests.codes.ok:
logger.debug(f''': logger.debug(f':\nStatus\t{r.status_code}URL\t{r.url}Headers\t{r.headers}Content:\n{r.text}')
Status\t{r.status_code}
URL\t{r.url}
Headers\t{r.headers}'
Content:\n{r.text}
'''
)
r.raise_for_status() r.raise_for_status()
def sendreplay(self): def sendreplay(self):
if not self.replayfile: if not self.replayfile:
return # Probably closing app return # Probably closing app
status = self.parent.children['status'] status = self.parent.children['status']
@ -148,17 +141,18 @@ Content:\n{r.text}
status['text'] = _("Error: Can't connect to EDDN") status['text'] = _("Error: Can't connect to EDDN")
return # stop sending return # stop sending
except Exception as e: except Exception as e:
logger.debug(f'Failed sending', exc_info=e) logger.debug('Failed sending', exc_info=e)
status['text'] = str(e) status['text'] = str(e)
return # stop sending return # stop sending
self.parent.after(self.REPLAYPERIOD, self.sendreplay) self.parent.after(self.REPLAYPERIOD, self.sendreplay)
def export_commodities(self, data, is_beta): def export_commodities(self, data, is_beta):
commodities = [] commodities = []
for commodity in data['lastStarport'].get('commodities') or []: for commodity in data['lastStarport'].get('commodities') or []:
if (category_map.get(commodity['categoryname'], True) and # Check marketable # Check 'marketable' and 'not prohibited'
not commodity.get('legality')): # check not prohibited if (category_map.get(commodity['categoryname'], True)
and not commodity.get('legality')):
commodities.append(OrderedDict([ commodities.append(OrderedDict([
('name', commodity['name'].lower()), ('name', commodity['name'].lower()),
('meanPrice', int(commodity['meanPrice'])), ('meanPrice', int(commodity['meanPrice'])),
@ -446,7 +440,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state):
logger.debug(f'Failed in export_journal_entry', exc_info=e) logger.debug(f'Failed in export_journal_entry', exc_info=e)
return _("Error: Can't connect to EDDN") return _("Error: Can't connect to EDDN")
except Exception as e: except Exception as e:
logger.debug(f'Failed in export_journal_entry', exc_info=e) logger.debug('Failed in export_journal_entry', exc_info=e)
return str(e) return str(e)
elif (config.getint('output') & config.OUT_MKT_EDDN and not state['Captain'] and elif (config.getint('output') & config.OUT_MKT_EDDN and not state['Captain'] and
@ -472,6 +466,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state):
logger.debug(f'Failed exporting {entry["event"]}', exc_info=e) logger.debug(f'Failed exporting {entry["event"]}', exc_info=e)
return str(e) return str(e)
def cmdr_data(data, is_beta): def cmdr_data(data, is_beta):
if data['commander'].get('docked') and config.getint('output') & config.OUT_MKT_EDDN: if data['commander'].get('docked') and config.getint('output') & config.OUT_MKT_EDDN:
try: try:
@ -492,9 +487,9 @@ def cmdr_data(data, is_beta):
status.update_idletasks() status.update_idletasks()
except requests.RequestException as e: except requests.RequestException as e:
logger.debug(f'Failed exporting data', exc_info=e) logger.debug('Failed exporting data', exc_info=e)
return _("Error: Can't connect to EDDN") return _("Error: Can't connect to EDDN")
except Exception as e: except Exception as e:
logger.debug(f'Failed exporting data', exc_info=e) logger.debug('Failed exporting data', exc_info=e)
return str(e) return str(e)

View File

@ -15,7 +15,9 @@ import json
import requests import requests
import sys import sys
import time import time
import urllib.request, urllib.error, urllib.parse import urllib.request
import urllib.error
import urllib.parse
from queue import Queue from queue import Queue
from threading import Thread from threading import Thread
import logging import logging
@ -357,7 +359,10 @@ def worker():
r.raise_for_status() r.raise_for_status()
reply = r.json() reply = r.json()
(msgnum, msg) = reply['msgnum'], reply['msg'] (msgnum, msg) = reply['msgnum'], reply['msg']
# 1xx = OK, 2xx = fatal error, 3&4xx not generated at top-level, 5xx = error but events saved for later processing # 1xx = OK
# 2xx = fatal error
# 3&4xx not generated at top-level
# 5xx = error but events saved for later processing
if msgnum // 100 == 2: if msgnum // 100 == 2:
logger.warning(f'EDSM\t{msgnum} {msg}\t{json.dumps(pending, separators = (",", ": "))}') logger.warning(f'EDSM\t{msgnum} {msg}\t{json.dumps(pending, separators = (",", ": "))}')
plug.show_error(_('Error: EDSM {MSG}').format(MSG=msg)) plug.show_error(_('Error: EDSM {MSG}').format(MSG=msg))
@ -366,9 +371,11 @@ def worker():
if not closing and e['event'] in ['StartUp', 'Location', 'FSDJump', 'CarrierJump']: if not closing and e['event'] in ['StartUp', 'Location', 'FSDJump', 'CarrierJump']:
# Update main window's system status # Update main window's system status
this.lastlookup = r this.lastlookup = r
this.system_link.event_generate('<<EDSMStatus>>', when="tail") # calls update_status in main thread # calls update_status in main thread
this.system_link.event_generate('<<EDSMStatus>>', when="tail")
elif r['msgnum'] // 100 != 1: elif r['msgnum'] // 100 != 1:
logger.warning(f'EDSM\t{r["msgnum"]} {r["msg"]}\t{json.dumps(e, separators = (",", ": "))}') logger.warning(f'EDSM\t{r["msgnum"]} {r["msg"]}\t'
f'{json.dumps(e, separators = (",", ": "))}')
pending = [] pending = []
break break

View File

@ -456,7 +456,7 @@ def journal_entry(cmdr, is_beta, system, station, entry, state):
call() call()
except Exception as e: except Exception as e:
logger.debug(f'Adding events', exc_info=e) logger.debug('Adding events', exc_info=e)
return str(e) return str(e)
# #
@ -895,11 +895,11 @@ def worker():
status = reply['header']['eventStatus'] status = reply['header']['eventStatus']
if callback: if callback:
callback(reply) callback(reply)
elif status // 100 != 2: # 2xx == OK (maybe with warnings) elif status // 100 != 2: # 2xx == OK (maybe with warnings)
# Log fatal errors # Log fatal errors
log.warning(f'Inara\t{status} {reply["header"].get("eventStatusText", "")}') logger.warning(f'Inara\t{status} {reply["header"].get("eventStatusText", "")}')
log.debug(f'JSON data:\n{json.dumps(data, indent=2, separators = (",", ": "))}') logger.debug(f'JSON data:\n{json.dumps(data, indent=2, separators = (",", ": "))}')
plug.show_error(_('Error: Inara {MSG}').format(MSG = reply['header'].get('eventStatusText', status))) plug.show_error(_('Error: Inara {MSG}').format(MSG=reply['header'].get('eventStatusText', status)))
else: else:
# Log individual errors and warnings # Log individual errors and warnings
for data_event, reply_event in zip(data['events'], reply['events']): for data_event, reply_event in zip(data['events'], reply['events']):
@ -907,17 +907,20 @@ def worker():
logger.warning(f'Inara\t{status} {reply_event.get("eventStatusText", "")}') logger.warning(f'Inara\t{status} {reply_event.get("eventStatusText", "")}')
logger.debug(f'JSON data:\n{json.dumps(data_event)}') logger.debug(f'JSON data:\n{json.dumps(data_event)}')
if reply_event['eventStatus'] // 100 != 2: if reply_event['eventStatus'] // 100 != 2:
plug.show_error(_('Error: Inara {MSG}').format(MSG = '%s, %s' % (data_event['eventName'], reply_event.get('eventStatusText', reply_event['eventStatus'])))) plug.show_error(_('Error: Inara {MSG}').format(
MSG=f'{data_event["eventName"]},'
f'{reply_event.get("eventStatusText", reply_event["eventStatus"])}'))
if data_event['eventName'] in ['addCommanderTravelCarrierJump', 'addCommanderTravelDock', 'addCommanderTravelFSDJump', 'setCommanderTravelLocation']: if data_event['eventName'] in ['addCommanderTravelCarrierJump', 'addCommanderTravelDock', 'addCommanderTravelFSDJump', 'setCommanderTravelLocation']:
this.lastlocation = reply_event.get('eventData', {}) this.lastlocation = reply_event.get('eventData', {})
this.system_link.event_generate('<<InaraLocation>>', when="tail") # calls update_location in main thread this.system_link.event_generate('<<InaraLocation>>', when="tail") # calls update_location in main thread
elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']:
this.lastship = reply_event.get('eventData', {}) this.lastship = reply_event.get('eventData', {})
this.system_link.event_generate('<<InaraShip>>', when="tail") # calls update_ship in main thread # calls update_ship in main thread
this.system_link.event_generate('<<InaraShip>>', when="tail")
break break
except Exception as e: except Exception as e:
logger.debug(f'Sending events', exc_info=e) logger.debug('Sending events', exc_info=e)
retrying += 1 retrying += 1
else: else:
if callback: if callback: