forked from EDCD/EDMarketConnector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.py
2162 lines (1755 loc) · 95.5 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 for new Journal files and contents of latest."""
import json
import pathlib
import queue
import re
import threading
from calendar import timegm
from collections import OrderedDict, defaultdict
from os import SEEK_END, SEEK_SET, listdir
from os.path import basename, expanduser, isdir, join
from sys import platform
from time import gmtime, localtime, sleep, strftime, strptime, time
from typing import TYPE_CHECKING, Any, BinaryIO, Dict, List, MutableMapping, Optional
from typing import OrderedDict as OrderedDictT
from typing import Tuple
if TYPE_CHECKING:
import tkinter
import util_ships
from config import config
from edmc_data import edmc_suit_shortnames, edmc_suit_symbol_localised
from EDMCLogging import get_main_logger
logger = get_main_logger()
STARTUP = 'journal.startup'
if TYPE_CHECKING:
def _(x: str) -> str:
return x
if platform == 'darwin':
from fcntl import fcntl
from AppKit import NSWorkspace
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
F_GLOBAL_NOCACHE = 55
elif platform == 'win32':
import ctypes
from ctypes.wintypes import BOOL, HWND, LPARAM, LPWSTR
from watchdog.events import FileCreatedEvent, FileSystemEventHandler
from watchdog.observers import Observer
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM)
CloseHandle = ctypes.windll.kernel32.CloseHandle
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowText.argtypes = [HWND, LPWSTR, ctypes.c_int]
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
GetProcessHandleFromHwnd = ctypes.windll.oleacc.GetProcessHandleFromHwnd
else:
# Linux's inotify doesn't work over CIFS or NFS, so poll
FileSystemEventHandler = object # dummy
# Journal handler
class EDLogs(FileSystemEventHandler): # type: ignore # See below
"""Monitoring of Journal files."""
# Magic with FileSystemEventHandler can confuse type checkers when they do not have access to every import
_POLL = 1 # Polling is cheap, so do it often
_RE_CANONICALISE = re.compile(r'\$(.+)_name;')
_RE_CATEGORY = re.compile(r'\$MICRORESOURCE_CATEGORY_(.+);')
_RE_LOGFILE = re.compile(r'^Journal(Alpha|Beta)?\.[0-9]{12}\.[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: Optional[str] = None # The actual logdir that we're monitoring
self.logfile: Optional[str] = None
self.observer: Optional['Observer'] = None
self.observed = None # a watchdog ObservedWatch, or None if polling
self.thread: Optional[threading.Thread] = 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
self.game_was_running = False # For generation of the "ShutDown" event
# Context for journal handling
self.version: Optional[str] = None
self.is_beta = False
self.mode: Optional[str] = None
self.group: Optional[str] = None
self.cmdr: Optional[str] = None
self.planet: Optional[str] = None
self.system: Optional[str] = None
self.station: Optional[str] = None
self.station_marketid: Optional[int] = None
self.stationtype: Optional[str] = None
self.coordinates: Optional[Tuple[float, float, float]] = None
self.systemaddress: Optional[int] = None
self.systempopulation: Optional[int] = None
self.started: Optional[int] = None # Timestamp of the LoadGame event
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
'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.
'Body': None,
'BodyType': 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 # type: ignore
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. Assumes logs sort alphabetically.
# 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
logfiles = sorted(
(x for x in listdir(self.currentdir) if self._RE_LOGFILE.search(x)),
key=lambda x: x.split('.')[1:]
)
self.logfile = join(self.currentdir, logfiles[-1]) if logfiles else None # type: ignore
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 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 stop(self) -> None:
"""Stop journal monitoring."""
logger.debug('Stopping monitoring Journal')
self.currentdir = None
self.version = None
self.mode = None
self.group = None
self.cmdr = None
self.planet = None
self.system = None
self.station = None
self.station_marketid = None
self.stationtype = None
self.stationservices = None
self.coordinates = None
self.systemaddress = None
self.is_beta = False
self.state['OnFoot'] = False
self.state['Body'] = None
self.state['BodyType'] = None
if self.observed:
logger.debug('self.observed: Calling unschedule_all()')
self.observed = None
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: 'FileCreatedEvent') -> 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
if platform == 'darwin':
fcntl(loghandle, F_GLOBAL_NOCACHE, -1) # required to avoid corruption on macOS over SMB
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)
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:
# Game is running locally
entry: OrderedDictT[str, Any] = OrderedDict([
('timestamp', strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())),
('event', 'StartUp'),
('StarSystem', self.system),
('StarPos', self.coordinates),
('SystemAddress', self.systemaddress),
('Population', self.systempopulation),
])
if self.planet:
entry['Body'] = self.planet
entry['Docked'] = bool(self.station)
if self.station:
entry['StationName'] = self.station
entry['StationType'] = self.stationtype
entry['MarketID'] = self.station_marketid
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
# 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.
emitter = self.observed and self.observer._emitter_for_watch[self.observed] # Note: Uses undocumented attribute
logger.debug('Entering loop...')
while True:
# Check whether new log file started, e.g. client (re)started.
if emitter and emitter.is_alive():
newlogfile = self.logfile # updated by on_created watchdog callback
else:
# Poll
try:
logfiles = sorted(
(x for x in listdir(self.currentdir) if self._RE_LOGFILE.search(x)),
key=lambda x: x.split('.')[1:]
)
newlogfile = join(self.currentdir, logfiles[-1]) if logfiles else None # type: ignore
except Exception:
logger.exception('Failed to find latest logfile')
newlogfile = None
if logfile:
loghandle.seek(0, SEEK_END) # required to make macOS notice log change over SMB
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 != newlogfile:
for _ in range(10):
logger.trace_if('journal.file', "****")
logger.info(f'New Journal File. Was "{logfile}", now "{newlogfile}"')
logfile = newlogfile
if loghandle:
loghandle.close()
if logfile:
loghandle = open(logfile, 'rb', 0) # unbuffered
if platform == 'darwin':
fcntl(loghandle, F_GLOBAL_NOCACHE, -1) # required to avoid corruption on macOS over SMB
log_pos = 0
sleep(self._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()
logger.debug('Done.')
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, object_pairs_hook=OrderedDict)
entry['timestamp'] # we expect this to exist # TODO: replace with assert? or an if key in check
event_type = entry['event'].lower()
if event_type == 'fileheader':
self.live = False
self.cmdr = None
self.mode = None
self.group = None
self.planet = None
self.system = None
self.station = None
self.station_marketid = None
self.stationtype = None
self.stationservices = None
self.coordinates = None
self.systemaddress = 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.planet = None
self.system = None
self.station = None
self.station_marketid = None
self.stationtype = None
self.stationservices = None
self.coordinates = None
self.systemaddress = 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,
'Body': None,
'BodyType': 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
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.station = None
self.station_marketid = None
self.stationtype = None
self.stationservices = None
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 transposrt 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.station = None
if entry.get('OnStation'):
self.station = entry.get('StationName', '')
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 transposrt 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.station = entry.get('StationName', '')
else:
self.station = 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 == 'docked':
self.station = entry.get('StationName') # May be None
self.station_marketid = entry.get('MarketID') # May be None
self.stationtype = entry.get('StationType') # 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 its those, the next event is a Disembark anyway
elif event_type in ('location', 'fsdjump', 'carrierjump'):
# alpha4 - any changes ?
# Location:
# New in Odyssey:
# • Taxi: bool
# • Multicrew: bool
# • InSRV: bool
# • OnFoot: bool
if event_type in ('location', 'carrierjump'):
self.planet = entry.get('Body') if entry.get('BodyType') == 'Planet' else None
self.state['Body'] = entry.get('Body')
self.state['BodyType'] = entry.get('BodyType')
if event_type == 'location':
logger.trace_if('journal.locations', '"Location" event')
elif event_type == 'fsdjump':
self.planet = None
self.state['Body'] = None
self.state['BodyType'] = None
if 'StarPos' in entry:
self.coordinates = tuple(entry['StarPos']) # type: ignore
self.systemaddress = entry.get('SystemAddress')
self.systempopulation = entry.get('Population')
self.system = 'CQC' if entry['StarSystem'] == 'ProvingGround' else entry['StarSystem']
self.station = entry.get('StationName') # 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.station = entry.get('Body')
self.station_marketid = entry.get('MarketID') # May be None
self.stationtype = entry.get('StationType') # May be None
self.stationservices = entry.get('StationServices') # None in Odyssey for on-foot 'Location'
self.state['Taxi'] = entry.get('Taxi', None)
if not self.state['Taxi']:
self.state['Dropship'] = None
elif event_type == 'approachbody':
self.planet = entry['Body']
self.state['Body'] = entry['Body']
self.state['BodyType'] = 'Planet' # Best guess. Journal says always planet.
elif event_type in ('leavebody', 'supercruiseentry'):
self.planet = None
self.state['Body'] = None
self.state['BodyType'] = None
elif event_type in ('rank', 'promotion'):
payload = dict(entry)
payload.pop('event')
payload.pop('timestamp')
self.state['Rank'].update({k: (v, 0) for k, v in payload.items()})
elif event_type == 'progress':
rank = self.state['Rank']
for k, v in entry.items():
if k in rank:
# perhaps not taken promotion mission yet
rank[k] = (rank[k][0], min(v, 100))
elif event_type in ('reputation', 'statistics'):
payload = OrderedDict(entry)
payload.pop('event')
payload.pop('timestamp')
# NB: We need the original casing for these keys
self.state[entry['event']] = payload
elif event_type == 'engineerprogress':
# Sanity check - at least once the 'Engineer' (name) was missing from this in early
# Odyssey 4.0.0.100. Might only have been a server issue causing incomplete data.
if self.event_valid_engineerprogress(entry):
engineers = self.state['Engineers']
if 'Engineers' in entry: # Startup summary
self.state['Engineers'] = {
e['Engineer']: ((e['Rank'], e.get('RankProgress', 0)) if 'Rank' in e else e['Progress'])
for e in entry['Engineers']
}
else: # Promotion
engineer = entry['Engineer']
if 'Rank' in entry:
engineers[engineer] = (entry['Rank'], entry.get('RankProgress', 0))
else:
engineers[engineer] = entry['Progress']
elif event_type == 'cargo' and entry.get('Vessel') == 'Ship':
self.state['Cargo'] = defaultdict(int)
# From 3.3 full Cargo event (after the first one) is written to a separate file
if 'Inventory' not in entry:
with open(join(self.currentdir, 'Cargo.json'), 'rb') as h: # type: ignore
entry = json.load(h, object_pairs_hook=OrderedDict) # Preserve property order because why not?
self.state['CargoJSON'] = entry
clean = self.coalesce_cargo(entry['Inventory'])
self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in clean})
elif event_type == 'cargotransfer':
for c in entry['Transfers']:
name = self.canonicalise(c['Type'])
if c['Direction'] == 'toship':
self.state['Cargo'][name] += c['Count']
else:
# So it's *from* the ship
self.state['Cargo'][name] -= c['Count']
elif event_type == 'shiplocker':
# As of 4.0.0.400 (2021-06-10)
# "ShipLocker" will be a full list written to the journal at startup/boarding, and also
# written to a separate shiplocker.json file - other updates will just update that file and mention it
# has changed with an empty shiplocker event in the main journal.
# Always attempt loading of this, but if it fails we'll hope this was
# a startup/boarding version and thus `entry` contains
# the data anyway.
currentdir_path = pathlib.Path(str(self.currentdir))
shiplocker_filename = currentdir_path / 'ShipLocker.json'
shiplocker_max_attempts = 5
shiplocker_fail_sleep = 0.01
attempts = 0
while attempts < shiplocker_max_attempts:
attempts += 1
try:
with open(shiplocker_filename, 'rb') as h: # type: ignore
entry = json.load(h, object_pairs_hook=OrderedDict)
self.state['ShipLockerJSON'] = entry
break
except FileNotFoundError:
logger.warning('ShipLocker event but no ShipLocker.json file')
sleep(shiplocker_fail_sleep)
pass
except json.JSONDecodeError as e:
logger.warning(f'ShipLocker.json failed to decode:\n{e!r}\n')
sleep(shiplocker_fail_sleep)
pass
else:
logger.warning(f'Failed to load & decode shiplocker after {shiplocker_max_attempts} tries. '
'Giving up.')
if not all(t in entry for t in ('Components', 'Consumables', 'Data', 'Items')):
logger.warning('ShipLocker event is missing at least one category')
# This event has the current totals, so drop any current data
self.state['Component'] = defaultdict(int)
self.state['Consumable'] = defaultdict(int)
self.state['Item'] = defaultdict(int)
self.state['Data'] = defaultdict(int)
clean_components = self.coalesce_cargo(entry['Components'])
self.state['Component'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_components}
)
clean_consumables = self.coalesce_cargo(entry['Consumables'])
self.state['Consumable'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_consumables}
)
clean_items = self.coalesce_cargo(entry['Items'])
self.state['Item'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_items}
)
clean_data = self.coalesce_cargo(entry['Data'])
self.state['Data'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_data}
)
# Journal v31 implies this was removed before Odyssey launch
elif event_type == 'backpackmaterials':
# Last seen in a 4.0.0.102 journal file.
logger.warning(f'We have a BackPackMaterials event, defunct since > 4.0.0.102 ?:\n{entry}\n')
pass
elif event_type in ('backpack', 'resupply'):
# as of v4.0.0.600, a `resupply` event is dropped when resupplying your suit at your ship.
# This event writes the same data as a backpack event. It will also be followed by a ShipLocker
# but that follows normal behaviour in its handler.
# TODO: v31 doc says this is`backpack.json` ... but Howard Chalkley
# said it's `Backpack.json`
backpack_file = pathlib.Path(str(self.currentdir)) / 'Backpack.json'
backpack_data = None
if not backpack_file.exists():
logger.warning(f'Failed to find backpack.json file as it appears not to exist? {backpack_file=}')
else:
backpack_data = backpack_file.read_bytes()
parsed = None
if backpack_data is None:
logger.warning('Unable to read backpack data!')
elif len(backpack_data) == 0:
logger.warning('Backpack.json was empty when we read it!')
else:
try:
parsed = json.loads(backpack_data)
except json.JSONDecodeError:
logger.exception('Unable to parse Backpack.json')
if parsed is not None:
entry = parsed # set entry so that it ends up in plugins with the right data
# Store in monitor.state
self.state['BackpackJSON'] = entry
# Assume this reflects the current state when written
self.backpack_set_empty()
clean_components = self.coalesce_cargo(entry['Components'])
self.state['BackPack']['Component'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_components}
)
clean_consumables = self.coalesce_cargo(entry['Consumables'])
self.state['BackPack']['Consumable'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_consumables}
)
clean_items = self.coalesce_cargo(entry['Items'])
self.state['BackPack']['Item'].update(
{self.canonicalise(x['Name']): x['Count'] for x in clean_items}
)
clean_data = self.coalesce_cargo(entry['Data'])
self.state['BackPack']['Data'].update(