-
Notifications
You must be signed in to change notification settings - Fork 156
/
monitor.py
2524 lines (2068 loc) · 113 KB
/
monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
monitor.py - Monitor for new Journal files and contents of latest.
Copyright (c) EDCD, All Rights Reserved
Licensed under the GNU General Public License.
See LICENSE file.
"""
from __future__ import annotations
import json
import pathlib
import queue
import re
import sys
import threading
from calendar import timegm
from collections import defaultdict
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 typing import TYPE_CHECKING, Any, BinaryIO, MutableMapping
import psutil
import semantic_version
import util_ships
from config import config, appname, appversion
from edmc_data import edmc_suit_shortnames, edmc_suit_symbol_localised, ship_name_map
from EDMCLogging import get_main_logger
from edshipyard import ships
if TYPE_CHECKING:
import tkinter
logger = get_main_logger()
STARTUP = 'journal.startup'
MAX_NAVROUTE_DISCREPANCY = 5 # Timestamp difference in seconds
MAX_FCMATERIALS_DISCREPANCY = 5 # Timestamp difference in seconds
if sys.platform == 'win32':
from watchdog.events import FileSystemEventHandler, FileSystemEvent
from watchdog.observers import Observer
from watchdog.observers.api import BaseObserver
else:
# Linux's inotify doesn't work over CIFS or NFS, so poll
FileSystemEventHandler = object # dummy
if TYPE_CHECKING:
# this isn't ever used, but this will make type checking happy
from watchdog.events import FileSystemEvent
from watchdog.observers import Observer
from watchdog.observers.api import BaseObserver
# Journal handler
class EDLogs(FileSystemEventHandler):
"""Monitoring of Journal files."""
# Magic with FileSystemEventHandler can confuse type checkers when they do not have access to every import
_POLL = 1 # Polling while running is cheap, so do it often
_INACTIVE_POLL = 10 # Polling while not running isn't as cheap, so do it less often
_RE_CANONICALISE = re.compile(r'\$(.+)_name;')
_RE_CATEGORY = re.compile(r'\$MICRORESOURCE_CATEGORY_(.+);')
_RE_LOGFILE = re.compile(r'^Journal(Alpha|Beta)?\.[0-9]{2,4}(-)?[0-9]{2}(-)?[0-9]{2}(T)?[0-9]{2}[0-9]{2}[0-9]{2}'
r'\.[0-9]{2}\.log$')
_RE_SHIP_ONFOOT = re.compile(r'^(FlightSuit|UtilitySuit_Class.|TacticalSuit_Class.|ExplorationSuit_Class.)$')
def __init__(self) -> None:
# 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
self.root: 'tkinter.Tk' = None # type: ignore # Don't use Optional[] - mypy thinks no methods
self.currentdir: str | None = None # The actual logdir that we're monitoring
self.logfile: str | None = None
self.observer: BaseObserver | None = None
self.observed = None # a watchdog ObservedWatch, or None if polling
self.thread: threading.Thread | None = None
# For communicating journal entries back to main thread
self.event_queue: queue.Queue = queue.Queue(maxsize=0)
# On startup we might be:
# 1) Looking at an old journal file because the game isn't running or the user has exited to the main menu.
# 2) Looking at an empty journal (only 'Fileheader') because the user is at the main menu.
# 3) In the middle of a 'live' game.
# If 1 or 2 a LoadGame event will happen when the game goes live.
# If 3 we need to inject a special 'StartUp' event since consumers won't see the LoadGame event.
self.live = False
# And whilst we're parsing *only to catch up on state*, we might not want to fully process some things
self.catching_up = False
self.game_was_running = False # For generation of the "ShutDown" event
self.running_process = None
# Context for journal handling
self.version: str | None = None
self.version_semantic: semantic_version.Version | None = None
self.is_beta = False
self.mode: str | None = None
self.group: str | None = None
self.cmdr: str | None = None
self.started: int | None = None # Timestamp of the LoadGame event
self.slef: str | None = None
self._navroute_retries_remaining = 0
self._last_navroute_journal_timestamp: float | None = None
self._fcmaterials_retries_remaining = 0
self._last_fcmaterials_journal_timestamp: float | None = None
# For determining Live versus Legacy galaxy.
# The assumption is gameversion will parse via `coerce()` and always
# be >= for Live, and < for Legacy.
self.live_galaxy_base_version = semantic_version.Version('4.0.0')
self.__init_state()
def __init_state(self) -> None:
# Cmdr state shared with EDSM and plugins
# If you change anything here update PLUGINS.md documentation!
self.state: dict = {
'GameLanguage': None, # From `Fileheader
'GameVersion': None, # From `Fileheader
'GameBuild': None, # From `Fileheader
'Captain': None, # On a crew
'Cargo': defaultdict(int),
'Credits': None,
'FID': None, # Frontier Cmdr ID
'Horizons': None, # Does this user have Horizons?
'Odyssey': False, # Have we detected we're running under Odyssey?
'Loan': None,
'Raw': defaultdict(int),
'Manufactured': defaultdict(int),
'Encoded': defaultdict(int),
'Engineers': {},
'Rank': {},
'Reputation': {},
'Statistics': {},
'Role': None, # Crew role - None, Idle, FireCon, FighterCon
'Friends': set(), # Online friends
'ShipID': None,
'ShipIdent': None,
'ShipName': None,
'ShipType': None,
'HullValue': None,
'ModulesValue': None,
'Rebuy': None,
'Modules': None,
'CargoJSON': None, # The raw data from the last time cargo.json was read
'Route': None, # Last plotted route from Route.json file
'IsDocked': False, # Whether we think cmdr is docked
'OnFoot': False, # Whether we think you're on-foot
'Component': defaultdict(int), # Odyssey Components in Ship Locker
'Item': defaultdict(int), # Odyssey Items in Ship Locker
'Consumable': defaultdict(int), # Odyssey Consumables in Ship Locker
'Data': defaultdict(int), # Odyssey Data in Ship Locker
'BackPack': { # Odyssey BackPack contents
'Component': defaultdict(int), # BackPack Components
'Consumable': defaultdict(int), # BackPack Consumables
'Item': defaultdict(int), # BackPack Items
'Data': defaultdict(int), # Backpack Data
},
'BackpackJSON': None, # Raw JSON from `Backpack.json` file, if available
'ShipLockerJSON': None, # Raw JSON from the `ShipLocker.json` file, if available
'SuitCurrent': None,
'Suits': {},
'SuitLoadoutCurrent': None,
'SuitLoadouts': {},
'Taxi': None, # True whenever we are _in_ a taxi. ie, this is reset on Disembark etc.
'Dropship': None, # Best effort as to whether or not the above taxi is a dropship.
'StarPos': None, # Best effort current system's galaxy position.
'SystemAddress': None,
'SystemName': None,
'SystemPopulation': None,
'Body': None,
'BodyID': None,
'BodyType': None,
'StationName': None,
'NavRoute': None,
}
def start(self, root: 'tkinter.Tk') -> bool: # noqa: CCR001
"""
Start journal monitoring.
:param root: The parent Tk window.
:return: bool - False if we couldn't access/find latest Journal file.
"""
logger.debug('Begin...')
self.root = root
journal_dir = config.get_str('journaldir')
if journal_dir == '' or journal_dir is None:
journal_dir = config.default_journal_dir
logdir = expanduser(journal_dir)
if not logdir or not isdir(logdir):
logger.error(f'Journal Directory is invalid: "{logdir}"')
self.stop()
return False
if self.currentdir and self.currentdir != logdir:
logger.debug(f'Journal Directory changed? Was "{self.currentdir}", now "{logdir}"')
self.stop()
self.currentdir = logdir
# Latest pre-existing logfile - e.g. if E:D is already running.
# Do this before setting up the observer in case the journal directory has gone away
try: # TODO: This should be replaced with something specific ONLY wrapping listdir
self.logfile = self.journal_newest_filename(self.currentdir)
except Exception:
logger.exception('Failed to find latest logfile')
self.logfile = None
return False
# Set up a watchdog observer.
# File system events are unreliable/non-existent over network drives on Linux.
# We can't easily tell whether a path points to a network drive, so assume
# any non-standard logdir might be on a network drive and poll instead.
polling = bool(config.get_str('journaldir')) and sys.platform != 'win32'
if not polling and not self.observer:
logger.debug('Not polling, no observer, starting an observer...')
self.observer = Observer()
self.observer.daemon = True
self.observer.start()
logger.debug('Done')
elif polling and self.observer:
logger.debug('Polling, but observer, so stopping observer...')
self.observer.stop()
self.observer = None
logger.debug('Done')
if not self.observed and not polling:
logger.debug('Not observed and not polling, setting observed...')
self.observed = self.observer.schedule(self, self.currentdir) # type: ignore
logger.debug('Done')
logger.info(f'{"Polling" if polling else "Monitoring"} Journal Folder: "{self.currentdir}"')
logger.info(f'Start Journal File: "{self.logfile}"')
if not self.running():
logger.debug('Starting Journal worker thread...')
self.thread = threading.Thread(target=self.worker, name='Journal worker')
self.thread.daemon = True
self.thread.start()
logger.debug('Done')
logger.debug('Done.')
return True
def journal_newest_filename(self, journals_dir) -> str | None:
"""
Determine the newest Journal file name.
:param journals_dir: The directory to check
:return: The `str` form of the full path to the newest Journal file
"""
# os.listdir(None) returns CWD's contents
if journals_dir is None:
return None
journal_files = (x for x in listdir(journals_dir) if self._RE_LOGFILE.search(x))
if journal_files:
# Odyssey Update 11 has, e.g. Journal.2022-03-15T152503.01.log
# Horizons Update 11 equivalent: Journal.220315152335.01.log
# So we can no longer use a naive sort.
journals_dir_path = pathlib.Path(journals_dir)
journal_files = (journals_dir_path / pathlib.Path(x) for x in journal_files)
return str(max(journal_files, key=getctime))
return None
def stop(self) -> None:
"""Stop journal monitoring."""
logger.debug('Stopping monitoring Journal')
self.currentdir = None
self.version = None
self.version_semantic = None
self.mode = None
self.group = None
self.cmdr = None
self.state['SystemAddress'] = None
self.state['SystemName'] = None
self.state['SystemPopulation'] = None
self.state['StarPos'] = None
self.state['Body'] = None
self.state['BodyID'] = None
self.state['BodyType'] = None
self.state['StationName'] = None
self.state['MarketID'] = None
self.state['StationType'] = None
self.stationservices = None
self.is_beta = False
self.state['OnFoot'] = False
self.state['IsDocked'] = False
if self.observed:
logger.debug('self.observed: Calling unschedule_all()')
self.observed = None
assert self.observer is not None, 'Observer was none but it is in use?'
self.observer.unschedule_all()
logger.debug('Done')
self.thread = None # Orphan the worker thread - will terminate at next poll
logger.debug('Done.')
def close(self) -> None:
"""Close journal monitoring."""
logger.debug('Calling self.stop()...')
self.stop()
logger.debug('Done')
if self.observer:
logger.debug('Calling self.observer.stop()...')
self.observer.stop()
logger.debug('Done')
if self.observer:
logger.debug('Joining self.observer thread...')
self.observer.join()
self.observer = None
logger.debug('Done')
logger.debug('Done.')
def running(self) -> bool:
"""
Determine if Journal watching is active.
:return: bool
"""
return bool(self.thread and self.thread.is_alive())
def on_created(self, event: 'FileSystemEvent') -> None:
"""Watchdog callback when, e.g. client (re)started."""
if not event.is_directory and self._RE_LOGFILE.search(basename(event.src_path)):
self.logfile = event.src_path
def worker(self) -> None: # noqa: C901, CCR001
"""
Watch latest Journal file.
1. Keep track of the latest Journal file, switching to a new one if
needs be.
2. Read in lines from the latest Journal file and queue them up for
get_entry() to process in the main thread.
"""
# Tk isn't thread-safe in general.
# event_generate() is the only safe way to poke the main thread from this thread:
# https://mail.python.org/pipermail/tkinter-discuss/2013-November/003522.html
logger.debug(f'Starting on logfile "{self.logfile}"')
# Seek to the end of the latest log file
log_pos = -1 # make this bound, but with something that should go bang if its misused
logfile = self.logfile
if logfile:
loghandle: BinaryIO = open(logfile, 'rb', 0) # unbuffered
self.catching_up = True
for line in loghandle:
try:
if b'"event":"Location"' in line:
logger.trace_if('journal.locations', '"Location" event in the past at startup')
self.parse_entry(line) # Some events are of interest even in the past
except Exception as ex:
logger.debug(f'Invalid journal entry:\n{line!r}\n', exc_info=ex)
# One-shot attempt to read in latest NavRoute, if present
navroute_data = self._parse_navroute_file()
if navroute_data is not None:
# If it's NavRouteClear contents, just keep those anyway.
self.state['NavRoute'] = navroute_data
self.catching_up = False
log_pos = loghandle.tell()
else:
loghandle = None # type: ignore
logger.debug('Now at end of latest file.')
self.game_was_running = self.game_running()
if self.live:
if self.game_was_running:
logger.info("Game is/was running, so synthesizing StartUp event for plugins")
# Game is running locally
entry = self.synthesize_startup_event()
self.event_queue.put(json.dumps(entry, separators=(', ', ':')))
else:
# Generate null event to update the display (with possibly out-of-date info)
self.event_queue.put(None)
self.live = False
emitter = None
# Watchdog thread -- there is a way to get this by using self.observer.emitters and checking for an attribute:
# watch, but that may have unforseen differences in behaviour.
if self.observed:
assert self.observer is not None, 'self.observer is None but also in use?'
# Note: Uses undocumented attribute
emitter = self.observed and self.observer._emitter_for_watch[self.observed]
logger.debug('Entering loop...')
while True:
# Check whether new log file started, e.g. client (re)started.
if emitter and emitter.is_alive():
new_journal_file: str | None = self.logfile # updated by on_created watchdog callback
else:
# Poll
try:
new_journal_file = self.journal_newest_filename(self.currentdir)
except Exception:
logger.exception('Failed to find latest logfile')
new_journal_file = None
if logfile:
loghandle.seek(0, SEEK_END) # required for macOS to notice log change over SMB. TODO: Do we need this?
loghandle.seek(log_pos, SEEK_SET) # reset EOF flag # TODO: log_pos reported as possibly unbound
for line in loghandle:
# Paranoia check to see if we're shutting down
if threading.current_thread() != self.thread:
logger.info("We're not meant to be running, exiting...")
return # Terminate
if b'"event":"Continue"' in line:
for _ in range(10):
logger.trace_if('journal.continuation', "****")
logger.trace_if('journal.continuation', 'Found a Continue event, its being added to the list, '
'we will finish this file up and then continue with the next')
self.event_queue.put(line)
if not self.event_queue.empty():
if not config.shutting_down:
logger.trace_if('journal.queue', 'Sending <<JournalEvent>>')
self.root.event_generate('<<JournalEvent>>', when="tail")
log_pos = loghandle.tell()
if logfile != new_journal_file:
for _ in range(10):
logger.trace_if('journal.file', "****")
logger.info(f'New Journal File. Was "{logfile}", now "{new_journal_file}"')
logfile = new_journal_file
if loghandle:
loghandle.close()
if logfile:
loghandle = open(logfile, 'rb', 0) # unbuffered
log_pos = 0
if self.game_was_running:
sleep(self._POLL)
else:
sleep(self._INACTIVE_POLL)
# Check whether we're still supposed to be running
if threading.current_thread() != self.thread:
logger.info("We're not meant to be running, exiting...")
if loghandle:
loghandle.close()
return # Terminate
if self.game_was_running:
if not self.game_running():
logger.info('Detected exit from game, synthesising ShutDown event')
timestamp = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())
self.event_queue.put(
f'{{ "timestamp":"{timestamp}", "event":"ShutDown" }}'
)
if not config.shutting_down:
logger.trace_if('journal.queue', 'Sending <<JournalEvent>>')
self.root.event_generate('<<JournalEvent>>', when="tail")
self.game_was_running = False
else:
self.game_was_running = self.game_running()
def synthesize_startup_event(self) -> dict[str, Any]:
"""
Synthesize a 'StartUp' event to notify plugins of initial state.
May be called, e.g. after 'catch up' loading of current latest
journal file on startup, or when a new journal file is detected without
the game running locally.
:return: Synthesized event as a dict
"""
entry: dict[str, Any] = {
'timestamp': strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()),
'event': 'StartUp',
'StarSystem': self.state['SystemName'],
'StarPos': self.state['StarPos'],
'SystemAddress': self.state['SystemAddress'],
'Population': self.state['SystemPopulation'],
}
if self.state['Body']:
entry['Body'] = self.state['Body']
entry['BodyID'] = self.state['BodyID']
entry['BodyType'] = self.state['BodyType']
if self.state['StationName']:
entry['Docked'] = True
entry['MarketID'] = self.state['MarketID']
entry['StationName'] = self.state['StationName']
entry['StationType'] = self.state['StationType']
else:
entry['Docked'] = False
return entry
def parse_entry(self, line: bytes) -> MutableMapping[str, Any]: # noqa: C901, CCR001
"""
Parse a Journal JSON line.
This augments some events, sets internal state in reaction to many and
loads some extra files, e.g. Cargo.json, as necessary.
:param line: bytes - The entry being parsed. Yes, this is bytes, not str.
We rely on json.loads() dealing with this properly.
:return: Dict of the processed event.
"""
# TODO(A_D): a bunch of these can be simplified to use if itertools.product and filters
if line is None:
return {'event': None} # Fake startup event
try:
# Preserve property order because why not?
entry: MutableMapping[str, Any] = json.loads(line)
assert 'timestamp' in entry, "Timestamp does not exist in the entry"
self.__navroute_retry()
event_type = entry['event'].lower()
if event_type == 'fileheader':
self.live = False
self.cmdr = None
self.mode = None
self.group = None
self.state['SystemAddress'] = None
self.state['SystemName'] = None
self.state['SystemPopulation'] = None
self.state['StarPos'] = None
self.state['Body'] = None
self.state['BodyID'] = None
self.state['StationName'] = None
self.state['MarketID'] = None
self.state['StationType'] = None
self.stationservices = None
self.started = None
self.__init_state()
# Do this AFTER __init_state() lest our nice new state entries be None
self.populate_version_info(entry)
elif event_type == 'commander':
self.live = True # First event in 3.0
self.cmdr = entry['Name']
self.state['FID'] = entry['FID']
logger.trace_if(STARTUP, f'"Commander" event, {monitor.cmdr=}, {monitor.state["FID"]=}')
elif event_type == 'loadgame':
# Odyssey Release Update 5 -- This contains data that doesn't match the format used in FileHeader above
self.populate_version_info(entry, suppress=True)
# alpha4
# Odyssey: bool
self.cmdr = entry['Commander']
# 'Open', 'Solo', 'Group', or None for CQC (and Training - but no LoadGame event)
if not entry.get('Ship') and not entry.get('GameMode') or entry.get('GameMode', '').lower() == 'cqc':
logger.trace_if('journal.loadgame.cqc', f'loadgame to cqc: {entry}')
self.mode = 'CQC'
else:
self.mode = entry.get('GameMode')
self.group = entry.get('Group')
self.state['SystemAddress'] = None
self.state['SystemName'] = None
self.state['SystemPopulation'] = None
self.state['StarPos'] = None
self.state['Body'] = None
self.state['BodyID'] = None
self.state['BodyType'] = None
self.state['StationName'] = None
self.state['MarketID'] = None
self.state['StationType'] = None
self.stationservices = None
self.started = timegm(strptime(entry['timestamp'], '%Y-%m-%dT%H:%M:%SZ'))
# Don't set Ship, ShipID etc since this will reflect Fighter or SRV if starting in those
self.state.update({
'Captain': None,
'Credits': entry['Credits'],
'FID': entry.get('FID'), # From 3.3
'Horizons': entry['Horizons'], # From 3.0
'Odyssey': entry.get('Odyssey', False), # From 4.0 Odyssey
'Loan': entry['Loan'],
# For Odyssey, by 4.0.0.100, and at least from Horizons 3.8.0.201 the order of events changed
# to LoadGame being after some 'status' events.
# 'Engineers': {}, # 'EngineerProgress' event now before 'LoadGame'
# 'Rank': {}, # 'Rank'/'Progress' events now before 'LoadGame'
# 'Reputation': {}, # 'Reputation' event now before 'LoadGame'
'Statistics': {}, # Still after 'LoadGame' in 4.0.0.903
'Role': None,
'Taxi': None,
'Dropship': None,
})
if entry.get('Ship') is not None and self._RE_SHIP_ONFOOT.search(entry['Ship']):
self.state['OnFoot'] = True
logger.trace_if(STARTUP, f'"LoadGame" event, {monitor.cmdr=}, {monitor.state["FID"]=}')
elif event_type == 'newcommander':
self.cmdr = entry['Name']
self.group = None
elif event_type == 'setusershipname':
self.state['ShipID'] = entry['ShipID']
if 'UserShipId' in entry: # Only present when changing the ship's ident
self.state['ShipIdent'] = entry['UserShipId']
self.state['ShipName'] = entry.get('UserShipName')
self.state['ShipType'] = self.canonicalise(entry['Ship'])
elif event_type == 'shipyardbuy':
self.state['ShipID'] = None
self.state['ShipIdent'] = None
self.state['ShipName'] = None
self.state['ShipType'] = self.canonicalise(entry['ShipType'])
self.state['HullValue'] = None
self.state['ModulesValue'] = None
self.state['Rebuy'] = None
self.state['Modules'] = None
self.state['Credits'] -= entry.get('ShipPrice', 0)
elif event_type == 'shipyardswap':
self.state['ShipID'] = entry['ShipID']
self.state['ShipIdent'] = None
self.state['ShipName'] = None
self.state['ShipType'] = self.canonicalise(entry['ShipType'])
self.state['HullValue'] = None
self.state['ModulesValue'] = None
self.state['Rebuy'] = None
self.state['Modules'] = None
elif (
event_type == 'loadout' and
'fighter' not in self.canonicalise(entry['Ship']) and
'buggy' not in self.canonicalise(entry['Ship'])
):
self.state['ShipID'] = entry['ShipID']
self.state['ShipIdent'] = entry['ShipIdent']
# Newly purchased ships can show a ShipName of "" initially,
# and " " after a game restart/relog.
# Players *can* also purposefully set " " as the name, but anyone
# doing that gets to live with EDMC showing ShipType instead.
if entry['ShipName'] and entry['ShipName'] not in ('', ' '):
self.state['ShipName'] = entry['ShipName']
self.state['ShipType'] = self.canonicalise(entry['Ship'])
self.state['HullValue'] = entry.get('HullValue') # not present on exiting Outfitting
self.state['ModulesValue'] = entry.get('ModulesValue') # not present on exiting Outfitting
self.state['Rebuy'] = entry.get('Rebuy')
# Remove spurious differences between initial Loadout event and subsequent
self.state['Modules'] = {}
for module in entry['Modules']:
module = dict(module)
module['Item'] = self.canonicalise(module['Item'])
if ('Hardpoint' in module['Slot'] and
not module['Slot'].startswith('TinyHardpoint') and
module.get('AmmoInClip') == module.get('AmmoInHopper') == 1): # lasers
module.pop('AmmoInClip')
module.pop('AmmoInHopper')
self.state['Modules'][module['Slot']] = module
# SLEF
initial_dict: dict[str, dict[str, Any]] = {
"header": {"appName": appname, "appVersion": str(appversion())}
}
data_dict = {}
for module in entry['Modules']:
if module.get('Slot') == 'FuelTank':
cap = module['Item'].split('size')
cap = cap[1].split('_')
cap = 2 ** int(cap[0])
ship = ship_name_map[entry["Ship"]]
fuel = {'Main': cap, 'Reserve': ships[ship]['reserveFuelCapacity']}
data_dict.update({"FuelCapacity": fuel})
data_dict.update({
'Ship': entry["Ship"],
'ShipName': entry['ShipName'],
'ShipIdent': entry['ShipIdent'],
'HullValue': entry['HullValue'],
'ModulesValue': entry['ModulesValue'],
'Rebuy': entry['Rebuy'],
'MaxJumpRange': entry['MaxJumpRange'],
'UnladenMass': entry['UnladenMass'],
'CargoCapacity': entry['CargoCapacity'],
'Modules': entry['Modules'],
})
initial_dict.update({'data': data_dict})
output = json.dumps(initial_dict, indent=4)
self.slef = str(f"[{output}]")
elif event_type == 'modulebuy':
self.state['Modules'][entry['Slot']] = {
'Slot': entry['Slot'],
'Item': self.canonicalise(entry['BuyItem']),
'On': True,
'Priority': 1,
'Health': 1.0,
'Value': entry['BuyPrice'],
}
self.state['Credits'] -= entry.get('BuyPrice', 0)
elif event_type == 'moduleretrieve':
self.state['Credits'] -= entry.get('Cost', 0)
elif event_type == 'modulesell':
self.state['Modules'].pop(entry['Slot'], None)
self.state['Credits'] += entry.get('SellPrice', 0)
elif event_type == 'modulesellremote':
self.state['Credits'] += entry.get('SellPrice', 0)
elif event_type == 'modulestore':
self.state['Modules'].pop(entry['Slot'], None)
self.state['Credits'] -= entry.get('Cost', 0)
elif event_type == 'moduleswap':
to_item = self.state['Modules'].get(entry['ToSlot'])
to_slot = entry['ToSlot']
from_slot = entry['FromSlot']
modules = self.state['Modules']
modules[to_slot] = modules[from_slot]
if to_item:
modules[from_slot] = to_item
else:
modules.pop(from_slot, None)
elif event_type == 'undocked':
self.state['StationName'] = None
self.state['MarketID'] = None
self.state['StationType'] = None
self.stationservices = None
self.state['IsDocked'] = False
elif event_type == 'embark':
# This event is logged when a player (on foot) gets into a ship or SRV
# Parameters:
# • SRV: true if getting into SRV, false if getting into a ship
# • Taxi: true when boarding a taxi transport ship
# • Multicrew: true when boarding another player’s vessel
# • ID: player’s ship ID (if players own vessel)
# • StarSystem
# • SystemAddress
# • Body
# • BodyID
# • OnStation: bool
# • OnPlanet: bool
# • StationName (if at a station)
# • StationType
# • MarketID
self.state['StationName'] = None
self.state['MarketID'] = None
if entry.get('OnStation'):
self.state['StationName'] = entry.get('StationName', '')
self.state['MarketID'] = entry.get('MarketID', '')
self.state['OnFoot'] = False
self.state['Taxi'] = entry['Taxi']
# We can't now have anything in the BackPack, it's all in the
# ShipLocker.
self.backpack_set_empty()
elif event_type == 'disembark':
# This event is logged when the player steps out of a ship or SRV
#
# Parameters:
# • SRV: true if getting out of SRV, false if getting out of a ship
# • Taxi: true when getting out of a taxi transport ship
# • Multicrew: true when getting out of another player’s vessel
# • ID: player’s ship ID (if players own vessel)
# • StarSystem
# • SystemAddress
# • Body
# • BodyID
# • OnStation: bool
# • OnPlanet: bool
# • StationName (if at a station)
# • StationType
# • MarketID
if entry.get('OnStation', False):
self.state['StationName'] = entry.get('StationName', '')
else:
self.state['StationName'] = None
self.state['OnFoot'] = True
if self.state['Taxi'] is not None and self.state['Taxi'] != entry.get('Taxi', False):
logger.warning('Disembarked from a taxi but we didn\'t know we were in a taxi?')
self.state['Taxi'] = False
self.state['Dropship'] = False
elif event_type == 'dropshipdeploy':
# We're definitely on-foot now
self.state['OnFoot'] = True
self.state['Taxi'] = False
self.state['Dropship'] = False
elif event_type == 'supercruiseexit':
# For any orbital station we have no way of determining the body
# it orbits:
#
# In-ship Status.json doesn't specify this.
# On-foot Status.json lists the station itself as Body.
# Location for stations (on-foot or in-ship) has station as Body.
# SupercruiseExit (own ship or taxi) lists the station as the Body.
if entry['BodyType'] == 'Station':
self.state['Body'] = None
self.state['BodyID'] = None
elif event_type == 'docked':
###############################################################
# Track: Station
###############################################################
self.state['IsDocked'] = True
self.state['StationName'] = entry.get('StationName') # It may be None
self.state['MarketID'] = entry.get('MarketID') # It may be None
self.state['StationType'] = entry.get('StationType') # It may be None
self.stationservices = entry.get('StationServices') # None under E:D < 2.4
# No need to set self.state['Taxi'] or Dropship here, if it's
# those, the next event is a Disembark anyway
###############################################################
elif event_type in ('location', 'fsdjump', 'carrierjump'):
"""
Notes on tracking of a player's location.
Body
---
There are some caveats about tracking Body name, ID and type,
mostly due to close-orbiting binary planets/moons.
Presence on or near a Body is indicated in several scenarios:
1. When the player logs in.
2. When the player's location changes due to being docked
on a Fleet Carrier when it jumps.
3. When the player flies within Orbital Cruise range of a
Body.
For the first case this will always be a 'Location' event.
If landed on a Body, or docked at a surface port then this
will be indicated. However, if docked at an orbital station
the 'Body' is the name of that station, with 'BodyType' having
'Station' as its value.
In the second case although it *should* be a 'CarrierJump'
event, for a while now it's actually been a 'Location' event.
This should follow the same rules as being docked at an
orbital station.
For the last case there are some caveats to do with close
orbiting binary bodies:
1. 'ApproachBody' indicates presence near the Body in question.
2. 'LeaveBody' indicates the player is no longer considered
to be near the Body. This is specifically when no longer
in Orbital Cruise around the Body such that the HUD for that
has been switched out for the normal SuperCruise one.
3. 'SupercruiseExit' does not indicate any change of presence
near a Body.
4. 'SupercruiseEntry' *also* **DOES NOT** indicate that the
player is no longer near the Body. They can easily utilise
Orbital Cruise to rapidly travel around the Body and then
land on it again **without a fresh 'ApproachBody'** event.
The only way to check for this is to utilise the Body (name)
present in `Status.json` data, as this *will* correctly
reflect the second Body.
"""
###############################################################
# Track: Body
###############################################################
if event_type in ('location', 'carrierjump'):
# We're not guaranteeing this is a planet, rather than a
# station.
self.state['Body'] = entry.get('Body')
self.state['BodyID'] = entry.get('BodyID')
self.state['BodyType'] = entry.get('BodyType')
elif event_type == 'fsdjump':
self.state['Body'] = None
self.state['BodyID'] = None
self.state['BodyType'] = None
###############################################################
###############################################################
# Track: IsDocked
###############################################################
if event_type == 'location':
logger.trace_if('journal.locations', '"Location" event')
self.state['IsDocked'] = entry.get('Docked', False)
###############################################################
###############################################################
# Track: Current System
###############################################################
if 'StarPos' in entry:
# Plugins need this as well, so copy in state
self.state['StarPos'] = tuple(entry['StarPos'])
else:
logger.warning(f"'{event_type}' event without 'StarPos' !!!:\n{entry}\n")
if 'SystemAddress' not in entry:
logger.warning(f"{event_type} event without SystemAddress !!!:\n{entry}\n")
# But we'll still *use* the value, because if a 'location' event doesn't
# have this we've still moved and now don't know where and MUST NOT
# continue to use any old value.
# Yes, explicitly state `None` here, so it's crystal clear.
self.state['SystemAddress'] = entry.get('SystemAddress', None)
self.state['SystemPopulation'] = entry.get('Population')
if entry['StarSystem'] == 'ProvingGround':
self.state['SystemName'] = 'CQC'
else:
self.state['SystemName'] = entry['StarSystem']
###############################################################
###############################################################
# Track: Current station, if applicable
###############################################################
if event_type == 'fsdjump':
self.state['StationName'] = None
self.state['MarketID'] = None
self.state['StationType'] = None
self.stationservices = None
else:
self.state['StationName'] = entry.get('StationName') # It may be None
# If on foot in-station 'Docked' is false, but we have a
# 'BodyType' of 'Station', and the 'Body' is the station name
# NB: No MarketID
if entry.get('BodyType') and entry['BodyType'] == 'Station':
self.state['StationName'] = entry.get('Body')
self.state['MarketID'] = entry.get('MarketID') # May be None
self.state['StationType'] = entry.get('StationType') # May be None
self.stationservices = entry.get('StationServices') # None in Odyssey for on-foot 'Location'
###############################################################
###############################################################
# Track: Whether in a Taxi/Dropship
###############################################################
self.state['Taxi'] = entry.get('Taxi', None)
if not self.state['Taxi']:
self.state['Dropship'] = None
###############################################################
elif event_type == 'approachbody':
self.state['Body'] = entry['Body']
self.state['BodyID'] = entry.get('BodyID')
# This isn't in the event, but Journal doc for ApproachBody says:
# when in Supercruise, and distance from planet drops to within the 'Orbital Cruise' zone
# Used in plugins/eddn.py for setting entry Body/BodyType
# on 'docked' events when Planetary.
self.state['BodyType'] = 'Planet'
elif event_type == 'leavebody':