-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmod_list.py
More file actions
381 lines (306 loc) · 12.9 KB
/
mod_list.py
File metadata and controls
381 lines (306 loc) · 12.9 KB
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
from __future__ import annotations
import json
import os
import re
import traceback
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from functools import cmp_to_key
from threading import Thread
from typing import TYPE_CHECKING
from urllib.request import Request, urlopen
import pyunrealsdk
import unrealsdk
from . import MODS_DIR, __version__
from .html_to_plain_text import html_to_plain_text
from .mod import CoopSupport, Game, Library, Mod, ModType
from .options import BaseOption, ButtonOption, GroupedOption, HiddenOption
from .settings import SETTINGS_DIR
if TYPE_CHECKING:
from pathlib import Path
from .command import AbstractCommand
from .hook import HookType
from .keybinds import KeybindType
# region Mod List
mod_list: list[Mod] = []
def register_mod(mod: Mod) -> None:
"""
Registers a mod instance.
Args:
mod: The mod to register.
Returns:
The mod which was registered.
"""
if mod in mod_list:
return
mod_list.append(mod)
mod.load_settings()
def deregister_mod(mod: Mod) -> None:
"""
Removes a mod from the mod list.
Args:
mod: The mod to remove.
"""
if mod.is_enabled:
mod.disable(dont_update_setting=True)
mod_list.remove(mod)
def get_ordered_mod_list() -> list[Mod]:
"""
Gets the list of mods, in display order.
Returns:
The ordered mod list.
"""
def cmp(a: Mod, b: Mod) -> int:
# The base mod should always appear at the start
if a == base_mod and b != base_mod:
return -1
if a != base_mod and b == base_mod:
return 1
# Sort libraries after all other mod types
if a.mod_type is not ModType.Library and b.mod_type is ModType.Library:
return -1
if a.mod_type is ModType.Library and b.mod_type is not ModType.Library:
return 1
# Finally, sort by name
# Strip html tags, whitespace, and compare case insensitively
a_plain = html_to_plain_text(a.name.strip()).lower()
b_plain = html_to_plain_text(b.name.strip()).lower()
if a_plain < b_plain:
return -1
if a_plain > b_plain:
return 1
return 0
return sorted(mod_list, key=cmp_to_key(cmp))
# endregion
# region Base Mod
MOD_DB_URL: str
MOD_RELEASE_API_URL: str
MOD_RELEASE_DOWNLOAD_URL: str
match Game.get_tree():
case Game.Willow1:
MOD_DB_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://bl-sdk.github.io/willow1-mod-db/"
)
MOD_RELEASE_API_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://api.github.com/repos/bl-sdk/willow1-mod-manager/releases/latest"
)
MOD_RELEASE_DOWNLOAD_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://github.com/bl-sdk/willow1-mod-manager/releases/"
)
case Game.Willow2:
MOD_DB_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://bl-sdk.github.io/willow2-mod-db/"
)
MOD_RELEASE_API_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://api.github.com/repos/bl-sdk/willow2-mod-manager/releases/latest"
)
MOD_RELEASE_DOWNLOAD_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://github.com/bl-sdk/willow2-mod-manager/releases/"
)
case Game.Oak:
MOD_DB_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://bl-sdk.github.io/oak-mod-db/"
)
MOD_RELEASE_API_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://api.github.com/repos/bl-sdk/oak-mod-manager/releases/latest"
)
MOD_RELEASE_DOWNLOAD_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://github.com/bl-sdk/oak-mod-manager/releases/"
)
case Game.Oak2:
MOD_DB_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://bl-sdk.github.io/oak2-mod-db/"
)
MOD_RELEASE_API_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://api.github.com/repos/bl-sdk/oak2-mod-manager/releases/latest"
)
MOD_RELEASE_DOWNLOAD_URL = ( # pyright: ignore[reportConstantRedefinition]
"https://github.com/bl-sdk/oak2-mod-manager/releases/"
)
MANAGER_VERSION = unrealsdk.config.get("mod_manager", {}).get("display_version", "Unknown Version")
RE_MANAGER_VERSION = re.compile(r"v?(\d+)\.(\d+)")
@dataclass
class BaseMod(Library):
name: str = "Python SDK"
author: str = "bl-sdk"
version: str = MANAGER_VERSION
coop_support: CoopSupport = CoopSupport.ClientSide
settings_file: Path | None = SETTINGS_DIR / "python-sdk.json"
# As an internal interface, the other submodules which the sdk ships with by default should add
# themselves to these fields on the `base_mod` object, rather than registering as their own mod.
# This helps avoid cluttering the default mod list.
keybinds: list[KeybindType] = field(default_factory=list) # type: ignore
options: list[BaseOption] = field(default_factory=list) # type: ignore
hooks: list[HookType] = field(default_factory=list) # type: ignore
commands: list[AbstractCommand] = field(default_factory=list) # type: ignore
@dataclass
class ComponentInfo:
name: str
version: str
# They should also all add themselves here, so we can record their versions
components: list[ComponentInfo] = field(default_factory=list[ComponentInfo])
# Base mod options
get_latest_release_button: ButtonOption = field(init=False)
latest_version_option: HiddenOption[str | None] = field(init=False)
next_version_check_time_option: HiddenOption[str] = field(init=False)
@property
def description(self) -> str:
"""Custom description getter, which builds it from the list of components."""
# We want to show components in alphabetical order
# Rather than use sorted, and throw away the result, might as well just do a proper sort
# Once already sorted, re-sorting should be relatively quick
self.components.sort(key=lambda c: c.name.lower())
description = "Components:"
description += "<ul>"
for comp in self.components:
description += f"<li>{comp.name}: {comp.version}</li>"
description += "</ul>"
return description
@description.setter
def description( # pyright: ignore[reportIncompatibleVariableOverride]
self,
_: str,
) -> None:
"""No-op description setter."""
def __post_init__(self) -> None:
super().__post_init__()
self.get_latest_release_button = ButtonOption(
"Get Latest Release",
on_press=lambda _: os.startfile(MOD_RELEASE_DOWNLOAD_URL), # type: ignore # noqa: S606
is_hidden=True,
)
self.latest_version_option = HiddenOption("Latest", None)
self.next_version_check_time_option = HiddenOption("Next Check Time", "")
self.options = [ # pyright: ignore[reportIncompatibleVariableOverride]
self.get_latest_release_button,
ButtonOption(
"Open Mod Database",
on_press=lambda _: os.startfile(MOD_DB_URL), # type: ignore # noqa: S606
),
ButtonOption(
"Open Installed Mods Folder",
on_press=lambda _: os.startfile(MODS_DIR), # type: ignore # noqa: S606
),
GroupedOption(
"Version Checking",
(
self.latest_version_option,
self.next_version_check_time_option,
),
is_hidden=True,
),
]
self.components = [
BaseMod.ComponentInfo("Base", __version__),
# Both of these start their version strings with their module name, strip it out
BaseMod.ComponentInfo("unrealsdk", unrealsdk.__version__.partition(" ")[2]),
BaseMod.ComponentInfo("pyunrealsdk", pyunrealsdk.__version__.partition(" ")[2]),
]
def get_this_release_tuple(self) -> tuple[int, ...] | None:
"""
Gets the version tuple for this release.
Returns:
The version tuple, or None if unknown.
"""
if self.version == "Unknown Version":
return None
version_match = RE_MANAGER_VERSION.match(MANAGER_VERSION)
if version_match is None:
return None
return tuple(int(x) for x in version_match.groups())
def fetch_latest_version(self) -> tuple[str, tuple[int, ...]] | tuple[None, None]:
"""
Fetches the version of the latest release from github.
Should be called in a thread, as this makes a blocking HTTP request.
Returns:
A tuple of the latest version name and version tuple, or None and None if unknown.
"""
try:
resp = urlopen( # noqa: S310 - hardcoded https
Request( # noqa: S310
MOD_RELEASE_API_URL,
headers={
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
),
).read()
tag: str = json.loads(resp)["tag_name"]
tag_match = RE_MANAGER_VERSION.match(tag)
if tag_match is None:
raise ValueError
return tag, tuple(int(x) for x in tag_match.groups())
except Exception: # noqa: BLE001
unrealsdk.logging.warning("SDK update check failed")
unrealsdk.logging.dev_warning(traceback.format_exc())
return None, None
def get_latest_cached_version(self) -> tuple[str, tuple[int, ...]] | tuple[None, None]:
"""
Gets the version of the latest release from our cached setting.
Returns:
A tuple of the latest version name and version tuple, or None and None if unknown.
"""
try:
name = self.latest_version_option.value
if name is None:
raise ValueError
match = RE_MANAGER_VERSION.match(name)
if match is None:
raise ValueError
return name, tuple(int(x) for x in match.groups())
except Exception: # noqa: BLE001
self.latest_version_option.value = None
self.save_settings()
return None, None
def perform_version_check(self) -> None:
"""
Checks if there's a newer version, and updates the options appropriately.
Should be called in a thread, as this makes a blocking HTTP request.
"""
this_version = self.get_this_release_tuple()
if this_version is None:
unrealsdk.logging.warning("Skipping SDK update check since current version is unknown")
return
fetch_new_version = False
try:
next_check_time = datetime.fromisoformat(self.next_version_check_time_option.value)
if next_check_time < datetime.now(UTC):
fetch_new_version = True
except ValueError:
# If we failed to parse the option, assume we need to re-fetch
fetch_new_version = True
if fetch_new_version:
latest_version_name, latest_version_tuple = self.fetch_latest_version()
else:
latest_version_name, latest_version_tuple = self.get_latest_cached_version()
if latest_version_name is None or latest_version_tuple is None:
return
if latest_version_tuple > this_version:
self.latest_version_option.value = latest_version_name
else:
self.latest_version_option.value = None
next_check_time = datetime.now(UTC) + timedelta(days=1)
self.next_version_check_time_option.value = next_check_time.isoformat()
self.save_settings()
def notify_latest_release(self) -> None:
"""
Checks for a newer release, and notifies if one's found.
Should be called in a thread, as this makes a blocking HTTP request.
"""
self.perform_version_check()
if self.latest_version_option.value is not None:
self.get_latest_release_button.is_hidden = False
unrealsdk.logging.warning(
f"A newer SDK release is available: {self.latest_version_option.value}",
)
def get_status(self) -> str:
"""Custom status which shows when updates are available."""
if self.latest_version_option.value is not None:
return "<font color='#ffff00'>Update Available</font>"
return super().get_status()
base_mod = BaseMod()
def register_base_mod() -> None:
"""Registers the base mod. Should be called by the mod loader after importing all components."""
register_mod(base_mod)
Thread(target=base_mod.notify_latest_release).start()
# endregion