1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-04-12 15:27:14 +03:00

[2303] Attempt Reversion

This commit is contained in:
David Sangrey 2024-09-30 18:42:09 -04:00
parent 348ad1d75f
commit 5ad7fcfa62
No known key found for this signature in database
GPG Key ID: 3AEADBB0186884BC
4 changed files with 33 additions and 37 deletions

View File

@ -14,7 +14,6 @@ import locale
import os import os
import queue import queue
import sys import sys
from pathlib import Path
from time import sleep, time from time import sleep, time
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
@ -213,16 +212,14 @@ def main(): # noqa: C901, CCR001
# 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 = Path(args.j).resolve() json_file = os.path.abspath(args.j)
try: try:
with open(json_file) as file_handle: with open(json_file) as file_handle:
data = json.load(file_handle) data = json.load(file_handle)
except UnicodeDecodeError: except UnicodeDecodeError:
with open(json_file, encoding='utf-8') as file_handle: with open(json_file, encoding='utf-8') as file_handle:
data = json.load(file_handle) data = json.load(file_handle)
file_path = Path(args.j) config.set('querytime', int(os.path.getmtime(args.j)))
modification_time = file_path.stat().st_mtime
config.set('querytime', int(modification_time))
else: else:
# Get state from latest Journal file # Get state from latest Journal file

View File

@ -11,7 +11,7 @@ import locale
import webbrowser import webbrowser
import platform import platform
import sys import sys
from os import chdir, environ from os import chdir, environ, path
import pathlib import pathlib
import logging import logging
from journal_lock import JournalLock from journal_lock import JournalLock
@ -19,10 +19,10 @@ from journal_lock import JournalLock
if getattr(sys, "frozen", False): if getattr(sys, "frozen", False):
# Under py2exe sys.path[0] is the executable name # Under py2exe sys.path[0] is the executable name
if sys.platform == "win32": if sys.platform == "win32":
chdir(pathlib.Path(sys.path[0]).parent) chdir(path.dirname(sys.path[0]))
# Allow executable to be invoked from any cwd # Allow executable to be invoked from any cwd
environ['TCL_LIBRARY'] = str(pathlib.Path(sys.path[0]).parent / 'lib' / 'tcl') environ["TCL_LIBRARY"] = path.join(path.dirname(sys.path[0]), "lib", "tcl")
environ['TK_LIBRARY'] = str(pathlib.Path(sys.path[0]).parent / 'lib' / 'tk') environ["TK_LIBRARY"] = path.join(path.dirname(sys.path[0]), "lib", "tk")
else: else:
# We still want to *try* to have CWD be where the main script is, even if # We still want to *try* to have CWD be where the main script is, even if
@ -44,12 +44,11 @@ def get_sys_report(config: config.AbstractConfig) -> str:
plt = platform.uname() plt = platform.uname()
locale.setlocale(locale.LC_ALL, "") locale.setlocale(locale.LC_ALL, "")
lcl = locale.getlocale() lcl = locale.getlocale()
monitor.currentdir = pathlib.Path(config.get_str( monitor.currentdir = config.get_str(
"journaldir", default=config.default_journal_dir "journaldir", default=config.default_journal_dir
)
) )
if not monitor.currentdir: if not monitor.currentdir:
monitor.currentdir = config.default_journal_dir_path monitor.currentdir = config.default_journal_dir
try: try:
logfile = monitor.journal_newest_filename(monitor.currentdir) logfile = monitor.journal_newest_filename(monitor.currentdir)
if logfile is None: if logfile is None:
@ -116,12 +115,12 @@ def main() -> None:
root.withdraw() # Hide the window initially to calculate the dimensions root.withdraw() # Hide the window initially to calculate the dimensions
try: try:
icon_image = tk.PhotoImage( icon_image = tk.PhotoImage(
file=cur_config.respath_path / "io.edcd.EDMarketConnector.png" file=path.join(cur_config.respath_path, "io.edcd.EDMarketConnector.png")
) )
root.iconphoto(True, icon_image) root.iconphoto(True, icon_image)
except tk.TclError: except tk.TclError:
root.iconbitmap(cur_config.respath_path / "EDMarketConnector.ico") root.iconbitmap(path.join(cur_config.respath_path, "EDMarketConnector.ico"))
sys_report = get_sys_report(cur_config) sys_report = get_sys_report(cur_config)

View File

