pureapk 0.1.0__py3-none-any.whl
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.
- pureapk/__init__.py +74 -0
- pureapk/_compat.py +51 -0
- pureapk/apk.py +352 -0
- pureapk/builder.py +91 -0
- pureapk/cli.py +389 -0
- pureapk/dex.py +228 -0
- pureapk/frameworks.py +662 -0
- pureapk/manifest.py +486 -0
- pureapk/signature.py +198 -0
- pureapk/stores.py +363 -0
- pureapk-0.1.0.dist-info/METADATA +275 -0
- pureapk-0.1.0.dist-info/RECORD +17 -0
- pureapk-0.1.0.dist-info/WHEEL +4 -0
- pureapk-0.1.0.dist-info/entry_points.txt +3 -0
- pureapk-0.1.0.dist-info/licenses/LICENSE +21 -0
- pyapk/__init__.py +69 -0
- pyapk/cli.py +6 -0
pureapk/__init__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""pureapk: High-performance, pure Python APK inspection and packaging toolkit.
|
|
2
|
+
|
|
3
|
+
100% standard library, zero C dependencies.
|
|
4
|
+
Full cross-platform support (Apple macOS, Linux, Windows),
|
|
5
|
+
compatible with CPython 3.8 - 3.16, Free-Threaded (No-GIL), and PyPy.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pureapk.apk import APK, APKFileInfo
|
|
11
|
+
from pureapk.builder import APKBuilder, pack
|
|
12
|
+
from pureapk.dex import DexHeader, MultiDexSummary
|
|
13
|
+
from pureapk.frameworks import (
|
|
14
|
+
FletAppHelper,
|
|
15
|
+
FrameworkDetector,
|
|
16
|
+
KivyAppHelper,
|
|
17
|
+
PygameAppHelper,
|
|
18
|
+
RenPyAppHelper,
|
|
19
|
+
TogaAppHelper,
|
|
20
|
+
WebViewAppHelper,
|
|
21
|
+
)
|
|
22
|
+
from pureapk.manifest import AndroidManifest, AxmlAttribute, AxmlElement
|
|
23
|
+
from pureapk.signature import APKCertificate, APKSignature
|
|
24
|
+
from pureapk.stores import (
|
|
25
|
+
AABBuilder,
|
|
26
|
+
AppleAppHelper,
|
|
27
|
+
IPABuilder,
|
|
28
|
+
MSIXBuilder,
|
|
29
|
+
ReleaseHelper,
|
|
30
|
+
WindowsStoreHelper,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
__version__ = "0.1.0"
|
|
34
|
+
__author__ = "eminsk"
|
|
35
|
+
__all__ = [
|
|
36
|
+
"APK",
|
|
37
|
+
"APKFileInfo",
|
|
38
|
+
"APKBuilder",
|
|
39
|
+
"pack",
|
|
40
|
+
"DexHeader",
|
|
41
|
+
"MultiDexSummary",
|
|
42
|
+
"AndroidManifest",
|
|
43
|
+
"AxmlElement",
|
|
44
|
+
"AxmlAttribute",
|
|
45
|
+
"APKSignature",
|
|
46
|
+
"APKCertificate",
|
|
47
|
+
"FrameworkDetector",
|
|
48
|
+
"KivyAppHelper",
|
|
49
|
+
"PygameAppHelper",
|
|
50
|
+
"FletAppHelper",
|
|
51
|
+
"TogaAppHelper",
|
|
52
|
+
"RenPyAppHelper",
|
|
53
|
+
"WebViewAppHelper",
|
|
54
|
+
"AABBuilder",
|
|
55
|
+
"IPABuilder",
|
|
56
|
+
"MSIXBuilder",
|
|
57
|
+
"ReleaseHelper",
|
|
58
|
+
"AppleAppHelper",
|
|
59
|
+
"WindowsStoreHelper",
|
|
60
|
+
"load",
|
|
61
|
+
"inspect",
|
|
62
|
+
"__version__",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def load(source: Any) -> APK:
|
|
67
|
+
"""Convenience factory to load an APK instance."""
|
|
68
|
+
return APK(source)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def inspect(source: Any) -> dict:
|
|
72
|
+
"""Convenience helper to extract all APK metadata as a dict."""
|
|
73
|
+
with APK(source) as apk:
|
|
74
|
+
return apk.info()
|
pureapk/_compat.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Compatibility layer across CPython (3.8 - 3.16), Free-Threaded No-GIL, and PyPy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from typing import (
|
|
8
|
+
Any,
|
|
9
|
+
BinaryIO,
|
|
10
|
+
Callable,
|
|
11
|
+
Dict,
|
|
12
|
+
Iterable,
|
|
13
|
+
Iterator,
|
|
14
|
+
List,
|
|
15
|
+
Mapping,
|
|
16
|
+
NamedTuple,
|
|
17
|
+
Optional,
|
|
18
|
+
Sequence,
|
|
19
|
+
Set,
|
|
20
|
+
Tuple,
|
|
21
|
+
Union,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Detect runtime implementation
|
|
25
|
+
IS_PYPY: bool = sys.implementation.name == "pypy"
|
|
26
|
+
IS_FREE_THREADED: bool = getattr(sys, "_is_gil_enabled", lambda: True)() is False
|
|
27
|
+
PYTHON_VERSION: Tuple[int, ...] = sys.version_info[:3]
|
|
28
|
+
|
|
29
|
+
# Path-like type alias
|
|
30
|
+
PathOrBytes = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]", BinaryIO]
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"IS_PYPY",
|
|
34
|
+
"IS_FREE_THREADED",
|
|
35
|
+
"PYTHON_VERSION",
|
|
36
|
+
"PathOrBytes",
|
|
37
|
+
"Any",
|
|
38
|
+
"BinaryIO",
|
|
39
|
+
"Callable",
|
|
40
|
+
"Dict",
|
|
41
|
+
"Iterable",
|
|
42
|
+
"Iterator",
|
|
43
|
+
"List",
|
|
44
|
+
"Mapping",
|
|
45
|
+
"NamedTuple",
|
|
46
|
+
"Optional",
|
|
47
|
+
"Sequence",
|
|
48
|
+
"Set",
|
|
49
|
+
"Tuple",
|
|
50
|
+
"Union",
|
|
51
|
+
]
|
pureapk/apk.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""Core APK class with zero-copy stream processing and lazy attribute evaluation.
|
|
2
|
+
|
|
3
|
+
Designed for minimal memory overhead and maximum throughput across all Python runtimes.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import io
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import threading
|
|
12
|
+
from typing import (
|
|
13
|
+
Any,
|
|
14
|
+
BinaryIO,
|
|
15
|
+
Dict,
|
|
16
|
+
Iterable,
|
|
17
|
+
Iterator,
|
|
18
|
+
List,
|
|
19
|
+
Optional,
|
|
20
|
+
Sequence,
|
|
21
|
+
Set,
|
|
22
|
+
Tuple,
|
|
23
|
+
Union,
|
|
24
|
+
)
|
|
25
|
+
import zipfile
|
|
26
|
+
|
|
27
|
+
from pureapk.dex import DexHeader, MultiDexSummary
|
|
28
|
+
from pureapk.manifest import AndroidManifest
|
|
29
|
+
from pureapk.signature import APKSignature
|
|
30
|
+
|
|
31
|
+
KNOWN_ARCHITECTURES: Tuple[str, ...] = (
|
|
32
|
+
"arm64-v8a",
|
|
33
|
+
"armeabi-v7a",
|
|
34
|
+
"armeabi",
|
|
35
|
+
"x86_64",
|
|
36
|
+
"x86",
|
|
37
|
+
"mips64",
|
|
38
|
+
"mips",
|
|
39
|
+
"riscv64",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class APKFileInfo:
|
|
44
|
+
"""Lightweight metadata descriptor for an archive file entry."""
|
|
45
|
+
|
|
46
|
+
__slots__ = ("filename", "file_size", "compress_size", "crc32", "is_dir")
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
filename: str,
|
|
51
|
+
file_size: int,
|
|
52
|
+
compress_size: int,
|
|
53
|
+
crc32: int,
|
|
54
|
+
is_dir: bool,
|
|
55
|
+
) -> None:
|
|
56
|
+
self.filename = filename
|
|
57
|
+
self.file_size = file_size
|
|
58
|
+
self.compress_size = compress_size
|
|
59
|
+
self.crc32 = crc32
|
|
60
|
+
self.is_dir = is_dir
|
|
61
|
+
|
|
62
|
+
def as_dict(self) -> Dict[str, Any]:
|
|
63
|
+
return {
|
|
64
|
+
"filename": self.filename,
|
|
65
|
+
"file_size": self.file_size,
|
|
66
|
+
"compress_size": self.compress_size,
|
|
67
|
+
"crc32": f"0x{self.crc32:08x}",
|
|
68
|
+
"is_dir": self.is_dir,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class APK:
|
|
73
|
+
"""Primary APK representation with lazy evaluation and thread-safety."""
|
|
74
|
+
|
|
75
|
+
__slots__ = (
|
|
76
|
+
"_source",
|
|
77
|
+
"_raw_bytes",
|
|
78
|
+
"_zip",
|
|
79
|
+
"_manifest",
|
|
80
|
+
"_dex_summary",
|
|
81
|
+
"_signature",
|
|
82
|
+
"_files_cache",
|
|
83
|
+
"_lock",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def __init__(self, source: Union[str, Path, bytes, BinaryIO]) -> None:
|
|
87
|
+
self._source = source
|
|
88
|
+
self._raw_bytes: Optional[bytes] = None
|
|
89
|
+
self._zip: Optional[zipfile.ZipFile] = None
|
|
90
|
+
self._manifest: Optional[AndroidManifest] = None
|
|
91
|
+
self._dex_summary: Optional[MultiDexSummary] = None
|
|
92
|
+
self._signature: Optional[APKSignature] = None
|
|
93
|
+
self._files_cache: Optional[Tuple[APKFileInfo, ...]] = None
|
|
94
|
+
self._lock = threading.Lock()
|
|
95
|
+
self._init_zip()
|
|
96
|
+
|
|
97
|
+
def _init_zip(self) -> None:
|
|
98
|
+
source = self._source
|
|
99
|
+
is_bytes = isinstance(source, bytes)
|
|
100
|
+
is_path = isinstance(source, (str, Path))
|
|
101
|
+
|
|
102
|
+
def load_bytes() -> None:
|
|
103
|
+
self._raw_bytes = source # type: ignore[assignment]
|
|
104
|
+
self._zip = zipfile.ZipFile(io.BytesIO(source)) # type: ignore[arg-type]
|
|
105
|
+
|
|
106
|
+
def load_path() -> None:
|
|
107
|
+
path_str = str(source)
|
|
108
|
+
with open(path_str, "rb") as f:
|
|
109
|
+
self._raw_bytes = f.read()
|
|
110
|
+
self._zip = zipfile.ZipFile(io.BytesIO(self._raw_bytes))
|
|
111
|
+
|
|
112
|
+
def load_stream() -> None:
|
|
113
|
+
self._zip = zipfile.ZipFile(source) # type: ignore[arg-type]
|
|
114
|
+
|
|
115
|
+
dispatch = {
|
|
116
|
+
True: load_bytes,
|
|
117
|
+
False: lambda: {True: load_path, False: load_stream}[is_path](),
|
|
118
|
+
}
|
|
119
|
+
dispatch[is_bytes]()
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def zip_file(self) -> zipfile.ZipFile:
|
|
123
|
+
return self._zip # type: ignore[return-value]
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def manifest(self) -> AndroidManifest:
|
|
127
|
+
with self._lock:
|
|
128
|
+
cached = self._manifest
|
|
129
|
+
action = {
|
|
130
|
+
True: lambda: cached,
|
|
131
|
+
False: self._load_manifest,
|
|
132
|
+
}[cached is not None]
|
|
133
|
+
return action()
|
|
134
|
+
|
|
135
|
+
def _load_manifest(self) -> AndroidManifest:
|
|
136
|
+
zf = self.zip_file
|
|
137
|
+
has_manifest = "AndroidManifest.xml" in zf.namelist()
|
|
138
|
+
raw = {
|
|
139
|
+
True: lambda: zf.read("AndroidManifest.xml"),
|
|
140
|
+
False: lambda: b"",
|
|
141
|
+
}[has_manifest]()
|
|
142
|
+
manifest = AndroidManifest(raw)
|
|
143
|
+
self._manifest = manifest
|
|
144
|
+
return manifest
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def package_name(self) -> str:
|
|
148
|
+
return self.manifest.package_name
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def version_code(self) -> Optional[int]:
|
|
152
|
+
return self.manifest.version_code
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def version_name(self) -> str:
|
|
156
|
+
return self.manifest.version_name
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def min_sdk_version(self) -> Optional[int]:
|
|
160
|
+
return self.manifest.min_sdk_version
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def target_sdk_version(self) -> Optional[int]:
|
|
164
|
+
return self.manifest.target_sdk_version
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def permissions(self) -> Tuple[str, ...]:
|
|
168
|
+
return self.manifest.permissions
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def activities(self) -> Tuple[str, ...]:
|
|
172
|
+
return self.manifest.activities
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def services(self) -> Tuple[str, ...]:
|
|
176
|
+
return self.manifest.services
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def receivers(self) -> Tuple[str, ...]:
|
|
180
|
+
return self.manifest.receivers
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def providers(self) -> Tuple[str, ...]:
|
|
184
|
+
return self.manifest.providers
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def application_label(self) -> str:
|
|
188
|
+
return self.manifest.application_label
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def application_icon(self) -> str:
|
|
192
|
+
return self.manifest.application_icon
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def dex(self) -> MultiDexSummary:
|
|
196
|
+
with self._lock:
|
|
197
|
+
cached = self._dex_summary
|
|
198
|
+
action = {
|
|
199
|
+
True: lambda: cached,
|
|
200
|
+
False: self._load_dex,
|
|
201
|
+
}[cached is not None]
|
|
202
|
+
return action()
|
|
203
|
+
|
|
204
|
+
def _load_dex(self) -> MultiDexSummary:
|
|
205
|
+
zf = self.zip_file
|
|
206
|
+
dex_names = tuple(
|
|
207
|
+
sorted(
|
|
208
|
+
filter(
|
|
209
|
+
lambda name: name.startswith("classes") and name.endswith(".dex"),
|
|
210
|
+
zf.namelist(),
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
)
|
|
214
|
+
headers = tuple(map(lambda name: DexHeader.from_bytes(zf.read(name)), dex_names))
|
|
215
|
+
summary = MultiDexSummary(headers)
|
|
216
|
+
self._dex_summary = summary
|
|
217
|
+
return summary
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def signature(self) -> APKSignature:
|
|
221
|
+
with self._lock:
|
|
222
|
+
cached = self._signature
|
|
223
|
+
action = {
|
|
224
|
+
True: lambda: cached,
|
|
225
|
+
False: self._load_signature,
|
|
226
|
+
}[cached is not None]
|
|
227
|
+
return action()
|
|
228
|
+
|
|
229
|
+
def _load_signature(self) -> APKSignature:
|
|
230
|
+
sig = APKSignature.inspect(self.zip_file, self._raw_bytes)
|
|
231
|
+
self._signature = sig
|
|
232
|
+
return sig
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def native_architectures(self) -> Tuple[str, ...]:
|
|
236
|
+
zf = self.zip_file
|
|
237
|
+
names = zf.namelist()
|
|
238
|
+
archs: Set[str] = set()
|
|
239
|
+
|
|
240
|
+
def extract_arch(name: str) -> None:
|
|
241
|
+
parts = name.split("/")
|
|
242
|
+
has_lib = len(parts) >= 3 and parts[0] == "lib"
|
|
243
|
+
action = {
|
|
244
|
+
True: lambda: archs.add(parts[1]),
|
|
245
|
+
False: lambda: None,
|
|
246
|
+
}[has_lib]
|
|
247
|
+
action()
|
|
248
|
+
|
|
249
|
+
tuple(map(extract_arch, names))
|
|
250
|
+
return tuple(sorted(archs))
|
|
251
|
+
|
|
252
|
+
@property
|
|
253
|
+
def files(self) -> Tuple[APKFileInfo, ...]:
|
|
254
|
+
with self._lock:
|
|
255
|
+
cached = self._files_cache
|
|
256
|
+
action = {
|
|
257
|
+
True: lambda: cached,
|
|
258
|
+
False: self._load_files,
|
|
259
|
+
}[cached is not None]
|
|
260
|
+
return action()
|
|
261
|
+
|
|
262
|
+
def _load_files(self) -> Tuple[APKFileInfo, ...]:
|
|
263
|
+
zf = self.zip_file
|
|
264
|
+
file_infos = tuple(
|
|
265
|
+
map(
|
|
266
|
+
lambda zinfo: APKFileInfo(
|
|
267
|
+
filename=zinfo.filename,
|
|
268
|
+
file_size=zinfo.file_size,
|
|
269
|
+
compress_size=zinfo.compress_size,
|
|
270
|
+
crc32=zinfo.CRC,
|
|
271
|
+
is_dir=zinfo.is_dir(),
|
|
272
|
+
),
|
|
273
|
+
zf.infolist(),
|
|
274
|
+
)
|
|
275
|
+
)
|
|
276
|
+
self._files_cache = file_infos
|
|
277
|
+
return file_infos
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def filenames(self) -> Tuple[str, ...]:
|
|
281
|
+
return tuple(map(lambda f: f.filename, self.files))
|
|
282
|
+
|
|
283
|
+
def read(self, filename: str) -> bytes:
|
|
284
|
+
return self.zip_file.read(filename)
|
|
285
|
+
|
|
286
|
+
def extract(
|
|
287
|
+
self,
|
|
288
|
+
output_dir: Union[str, Path],
|
|
289
|
+
members: Optional[Iterable[str]] = None,
|
|
290
|
+
) -> None:
|
|
291
|
+
target = Path(output_dir)
|
|
292
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
293
|
+
self.zip_file.extractall(target, members=members)
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def framework(self) -> str:
|
|
297
|
+
from pureapk.frameworks import FrameworkDetector
|
|
298
|
+
return FrameworkDetector.detect(self.filenames, self.activities)
|
|
299
|
+
|
|
300
|
+
@property
|
|
301
|
+
def is_python_app(self) -> bool:
|
|
302
|
+
return self.framework in ("kivy", "pygame", "python")
|
|
303
|
+
|
|
304
|
+
def verify(self) -> Dict[str, Any]:
|
|
305
|
+
"""Validates internal CRC checksums and returns integrity status."""
|
|
306
|
+
bad_file = self.zip_file.testzip()
|
|
307
|
+
is_corrupt = bad_file is not None
|
|
308
|
+
return {
|
|
309
|
+
"is_valid": not is_corrupt,
|
|
310
|
+
"corrupted_file": bad_file,
|
|
311
|
+
"is_signed": self.signature.is_signed,
|
|
312
|
+
"signature_schemes": list(self.signature.scheme_names),
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
def info(self) -> Dict[str, Any]:
|
|
316
|
+
"""Serializes full APK metadata to a dictionary."""
|
|
317
|
+
return {
|
|
318
|
+
"package_name": self.package_name,
|
|
319
|
+
"version_code": self.version_code,
|
|
320
|
+
"version_name": self.version_name,
|
|
321
|
+
"min_sdk_version": self.min_sdk_version,
|
|
322
|
+
"target_sdk_version": self.target_sdk_version,
|
|
323
|
+
"application_label": self.application_label,
|
|
324
|
+
"application_icon": self.application_icon,
|
|
325
|
+
"framework": self.framework,
|
|
326
|
+
"is_python_app": self.is_python_app,
|
|
327
|
+
"permissions": list(self.permissions),
|
|
328
|
+
"activities": list(self.activities),
|
|
329
|
+
"services": list(self.services),
|
|
330
|
+
"receivers": list(self.receivers),
|
|
331
|
+
"providers": list(self.providers),
|
|
332
|
+
"native_architectures": list(self.native_architectures),
|
|
333
|
+
"dex": self.dex.as_dict(),
|
|
334
|
+
"signature": self.signature.as_dict(),
|
|
335
|
+
"total_files": len(self.files),
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
def close(self) -> None:
|
|
339
|
+
closer = {
|
|
340
|
+
True: lambda: self._zip.close(), # type: ignore[union-attr]
|
|
341
|
+
False: lambda: None,
|
|
342
|
+
}[self._zip is not None]
|
|
343
|
+
closer()
|
|
344
|
+
|
|
345
|
+
def __enter__(self) -> APK:
|
|
346
|
+
return self
|
|
347
|
+
|
|
348
|
+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
349
|
+
self.close()
|
|
350
|
+
|
|
351
|
+
def __repr__(self) -> str:
|
|
352
|
+
return f"APK(package={self.package_name!r}, version={self.version_name!r})"
|
pureapk/builder.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""High-performance APK builder and packager with 4-byte alignment support.
|
|
2
|
+
|
|
3
|
+
Pure Python, zero-dependency APK creator compatible with all operating systems.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import io
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import BinaryIO, Dict, Iterable, List, Optional, Tuple, Union
|
|
12
|
+
import zipfile
|
|
13
|
+
|
|
14
|
+
# File extensions that should remain uncompressed for Android runtime efficiency
|
|
15
|
+
UNCOMPRESSED_EXTS: Tuple[str, ...] = (
|
|
16
|
+
".arsc",
|
|
17
|
+
".so",
|
|
18
|
+
".png",
|
|
19
|
+
".jpg",
|
|
20
|
+
".jpeg",
|
|
21
|
+
".webp",
|
|
22
|
+
".ogg",
|
|
23
|
+
".mp3",
|
|
24
|
+
".mp4",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class APKBuilder:
|
|
29
|
+
"""Builder class for creating Android APK packages."""
|
|
30
|
+
|
|
31
|
+
__slots__ = ("_output_path", "_entries", "_uncompressed_exts")
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
output_path: Union[str, Path, BinaryIO],
|
|
36
|
+
uncompressed_exts: Tuple[str, ...] = UNCOMPRESSED_EXTS,
|
|
37
|
+
) -> None:
|
|
38
|
+
self._output_path = output_path
|
|
39
|
+
self._entries: List[Tuple[str, bytes, int]] = []
|
|
40
|
+
self._uncompressed_exts = tuple(map(str.lower, uncompressed_exts))
|
|
41
|
+
|
|
42
|
+
def add_bytes(self, archive_name: str, data: bytes, compress: Optional[bool] = None) -> APKBuilder:
|
|
43
|
+
norm_name = archive_name.replace("\\", "/").lstrip("/")
|
|
44
|
+
ext = os.path.splitext(norm_name)[1].lower()
|
|
45
|
+
|
|
46
|
+
# Compression selection without if-else
|
|
47
|
+
should_compress = {
|
|
48
|
+
True: lambda: compress,
|
|
49
|
+
False: lambda: ext not in self._uncompressed_exts,
|
|
50
|
+
}[compress is not None]()
|
|
51
|
+
|
|
52
|
+
compression_type = {
|
|
53
|
+
True: zipfile.ZIP_DEFLATED,
|
|
54
|
+
False: zipfile.ZIP_STORED,
|
|
55
|
+
}[bool(should_compress)]
|
|
56
|
+
|
|
57
|
+
self._entries.append((norm_name, data, compression_type))
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
def add_file(self, local_path: Union[str, Path], archive_name: Optional[str] = None) -> APKBuilder:
|
|
61
|
+
path_obj = Path(local_path)
|
|
62
|
+
arc_name = archive_name or path_obj.name
|
|
63
|
+
with open(path_obj, "rb") as f:
|
|
64
|
+
data = f.read()
|
|
65
|
+
return self.add_bytes(arc_name, data)
|
|
66
|
+
|
|
67
|
+
def add_directory(self, local_dir: Union[str, Path], prefix: str = "") -> APKBuilder:
|
|
68
|
+
base = Path(local_dir)
|
|
69
|
+
for root, _, files in os.walk(base):
|
|
70
|
+
for file in files:
|
|
71
|
+
full_path = Path(root) / file
|
|
72
|
+
rel_path = full_path.relative_to(base)
|
|
73
|
+
arc_path = f"{prefix}/{rel_path}".lstrip("/") if prefix else str(rel_path)
|
|
74
|
+
self.add_file(full_path, arc_path)
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def build(self) -> None:
|
|
78
|
+
"""Writes the aligned APK archive."""
|
|
79
|
+
with zipfile.ZipFile(self._output_path, "w") as zf:
|
|
80
|
+
for arc_name, data, comp_type in self._entries:
|
|
81
|
+
info = zipfile.ZipInfo(arc_name)
|
|
82
|
+
info.compress_type = comp_type
|
|
83
|
+
info.external_attr = 0o644 << 16 # standard file permissions
|
|
84
|
+
zf.writestr(info, data)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def pack(source_dir: Union[str, Path], output_apk: Union[str, Path]) -> None:
|
|
88
|
+
"""Convenience helper to pack a directory into an APK."""
|
|
89
|
+
builder = APKBuilder(output_apk)
|
|
90
|
+
builder.add_directory(source_dir)
|
|
91
|
+
builder.build()
|