-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy patheddn.py
2699 lines (2238 loc) · 108 KB
/
eddn.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
"""
eddn.py - Exporting Data to EDDN.
Copyright (c) EDCD, All Rights Reserved
Licensed under the GNU General Public License.
See LICENSE file.
This is an EDMC 'core' plugin.
All EDMC plugins are *dynamically* loaded at run-time.
We build for Windows using `py2exe`.
`py2exe` can't possibly know about anything in the dynamically loaded core plugins.
Thus, you **MUST** check if any imports you add in this file are only
referenced in this file (or only in any other core plugin), and if so...
YOU MUST ENSURE THAT PERTINENT ADJUSTMENTS ARE MADE IN
`build.py` TO ENSURE THE FILES ARE ACTUALLY PRESENT
IN AN END-USER INSTALLATION ON WINDOWS.
"""
from __future__ import annotations
import http
import itertools
import json
import os
import pathlib
import re
import sqlite3
import tkinter as tk
from platform import system
from textwrap import dedent
from threading import Lock
from typing import Any, Iterator, Mapping, MutableMapping
import requests
import companion
import edmc_data
import killswitch
import myNotebook as nb # noqa: N813
import plug
from companion import CAPIData, category_map
from config import applongname, appname, appversion_nobuild, config, debug_senders, user_agent
from EDMCLogging import get_main_logger
from monitor import monitor
from myNotebook import Frame
from prefs import prefsVersion
from ttkHyperlinkLabel import HyperlinkLabel
from util import text
from l10n import translations as tr
logger = get_main_logger()
class This:
"""Holds module globals."""
def __init__(self):
# Game version and build
self.game_version = ""
self.game_build = ""
# Commander Name
self.cmdr_name = ""
# Track if we're on foot
self.on_foot = False
# Track if we're docked
self.docked = False
# Horizons ?
self.horizons = False
# Running under Odyssey?
self.odyssey = False
# Track location to add to Journal events
self.system_address: str | None = None
self.system_name: str | None = None
self.coordinates: tuple | None = None
self.body_name: str | None = None
self.body_id: int | None = None
self.body_type: int | None = None
self.station_name: str | None = None
self.station_type: str | None = None
self.station_marketid: str | None = None
# Track Status.json data
self.status_body_name: str | None = None
# Avoid duplicates
self.marketId: str | None = None
self.commodities: list[dict[str, Any]] | None = None
self.outfitting: tuple[bool, list[str]] | None = None
self.shipyard: tuple[bool, list[Mapping[str, Any]]] | None = None
self.fcmaterials_marketid: int = 0
self.fcmaterials: list[dict[str, Any]] | None = None
self.fcmaterials_capi_marketid: int = 0
self.fcmaterials_capi: list[dict[str, Any]] | None = None
# For the tkinter parent window, so we can call update_idletasks()
self.parent: tk.Tk
# To hold EDDN class instance
self.eddn: EDDN
# tkinter UI bits.
self.eddn_station: tk.IntVar
self.eddn_station_button: nb.Checkbutton
self.eddn_system: tk.IntVar
self.eddn_system_button: nb.Checkbutton
self.eddn_delay: tk.IntVar
self.eddn_delay_button: nb.Checkbutton
# Tracking UI
self.ui: tk.Frame
self.ui_system_name: tk.Label
self.ui_system_address: tk.Label
self.ui_j_body_name: tk.Label
self.ui_j_body_id: tk.Label
self.ui_j_body_type: tk.Label
self.ui_s_body_name: tk.Label
self.ui_station_name: tk.Label
self.ui_station_type: tk.Label
self.ui_station_marketid: tk.Label
this = This()
# This SKU is tagged on any module or ship that you must have Horizons for.
HORIZONS_SKU = 'ELITE_HORIZONS_V_PLANETARY_LANDINGS'
# ELITE_HORIZONS_V_COBRA_MK_IV_1000` is for the Cobra Mk IV, but
# is also available in the base game, if you have entitlement.
# `ELITE_HORIZONS_V_GUARDIAN_FSDBOOSTER` is for the Guardian FSD Boosters,
# which you need Horizons in order to unlock, but could be on sale even in the
# base game due to entitlement.
# Thus do **NOT** use either of these in addition to the PLANETARY_LANDINGS
# one.
class EDDNSender:
"""Handle sending of EDDN messages to the Gateway."""
SQLITE_DB_FILENAME_V1 = 'eddn_queue-v1.db'
# EDDN schema types that pertain to station data
STATION_SCHEMAS = ('commodity', 'fcmaterials_capi', 'fcmaterials_journal', 'outfitting', 'shipyard')
TIMEOUT = 10 # requests timeout
UNKNOWN_SCHEMA_RE = re.compile(
r"^FAIL: \[JsonValidationException\('Schema "
r"https://eddn.edcd.io/schemas/(?P<schema_name>.+)/(?P<schema_version>[0-9]+) is unknown, "
r"unable to validate.',\)]$"
)
def __init__(self, eddn: 'EDDN', eddn_endpoint: str) -> None:
"""
Prepare the system for processing messages.
- Ensure the sqlite3 database for EDDN replays exists and has schema.
- Convert any legacy file into the database.
- (Future) Handle any database migrations.
:param eddn: Reference to the `EDDN` instance this is for.
:param eddn_endpoint: Where messages should be sent.
"""
self.eddn = eddn
self.eddn_endpoint = eddn_endpoint
self.session = requests.Session()
self.session.headers['User-Agent'] = user_agent
self.db_conn = self.sqlite_queue_v1()
self.db = self.db_conn.cursor()
#######################################################################
# Queue database migration
#######################################################################
self.convert_legacy_file()
#######################################################################
self.queue_processing = Lock()
# Initiate retry/send-now timer
logger.trace_if(
"plugin.eddn.send",
f"First queue run scheduled for {self.eddn.REPLAY_STARTUP_DELAY}ms from now"
)
if not os.getenv("EDMC_NO_UI"):
self.eddn.parent.after(self.eddn.REPLAY_STARTUP_DELAY, self.queue_check_and_send, True)
def sqlite_queue_v1(self) -> sqlite3.Connection:
"""
Initialise a v1 EDDN queue database.
:return: sqlite3 connection
"""
db_conn = sqlite3.connect(config.app_dir_path / self.SQLITE_DB_FILENAME_V1)
db = db_conn.cursor()
try:
db.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created TEXT NOT NULL,
cmdr TEXT NOT NULL,
edmc_version TEXT,
game_version TEXT,
game_build TEXT,
message TEXT NOT NULL
)
""")
db.execute("CREATE INDEX IF NOT EXISTS messages_created ON messages (created)")
db.execute("CREATE INDEX IF NOT EXISTS messages_cmdr ON messages (cmdr)")
logger.info("New 'eddn_queue-v1.db' created")
except sqlite3.OperationalError as e:
if str(e) != "table messages already exists":
# Cleanup, as schema creation failed
db.close()
db_conn.close()
raise e
return db_conn
def convert_legacy_file(self):
"""Convert a legacy file's contents into the sqlite3 db."""
filename = config.app_dir_path / 'replay.jsonl'
try:
with open(filename, 'r+', buffering=1) as replay_file:
logger.info("Converting legacy `replay.jsonl` to `eddn_queue-v1.db`")
for line in replay_file:
cmdr, msg = json.loads(line)
self.add_message(cmdr, msg)
except FileNotFoundError:
return
logger.info("Conversion to `eddn_queue-v1.db` complete, removing `replay.jsonl`")
# Best effort at removing the file/contents
with open(filename, 'w') as replay_file:
replay_file.truncate()
os.unlink(filename)
def close(self) -> None:
"""Clean up any resources."""
logger.debug('Closing db cursor.')
if self.db:
self.db.close()
logger.debug('Closing db connection.')
if self.db_conn:
self.db_conn.close()
logger.debug('Closing EDDN requests.Session.')
self.session.close()
def add_message(self, cmdr: str, msg: MutableMapping[str, Any]) -> int:
"""
Add an EDDN message to the database.
`msg` absolutely needs to be the **FULL** EDDN message, including all
of `header`, `$schemaRef` and `message`. Code handling this not being
the case is only for loading the legacy `replay.json` file messages.
NB: Although `cmdr` *should* be the same as `msg->header->uploaderID`
we choose not to assume that.
:param cmdr: Name of the Commander that created this message.
:param msg: The full, transmission-ready, EDDN message.
:return: ID of the successfully inserted row.
"""
logger.trace_if("plugin.eddn.send", f"Message for {msg['$schemaRef']=}")
# Cater for legacy replay.json messages
if 'header' not in msg:
msg['header'] = {
# We have to lie and say it's *this* version, but denote that
# it might not actually be this version.
'softwareName': f'{applongname} [{system()}]'
' (legacy replay)',
'softwareVersion': str(appversion_nobuild()),
'uploaderID': cmdr,
'gameversion': '', # Can't add what we don't know
'gamebuild': '', # Can't add what we don't know
}
created = msg['message']['timestamp']
edmc_version = msg['header']['softwareVersion']
game_version = msg['header'].get('gameversion', '')
game_build = msg['header'].get('gamebuild', '')
uploader = msg['header']['uploaderID']
try:
self.db.execute(
"""
INSERT INTO messages (
created, cmdr, edmc_version, game_version, game_build, message
)
VALUES (
?, ?, ?, ?, ?, ?
)
""",
(created, uploader, edmc_version, game_version, game_build, json.dumps(msg))
)
self.db_conn.commit()
except Exception:
logger.exception('INSERT error')
# Can't possibly be a valid row id
return -1
logger.trace_if("plugin.eddn.send", f"Message for {msg['$schemaRef']=} recorded, id={self.db.lastrowid}")
return self.db.lastrowid or -1
def delete_message(self, row_id: int) -> None:
"""
Delete a queued message by row id.
:param row_id: id of message to be deleted.
"""
logger.trace_if("plugin.eddn.send", f"Deleting message with {row_id=}")
self.db.execute(
"""
DELETE FROM messages WHERE id = :row_id
""",
{'row_id': row_id}
)
self.db_conn.commit()
def send_message_by_id(self, id: int):
"""
Transmit the message identified by the given ID.
:param id:
:return:
"""
logger.trace_if("plugin.eddn.send", f"Sending message with {id=}")
self.db.execute(
"""
SELECT * FROM messages WHERE id = :row_id
""",
{'row_id': id}
)
row = dict(zip([c[0] for c in self.db.description], self.db.fetchone()))
try:
if self.send_message(row['message']):
self.delete_message(id)
return True
except requests.exceptions.HTTPError as e:
logger.warning(f"HTTPError: {str(e)}")
return False
def set_ui_status(self, text: str) -> None:
"""
Set the UI status text, if applicable.
When running as a CLI there is no such thing, so log to INFO instead.
:param text: The status text to be set/logged.
"""
if os.getenv('EDMC_NO_UI'):
logger.info(text)
return
self.eddn.parent.nametowidget(f".{appname.lower()}.status")['text'] = text
def send_message(self, msg: str) -> bool:
"""
Transmit a fully-formed EDDN message to the Gateway.
If this is called then the attempt *will* be made. This is not where
options to not send to EDDN, or to delay the sending until docked,
are checked.
It *is* however the one 'sending' place that the EDDN killswitches are checked.
Should catch and handle all failure conditions. A `True` return might
mean that the message was successfully sent, *or* that this message
should not be retried after a failure, i.e. too large.
:param msg: Fully formed, string, message.
:return: `True` for "now remove this message from the queue"
"""
logger.trace_if("plugin.eddn.send", "Sending message")
should_return: bool
new_data: dict[str, Any]
should_return, new_data = killswitch.check_killswitch('plugins.eddn.send', json.loads(msg))
if should_return:
logger.warning('eddn.send has been disabled via killswitch. Returning.')
return False
# Even the smallest possible message compresses somewhat, so always compress
encoded, compressed = text.gzip(json.dumps(new_data, separators=(',', ':')), max_size=0)
headers: dict[str, str] | None = None
if compressed:
headers = {'Content-Encoding': 'gzip'}
try:
r = self.session.post(self.eddn_endpoint, data=encoded, timeout=self.TIMEOUT, headers=headers)
if r.status_code == requests.codes.ok:
return True
if r.status_code == http.HTTPStatus.REQUEST_ENTITY_TOO_LARGE:
extra_data = {
'schema_ref': new_data.get('$schemaRef', 'Unset $schemaRef!'),
'sent_data_len': str(len(encoded)),
}
if '/journal/' in extra_data['schema_ref']:
extra_data['event'] = new_data.get('message', {}).get('event', 'No Event Set')
self._log_response(r, header_msg='Got "Payload Too Large" while POSTing data', **extra_data)
return True
self._log_response(r, header_msg="Status from POST wasn't 200 (OK)")
r.raise_for_status()
except requests.exceptions.HTTPError as e:
if unknown_schema := self.UNKNOWN_SCHEMA_RE.match(e.response.text): # type: ignore
logger.debug(f"EDDN doesn't (yet?) know about schema: {unknown_schema['schema_name']}"
f"/{unknown_schema['schema_version']}")
# This dropping is to cater for the time period when EDDN doesn't *yet* support a new schema.
return True
if e.response.status_code == http.HTTPStatus.BAD_REQUEST: # type: ignore
# EDDN straight up says no, so drop the message
logger.debug(f"EDDN responded '400 Bad Request' to the message, dropping:\n{msg!r}")
return True
# This should catch anything else, e.g. timeouts, gateway errors
self.set_ui_status(self.http_error_to_log(e))
except requests.exceptions.RequestException as e:
logger.debug('Failed sending', exc_info=e)
# LANG: Error while trying to send data to EDDN
self.set_ui_status(tr.tl("Error: Can't connect to EDDN"))
except Exception as e:
logger.debug('Failed sending', exc_info=e)
self.set_ui_status(str(e))
return False
def queue_check_and_send(self, reschedule: bool = False) -> None: # noqa: CCR001
"""
Check if we should be sending queued messages, and send if we should.
:param reschedule: Boolean indicating if we should call `after()` again.
"""
logger.trace_if("plugin.eddn.send", "Called")
# Mutex in case we're already processing
if not self.queue_processing.acquire(blocking=False):
logger.trace_if("plugin.eddn.send", "Couldn't obtain mutex")
if reschedule:
logger.trace_if(
"plugin.eddn.send",
f"Next run scheduled for {self.eddn.REPLAY_PERIOD}ms from now",
)
self.eddn.parent.after(
self.eddn.REPLAY_PERIOD, self.queue_check_and_send, reschedule
)
else:
logger.trace_if(
"plugin.eddn.send",
"NO next run scheduled (there should be another one already set)",
)
return
logger.trace_if("plugin.eddn.send", "Obtained mutex")
# Used to indicate if we've rescheduled at the faster rate already.
have_rescheduled = False
# We send either if docked or 'Delay sending until docked' not set
if this.docked or not config.get_int('output') & config.OUT_EDDN_DELAY:
logger.trace_if("plugin.eddn.send", "Should send")
# We need our own cursor here, in case the semantics of
# tk `after()` could allow this to run in the middle of other
# database usage.
db_cursor = self.db_conn.cursor()
# Options:
# 1. Process every queued message, regardless.
# 2. Bail if we get any sort of connection error from EDDN.
# Every queued message that is for *this* commander. We do **NOT**
# check if it's station/not-station, as the control of if a message
# was even created, versus the Settings > EDDN options, is applied
# *then*, not at time of sending.
try:
db_cursor.execute(
"""
SELECT id FROM messages
ORDER BY created
LIMIT 1
"""
)
except Exception:
logger.exception("DB error querying queued messages")
else:
row = db_cursor.fetchone()
if row:
row = dict(zip([c[0] for c in db_cursor.description], row))
if self.send_message_by_id(row['id']):
# If `True` was returned then we're done with this message.
# `False` means "failed to send, but not because the message
# is bad", i.e. an EDDN Gateway problem. Thus, in that case
# we do *NOT* schedule attempting the next message.
# Always re-schedule as this is only a "Don't hammer EDDN" delay
logger.trace_if("plugin.eddn.send", f"Next run scheduled for {self.eddn.REPLAY_DELAY}ms from "
"now")
self.eddn.parent.after(self.eddn.REPLAY_DELAY, self.queue_check_and_send, reschedule)
have_rescheduled = True
db_cursor.close()
else:
logger.trace_if("plugin.eddn.send", "Should NOT send")
self.queue_processing.release()
logger.trace_if("plugin.eddn.send", "Mutex released")
if reschedule and not have_rescheduled:
# Set us up to run again per the configured period
logger.trace_if("plugin.eddn.send", f"Next run scheduled for {self.eddn.REPLAY_PERIOD}ms from now")
self.eddn.parent.after(self.eddn.REPLAY_PERIOD, self.queue_check_and_send, reschedule)
def _log_response(
self,
response: requests.Response,
header_msg='Failed to POST to EDDN',
**kwargs
) -> None:
"""
Log a response object with optional additional data.
:param response: The response to log
:param header_msg: A header message to add to the log, defaults to 'Failed to POST to EDDN'
:param kwargs: Any other notes to add, will be added below the main data in the same format.
"""
additional_data = "\n".join(
f'''{name.replace('_', ' ').title():<8}:\t{value}''' for name, value in kwargs.items()
)
logger.debug(dedent(f'''\
{header_msg}:
Status :\t{response.status_code}
URL :\t{response.url}
Headers :\t{response.headers}
Content :\t{response.text}
''')+additional_data)
@staticmethod
def http_error_to_log(exception: requests.exceptions.HTTPError) -> str:
"""Convert an exception from raise_for_status to a log message and displayed error."""
status_code = exception.errno
if status_code == 429: # HTTP UPGRADE REQUIRED
logger.warning('EDMC is sending schemas that are too old')
# LANG: EDDN has banned this version of our client
return tr.tl('EDDN Error: EDMC is too old for EDDN. Please update.')
if status_code == 400:
# we a validation check or something else.
logger.warning(f'EDDN Error: {status_code} -- {exception.response}')
# LANG: EDDN returned an error that indicates something about what we sent it was wrong
return tr.tl('EDDN Error: Validation Failed (EDMC Too Old?). See Log')
logger.warning(f'Unknown status code from EDDN: {status_code} -- {exception.response}')
# LANG: EDDN returned some sort of HTTP error, one we didn't expect. {STATUS} contains a number
return tr.tl('EDDN Error: Returned {STATUS} status code').format(STATUS=status_code)
# TODO: a good few of these methods are static or could be classmethods. they should be created as such.
class EDDN:
"""EDDN Data export."""
DEFAULT_URL = 'https://eddn.edcd.io:4430/upload/'
if 'eddn' in debug_senders:
DEFAULT_URL = f'http://{edmc_data.DEBUG_WEBSERVER_HOST}:{edmc_data.DEBUG_WEBSERVER_PORT}/eddn'
# FIXME: Change back to `300_000`
REPLAY_STARTUP_DELAY = 10_000 # Delay during startup before checking queue [milliseconds]
REPLAY_PERIOD = 300_000 # How often to try (re-)sending the queue, [milliseconds]
REPLAY_DELAY = 400 # Roughly two messages per second, accounting for send delays [milliseconds]
REPLAYFLUSH = 20 # Update log on disk roughly every 10 seconds
MODULE_RE = re.compile(r'^Hpt_|^Int_|Armour_', re.IGNORECASE)
CANONICALISE_RE = re.compile(r'\$(.+)_name;')
CAPI_LOCALISATION_RE = re.compile(r'^loc[A-Z].+')
def __init__(self, parent: tk.Tk):
self.parent: tk.Tk = parent
if config.eddn_url is not None:
self.eddn_url = config.eddn_url
else:
self.eddn_url = self.DEFAULT_URL
self.sender = EDDNSender(self, self.eddn_url)
self.fss_signals: list[Mapping[str, Any]] = []
def close(self):
"""Close down the EDDN class instance."""
logger.debug('Closing Sender...')
if self.sender:
self.sender.close()
logger.debug('Done.')
def export_commodities(self, data: CAPIData, is_beta: bool) -> None: # noqa: CCR001
"""
Update EDDN with the commodities on the current (lastStarport) station.
Once the send is complete, this.commodities is updated with the new data.
NB: This does *not* go through the replaylog, unlike most of the
Journal-sourced data. This kind of timely data is often rejected by
listeners if 'too old' anyway, so little point.
:param data: a dict containing the starport data
:param is_beta: whether or not we're currently in beta mode
"""
should_return: bool
new_data: dict[str, Any]
should_return, new_data = killswitch.check_killswitch('capi.request./market', {})
if should_return:
logger.warning("capi.request./market has been disabled by killswitch. Returning.")
return
should_return, new_data = killswitch.check_killswitch('eddn.capi_export.commodities', {})
if should_return:
logger.warning("eddn.capi_export.commodities has been disabled by killswitch. Returning.")
return
modules, ships = self.safe_modules_and_ships(data)
horizons: bool = capi_is_horizons(
data['lastStarport'].get('economies', {}),
modules,
ships
)
commodities: list[dict[str, Any]] = []
for commodity in data['lastStarport'].get('commodities') or []:
# Check 'marketable' and 'not prohibited'
if (category_map.get(commodity['categoryname'], True)
and not commodity.get('legality')):
commodities.append({
'name': commodity['name'].lower(),
'meanPrice': int(commodity['meanPrice']),
'buyPrice': int(commodity['buyPrice']),
'stock': int(commodity['stock']),
'stockBracket': commodity['stockBracket'],
'sellPrice': int(commodity['sellPrice']),
'demand': int(commodity['demand']),
'demandBracket': commodity['demandBracket'],
})
if commodity['statusFlags']:
commodities[-1]['statusFlags'] = commodity['statusFlags']
commodities.sort(key=lambda c: c['name'])
# This used to have a check `commodities and ` at the start so as to
# not send an empty commodities list, as the EDDN Schema doesn't allow
# it (as of 2020-09-28).
# BUT, Fleet Carriers can go from having buy/sell orders to having
# none and that really does need to be recorded over EDDN so that
# tools can update in a timely manner.
if this.commodities != commodities:
message: dict[str, Any] = {
'timestamp': data['timestamp'],
'systemName': data['lastSystem']['name'],
'stationName': data['lastStarport']['name'],
'marketId': data['lastStarport']['id'],
'commodities': commodities,
'horizons': horizons,
'odyssey': this.odyssey,
}
if 'economies' in data['lastStarport']:
message['economies'] = sorted(
(x for x in (data['lastStarport']['economies'] or {}).values()), key=lambda x: x['name']
)
if 'prohibited' in data['lastStarport']:
message['prohibited'] = sorted(x for x in (data['lastStarport']['prohibited'] or {}).values())
self.send_message(data['commander']['name'], {
'$schemaRef': f'https://eddn.edcd.io/schemas/commodity/3{"/test" if is_beta else ""}',
'message': message,
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_MARKET
),
game_build=''
),
})
this.commodities = commodities
# Send any FCMaterials.json-equivalent 'orders' as well
self.export_capi_fcmaterials(data, is_beta, horizons)
def safe_modules_and_ships(self, data: Mapping[str, Any]) -> tuple[dict, dict]:
"""
Produce a sanity-checked version of ships and modules from CAPI data.
Principally this catches where the supplied CAPI data either doesn't
contain expected elements, or they're not of the expected type (e.g.
a list instead of a dict).
:param data: The raw CAPI data.
:return: Sanity-checked data.
"""
modules: dict[str, Any] = data['lastStarport'].get('modules')
if modules is None or not isinstance(modules, dict):
if modules is None:
logger.debug('modules was None. FC or Damaged Station?')
elif isinstance(modules, list):
if len(modules) == 0:
logger.debug('modules is empty list. FC or Damaged Station?')
else:
logger.error(f'modules is non-empty list: {modules!r}')
else:
logger.error(f'modules was not None, a list, or a dict! type = {type(modules)}')
# Set a safe value
modules = {}
ships: dict[str, Any] = data['lastStarport'].get('ships')
if ships is None or not isinstance(ships, dict):
if ships is None:
logger.debug('ships was None')
else:
logger.error(f'ships was neither None nor a dict! Type = {type(ships)}')
# Set a safe value
ships = {'shipyard_list': {}, 'unavailable_list': []}
return modules, ships
def export_outfitting(self, data: CAPIData, is_beta: bool) -> None:
"""
Update EDDN with the current (lastStarport) station's outfitting options, if any.
Once the send is complete, this.outfitting is updated with the given data.
NB: This does *not* go through the replaylog, unlike most of the
Journal-sourced data. This kind of timely data is often rejected by
listeners if 'too old' anyway, so little point.
:param data: dict containing the outfitting data
:param is_beta: whether or not we're currently in beta mode
"""
should_return: bool
new_data: dict[str, Any]
should_return, new_data = killswitch.check_killswitch('capi.request./shipyard', {})
if should_return:
logger.warning("capi.request./shipyard has been disabled by killswitch. Returning.")
return
should_return, new_data = killswitch.check_killswitch('eddn.capi_export.outfitting', {})
if should_return:
logger.warning("eddn.capi_export.outfitting has been disabled by killswitch. Returning.")
return
modules, ships = self.safe_modules_and_ships(data)
# Horizons flag - will hit at least Int_PlanetApproachSuite other than at engineer bases ("Colony"),
# prison or rescue Megaships, or under Pirate Attack etc
horizons: bool = capi_is_horizons(
data['lastStarport'].get('economies', {}),
modules,
ships
)
to_search: Iterator[Mapping[str, Any]] = filter(
lambda m: self.MODULE_RE.search(m['name']) and m.get('sku') in (None, HORIZONS_SKU)
and m['name'] != 'Int_PlanetApproachSuite', # noqa: E131
modules.values()
)
outfitting: list[str] = sorted(
self.MODULE_RE.sub(lambda match: match.group(0).capitalize(), mod['name'].lower()) for mod in to_search
)
# Don't send empty modules list - schema won't allow it
if outfitting and this.outfitting != (horizons, outfitting):
self.send_message(data['commander']['name'], {
'$schemaRef': f'https://eddn.edcd.io/schemas/outfitting/2{"/test" if is_beta else ""}',
'message': {
'timestamp': data['timestamp'],
'systemName': data['lastSystem']['name'],
'stationName': data['lastStarport']['name'],
'marketId': data['lastStarport']['id'],
'horizons': horizons,
'modules': outfitting,
'odyssey': this.odyssey,
},
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_SHIPYARD
),
game_build=''
),
})
this.outfitting = (horizons, outfitting)
def export_shipyard(self, data: CAPIData, is_beta: bool) -> None:
"""
Update EDDN with the current (lastStarport) station's outfitting options, if any.
Once the send is complete, this.shipyard is updated to the new data.
NB: This does *not* go through the replaylog, unlike most of the
Journal-sourced data. This kind of timely data is often rejected by
listeners if 'too old' anyway, so little point.
:param data: dict containing the shipyard data
:param is_beta: whether or not we are in beta mode
"""
should_return: bool
new_data: dict[str, Any]
should_return, new_data = killswitch.check_killswitch('capi.request./shipyard', {})
if should_return:
logger.warning("capi.request./shipyard has been disabled by killswitch. Returning.")
return
should_return, new_data = killswitch.check_killswitch('eddn.capi_export.shipyard', {})
if should_return:
logger.warning("eddn.capi_export.shipyard has been disabled by killswitch. Returning.")
return
modules, ships = self.safe_modules_and_ships(data)
horizons: bool = capi_is_horizons(
data['lastStarport'].get('economies', {}),
modules,
ships
)
shipyard: list[Mapping[str, Any]] = sorted(
itertools.chain(
(ship['name'].lower() for ship in (ships['shipyard_list'] or {}).values()),
(ship['name'].lower() for ship in ships['unavailable_list'] or {}),
)
)
# Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard.
if shipyard and this.shipyard != (horizons, shipyard):
self.send_message(data['commander']['name'], {
'$schemaRef': f'https://eddn.edcd.io/schemas/shipyard/2{"/test" if is_beta else ""}',
'message': {
'timestamp': data['timestamp'],
'systemName': data['lastSystem']['name'],
'stationName': data['lastStarport']['name'],
'marketId': data['lastStarport']['id'],
'horizons': horizons,
'ships': shipyard,
'odyssey': this.odyssey,
},
'header': self.standard_header(
game_version=self.capi_gameversion_from_host_endpoint(
data.source_host, companion.Session.FRONTIER_CAPI_PATH_SHIPYARD
),
game_build=''
),
})
this.shipyard = (horizons, shipyard)
def export_journal_commodities(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None:
"""
Update EDDN with Journal commodities data from the current station (lastStarport).
As a side effect, it also updates this.commodities with the data.
NB: This does *not* go through the replaylog, unlike most of the
Journal-sourced data. This kind of timely data is often rejected by
listeners if 'too old' anyway, so little point.
:param cmdr: The commander to send data under
:param is_beta: whether or not we're in beta mode
:param entry: the journal entry containing the commodities data
"""
items: list[Mapping[str, Any]] = entry.get('Items') or []
commodities: list[dict[str, Any]] = sorted(
(
{
'name': self.canonicalise(commodity['Name']),
'meanPrice': commodity['MeanPrice'],
'buyPrice': commodity['BuyPrice'],
'stock': commodity['Stock'],
'stockBracket': commodity['StockBracket'],
'sellPrice': commodity['SellPrice'],
'demand': commodity['Demand'],
'demandBracket': commodity['DemandBracket'],
}
for commodity in items
),
key=lambda c: c['name']
)
# This used to have a check `commodities and ` at the start so as to
# not send an empty commodities list, as the EDDN Schema doesn't allow
# it (as of 2020-09-28).
# BUT, Fleet Carriers can go from having buy/sell orders to having
# none and that really does need to be recorded over EDDN so that
# tools can update in a timely manner.
if this.commodities != commodities:
message: dict[str, Any] = { # Yes, this is a broad type hint.
'$schemaRef': f'https://eddn.edcd.io/schemas/commodity/3{"/test" if is_beta else ""}',
'message': {
'timestamp': entry['timestamp'],
'systemName': entry['StarSystem'],
'stationName': entry['StationName'],
'marketId': entry['MarketID'],
'commodities': commodities,
'horizons': this.horizons,
'odyssey': this.odyssey,
'stationType': entry['StationType'],
}
}
if entry.get('CarrierDockingAccess'):
message['message']['carrierDockingAccess'] = entry['CarrierDockingAccess']
self.send_message(cmdr, message)
this.commodities = commodities
def export_journal_outfitting(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None:
"""
Update EDDN with Journal oufitting data from the current station (lastStarport).
As a side effect, it also updates this.outfitting with the data.
NB: This does *not* go through the replaylog, unlike most of the
Journal-sourced data. This kind of timely data is often rejected by
listeners if 'too old' anyway, so little point.
:param cmdr: The commander to send data under
:param is_beta: Whether or not we're in beta mode
:param entry: The relevant journal entry
"""
modules: list[Mapping[str, Any]] = entry.get('Items', [])
horizons: bool = entry.get('Horizons', False)
# outfitting = sorted([self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), module['Name'])
# for module in modules if module['Name'] != 'int_planetapproachsuite'])
outfitting: list[str] = sorted(
self.MODULE_RE.sub(lambda m: m.group(0).capitalize(), mod['Name']) for mod in
filter(lambda m: m['Name'] != 'int_planetapproachsuite', modules)
)
# Don't send empty modules list - schema won't allow it
if outfitting and this.outfitting != (horizons, outfitting):
self.send_message(cmdr, {
'$schemaRef': f'https://eddn.edcd.io/schemas/outfitting/2{"/test" if is_beta else ""}',
'message': {
'timestamp': entry['timestamp'],
'systemName': entry['StarSystem'],
'stationName': entry['StationName'],
'marketId': entry['MarketID'],
'horizons': horizons,
'modules': outfitting,
'odyssey': entry['odyssey']
},
})
this.outfitting = (horizons, outfitting)
def export_journal_shipyard(self, cmdr: str, is_beta: bool, entry: Mapping[str, Any]) -> None:
"""
Update EDDN with Journal shipyard data from the current station (lastStarport).
As a side effect, this.shipyard is updated with the data.
NB: This does *not* go through the replaylog, unlike most of the
Journal-sourced data. This kind of timely data is often rejected by
listeners if 'too old' anyway, so little point.
:param cmdr: the commander to send this update under
:param is_beta: Whether or not we're in beta mode
:param entry: the relevant journal entry
"""
ships: list[Mapping[str, Any]] = entry.get('Pricelist') or []
horizons: bool = entry.get('Horizons', False)
shipyard = sorted(ship['ShipType'] for ship in ships)
# Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard.
if shipyard and this.shipyard != (horizons, shipyard):
self.send_message(cmdr, {
'$schemaRef': f'https://eddn.edcd.io/schemas/shipyard/2{"/test" if is_beta else ""}',
'message': {
'timestamp': entry['timestamp'],
'systemName': entry['StarSystem'],
'stationName': entry['StationName'],
'marketId': entry['MarketID'],
'horizons': horizons,
'ships': shipyard,