@ -8,7 +8,7 @@ See LICENSE file.
from __future__ import annotations from __future__ import annotations
import json import json
from pathlib import Path import pathlib
import queue import queue
import re import re
import sys import sys
@ -16,6 +16,7 @@ import threading
from calendar import timegm from calendar import timegm
from collections import defaultdict from collections import defaultdict
from os import SEEK_END, SEEK_SET, listdir from os import SEEK_END, SEEK_SET, listdir
from os.path import basename, expanduser, getctime, isdir, join
from time import gmtime, localtime, mktime, sleep, strftime, strptime, time from time import gmtime, localtime, mktime, sleep, strftime, strptime, time
from typing import TYPE_CHECKING, Any, BinaryIO, MutableMapping from typing import TYPE_CHECKING, Any, BinaryIO, MutableMapping
import psutil import psutil
@ -67,7 +68,7 @@ class EDLogs(FileSystemEventHandler):
# TODO(A_D): A bunch of these should be switched to default values (eg '' for strings) and no longer be Optional # TODO(A_D): A bunch of these should be switched to default values (eg '' for strings) and no longer be Optional
FileSystemEventHandler.__init__(self) # futureproofing - not need for current version of watchdog FileSystemEventHandler.__init__(self) # futureproofing - not need for current version of watchdog
self.root: 'tkinter.Tk' = None # type: ignore # Don't use Optional[] - mypy thinks no methods self.root: 'tkinter.Tk' = None # type: ignore # Don't use Optional[] - mypy thinks no methods
self.currentdir: Path | None = None # The actual logdir that we're monitoring self.currentdir: str | None = None # The actual logdir that we're monitoring
self.logfile: str | None = None self.logfile: str | None = None
self.observer: BaseObserver | None = None self.observer: BaseObserver | None = None
self.observed = None # a watchdog ObservedWatch, or None if polling self.observed = None # a watchdog ObservedWatch, or None if polling
@ -190,9 +191,9 @@ class EDLogs(FileSystemEventHandler):
if journal_dir == '' or journal_dir is None: if journal_dir == '' or journal_dir is None:
journal_dir = config.default_journal_dir journal_dir = config.default_journal_dir
logdir = Path(journal_dir).expanduser() logdir = expanduser(journal_dir)
if not logdir or not Path.is_dir(logdir): if not logdir or not isdir(logdir):
logger.error(f'Journal Directory is invalid: "{logdir}"') logger.error(f'Journal Directory is invalid: "{logdir}"')
self.stop() self.stop()
return False return False
@ -265,10 +266,9 @@ class EDLogs(FileSystemEventHandler):
# Odyssey Update 11 has, e.g. Journal.2022-03-15T152503.01.log # Odyssey Update 11 has, e.g. Journal.2022-03-15T152503.01.log
# Horizons Update 11 equivalent: Journal.220315152335.01.log # Horizons Update 11 equivalent: Journal.220315152335.01.log
# So we can no longer use a naive sort. # So we can no longer use a naive sort.
journals_dir_path = Path(journals_dir) journals_dir_path = pathlib.Path(journals_dir)
journal_files = (journals_dir_path / Path(x) for x in journal_files) journal_files = (journals_dir_path / pathlib.Path(x) for x in journal_files)
latest_file = max(journal_files, key=lambda f: Path(f).stat().st_ctime) return str(max(journal_files, key=getctime))
return str(latest_file)
return None return None
@ -337,7 +337,7 @@ class EDLogs(FileSystemEventHandler):
def on_created(self, event: 'FileSystemEvent') -> None: def on_created(self, event: 'FileSystemEvent') -> None:
"""Watchdog callback when, e.g. client (re)started.""" """Watchdog callback when, e.g. client (re)started."""
if not event.is_directory and self._RE_LOGFILE.search(Path(event.src_path).name): if not event.is_directory and self._RE_LOGFILE.search(basename(event.src_path)):
self.logfile = event.src_path self.logfile = event.src_path
@ -1076,7 +1076,7 @@ class EDLogs(FileSystemEventHandler):
self.state['Cargo'] = defaultdict(int) self.state['Cargo'] = defaultdict(int)
# From 3.3 full Cargo event (after the first one) is written to a separate file # From 3.3 full Cargo event (after the first one) is written to a separate file
if 'Inventory' not in entry: if 'Inventory' not in entry:
with open(self.currentdir / 'Cargo.json', 'rb') as h: # type: ignore with open(join(self.currentdir, 'Cargo.json'), 'rb') as h: # type: ignore
entry = json.load(h) entry = json.load(h)
self.state['CargoJSON'] = entry self.state['CargoJSON'] = entry
@ -1103,7 +1103,7 @@ class EDLogs(FileSystemEventHandler):
# Always attempt loading of this, but if it fails we'll hope this was # Always attempt loading of this, but if it fails we'll hope this was
# a startup/boarding version and thus `entry` contains # a startup/boarding version and thus `entry` contains
# the data anyway. # the data anyway.
currentdir_path = Path(str(self.currentdir)) currentdir_path = pathlib.Path(str(self.currentdir))
shiplocker_filename = currentdir_path / 'ShipLocker.json' shiplocker_filename = currentdir_path / 'ShipLocker.json'
shiplocker_max_attempts = 5 shiplocker_max_attempts = 5
shiplocker_fail_sleep = 0.01 shiplocker_fail_sleep = 0.01
@ -1172,7 +1172,7 @@ class EDLogs(FileSystemEventHandler):
# TODO: v31 doc says this is`backpack.json` ... but Howard Chalkley # TODO: v31 doc says this is`backpack.json` ... but Howard Chalkley
# said it's `Backpack.json` # said it's `Backpack.json`
backpack_file = Path(str(self.currentdir)) / 'Backpack.json' backpack_file = pathlib.Path(str(self.currentdir)) / 'Backpack.json'
backpack_data = None backpack_data = None
if not backpack_file.exists(): if not backpack_file.exists():
@ -1548,7 +1548,7 @@ class EDLogs(FileSystemEventHandler):
entry = fcmaterials entry = fcmaterials
elif event_type == 'moduleinfo': elif event_type == 'moduleinfo':
with open(self.currentdir / 'ModulesInfo.json', 'rb') as mf: # type: ignore with open(join(self.currentdir, 'ModulesInfo.json'), 'rb') as mf: # type: ignore
try: try:
entry = json.load(mf) entry = json.load(mf)
@ -2259,14 +2259,14 @@ class EDLogs(FileSystemEventHandler):
oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x))) oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x)))
if oldfiles: if oldfiles:
try: try:
with open(config.get_str('outdir') / Path(oldfiles[-1]), encoding='utf-8') as h: with open(join(config.get_str('outdir'), oldfiles[-1]), encoding='utf-8') as h:
if h.read() == string: if h.read() == string:
return # same as last time - don't write return # same as last time - don't write
except UnicodeError: except UnicodeError:
logger.exception("UnicodeError reading old ship loadout with utf-8 encoding, trying without...") logger.exception("UnicodeError reading old ship loadout with utf-8 encoding, trying without...")
try: try:
with open(config.get_str('outdir') / Path(oldfiles[-1])) as h: with open(join(config.get_str('outdir'), oldfiles[-1])) as h:
if h.read() == string: if h.read() == string:
return # same as last time - don't write return # same as last time - don't write
@ -2285,7 +2285,7 @@ class EDLogs(FileSystemEventHandler):
# Write # Write
ts = strftime('%Y-%m-%dT%H.%M.%S', localtime(time())) ts = strftime('%Y-%m-%dT%H.%M.%S', localtime(time()))
filename = config.get_str('outdir') / Path(f'{ship}.{ts}.txt') filename = join(config.get_str('outdir'), f'{ship}.{ts}.txt')
try: try:
with open(filename, 'wt', encoding='utf-8') as h: with open(filename, 'wt', encoding='utf-8') as h:
@ -2372,7 +2372,7 @@ class EDLogs(FileSystemEventHandler):
try: try:
with open(self.currentdir / 'NavRoute.json') as f: with open(join(self.currentdir, 'NavRoute.json')) as f:
raw = f.read() raw = f.read()
except Exception as e: except Exception as e:
@ -2398,7 +2398,7 @@ class EDLogs(FileSystemEventHandler):
try: try:
with open(self.currentdir / 'FCMaterials.json') as f: with open(join(self.currentdir, 'FCMaterials.json')) as f:
raw = f.read() raw = f.read()
except Exception as e: except Exception as e:

