-
Notifications
You must be signed in to change notification settings - Fork 32
/
plugin_manager.py
2919 lines (2567 loc) · 123 KB
/
plugin_manager.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
# ba_meta require api 8
from babase._meta import EXPORT_CLASS_NAME_SHORTCUTS
from baenv import TARGET_BALLISTICA_BUILD
import babase
import _babase
import bauiv1 as bui
import _bauiv1
import _bascenev1
from bauiv1lib import popup, confirm
import urllib.request
import http.client
import socket
import ssl
import json
import os
import sys
import asyncio
import re
import pathlib
import contextlib
import hashlib
import copy
import traceback
from typing import Union, Optional, cast
from datetime import datetime
# Modules used for overriding AllSettingsWindow
from threading import Thread
import logging
PLUGIN_MANAGER_VERSION = "1.0.22"
REPOSITORY_URL = "https://github.com/bombsquad-community/plugin-manager"
# Current tag can be changed to "staging" or any other branch in
# plugin manager repo for testing purpose.
CURRENT_TAG = "main"
if TARGET_BALLISTICA_BUILD < 21282:
# These attributes have been deprecated as of 1.7.27. For more info see:
# https://github.com/efroemling/ballistica/blob/master/CHANGELOG.md#1727-build-21282-api-8-2023-08-30
# Adding a compatibility layer here so older builds still work fine.
class Dummy:
pass
babase.app.env = Dummy()
babase.app.env.engine_build_number = babase.app.build_number
babase.app.env.device_name = babase.app.device_name
babase.app.env.config_file_path = babase.app.config_file_path
babase.app.env.engine_version = babase.app.version
babase.app.env.debug = babase.app.debug_build
babase.app.env.test = babase.app.test_build
babase.app.env.data_directory = babase.app.data_directory
babase.app.env.python_directory_user = babase.app.python_directory_user
babase.app.env.python_directory_app = babase.app.python_directory_app
babase.app.env.python_directory_app_site = babase.app.python_directory_app_site
babase.app.env.api_version = babase.app.api_version
babase.app.env.tv = babase.app.on_tv
babase.app.env.vr = babase.app.vr_mode
babase.app.env.arcade = babase.app.arcade_mode
babase.app.env.headless = babase.app.arcade_mode
babase.app.env.demo = babase.app.demo_mode
_bascenev1.protocol_version = lambda: babase.app.protocol_version
_bauiv1.toolbar_test = lambda: babase.app.toolbar_test
if TARGET_BALLISTICA_BUILD < 21852:
class Dummy(babase.app.env):
engine_build_number = babase.app.env.build_number
engine_version = babase.app.env.version
babase.app.env = Dummy
_env = _babase.env()
_uiscale = bui.app.ui_v1.uiscale
INDEX_META = "{repository_url}/{content_type}/{tag}/index.json"
CHANGELOG_META = "{repository_url}/{content_type}/{tag}/CHANGELOG.md"
HEADERS = {
"User-Agent": _env["legacy_user_agent_string"],
}
PLUGIN_DIRECTORY = _env["python_directory_user"]
loop = babase._asyncio._asyncio_event_loop
def _regexp_friendly_class_name_shortcut(string): return string.replace(".", "\\.")
REGEXP = {
"plugin_api_version": re.compile(b"(?<=ba_meta require api )(.*)"),
"plugin_entry_points": re.compile(
bytes(
"(ba_meta export (plugin|{})\n+class )(.*)\\(".format(
_regexp_friendly_class_name_shortcut(EXPORT_CLASS_NAME_SHORTCUTS["plugin"]),
),
"utf-8"
),
),
"minigames": re.compile(
bytes(
"(ba_meta export ({})\n+class )(.*)\\(".format(
_regexp_friendly_class_name_shortcut("bascenev1.GameActivity"),
),
"utf-8"
),
),
}
DISCORD_URL = "https://ballistica.net/discord"
_CACHE = {}
class MD5CheckSumFailed(Exception):
pass
class PluginNotInstalled(Exception):
pass
class CategoryDoesNotExist(Exception):
pass
class NoCompatibleVersion(Exception):
pass
class PluginSourceNetworkError(Exception):
pass
class CategoryMetadataParseError(Exception):
pass
def send_network_request(request):
return urllib.request.urlopen(request)
async def async_send_network_request(request):
response = await loop.run_in_executor(None, send_network_request, request)
return response
def stream_network_response_to_file(request, file, md5sum=None, retries=3):
response = urllib.request.urlopen(request)
chunk_size = 16 * 1024
content = b""
with open(file, "wb") as fout:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
fout.write(chunk)
content += chunk
if md5sum and hashlib.md5(content).hexdigest() != md5sum:
if retries <= 0:
raise MD5CheckSumFailed("MD5 checksum match failed.")
return stream_network_response_to_file(
request,
file,
md5sum=md5sum,
retries=retries-1,
)
return content
async def async_stream_network_response_to_file(request, file, md5sum=None, retries=3):
content = await loop.run_in_executor(
None,
stream_network_response_to_file,
request,
file,
md5sum,
retries,
)
return content
def partial_format(string_template, **kwargs):
for key, value in kwargs.items():
string_template = string_template.replace("{" + key + "}", value)
return string_template
class DNSBlockWorkaround:
"""
Some ISPs put a DNS block on domains that are needed for plugin manager to
work properly. This class stores methods to workaround such blocks by adding
dns.google as a fallback.
Such as Jio, a pretty popular ISP in India has a DNS block on
raw.githubusercontent.com (sigh..).
References:
* https://github.com/orgs/community/discussions/42655
Usage:
-----
>>> import urllib.request
>>> import http.client
>>> import socket
>>> import ssl
>>> import json
>>> DNSBlockWorkaround.apply()
>>> response = urllib.request.urlopen("https://dnsblockeddomain.com/path/to/resource/")
"""
_google_dns_cache = {}
def apply():
opener = urllib.request.build_opener(
DNSBlockWorkaround._HTTPHandler,
DNSBlockWorkaround._HTTPSHandler,
)
urllib.request.install_opener(opener)
def _resolve_using_google_dns(hostname):
response = urllib.request.urlopen(f"https://dns.google/resolve?name={hostname}")
response = response.read()
response = json.loads(response)
resolved_host = response["Answer"][0]["data"]
return resolved_host
def _resolve_using_system_dns(hostname):
resolved_host = socket.gethostbyname(hostname)
return resolved_host
def _resolve_with_workaround(hostname):
resolved_host_from_cache = DNSBlockWorkaround._google_dns_cache.get(hostname)
if resolved_host_from_cache:
return resolved_host_from_cache
resolved_host_by_system_dns = DNSBlockWorkaround._resolve_using_system_dns(hostname)
if DNSBlockWorkaround._is_blocked(hostname, resolved_host_by_system_dns):
resolved_host = DNSBlockWorkaround._resolve_using_google_dns(hostname)
DNSBlockWorkaround._google_dns_cache[hostname] = resolved_host
else:
resolved_host = resolved_host_by_system_dns
return resolved_host
def _is_blocked(hostname, address):
is_blocked = False
if hostname == "raw.githubusercontent.com":
# Jio's DNS server may be blocking it.
is_blocked = address.startswith("49.44.")
return is_blocked
class _HTTPConnection(http.client.HTTPConnection):
def connect(self):
host = DNSBlockWorkaround._resolve_with_workaround(self.host)
self.sock = socket.create_connection(
(host, self.port),
self.timeout,
)
class _HTTPSConnection(http.client.HTTPSConnection):
def connect(self):
host = DNSBlockWorkaround._resolve_with_workaround(self.host)
sock = socket.create_connection(
(host, self.port),
self.timeout,
)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
sock = context.wrap_socket(sock, server_hostname=self.host)
self.sock = sock
class _HTTPHandler(urllib.request.HTTPHandler):
def http_open(self, req):
return self.do_open(DNSBlockWorkaround._HTTPConnection, req)
class _HTTPSHandler(urllib.request.HTTPSHandler):
def https_open(self, req):
return self.do_open(DNSBlockWorkaround._HTTPSConnection, req)
class StartupTasks:
def __init__(self):
self.plugin_manager = PluginManager()
def setup_config(self):
# is_config_updated = False
existing_plugin_manager_config = copy.deepcopy(
babase.app.config.get("Community Plugin Manager"))
plugin_manager_config = babase.app.config.setdefault("Community Plugin Manager", {})
plugin_manager_config.setdefault("Custom Sources", [])
installed_plugins = plugin_manager_config.setdefault("Installed Plugins", {})
for plugin_name in tuple(installed_plugins.keys()):
plugin = PluginLocal(plugin_name)
if not plugin.is_installed:
del installed_plugins[plugin_name]
# This order is the options will show up in Settings window.
current_settings = {
"Auto Update Plugin Manager": True,
"Auto Update Plugins": True,
"Auto Enable Plugins After Installation": True,
"Notify New Plugins": True
}
settings = plugin_manager_config.setdefault("Settings", {})
for setting, value in settings.items():
if setting in current_settings:
current_settings[setting] = value
plugin_manager_config["Settings"] = current_settings
if plugin_manager_config != existing_plugin_manager_config:
babase.app.config.commit()
async def update_plugin_manager(self):
if not babase.app.config["Community Plugin Manager"]["Settings"]["Auto Update Plugin Manager"]:
return
update_details = await self.plugin_manager.get_update_details()
if update_details:
to_version, commit_sha = update_details
bui.screenmessage(f"Plugin Manager is being updated to v{to_version}")
try:
await self.plugin_manager.update(to_version, commit_sha)
except MD5CheckSumFailed:
bui.getsound('error').play()
else:
bui.screenmessage("Update successful. Restart game to reload changes.",
color=(0, 1, 0))
bui.getsound('shieldUp').play()
async def update_plugins(self):
if not babase.app.config["Community Plugin Manager"]["Settings"]["Auto Update Plugins"]:
return
await self.plugin_manager.setup_index()
all_plugins = await self.plugin_manager.categories["All"].get_plugins()
plugins_to_update = []
for plugin in all_plugins:
if plugin.is_installed and await plugin.get_local().is_enabled() and plugin.has_update():
plugins_to_update.append(plugin.update())
await asyncio.gather(*plugins_to_update)
@staticmethod
def _is_new_supported_plugin(plugin):
is_an_update = len(plugin.versions) > 1
if is_an_update:
return False
try:
plugin.latest_compatible_version
except NoCompatibleVersion:
return False
else:
return True
async def notify_new_plugins(self):
if not babase.app.config["Community Plugin Manager"]["Settings"]["Notify New Plugins"]:
return
show_max_names = 2
await self.plugin_manager.setup_index()
new_num_of_plugins = len(await self.plugin_manager.categories["All"].get_plugins())
try:
existing_num_of_plugins = babase.app.config["Community Plugin Manager"]["Existing Number of Plugins"]
except KeyError:
babase.app.config["Community Plugin Manager"]["Existing Number of Plugins"] = new_num_of_plugins
babase.app.config.commit()
return
def title_it(plug):
plug = str(plug).replace('_', ' ').title()
return plug
if existing_num_of_plugins < new_num_of_plugins:
new_plugin_count = new_num_of_plugins - existing_num_of_plugins
all_plugins = await self.plugin_manager.categories["All"].get_plugins()
new_supported_plugins = list(filter(self._is_new_supported_plugin, all_plugins))
new_supported_plugins.sort(
key=lambda plugin: plugin.latest_compatible_version.released_on_date,
reverse=True,
)
new_supported_plugins = new_supported_plugins[:new_plugin_count]
new_supported_plugins_count = len(new_supported_plugins)
if new_supported_plugins_count > 0:
new_supported_plugins = ", ".join(map(title_it, (new_supported_plugins
if new_supported_plugins_count <= show_max_names else
new_supported_plugins[0:show_max_names])
))
if new_supported_plugins_count == 1:
notification_text = f"{new_supported_plugins_count} new plugin ({new_supported_plugins}) is available!"
else:
notification_text = new_supported_plugins + \
('' if new_supported_plugins_count <= show_max_names else ' and +' +
str(new_supported_plugins_count-show_max_names)) + " new plugins are available"
bui.screenmessage(notification_text, color=(0, 1, 0))
if existing_num_of_plugins != new_num_of_plugins:
babase.app.config["Community Plugin Manager"]["Existing Number of Plugins"] = new_num_of_plugins
babase.app.config.commit()
async def execute(self):
self.setup_config()
try:
await asyncio.gather(
self.update_plugin_manager(),
self.update_plugins(),
self.notify_new_plugins(),
)
except urllib.error.URLError:
pass
class Category:
def __init__(self, meta_url, tag=CURRENT_TAG):
self.meta_url = meta_url
self.tag = tag
self.request_headers = HEADERS
self._metadata = _CACHE.get("categories", {}).get(meta_url, {}).get("metadata")
self._plugins = _CACHE.get("categories", {}).get(meta_url, {}).get("plugins")
async def fetch_metadata(self):
if self._metadata is None:
# Let's keep depending on the "main" branch for 3rd party sources
# even if we're using a different branch of plugin manager's repository.
request = urllib.request.Request(
self.meta_url.format(content_type="raw", tag=self.tag),
headers=self.request_headers,
)
response = await async_send_network_request(request)
self._metadata = json.loads(response.read())
self.set_category_global_cache("metadata", self._metadata)
return self
async def validate(self):
try:
await self.fetch_metadata()
except urllib.error.HTTPError as e:
raise PluginSourceNetworkError(str(e))
except json.decoder.JSONDecodeError as e:
raise CategoryMetadataParseError(f"Failed to parse JSON: {str(e)}")
try:
await asyncio.gather(
self.get_name(),
self.get_description(),
self.get_plugins_base_url(),
self.get_plugins(),
)
except KeyError:
raise CategoryMetadataParseError(f"Failed to parse JSON; missing required fields.")
else:
return True
async def get_name(self):
await self.fetch_metadata()
return self._metadata["name"]
async def get_description(self):
await self.fetch_metadata()
return self._metadata["description"]
async def get_plugins_base_url(self):
await self.fetch_metadata()
return self._metadata["plugins_base_url"]
async def get_plugins(self):
if self._plugins is None:
await self.fetch_metadata()
self._plugins = ([
Plugin(
plugin_info,
f"{await self.get_plugins_base_url()}/{plugin_info[0]}.py",
tag=self.tag,
)
for plugin_info in self._metadata["plugins"].items()
])
self.set_category_global_cache("plugins", self._plugins)
return self._plugins
def set_category_global_cache(self, key, value):
if "categories" not in _CACHE:
_CACHE["categories"] = {}
if self.meta_url not in _CACHE["categories"]:
_CACHE["categories"][self.meta_url] = {}
_CACHE["categories"][self.meta_url][key] = value
def unset_category_global_cache(self):
try:
del _CACHE["categories"][self.meta_url]
except KeyError:
pass
def cleanup(self):
self._metadata = None
self._plugins.clear()
self.unset_category_global_cache()
async def refresh(self):
self.cleanup()
await self.get_plugins()
def save(self):
babase.app.config["Community Plugin Manager"]["Custom Sources"].append(self.meta_url)
babase.app.config.commit()
class CategoryAll(Category):
def __init__(self, plugins={}):
super().__init__(meta_url=None)
self._name = "All"
self._description = "All plugins"
self._plugins = plugins
class PluginLocal:
def __init__(self, name):
"""
Initialize a plugin locally installed on the device.
"""
self.name = name
self.install_path = os.path.join(PLUGIN_DIRECTORY, f"{name}.py")
self._entry_point_initials = f"{self.name}."
self.cleanup()
def cleanup(self):
self._content = None
self._api_version = None
self._entry_points = []
self._has_minigames = None
@property
def is_installed(self):
return os.path.isfile(self.install_path)
@property
def is_installed_via_plugin_manager(self):
return self.name in babase.app.config["Community Plugin Manager"]["Installed Plugins"]
def initialize(self):
if self.name not in babase.app.config["Community Plugin Manager"]["Installed Plugins"]:
babase.app.config["Community Plugin Manager"]["Installed Plugins"][self.name] = {}
return self
async def uninstall(self):
if await self.has_minigames():
self.unload_minigames()
try:
os.remove(self.install_path)
except FileNotFoundError:
pass
try:
del babase.app.config["Community Plugin Manager"]["Installed Plugins"][self.name]
except KeyError:
pass
else:
self.save()
@property
def version(self):
try:
version = (babase.app.config["Community Plugin Manager"]
["Installed Plugins"][self.name]["version"])
except KeyError:
version = None
return version
def _get_content(self):
with open(self.install_path, "rb") as fin:
return fin.read()
def _set_content(self, content):
with open(self.install_path, "wb") as fout:
fout.write(content)
def has_settings(self):
for plugin_entry_point, plugin_spec in bui.app.plugins.plugin_specs.items():
if plugin_entry_point.startswith(self._entry_point_initials):
return plugin_spec.plugin.has_settings_ui()
def launch_settings(self, source_widget):
for plugin_entry_point, plugin_spec in bui.app.plugins.plugin_specs.items():
if plugin_entry_point.startswith(self._entry_point_initials):
return plugin_spec.plugin.show_settings_ui(source_widget)
async def get_content(self):
if self._content is None:
if not self.is_installed:
raise PluginNotInstalled("Plugin is not available locally.")
self._content = await loop.run_in_executor(None, self._get_content)
return self._content
async def get_api_version(self):
if self._api_version is None:
content = await self.get_content()
self._api_version = REGEXP["plugin_api_version"].search(content).group()
return self._api_version
async def get_entry_points(self):
if not self._entry_points:
content = await self.get_content()
groups = REGEXP["plugin_entry_points"].findall(content)
# Actual entry points are stored in the last index inside the matching groups.
entry_points = tuple(f"{self.name}.{group[-1].decode('utf-8')}" for group in groups)
self._entry_points = entry_points
return self._entry_points
async def has_minigames(self):
if self._has_minigames is None:
content = await self.get_content()
self._has_minigames = REGEXP["minigames"].search(content) is not None
return self._has_minigames
async def has_plugins(self):
entry_points = await self.get_entry_points()
return len(entry_points) > 0
def load_minigames(self):
scanner = babase._meta.DirectoryScan(paths="")
directory, module = self.install_path.rsplit(os.path.sep, 1)
scanner._scan_module(
pathlib.Path(directory),
pathlib.Path(module),
)
scanned_results = set(babase.app.meta.scanresults.exports["bascenev1.GameActivity"])
for game in scanner.results.exports["bascenev1.GameActivity"]:
if game not in scanned_results:
bui.screenmessage(f"{game} minigame loaded")
babase.app.meta.scanresults.exports["bascenev1.GameActivity"].append(game)
def unload_minigames(self):
scanner = babase._meta.DirectoryScan(paths="")
directory, module = self.install_path.rsplit(os.path.sep, 1)
scanner._scan_module(
pathlib.Path(directory),
pathlib.Path(module),
)
new_scanned_results_games = []
for game in babase.app.meta.scanresults.exports["bascenev1.GameActivity"]:
if game in scanner.results.exports["bascenev1.GameActivity"]:
bui.screenmessage(f"{game} minigame unloaded")
else:
new_scanned_results_games.append(game)
babase.app.meta.scanresults.exports["bascenev1.GameActivity"] = new_scanned_results_games
async def is_enabled(self):
"""
Return True even if a single entry point is enabled or contains minigames.
"""
if not await self.has_plugins():
return True
for entry_point, plugin_info in babase.app.config["Plugins"].items():
if entry_point.startswith(self._entry_point_initials) and plugin_info["enabled"]:
return True
# XXX: The below logic is more accurate but less efficient, since it actually
# reads the local plugin file and parses entry points from it.
# for entry_point in await self.get_entry_points():
# if babase.app.config["Plugins"][entry_point]["enabled"]:
# return True
return False
# XXX: Commenting this out for now, since `enable` and `disable` currently have their
# own separate logic.
# async def _set_status(self, to_enable=True):
# for entry_point in await self.get_entry_points:
# if entry_point not in babase.app.config["Plugins"]:
# babase.app.config["Plugins"][entry_point] = {}
# babase.app.config["Plugins"][entry_point]["enabled"] = to_enable
async def enable(self):
for entry_point in await self.get_entry_points():
if entry_point not in babase.app.config["Plugins"]:
babase.app.config["Plugins"][entry_point] = {}
babase.app.config["Plugins"][entry_point]["enabled"] = True
plugin_spec = bui.app.plugins.plugin_specs.get(entry_point)
if plugin_spec not in bui.app.plugins.active_plugins:
self.load_plugin(entry_point)
bui.screenmessage(f"{entry_point} loaded")
if await self.has_minigames():
self.load_minigames()
# await self._set_status(to_enable=True)
self.save()
def load_plugin(self, entry_point):
plugin_class = babase._general.getclass(entry_point, babase.Plugin)
loaded_plugin_instance = plugin_class()
loaded_plugin_instance.on_app_running()
plugin_spec = babase.PluginSpec(class_path=entry_point, loadable=True)
plugin_spec.enabled = True
plugin_spec.plugin = loaded_plugin_instance
bui.app.plugins.plugin_specs[entry_point] = plugin_spec
bui.app.plugins.active_plugins.append(plugin_spec.plugin)
def disable(self):
for entry_point, plugin_info in babase.app.config["Plugins"].items():
if entry_point.startswith(self._entry_point_initials):
# if plugin_info["enabled"]:
plugin_info["enabled"] = False
# XXX: The below logic is more accurate but less efficient, since it actually
# reads the local plugin file and parses entry points from it.
# await self._set_status(to_enable=False)
self.save()
def set_version(self, version):
app = babase.app
app.config["Community Plugin Manager"]["Installed Plugins"][self.name]["version"] = version
return self
# def set_entry_points(self):
# if not "entry_points" in babase.app.config["Community Plugin Manager"]
# ["Installed Plugins"][self.name]:
# babase.app.config["Community Plugin Manager"]["Installed Plugins"]
# [self.name]["entry_points"] = []
# for entry_point in await self.get_entry_points():
# babase.app.config["Community Plugin Manager"]["Installed Plugins"][self.name]
# ["entry_points"].append(entry_point)
async def set_content(self, content):
if not self._content:
await loop.run_in_executor(None, self._set_content, content)
self._content = content
return self
async def set_content_from_network_response(self, request, md5sum=None, retries=3):
if not self._content:
self._content = await async_stream_network_response_to_file(
request,
self.install_path,
md5sum=md5sum,
retries=retries,
)
return self._content
def save(self):
babase.app.config.commit()
return self
class PluginVersion:
def __init__(self, plugin, version, tag=CURRENT_TAG):
self.number, info = version
self.plugin = plugin
self.api_version = info["api_version"]
self.released_on = info["released_on"]
self.commit_sha = info["commit_sha"]
self.md5sum = info["md5sum"]
self.download_url = self.plugin.url.format(content_type="raw", tag=tag)
self.view_url = self.plugin.url.format(content_type="blob", tag=tag)
def __eq__(self, plugin_version):
return (self.number, self.plugin.name) == (plugin_version.number,
plugin_version.plugin.name)
def __repr__(self):
return f"<PluginVersion({self.plugin.name} {self.number})>"
@property
def released_on_date(self):
return datetime.strptime(self.released_on, "%d-%m-%Y")
async def _download(self, retries=3):
local_plugin = self.plugin.create_local()
await local_plugin.set_content_from_network_response(
self.download_url,
md5sum=self.md5sum,
retries=retries,
)
local_plugin.set_version(self.number)
local_plugin.save()
return local_plugin
async def install(self, suppress_screenmessage=False):
try:
local_plugin = await self._download()
except MD5CheckSumFailed:
if not suppress_screenmessage:
bui.screenmessage(
f"{self.plugin.name} failed MD5 checksum during installation", color=(1, 0, 0))
return False
else:
if not suppress_screenmessage:
bui.screenmessage(f"{self.plugin.name} installed", color=(0, 1, 0))
check = babase.app.config["Community Plugin Manager"]["Settings"]
if check["Auto Enable Plugins After Installation"]:
await local_plugin.enable()
return True
class Plugin:
def __init__(self, plugin, url, tag=CURRENT_TAG):
"""
Initialize a plugin from network repository.
"""
self.name, self.info = plugin
self.install_path = os.path.join(PLUGIN_DIRECTORY, f"{self.name}.py")
self.url = url
self.tag = tag
self._local_plugin = None
self._versions = None
self._latest_version = None
self._latest_compatible_version = None
def __repr__(self):
return f"<Plugin({self.name})>"
def __str__(self):
return self.name
@property
def view_url(self):
if self.latest_compatible_version == self.latest_version:
tag = CURRENT_TAG
else:
tag = self.latest_compatible_version.commit_sha
return self.url.format(content_type="blob", tag=tag)
@property
def is_installed(self):
return os.path.isfile(self.install_path)
@property
def versions(self):
if self._versions is None:
self._versions = [
PluginVersion(
self,
version,
tag=self.tag,
) for version in self.info["versions"].items()
]
return self._versions
@property
def latest_version(self):
if self._latest_version is None:
self._latest_version = PluginVersion(
self,
tuple(self.info["versions"].items())[0],
tag=self.tag,
)
return self._latest_version
@property
def latest_compatible_version(self):
if self._latest_compatible_version is None:
for number, info in self.info["versions"].items():
if info["api_version"] == babase.app.env.api_version:
self._latest_compatible_version = PluginVersion(
self,
(number, info),
tag=self.tag if self.latest_version.number == number else info["commit_sha"]
)
break
if self._latest_compatible_version is None:
raise NoCompatibleVersion(
f"{self.name} has no version compatible with API {babase.app.env.api_version}."
)
return self._latest_compatible_version
def get_local(self):
if not self.is_installed:
raise PluginNotInstalled(
f"{self.name} needs to be installed to get its local plugin.")
if self._local_plugin is None:
self._local_plugin = PluginLocal(self.name)
return self._local_plugin
def create_local(self):
return (
PluginLocal(self.name)
.initialize()
)
async def uninstall(self):
await self.get_local().uninstall()
bui.screenmessage(f"{self.name} uninstalled", color=(0.9, 1, 0))
def has_update(self):
try:
latest_compatible_version = self.latest_compatible_version
except NoCompatibleVersion:
return False
else:
return self.get_local().version != latest_compatible_version.number
async def update(self):
if await self.latest_compatible_version.install(suppress_screenmessage=True):
bui.screenmessage(f"{self.name} updated to {self.latest_compatible_version.number}",
color=(0, 1, 0))
bui.getsound('shieldUp').play()
else:
bui.screenmessage(f"{self.name} failed MD5 checksum while updating to "
f"{self.latest_compatible_version.number}",
color=(1, 0, 0))
bui.getsound('error').play()
class ChangelogWindow(popup.PopupWindow):
def __init__(self, origin_widget):
self.scale_origin = origin_widget.get_screen_space_center()
bui.getsound('swish').play()
s = 1.65 if _uiscale is babase.UIScale.SMALL else 1.39 if _uiscale is babase.UIScale.MEDIUM else 1.67
width = 400 * s
height = width * 0.5
color = (1, 1, 1)
text_scale = 0.7 * s
self._transition_out = 'out_scale'
transition = 'in_scale'
self._root_widget = bui.containerwidget(size=(width, height),
on_outside_click_call=self._back,
transition=transition,
scale=(1.5 if _uiscale is babase.UIScale.SMALL else 1.5
if _uiscale is babase.UIScale.MEDIUM else 1.0),
scale_origin_stack_offset=self.scale_origin)
bui.textwidget(parent=self._root_widget,
position=(width * 0.49, height * 0.87), size=(0, 0),
h_align='center', v_align='center', text='ChangeLog',
scale=text_scale * 1.25, color=bui.app.ui_v1.title_color,
maxwidth=width * 0.9)
back_button = bui.buttonwidget(
parent=self._root_widget,
position=(width * 0.1, height * 0.8),
size=(60, 60),
scale=0.8,
label=babase.charstr(babase.SpecialChar.BACK),
# autoselect=True,
button_type='backSmall',
on_activate_call=self._back)
bui.containerwidget(edit=self._root_widget, cancel_button=back_button)
try:
released_on = _CACHE['changelog']['released_on']
logs = _CACHE['changelog']['info'].split('\n')
h_align = 'left'
extra = 0.1
except KeyError:
released_on = ''
logs = ["Could not load ChangeLog"]
h_align = 'center'
extra = 1
bui.textwidget(parent=self._root_widget,
position=(width * 0.49, height * 0.72), size=(0, 0),
h_align='center', v_align='center',
text=PLUGIN_MANAGER_VERSION + released_on,
scale=text_scale * 0.9, color=color,
maxwidth=width * 0.9)
bui.buttonwidget(
parent=self._root_widget,
position=(width * 0.7, height * 0.72 - 20),
size=(140, 60),
scale=0.8,
label='Full ChangeLog',
button_type='square',
on_activate_call=lambda: bui.open_url(REPOSITORY_URL + '/blob/main/CHANGELOG.md'))
loop_height = height * 0.62
for log in logs:
bui.textwidget(parent=self._root_widget,
position=(width * 0.5 * extra, loop_height), size=(0, 0),
h_align=h_align, v_align='top', text=log,
scale=text_scale, color=color,
maxwidth=width * 0.9)
loop_height -= 35
def _back(self) -> None:
bui.getsound('swish').play()
bui.containerwidget(edit=self._root_widget, transition='out_scale')
class AuthorsWindow(popup.PopupWindow):
def __init__(self, authors_info, origin_widget):
self.authors_info = authors_info
self.scale_origin = origin_widget.get_screen_space_center()
bui.getsound('swish').play()
s = 1.25 if _uiscale is babase.UIScale.SMALL else 1.39 if _uiscale is babase.UIScale.MEDIUM else 1.67
width = 400 * s
height = width * 0.8
color = (1, 1, 1)
text_scale = 0.7 * s
self._transition_out = 'out_scale'
transition = 'in_scale'
self._root_widget = bui.containerwidget(size=(width, height),
on_outside_click_call=self._back,
transition=transition,
scale=(1.5 if _uiscale is babase.UIScale.SMALL else 1.5
if _uiscale is babase.UIScale.MEDIUM else 1.0),