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

[635] Remove Ordered Dict

This commit is contained in:
David Sangrey 2024-01-03 23:55:12 -05:00
parent 5419e2e47f
commit 7cac00b2e8
No known key found for this signature in database
GPG Key ID: 3AEADBB0186884BC
8 changed files with 172 additions and 167 deletions

View File

@ -28,7 +28,7 @@ import urllib.parse
import webbrowser
from email.utils import parsedate
from queue import Queue
from typing import TYPE_CHECKING, Any, Mapping, OrderedDict, TypeVar
from typing import TYPE_CHECKING, Any, Mapping, TypeVar
import requests
import config as conf_module
import killswitch
@ -1328,7 +1328,7 @@ def index_possibly_sparse_list(data: Mapping[str, V] | list[V], key: int) -> V:
if isinstance(data, list):
return data[key]
if isinstance(data, (dict, OrderedDict)):
if isinstance(data, (dict, dict)):
return data[str(key)]
raise ValueError(f'Unexpected data type {type(data)}')

View File

@ -16,7 +16,6 @@ FDevIDs/ version of the file, copy it over the local one.
import json
import subprocess
import sys
from collections import OrderedDict
import outfitting
from edmc_data import coriolis_ship_map, ship_name_map
@ -56,7 +55,7 @@ if __name__ == "__main__":
for i, bulkhead in enumerate(bulkheads):
modules['_'.join([reverse_ship_map[name], 'armour', bulkhead])] = {'mass': m['bulkheads'][i]['mass']}
ships = OrderedDict([(k, ships[k]) for k in sorted(ships)]) # sort for easier diffing
ships = {k: ships[k] for k in sorted(ships)}
with open("ships.json", "w") as ships_file:
json.dump(ships, ships_file, indent=4)
@ -91,6 +90,6 @@ if __name__ == "__main__":
add(modules, 'hpt_multicannon_fixed_small_advanced', {'mass': 2})
add(modules, 'hpt_multicannon_fixed_medium_advanced', {'mass': 4})
modules = OrderedDict([(k, modules[k]) for k in sorted(modules)]) # sort for easier diffing
modules = {k: modules[k] for k in sorted(modules)}
with open("modules.json", "w") as modules_file:
json.dump(modules, modules_file, indent=4)

View File