View File

@ -4,7 +4,7 @@ from __future__ import annotations
import contextlib import contextlib
import logging import logging
from os.path import expandvars from os.path import expandvars, join, normpath
from pathlib import Path from pathlib import Path
import subprocess import subprocess
import sys import sys
@ -1100,7 +1100,7 @@ class PreferencesDialog(tk.Toplevel):
if sys.platform == 'win32': if sys.platform == 'win32':
start = len(config.home.split('\\')) if pathvar.get().lower().startswith(config.home.lower()) else 0 start = len(config.home.split('\\')) if pathvar.get().lower().startswith(config.home.lower()) else 0
display = [] display = []
components = Path(pathvar.get()).resolve().parts components = normpath(pathvar.get()).split('\\')
buf = ctypes.create_unicode_buffer(MAX_PATH) buf = ctypes.create_unicode_buffer(MAX_PATH)
pidsRes = ctypes.c_int() # noqa: N806 # Windows convention pidsRes = ctypes.c_int() # noqa: N806 # Windows convention
for i in range(start, len(components)): for i in range(start, len(components)):
@ -1253,7 +1253,7 @@ class PreferencesDialog(tk.Toplevel):
config.set( config.set(
'outdir', 'outdir',
str(config.home_path / self.outdir.get()[2:]) if self.outdir.get().startswith('~') else self.outdir.get() join(config.home_path, self.outdir.get()[2:]) if self.outdir.get().startswith('~') else self.outdir.get()
) )
logdir = self.logdir.get() logdir = self.logdir.get()
@ -1296,8 +1296,8 @@ class PreferencesDialog(tk.Toplevel):
if self.plugdir.get() != config.get('plugin_dir'): if self.plugdir.get() != config.get('plugin_dir'):
config.set( config.set(
'plugin_dir', 'plugin_dir',
str(Path(config.home_path, self.plugdir.get()[2:])) if self.plugdir.get().startswith('~') else join(config.home_path, self.plugdir.get()[2:]) if self.plugdir.get().startswith(
str(Path(self.plugdir.get())) '~') else self.plugdir.get()
) )
self.req_restart = True self.req_restart = True