Merge pull request #2584 from HullSeals/enhancement/companion-optimize-run

Companion-Focused Refactor Run
This commit is contained in:
David Sangrey authored and GitHub committed 2026-01-07 21:07:40 -05:00
commit 618fc96711
13 files changed
+809 -914

No files matched your search

+3 -2
View File
@@ -51,7 +51,8 @@ from threading import get_native_id as thread_native_id
from time import gmtime
from traceback import print_exc
from typing import TYPE_CHECKING, cast
from config import appcmdname, appname, config, trace_on, config_logger
import config as config_mod # This has to be imported separately for trace_if to work... for some reason.
from config import appcmdname, appname, config, config_logger
# TODO: Tests:
#
@@ -102,7 +103,7 @@ warnings.simplefilter('default', DeprecationWarning)
def _trace_if(self: logging.Logger, condition: str, message: str, *args, **kwargs) -> None:
if any(fnmatch(condition, p) for p in trace_on):
if any(fnmatch(condition, p) for p in config_mod.trace_on):
self._log(logging.TRACE, message, args, **kwargs) # type: ignore # we added it
return
+1 -1
View File
@@ -1244,7 +1244,7 @@ class AppWindow:
logger.error(msg)
raise ValueError(msg)
if capi_response.capi_data.source_endpoint == companion.session.FRONTIER_CAPI_PATH_FLEETCARRIER:
if capi_response.capi_data.source_endpoint == companion.CAPIEndpoint.FLEETCARRIER:
# Fleetcarrier CAPI response
# Validation
if 'name' not in capi_response.capi_data:
-3
View File
@@ -27,9 +27,6 @@
/* companion.py: Generic error prefix - following text is from Frontier auth service; In files: companion.py:432; companion.py:517; */
"Error" = "Error";
/* companion.py: Frontier auth, no 'usr' section in returned data; companion.py: Frontier auth, no 'customer_id' in 'usr' section in returned data; In files: companion.py:475; companion.py:480; */
"Error: Couldn't check token customer_id" = "Error: Couldn't check token customer_id";
/* companion.py: Frontier auth customer_id doesn't match game session FID; In files: companion.py:486; */
"Error: customer_id doesn't match!" = "Error: customer_id doesn't match!";
+373 -422
View File
File diff suppressed because it is too large. Load diff
+8 -8
View File
@@ -119,7 +119,7 @@ class PluginBrowserMixIn:
background=nb.Label().cget("background"),
url="https://github.com/Rixxan/EDMC_Plugin_Registry_Dev", # Fixme
underline=True,
).grid(row=row.get(), padx=self.PADX, pady=(self.PADY, 1), sticky=tk.W)
).grid(row=next(row), padx=self.PADX, pady=(self.PADY, 1), sticky=tk.W)
# Add after the "Available Plugins" label
categories = sorted(
@@ -137,7 +137,7 @@ class PluginBrowserMixIn:
# LANG: Filter Plugin Categories
category_label = nb.Label(plugins_frame, text=tr.tl("Filter by Category:"))
category_label.grid(
row=row.get(), column=0, sticky=tk.W, padx=self.PADX, pady=(0, self.PADY)
row=next(row), column=0, sticky=tk.W, padx=self.PADX, pady=(0, self.PADY)
)
category_dropdown = nb.OptionMenu(
@@ -149,14 +149,14 @@ class PluginBrowserMixIn:
)
category_dropdown.config(width=25) # make the dropdown wider
category_dropdown.grid(
row=row.get(), column=0, sticky=tk.W, padx=self.PADX, pady=(0, self.PADY)
row=next(row), column=0, sticky=tk.W, padx=self.PADX, pady=(0, self.PADY)
)
ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid(
columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get()
columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=next(row)
)
tree_container = nb.Frame(plugins_frame) # type: ignore
tree_row = row.get()
tree_row = next(row)
tree_container.grid(row=tree_row, column=0, sticky=tk.NSEW, padx=self.PADX)
plugins_frame.columnconfigure(0, weight=1)
@@ -216,11 +216,11 @@ class PluginBrowserMixIn:
tree_container.rowconfigure(0, weight=0)
ttk.Separator(plugins_frame, orient=tk.HORIZONTAL).grid(
columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=row.get()
columnspan=4, padx=self.PADX, pady=self.SEPY, sticky=tk.EW, row=next(row)
)
self.plugin_details_frame = nb.Frame(plugins_frame) # type: ignore
details_row = row.get()
details_row = next(row)
self.plugin_details_frame.grid(
row=details_row, column=0, sticky=tk.NW, padx=self.PADX
)
@@ -258,8 +258,8 @@ class PluginBrowserMixIn:
self.__populate_plugins_tree()
notebook.add(
# LANG: Plugin Browser Title
plugins_frame,
# LANG: Plugin Browser Title
text=tr.tl("Plugin Browser"),
)
+16 -20
View File
@@ -28,6 +28,7 @@ import os
import pathlib
import re
import sqlite3
import gzip
import tkinter as tk
from tkinter import ttk
from platform import system
@@ -48,7 +49,6 @@ from monitor import monitor
from myNotebook import Frame
from prefs import prefsVersion
from ttkHyperlinkLabel import HyperlinkLabel
from util import text
from l10n import translations as tr
from plugins.common_coreutils import PADX, PADY, BUTTONX, this_format_common
@@ -359,19 +359,16 @@ class EDDNSender:
:return: `True` for "now remove this message from the queue"
"""
logger.trace_if("plugin.eddn.send", "Sending message")
should_return: bool
new_data: dict[str, Any]
should_return, new_data = killswitch.check_killswitch('plugins.eddn.send', json.loads(msg))
if should_return:
logger.warning('eddn.send has been disabled via killswitch. Returning.')
return False
# Even the smallest possible message compresses somewhat, so always compress
encoded, compressed = text.gzip(json.dumps(new_data, separators=(',', ':')), max_size=0)
headers: dict[str, str] | None = None
if compressed:
headers = {'Content-Encoding': 'gzip'}
# Always compress for EDDN
payload = json.dumps(new_data, separators=(",", ":")).encode()
encoded = gzip.compress(payload)
headers = {"Content-Encoding": "gzip"}
try:
r = self.session.post(self.eddn_endpoint, data=encoded, timeout=self.TIMEOUT, headers=headers)
@@ -394,15 +391,14 @@ class EDDNSender:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
if unknown_schema := self.UNKNOWN_SCHEMA_RE.match(e.response.text): # type: ignore
logger.debug(f"EDDN doesn't (yet?) know about schema: {unknown_schema['schema_name']}"
f"/{unknown_schema['schema_version']}")
response = e.response # type: ignore[assignment]
if response and (m := self.UNKNOWN_SCHEMA_RE.match(response.text)):
logger.debug(f"EDDN doesn't (yet?) know about schema: {m['schema_name']}/{m['schema_version']}")
# This dropping is to cater for the time period when EDDN doesn't *yet* support a new schema.
return True
if e.response.status_code == http.HTTPStatus.BAD_REQUEST: # type: ignore
# EDDN straight up says no, so drop the message
logger.debug(f"EDDN responded '400 Bad Request' to the message, dropping:\n{msg!r}")
if response and response.status_code == http.HTTPStatus.BAD_REQUEST:
logger.debug("EDDN responded '400 Bad Request' to the message, dropping:\n%r", msg)
return True
# This should catch anything else, e.g. timeouts, gateway errors
@@ -669,7 +665,7 @@ class EDDN:
'message': message,
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_MARKET
data.source_host, companion.CAPIEndpoint.MARKET
),
game_build=''
),
@@ -780,7 +776,7 @@ class EDDN:
},
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_SHIPYARD
data.source_host, companion.CAPIEndpoint.SHIPYARD
),
game_build=''
),
@@ -842,7 +838,7 @@ class EDDN:
},
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_SHIPYARD
data.source_host, companion.CAPIEndpoint.SHIPYARD
),
game_build=''
),
@@ -1552,7 +1548,7 @@ class EDDN:
'message': entry,
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_MARKET
data.source_host, companion.CAPIEndpoint.MARKET
), game_build=''
),
}
@@ -1953,10 +1949,10 @@ class EDDN:
#######################################################################
# endpoint
if capi_endpoint == companion.Session.FRONTIER_CAPI_PATH_MARKET:
if capi_endpoint == companion.CAPIEndpoint.MARKET:
gv += 'market'
elif capi_endpoint == companion.Session.FRONTIER_CAPI_PATH_SHIPYARD:
elif capi_endpoint == companion.CAPIEndpoint.SHIPYARD:
gv += 'shipyard'
else:
+329 -370
View File
File diff suppressed because it is too large. Load diff
+19 -25
View File
@@ -377,6 +377,24 @@ else: # Linux / Run from source
class HTTPRequestHandler(BaseHTTPRequestHandler):
"""Simple HTTP server to handle IPC from protocol handler."""
AUTH_RESPONSE_HTML = """\
<html>
<head>
<title>Authentication successful - Elite: Dangerous</title>
<style>
body { background-color: #000; color: #fff; font-family: "Helvetica Neue", Arial, sans-serif; }
h1 { text-align: center; margin-top: 100px; }
p { text-align: center; }
</style>
</head>
<body>
<h1>Authentication successful</h1>
<p>Thank you for authenticating.</p>
<p>Please close this browser tab now.</p>
</body>
</html>
"""
def parse(self) -> bool:
"""Parse a request."""
logger.trace_if("frontier-auth.http", f"Got message on path: {self.path}")
@@ -401,7 +419,7 @@ else: # Linux / Run from source
if self.parse():
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(self._generate_auth_response().encode())
self.wfile.write(self.AUTH_RESPONSE_HTML.encode())
else:
self.send_response(404)
self.end_headers()
@@ -409,30 +427,6 @@ else: # Linux / Run from source
def log_request(self, code: int | str = "-", size: int | str = "-") -> None:
"""Override to prevent logging."""
def _generate_auth_response(self) -> str:
"""
Generate the authentication response HTML.
:return: The HTML content of the authentication response.
"""
return (
"<html>"
"<head>"
"<title>Authentication successful - Elite: Dangerous</title>"
"<style>"
'body { background-color: #000; color: #fff; font-family: "Helvetica Neue", Arial, sans-serif; }'
"h1 { text-align: center; margin-top: 100px; }"
"p { text-align: center; }"
"</style>"
"</head>"
"<body>"
"<h1>Authentication successful</h1>"
"<p>Thank you for authenticating.</p>"
"<p>Please close this browser tab now.</p>"
"</body>"
"</html>"
)
def get_handler_impl() -> type[GenericProtocolHandler]:
"""
@@ -37,7 +37,6 @@ UninstallDisplayIcon={app}\{#MyAppExeName}
MinVersion=6.2
ChangesAssociations = yes
UsedUserAreasWarning = no
VersionInfoVersion={#MyAppVersion}
VersionInfoCompany={#MyAppPublisher}
VersionInfoDescription={#MyAppLongName}
VersionInfoCopyright={#MyAppCopyright}
+21 -22
View File
@@ -1,38 +1,37 @@
"""Export list of ships as CSV."""
import csv
from itertools import chain
import companion
from edmc_data import ship_name_map
def export(data: companion.CAPIData, filename: str) -> None:
"""
Write shipyard data in Companion API JSON format.
Write shipyard data in Companion API CSV format.
:param data: The CAPI data.
:param filename: Optional filename to write to.
:return:
:param filename: Target CSV filename
"""
if not data['lastSystem'].get('name'):
system_name = data['lastSystem'].get('name')
if not system_name:
raise ValueError("Missing 'name' in 'lastSystem'")
if not data['lastStarport'].get('name'):
starport = data['lastStarport']
station_name = starport.get('name')
ships_info = starport.get('ships')
if not station_name:
raise ValueError("Missing 'name' in 'lastStarport'")
if not data['lastStarport'].get('ships'):
if not ships_info:
raise ValueError("Missing 'ships' in 'lastStarport'")
with open(filename, 'w', newline='') as f:
c = csv.writer(f)
c.writerow(('System', 'Station', 'Ship', 'FDevID', 'Date'))
shipyard_list = ships_info.get('shipyard_list', {}).values()
unavailable_list = ships_info.get('unavailable_list', [])
all_ships = chain(shipyard_list, unavailable_list)
for (name, fdevid) in [
(
ship_name_map.get(ship['name'].lower(), ship['name']),
ship['id']
) for ship in list(
(data['lastStarport']['ships'].get('shipyard_list') or {}).values()
) + data['lastStarport']['ships'].get('unavailable_list')
]:
c.writerow((
data['lastSystem']['name'], data['lastStarport']['name'],
name, fdevid, data['timestamp']
))
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['System', 'Station', 'Ship', 'FDevID', 'Date'])
for ship in all_ships:
name = ship_name_map.get(ship['name'].lower(), ship['name'])
fdevid = ship['id']
writer.writerow([system_name, station_name, name, fdevid, data['timestamp']])
+12 -12
View File
@@ -205,11 +205,11 @@ def export_status(data: dict[str, Any], filename: AnyStr) -> None:
:param data: The data to generate the file from
:param filename: The target file
"""
with open(filename, 'w') as f:
h = csv.writer(f)
h.writerow(('Category', 'Value'))
for thing in status(data):
h.writerow(list(thing))
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(('Category', 'Value'))
for cat, val in status(data):
writer.writerow((cat, val))
class ShipRet(NamedTuple):
@@ -278,11 +278,11 @@ def export_ships(companion_data: dict[str, Any], filename: AnyStr) -> None:
:param companion_data: Data from which to generate the ship list
:param filename: The target file
"""
with open(filename, 'w') as f:
h = csv.writer(f)
h.writerow(['Id', 'Ship', 'Name', 'System', 'Station', 'Value'])
for thing in ships(companion_data):
h.writerow(list(thing))
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Id', 'Ship', 'Name', 'System', 'Station', 'Value'])
for ship in ships(companion_data):
writer.writerow(ship)
class StatsDialog:
@@ -302,7 +302,7 @@ class StatsDialog:
return
# TODO: This needs to use cached data
if companion.session.FRONTIER_CAPI_PATH_PROFILE not in companion.session.capi_raw_data:
if companion.CAPIEndpoint.PROFILE not in companion.session.capi_raw_data:
logger.info('No cached data, aborting...')
hotkeymgr.play_bad()
# LANG: No Frontier CAPI data yet when trying to use 'File' > 'Status'
@@ -310,7 +310,7 @@ class StatsDialog:
return
capi_data = json.loads(
companion.session.capi_raw_data[companion.session.FRONTIER_CAPI_PATH_PROFILE].raw_data
companion.session.capi_raw_data[companion.CAPIEndpoint.PROFILE].raw_data
)
if not capi_data.get('commander') or not capi_data['commander'].get('name', '').strip():
+25 -28
View File
@@ -1,7 +1,7 @@
"""Export data for Trade Dangerous."""
import pathlib
import time
from datetime import datetime
from collections import defaultdict
from operator import itemgetter
from platform import system
@@ -23,43 +23,40 @@ stockbracketmap = {0: '-',
def export(data: CAPIData) -> None:
"""Export market data in TD format."""
data_path = pathlib.Path(config.get_str('outdir'))
timestamp = time.strftime('%Y-%m-%dT%H.%M.%S', time.strptime(data['timestamp'], '%Y-%m-%dT%H:%M:%SZ'))
data_filename = f"{data['lastSystem']['name'].strip()}.{data['lastStarport']['name'].strip()}.{timestamp}.prices"
# codecs can't automatically handle line endings, so encode manually where
# required
with open(data_path / data_filename, 'wb') as h:
# Format described here: https://github.com/eyeonus/Trade-Dangerous/wiki/Price-Data
h.write(b'#! trade.py import -\n')
this_platform = system()
cmdr_name = data['commander']['name'].strip()
h.write(
f'# Created by {applongname} {appversion()} on {this_platform} for Cmdr {cmdr_name}.\n'.encode()
)
h.write(
b'#\n# <item name> <sellCR> <buyCR> <demand> <stock> <timestamp>\n\n'
)
system_name = data['lastSystem']['name'].strip()
starport_name = data['lastStarport']['name'].strip()
h.write(f'@ {system_name}/{starport_name}\n'.encode())
# parse timestamp once
ts = datetime.fromisoformat(data['timestamp'].replace('Z', '+00:00'))
ts_file = ts.strftime('%Y-%m-%dT%H.%M.%S')
ts_data = ts.strftime('%Y-%m-%d %H:%M:%S')
# sort commodities by category
system_name = data['lastSystem']['name'].strip()
starport_name = data['lastStarport']['name'].strip()
cmdr_name = data['commander']['name'].strip()
data_filename = f"{system_name}.{starport_name}.{ts_file}.prices"
with open(data_path / data_filename, 'w', encoding='utf-8', newline='\n') as h:
h.write('#! trade.py import -\n')
h.write(f'# Created by {applongname} {appversion()} on {system()} for Cmdr {cmdr_name}.\n')
h.write('#\n# <item name> <sellCR> <buyCR> <demand> <stock> <timestamp>\n\n')
h.write(f'@ {system_name}/{starport_name}\n')
# group by category
by_category = defaultdict(list)
for commodity in data['lastStarport']['commodities']:
by_category[commodity['categoryname']].append(commodity)
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(data['timestamp'], '%Y-%m-%dT%H:%M:%SZ'))
for category in sorted(by_category):
h.write(f' + {format(category)}\n'.encode())
# corrections to commodity names can change the sort order
h.write(f' + {category}\n')
for commodity in sorted(by_category[category], key=itemgetter('name')):
demand_val = str(int(commodity['demand'])) if commodity['demandBracket'] else ''
stock_val = str(int(commodity['stock'])) if commodity['stockBracket'] else ''
h.write(
f" {commodity['name']:<23}"
f" {int(commodity['sellPrice']):7d}"
f" {int(commodity['buyPrice']):7d}"
f" {int(commodity['demand']) if commodity['demandBracket'] else '':9}"
f"{demandbracketmap[commodity['demandBracket']]:1}"
f" {int(commodity['stock']) if commodity['stockBracket'] else '':8}"
f"{stockbracketmap[commodity['stockBracket']]:1}"
f" {timestamp}\n".encode()
f" {demand_val:9}{demandbracketmap[commodity['demandBracket']]:1}"
f" {stock_val:8}{stockbracketmap[commodity['stockBracket']]:1}"
f" {ts_data}\n"
)
+2
View File
@@ -8,10 +8,12 @@ See LICENSE file.
from __future__ import annotations
from gzip import compress
from warnings import deprecated
__all__ = ['gzip']
@deprecated("text.gzip is deprecated and will be removed in a later version!")
def gzip(data: str | bytes, max_size: int = 512, encoding='utf-8') -> tuple[bytes, bool]:
"""
Compress the given data if the max size is greater than specified.