@ -4,7 +4,6 @@ Static data.
For easy reference any variable should be prefixed with the name of the file it
was either in originally, or where the primary code utilising it is.
"""
from collections import OrderedDict
# Map numeric 'demand/supply brackets' to the names as shown in-game.
commodity_bracketmap = {
@ -57,13 +56,14 @@ edshipyard_slot_map = {
# Map API module names to in-game names
outfitting_armour_map = OrderedDict([
('grade1', 'Lightweight Alloy'),
('grade2', 'Reinforced Alloy'),
('grade3', 'Military Grade Composite'),
('mirrored', 'Mirrored Surface Composite'),
('reactive', 'Reactive Surface Composite'),
])
outfitting_armour_map = {
'grade1': 'Lightweight Alloy',
'grade2': 'Reinforced Alloy',
'grade3': 'Military Grade Composite',
'mirrored': 'Mirrored Surface Composite',
'reactive': 'Reactive Surface Composite',
}
outfitting_weapon_map = {
'advancedtorppylon': 'Torpedo Pylon',

View File

@ -16,7 +16,6 @@ import numbers
import re
import sys
import warnings
from collections import OrderedDict
from contextlib import suppress
from os import pardir, listdir, sep, makedirs
from os.path import basename, dirname, isdir, isfile, join, abspath, exists
@ -192,10 +191,10 @@ class _Translations:
def available_names(self) -> dict[str | None, str]:
"""Available language names by code."""
names: dict[str | None, str] = OrderedDict([
names: dict[str | None, str] = {
# LANG: The system default language choice in Settings > Appearance
(None, _('Default')), # Appearance theme and language setting
])
None: _('Default'), # Appearance theme and language setting
}
names.update(sorted(
[(lang, self.contents(lang).get(LANGUAGE_ID, lang)) for lang in self.available()] +
[(_Translations.FALLBACK, _Translations.FALLBACK_NAME)],

View File

@ -14,7 +14,7 @@ import re
import sys
import threading
from calendar import timegm
from collections import OrderedDict, defaultdict
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
@ -567,7 +567,7 @@ class EDLogs(FileSystemEventHandler):
try:
# Preserve property order because why not?
entry: MutableMapping[str, Any] = json.loads(line, object_pairs_hook=OrderedDict)
entry: MutableMapping[str, Any] = json.loads(line)
assert 'timestamp' in entry, "Timestamp does not exist in the entry"
self.__navroute_retry()
@ -1042,7 +1042,7 @@ class EDLogs(FileSystemEventHandler):
rank[k] = (rank[k][0], min(v, 100))
elif event_type in ('reputation', 'statistics'):
payload = OrderedDict(entry)
payload = dict(entry)
payload.pop('event')
payload.pop('timestamp')
# NB: We need the original casing for these keys
@ -1073,7 +1073,7 @@ class EDLogs(FileSystemEventHandler):
# 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?
entry = json.load(h) # Preserve property order because why not?
self.state['CargoJSON'] = entry
clean = self.coalesce_cargo(entry['Inventory'])
@ -1108,7 +1108,7 @@ class EDLogs(FileSystemEventHandler):
attempts += 1
try:
with open(shiplocker_filename, 'rb') as h:
entry = json.load(h, object_pairs_hook=OrderedDict)
entry = json.load(h)
self.state['ShipLockerJSON'] = entry
break
@ -2189,7 +2189,7 @@ class EDLogs(FileSystemEventHandler):
'PowerDistributor', 'Radar', 'FuelTank'
)
d: MutableMapping[str, Any] = OrderedDict()
d: MutableMapping[str, Any] = {}
if timestamped:
d['timestamp'] = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())

View File

@ -8,8 +8,6 @@ See LICENSE file.
from __future__ import annotations
import json
from collections import OrderedDict
from typing import OrderedDict as OrderedDictT
from config import config
from edmc_data import (
outfitting_armour_map as armour_map,
@ -36,7 +34,7 @@ from EDMCLogging import get_main_logger
logger = get_main_logger()
# Module mass, FSD data etc
moduledata: OrderedDictT = OrderedDict()
moduledata: dict = {}
def lookup(module, ship_map, entitled=False) -> dict | None: # noqa: C901, CCR001

View File

@ -29,7 +29,6 @@ import re
import sqlite3
import sys
import tkinter as tk
from collections import OrderedDict
from platform import system
from textwrap import dedent
from threading import Lock
@ -40,7 +39,6 @@ from typing import (
Mapping,
MutableMapping,
)
from typing import OrderedDict as OrderedDictT
import requests
import companion
import edmc_data
@ -98,13 +96,13 @@ class This:
# Avoid duplicates
self.marketId: str | None = None
self.commodities: list[OrderedDictT[str, Any]] | 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[OrderedDictT[str, Any]] | None = None
self.fcmaterials: list[dict[str, Any]] | None = None
self.fcmaterials_capi_marketid: int = 0
self.fcmaterials_capi: list[OrderedDictT[str, Any]] | None = None
self.fcmaterials_capi: list[dict[str, Any]] | None = None
# For the tkinter parent window, so we can call update_idletasks()
self.parent: tk.Tk
@ -651,21 +649,21 @@ class EDDN:
modules,
ships
)
commodities: list[OrderedDictT[str, Any]] = []
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(OrderedDict([
('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']),
]))
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']
@ -679,15 +677,15 @@ class EDDN:
# 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: OrderedDictT[str, Any] = OrderedDict([
('timestamp', data['timestamp']),
('systemName', data['lastSystem']['name']),
('stationName', data['lastStarport']['name']),
('marketId', data['lastStarport']['id']),
('commodities', commodities),
('horizons', horizons),
('odyssey', this.odyssey),
])
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(
@ -802,7 +800,7 @@ class EDDN:
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': OrderedDict([
'message': {
('timestamp', data['timestamp']),
('systemName', data['lastSystem']['name']),
('stationName', data['lastStarport']['name']),
@ -810,7 +808,7 @@ class EDDN:
('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
@ -864,7 +862,7 @@ class EDDN:
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': OrderedDict([
'message': {
('timestamp', data['timestamp']),
('systemName', data['lastSystem']['name']),
('stationName', data['lastStarport']['name']),
@ -872,7 +870,7 @@ class EDDN:
('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
@ -898,16 +896,22 @@ class EDDN:
:param entry: the journal entry containing the commodities data
"""
items: list[Mapping[str, Any]] = entry.get('Items') or []
commodities: list[OrderedDictT[str, Any]] = sorted((OrderedDict([
('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'])
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
@ -918,7 +922,7 @@ class EDDN:
if this.commodities != commodities:
self.send_message(cmdr, {
'$schemaRef': f'https://eddn.edcd.io/schemas/commodity/3{"/test" if is_beta else ""}',
'message': OrderedDict([
'message': {
('timestamp', entry['timestamp']),
('systemName', entry['StarSystem']),
('stationName', entry['StationName']),
@ -926,7 +930,7 @@ class EDDN:
('commodities', commodities),
('horizons', this.horizons),
('odyssey', this.odyssey),
]),
},
})
this.commodities = commodities
@ -957,7 +961,7 @@ class EDDN:
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': OrderedDict([
'message': {
('timestamp', entry['timestamp']),
('systemName', entry['StarSystem']),
('stationName', entry['StationName']),
@ -965,7 +969,7 @@ class EDDN:
('horizons', horizons),
('modules', outfitting),
('odyssey', entry['odyssey'])
]),
},
})
this.outfitting = (horizons, outfitting)
@ -991,7 +995,7 @@ class EDDN:
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': OrderedDict([
'message': {
('timestamp', entry['timestamp']),
('systemName', entry['StarSystem']),
('stationName', entry['StationName']),
@ -999,7 +1003,7 @@ class EDDN:
('horizons', horizons),
('ships', shipyard),
('odyssey', entry['odyssey'])
]),
},
})
# this.shipyard = (horizons, shipyard)
@ -2182,14 +2186,14 @@ def plugin_stop() -> None:
logger.debug('Done.')
def filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]:
def filter_localised(d: Mapping[str, Any]) -> dict[str, Any]:
"""
Recursively remove any dict keys with names ending `_Localised` from a dict.
:param d: dict to filter keys of.
:return: The filtered dict.
"""
filtered: OrderedDictT[str, Any] = OrderedDict()
filtered: dict[str, Any] = {}
for k, v in d.items():
if k.endswith('_Localised'):
pass
@ -2206,14 +2210,14 @@ def filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]:
return filtered
def capi_filter_localised(d: Mapping[str, Any]) -> OrderedDictT[str, Any]:
def capi_filter_localised(d: Mapping[str, Any]) -> dict[str, Any]:
"""
Recursively remove any dict keys for known CAPI 'localised' names.
:param d: dict to filter keys of.
:return: The filtered dict.
"""
filtered: OrderedDictT[str, Any] = OrderedDict()
filtered: dict[str, Any] = {}
for k, v in d.items():
if EDDN.CAPI_LOCALISATION_RE.search(k):
pass

