1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-05-31 23:59:38 +03:00

[2051] EDMC Pass + Readd LANG

This commit is contained in:
David Sangrey 2023-11-17 18:07:37 -05:00
parent 724dd2ce6a
commit ff1f931afd
No known key found for this signature in database
GPG Key ID: 3AEADBB0186884BC
2 changed files with 44 additions and 41 deletions

74
EDMC.py
View File

@ -1,6 +1,11 @@
#!/usr/bin/env python3 """
"""Command-line interface. Requires prior setup through the GUI.""" EDMC.py - Command-line interface. Requires prior setup through the GUI.
Copyright (c) EDCD, All Rights Reserved
Licensed under the GNU General Public License.
See LICENSE file.
"""
from __future__ import annotations
import argparse import argparse
import json import json
@ -8,24 +13,22 @@ import locale
import os import os
import queue import queue
import sys import sys
from os.path import getmtime
from time import sleep, time from time import sleep, time
from typing import TYPE_CHECKING, Any, List, Optional from typing import TYPE_CHECKING, Any
# isort: off # isort: off
os.environ["EDMC_NO_UI"] = "1" os.environ["EDMC_NO_UI"] = "1"
# See EDMCLogging.py docs. # See EDMCLogging.py docs.
# workaround for https://github.com/EDCD/EDMarketConnector/issues/568 # workaround for https://github.com/EDCD/EDMarketConnector/issues/568
from EDMCLogging import edmclogger, logger, logging from EDMCLogging import edmclogger, logger, logging
if TYPE_CHECKING: if TYPE_CHECKING:
from logging import TRACE # type: ignore # noqa: F401 # needed to make mypy happy from logging import TRACE # type: ignore # noqa: F401 # needed to make mypy happy
edmclogger.set_channels_loglevel(logging.INFO) edmclogger.set_channels_loglevel(logging.INFO)
# isort: on # isort: on
import collate import collate
import commodity import commodity
import companion import companion
@ -45,6 +48,8 @@ sys.path.append(config.internal_plugin_dir)
# The sys.path.append has to be after `import sys` and `from config import config` # The sys.path.append has to be after `import sys` and `from config import config`
# isort: off # isort: off
import eddn # noqa: E402 import eddn # noqa: E402
# isort: on # isort: on
@ -66,7 +71,7 @@ EXIT_SUCCESS, EXIT_SERVER, EXIT_CREDENTIALS, EXIT_VERIFICATION, EXIT_LAGGING, EX
EXIT_JOURNAL_READ_ERR, EXIT_COMMANDER_UNKNOWN = range(9) EXIT_JOURNAL_READ_ERR, EXIT_COMMANDER_UNKNOWN = range(9)
def versioncmp(versionstring) -> List: def versioncmp(versionstring) -> list:
"""Quick and dirty version comparison assuming "strict" numeric only version numbers.""" """Quick and dirty version comparison assuming "strict" numeric only version numbers."""
return list(map(int, versionstring.split('.'))) return list(map(int, versionstring.split('.')))
@ -98,9 +103,7 @@ def deep_get(target: dict | companion.CAPIData, *args: str, default=None) -> Any
res = current.get(arg) res = current.get(arg)
if res is None: if res is None:
return default return default
current = res current = res
return current return current
@ -155,16 +158,15 @@ def main(): # noqa: C901, CCR001
args = parser.parse_args() args = parser.parse_args()
if args.version: if args.version:
updater = Updater(provider='internal') updater = Updater()
newversion: Optional[EDMCVersion] = updater.check_appcast() newversion: EDMCVersion | None = updater.check_appcast()
if newversion: if newversion:
print(f'{appversion()} ({newversion.title!r} is available)') print(f'{appversion()} ({newversion.title!r} is available)')
else: else:
print(appversion()) print(appversion())
return return
level_to_set: Optional[int] = None level_to_set: int | None = None
if args.trace or args.trace_on: if args.trace or args.trace_on:
level_to_set = logging.TRACE # type: ignore # it exists level_to_set = logging.TRACE # type: ignore # it exists
logger.info('Setting TRACE level debugging due to either --trace or a --trace-on') logger.info('Setting TRACE level debugging due to either --trace or a --trace-on')
@ -185,10 +187,10 @@ def main(): # noqa: C901, CCR001
logger.debug(f'Startup v{appversion()} : Running on Python v{sys.version}') logger.debug(f'Startup v{appversion()} : Running on Python v{sys.version}')
logger.debug(f'''Platform: {sys.platform} logger.debug(f'''Platform: {sys.platform}
argv[0]: {sys.argv[0]} argv[0]: {sys.argv[0]}
exec_prefix: {sys.exec_prefix} exec_prefix: {sys.exec_prefix}
executable: {sys.executable} executable: {sys.executable}
sys.path: {sys.path}''' sys.path: {sys.path}'''
) )
if args.trace_on and len(args.trace_on) > 0: if args.trace_on and len(args.trace_on) > 0:
import config as conf_module import config as conf_module
@ -207,12 +209,14 @@ sys.path: {sys.path}'''
# system, chances are its the current locale, and not utf-8. Otherwise if it was copied, its probably # system, chances are its the current locale, and not utf-8. Otherwise if it was copied, its probably
# utf8. Either way, try the system FIRST because reading something like cp1251 in UTF-8 results in garbage # utf8. Either way, try the system FIRST because reading something like cp1251 in UTF-8 results in garbage
# but the reverse results in an exception. # but the reverse results in an exception.
json_file = os.path.abspath(args.j)
try: try:
data = json.load(open(args.j)) with open(json_file) as file_handle:
data = json.load(file_handle)
except UnicodeDecodeError: except UnicodeDecodeError:
data = json.load(open(args.j, encoding='utf-8')) with open(json_file, encoding='utf-8') as file_handle:
data = json.load(file_handle)
config.set('querytime', int(getmtime(args.j))) config.set('querytime', int(os.path.getmtime(args.j)))
else: else:
# Get state from latest Journal file # Get state from latest Journal file
@ -255,10 +259,7 @@ sys.path: {sys.path}'''
for idx, cmdr in enumerate(cmdrs): for idx, cmdr in enumerate(cmdrs):
if cmdr.lower() == args.p.lower(): if cmdr.lower() == args.p.lower():
break break
raise companion.CredentialsError()
else:
raise companion.CredentialsError()
companion.session.login(cmdrs[idx], monitor.is_beta) companion.session.login(cmdrs[idx], monitor.is_beta)
else: else:
@ -292,9 +293,7 @@ sys.path: {sys.path}'''
logger.trace_if('capi.worker', f'Failed Request: {capi_response.message}') logger.trace_if('capi.worker', f'Failed Request: {capi_response.message}')
if capi_response.exception: if capi_response.exception:
raise capi_response.exception raise capi_response.exception
raise ValueError(capi_response.message)
else:
raise ValueError(capi_response.message)
logger.trace_if('capi.worker', 'Answer is not a Failure') logger.trace_if('capi.worker', 'Answer is not a Failure')
if not isinstance(capi_response, companion.EDMCCAPIResponse): if not isinstance(capi_response, companion.EDMCCAPIResponse):
@ -366,20 +365,19 @@ sys.path: {sys.path}'''
else: else:
print(deep_get(data, 'lastSystem', 'name', default='Unknown')) print(deep_get(data, 'lastSystem', 'name', default='Unknown'))
if (args.m or args.o or args.s or args.n or args.j): if args.m or args.o or args.s or args.n or args.j:
if not data['commander'].get('docked'): if not data['commander'].get('docked'):
logger.error("Can't use -m, -o, -s, -n or -j because you're not currently docked!") logger.error("Can't use -m, -o, -s, -n or -j because you're not currently docked!")
return return
elif not deep_get(data, 'lastStarport', 'name'): if not deep_get(data, 'lastStarport', 'name'):
logger.error("No data['lastStarport']['name'] from CAPI") logger.error("No data['lastStarport']['name'] from CAPI")
sys.exit(EXIT_LAGGING) sys.exit(EXIT_LAGGING)
# Ignore possibly missing shipyard info # Ignore possibly missing shipyard info
elif not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')): if not (data['lastStarport'].get('commodities') or data['lastStarport'].get('modules')):
logger.error("No commodities or outfitting (modules) in CAPI data") logger.error("No commodities or outfitting (modules) in CAPI data")
return return
else: else:
return return
@ -410,8 +408,8 @@ sys.path: {sys.path}'''
else: else:
logger.error("Station doesn't supply outfitting") logger.error("Station doesn't supply outfitting")
if (args.s or args.n) and not args.j and not \ if ((args.s or args.n) and not args.j and not data['lastStarport'].get('ships')
data['lastStarport'].get('ships') and data['lastStarport']['services'].get('shipyard'): and data['lastStarport']['services'].get('shipyard')):
# Retry for shipyard # Retry for shipyard
sleep(SERVER_RETRY) sleep(SERVER_RETRY)
@ -462,14 +460,14 @@ sys.path: {sys.path}'''
except Exception: except Exception:
logger.exception('Failed to send data to EDDN') logger.exception('Failed to send data to EDDN')
except companion.ServerError:
logger.exception('Frontier CAPI Server returned an error')
sys.exit(EXIT_SERVER)
except companion.ServerConnectionError: except companion.ServerConnectionError:
logger.exception('Exception while contacting server') logger.exception('Exception while contacting server')
sys.exit(EXIT_SERVER) sys.exit(EXIT_SERVER)
except companion.ServerError:
logger.exception('Frontier CAPI Server returned an error')
sys.exit(EXIT_SERVER)
except companion.CredentialsError: except companion.CredentialsError:
logger.error('Frontier CAPI Server: Invalid Credentials') logger.error('Frontier CAPI Server: Invalid Credentials')
sys.exit(EXIT_CREDENTIALS) sys.exit(EXIT_CREDENTIALS)

View File

@ -1007,19 +1007,24 @@ class AppWindow:
commodities_flag = config.OUT_MKT_CSV | config.OUT_MKT_TD commodities_flag = config.OUT_MKT_CSV | config.OUT_MKT_TD
if output_flags & config.OUT_STATION_ANY: if output_flags & config.OUT_STATION_ANY:
if not is_docked and not monitor.state['OnFoot']: if not is_docked and not monitor.state['OnFoot'] and not self.status['text']:
# Signal as error because the user might actually be docked # Signal as error because the user might actually be docked
# but the server hosting the Companion API hasn't caught up # but the server hosting the Companion API hasn't caught up
# LANG: Player is not docked at a station, when we expect them to be
self._handle_status(_("You're not docked at a station!")) self._handle_status(_("You're not docked at a station!"))
return False return False
if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules): # Ignore possibly missing shipyard info
if output_flags & config.OUT_EDDN_SEND_STATION_DATA and not (has_commodities or has_modules) and not self.status['text']:
# LANG: Status - Either no market or no modules data for station from Frontier CAPI
self._handle_status(_("Station doesn't have anything!")) self._handle_status(_("Station doesn't have anything!"))
elif not has_commodities: elif not has_commodities and not self.status['text']:
# LANG: Status - No station market data from Frontier CAPI
self._handle_status(_("Station doesn't have a market!")) self._handle_status(_("Station doesn't have a market!"))
elif output_flags & commodities_flag: elif output_flags & commodities_flag:
# Fixup anomalies in the comodity data
fixed = companion.fixup(data) fixed = companion.fixup(data)
if output_flags & config.OUT_MKT_CSV: if output_flags & config.OUT_MKT_CSV:
commodity.export(fixed, COMMODITY_CSV) commodity.export(fixed, COMMODITY_CSV)