View File

@ -24,14 +24,13 @@ import json
import threading
import time
import tkinter as tk
from collections import OrderedDict, defaultdict, deque
from collections import defaultdict, deque
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from operator import itemgetter
from threading import Lock, Thread
from tkinter import ttk
from typing import TYPE_CHECKING, Any, Callable, Deque, Mapping, NamedTuple, Sequence, cast, Union
from typing import OrderedDict as OrderedDictT
import requests
import edmc_data
import killswitch
@ -102,12 +101,12 @@ class This:
self.newsession: bool = True # starting a new session - wait for Cargo event
self.undocked: bool = False # just undocked
self.suppress_docked = False # Skip initial Docked event if started docked
self.cargo: list[OrderedDictT[str, Any]] | None = None
self.materials: list[OrderedDictT[str, Any]] | None = None
self.cargo: list[dict[str, Any]] | None = None
self.materials: list[dict[str, Any]] | None = None
self.last_credits: int = 0 # Send credit update soon after Startup / new game
self.storedmodules: list[OrderedDictT[str, Any]] | None = None
self.loadout: OrderedDictT[str, Any] | None = None
self.fleet: list[OrderedDictT[str, Any]] | None = None
self.storedmodules: list[dict[str, Any]] | None = None
self.loadout: dict[str, Any] | None = None
self.fleet: list[dict[str, Any]] | None = None
self.shipswap: bool = False # just swapped ship
self.on_foot = False
@ -721,13 +720,13 @@ def journal_entry( # noqa: C901, CCR001
this.suppress_docked = True
# Send cargo and materials if changed
cargo = [OrderedDict({'itemName': k, 'itemCount': state['Cargo'][k]}) for k in sorted(state['Cargo'])]
cargo = [{'itemName': k, 'itemCount': state['Cargo'][k]} for k in sorted(state['Cargo'])]
if this.cargo != cargo:
new_add_event('setCommanderInventoryCargo', entry['timestamp'], cargo)
this.cargo = cargo
materials = [
OrderedDict([('itemName', k), ('itemCount', state[category][k])])
{'itemName': k, 'itemCount': state[category][k]}
for category in ('Raw', 'Manufactured', 'Encoded')
for k in sorted(state[category])
]
@ -823,24 +822,30 @@ def journal_entry( # noqa: C901, CCR001
# Fleet
if event_name == 'StoredShips':
fleet: list[OrderedDictT[str, Any]] = sorted(
[OrderedDict({
'shipType': x['ShipType'],
'shipGameID': x['ShipID'],
'shipName': x.get('Name'),
'isHot': x['Hot'],
'starsystemName': entry['StarSystem'],
'stationName': entry['StationName'],
'marketID': entry['MarketID'],
}) for x in entry['ShipsHere']] +
[OrderedDict({
'shipType': x['ShipType'],
'shipGameID': x['ShipID'],
'shipName': x.get('Name'),
'isHot': x['Hot'],
'starsystemName': x.get('StarSystem'), # Not present for ships in transit
'marketID': x.get('ShipMarketID'), # "
}) for x in entry['ShipsRemote']],
fleet = sorted(
[
{
'shipType': x['ShipType'],
'shipGameID': x['ShipID'],
'shipName': x.get('Name'),
'isHot': x['Hot'],
'starsystemName': entry['StarSystem'],
'stationName': entry['StationName'],
'marketID': entry['MarketID'],
}
for x in entry['ShipsHere']
] +
[
{
'shipType': x['ShipType'],
'shipGameID': x['ShipID'],
'shipName': x.get('Name'),
'isHot': x['Hot'],
'starsystemName': x.get('StarSystem'), # Not present for ships in transit
'marketID': x.get('ShipMarketID'), # "
}
for x in entry['ShipsRemote']
],
key=itemgetter('shipGameID')
)
@ -851,7 +856,6 @@ def journal_entry( # noqa: C901, CCR001
# this.events = [x for x in this.events if x['eventName'] != 'setCommanderShip'] # Remove any unsent
for ship in this.fleet:
new_add_event('setCommanderShip', entry['timestamp'], ship)
# Loadout
if event_name == 'Loadout' and not this.newsession:
loadout = make_loadout(state)
@ -870,14 +874,14 @@ def journal_entry( # noqa: C901, CCR001
# Stored modules
if event_name == 'StoredModules':
items = {mod['StorageSlot']: mod for mod in entry['Items']} # Impose an order
modules: list[OrderedDictT[str, Any]] = []
modules: list[dict[str, Any]] = []
for slot in sorted(items):
item = items[slot]
module: OrderedDictT[str, Any] = OrderedDict([
('itemName', item['Name']),
('itemValue', item['BuyPrice']),
('isHot', item['Hot']),
])
module: dict[str, Any] = {
'itemName': item['Name'],
'itemValue': item['BuyPrice'],
'isHot': item['Hot'],
}
# Location can be absent if in transit
if 'StarSystem' in item:
@ -887,7 +891,7 @@ def journal_entry( # noqa: C901, CCR001
module['marketID'] = item['MarketID']
if 'EngineerModifications' in item:
module['engineering'] = OrderedDict([('blueprintName', item['EngineerModifications'])])
module['engineering'] = {'blueprintName': item['EngineerModifications']}
if 'Level' in item:
module['engineering']['blueprintLevel'] = item['Level']
@ -907,15 +911,15 @@ def journal_entry( # noqa: C901, CCR001
# Missions
if event_name == 'MissionAccepted':
data: OrderedDictT[str, Any] = OrderedDict([
('missionName', entry['Name']),
('missionGameID', entry['MissionID']),
('influenceGain', entry['Influence']),
('reputationGain', entry['Reputation']),
('starsystemNameOrigin', system),
('stationNameOrigin', station),
('minorfactionNameOrigin', entry['Faction']),
])
data: dict[str, Any] = {
'missionName': entry['Name'],
'missionGameID': entry['MissionID'],
'influenceGain': entry['Influence'],
'reputationGain': entry['Reputation'],
'starsystemNameOrigin': system,
'stationNameOrigin': station,
'minorfactionNameOrigin': entry['Faction'],
}
# optional mission-specific properties
for (iprop, prop) in (
@ -946,7 +950,7 @@ def journal_entry( # noqa: C901, CCR001
for x in entry.get('PermitsAwarded', []):
new_add_event('addCommanderPermit', entry['timestamp'], {'starsystemName': x})
data = OrderedDict([('missionGameID', entry['MissionID'])])
data = {'missionGameID': entry['MissionID']}
if 'Donation' in entry:
data['donationCredits'] = entry['Donation']
@ -966,7 +970,7 @@ def journal_entry( # noqa: C901, CCR001
factioneffects = []
for faction in entry.get('FactionEffects', []):
effect: OrderedDictT[str, Any] = OrderedDict([('minorfactionName', faction['Faction'])])
effect: dict[str, Any] = {'minorfactionName': faction['Faction']}
for influence in faction.get('Influence', []):
if 'Influence' in influence:
highest_gain = influence['Influence']
@ -990,7 +994,7 @@ def journal_entry( # noqa: C901, CCR001
# Combat
if event_name == 'Died':
data = OrderedDict([('starsystemName', system)])
data = {'starsystemName': system}
if 'Killers' in entry:
data['wingOpponentNames'] = [x['Name'] for x in entry['Killers']]
@ -1000,10 +1004,11 @@ def journal_entry( # noqa: C901, CCR001
new_add_event('addCommanderCombatDeath', entry['timestamp'], data)
elif event_name == 'Interdicted':
data = OrderedDict([('starsystemName', system),
('isPlayer', entry['IsPlayer']),
('isSubmit', entry['Submitted']),
])
data = {
'starsystemName': system,
'isPlayer': entry['IsPlayer'],
'isSubmit': entry['Submitted']
}
if 'Interdictor' in entry:
data['opponentName'] = entry['Interdictor']
@ -1022,11 +1027,11 @@ def journal_entry( # noqa: C901, CCR001
new_add_event('addCommanderCombatInterdicted', entry['timestamp'], data)
elif event_name == 'Interdiction':
data = OrderedDict([
('starsystemName', system),
('isPlayer', entry['IsPlayer']),
('isSuccess', entry['Success']),
])
data = {
'starsystemName': system,
'isPlayer': entry['IsPlayer'],
'isSuccess': entry['Success'],
}
if 'Interdicted' in entry:
data['opponentName'] = entry['Interdicted']
@ -1256,16 +1261,16 @@ def journal_entry( # noqa: C901, CCR001
# ))
for goal in entry['CurrentGoals']:
data = OrderedDict([
('communitygoalGameID', goal['CGID']),
('communitygoalName', goal['Title']),
('starsystemName', goal['SystemName']),
('stationName', goal['MarketName']),
('goalExpiry', goal['Expiry']),
('isCompleted', goal['IsComplete']),
('contributorsNum', goal['NumContributors']),
('contributionsTotal', goal['CurrentTotal']),
])
data = {
'communitygoalGameID': goal['CGID'],
'communitygoalName': goal['Title'],
'starsystemName': goal['SystemName'],
'stationName': goal['MarketName'],
'goalExpiry': goal['Expiry'],
'isCompleted': goal['IsComplete'],
'contributorsNum': goal['NumContributors'],
'contributionsTotal': goal['CurrentTotal'],
}
if 'TierReached' in goal:
data['tierReached'] = int(goal['TierReached'].split()[-1])
@ -1279,11 +1284,11 @@ def journal_entry( # noqa: C901, CCR001
new_add_event('setCommunityGoal', entry['timestamp'], data)
data = OrderedDict([
('communitygoalGameID', goal['CGID']),
('contribution', goal['PlayerContribution']),
('percentileBand', goal['PlayerPercentileBand']),
])
data = {
'communitygoalGameID': goal['CGID'],
'contribution': goal['PlayerContribution'],
'percentileBand': goal['PlayerPercentileBand'],
}
if 'Bonus' in goal:
data['percentileBandReward'] = goal['Bonus']
@ -1380,7 +1385,7 @@ def cmdr_data(data: CAPIData, is_beta): # noqa: CCR001, reanalyze me later
pass
def make_loadout(state: dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR001
def make_loadout(state: dict[str, Any]) -> dict[str, Any]: # noqa: CCR001
"""
Construct an inara loadout from an event.
@ -1389,13 +1394,13 @@ def make_loadout(state: dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR0
"""
modules = []
for m in state['Modules'].values():
module: OrderedDictT[str, Any] = OrderedDict([
('slotName', m['Slot']),
('itemName', m['Item']),
('itemHealth', m['Health']),
('isOn', m['On']),
('itemPriority', m['Priority']),
])
module: dict[str, Any] = {
'slotName': m['Slot'],
'itemName': m['Item'],
'itemHealth': m['Health'],
'isOn': m['On'],
'itemPriority': m['Priority'],
}
if 'AmmoInClip' in m:
module['itemAmmoClip'] = m['AmmoInClip']
@ -1410,20 +1415,20 @@ def make_loadout(state: dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR0
module['isHot'] = m['Hot']
if 'Engineering' in m:
engineering: OrderedDictT[str, Any] = OrderedDict([
('blueprintName', m['Engineering']['BlueprintName']),
('blueprintLevel', m['Engineering']['Level']),
('blueprintQuality', m['Engineering']['Quality']),
])
engineering: dict[str, Any] = {
'blueprintName': m['Engineering']['BlueprintName'],
'blueprintLevel': m['Engineering']['Level'],
'blueprintQuality': m['Engineering']['Quality'],
}
if 'ExperimentalEffect' in m['Engineering']:
engineering['experimentalEffect'] = m['Engineering']['ExperimentalEffect']
engineering['modifiers'] = []
for mod in m['Engineering']['Modifiers']:
modifier: OrderedDictT[str, Any] = OrderedDict([
('name', mod['Label']),
])
modifier: dict[str, Any] = {
'name': mod['Label'],
}
if 'OriginalValue' in mod:
modifier['value'] = mod['Value']
@ -1439,11 +1444,11 @@ def make_loadout(state: dict[str, Any]) -> OrderedDictT[str, Any]: # noqa: CCR0
modules.append(module)
return OrderedDict([
('shipType', state['ShipType']),
('shipGameID', state['ShipID']),
('shipLoadout', modules),
])
return {
'shipType': state['ShipType'],
'shipGameID': state['ShipID'],
'shipLoadout': modules,
}
def new_add_event(