Repository navigation
Expand file tree
/
Copy pathpatch_android.py
More file actions
executable file
·447 lines (413 loc) · 19.6 KB
/
Copy pathpatch_android.py
File metadata and controls
executable file
·447 lines (413 loc) · 19.6 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
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
#!/usr/bin/env python3
"""Copies the Blocker sources into a fresh React Native 0.73 project and patches its Android files.
Usage: patch_android.py <project_dir> <source_dir> (safe to run more than once)"""
import re
import shutil
import sys
from pathlib import Path
proj, src = Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve()
here = Path(__file__).resolve().parent
main = proj / "android" / "app" / "src" / "main"
warnings = []
def read(p): return p.read_text(encoding="utf-8")
def write(p, t): p.write_text(t, encoding="utf-8")
# 1. JS side (legacy RN support, skipped in Pure Kotlin)
if (src / "App.tsx").exists():
shutil.copy(src / "App.tsx", proj / "App.tsx")
if (src / "src").exists():
shutil.copytree(src / "src", proj / "src", dirs_exist_ok=True)
# 2. Kotlin files (use whatever package the generated project has)
app_kt = next(main.glob("java/**/MainApplication.kt"), None)
if app_kt is None:
sys.exit("ERROR: MainApplication.kt not found.")
pkg = re.search(r"^package\s+([\w.]+)", read(app_kt), re.M).group(1)
for kt in (src / "android").glob("*.kt"):
write(app_kt.parent / kt.name, re.sub(r"^package\s+[\w.]+", f"package {pkg}", read(kt), count=1, flags=re.M))
for ks in (src / "android").glob("*.keystore"):
shutil.copy(ks, proj / "android" / "app" / ks.name)
for sub in ["data", "ui"]:
subdir = src / "android" / sub
if subdir.exists():
shutil.copytree(subdir, app_kt.parent / sub, dirs_exist_ok=True)
# 2b. Native C++ engine (CMake + C++ sources)
cpp_src = src / "android" / "cpp"
if cpp_src.exists():
cpp_dest = main / "cpp"
shutil.copytree(cpp_src, cpp_dest, dirs_exist_ok=True)
# 2c. Pre-compiled binary assets
assets_src = src / "android" / "assets"
if assets_src.exists():
assets_dest = main / "assets"
shutil.copytree(assets_src, assets_dest, dirs_exist_ok=True)
# 2d. Resources in source/android/res (drawables, etc.)
res_src = src / "android" / "res"
if res_src.exists():
shutil.copytree(res_src, main / "res", dirs_exist_ok=True)
# 3. XML resources
xml_dir = main / "res" / "xml"
xml_dir.mkdir(parents=True, exist_ok=True)
write(xml_dir / "accessibility_service_config.xml", """<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged|typeViewClicked|typeViewLongClicked"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews|flagReportViewIds"
android:canRetrieveWindowContent="true"
android:isAccessibilityTool="true"
android:notificationTimeout="20"
android:description="@string/a11y_desc"/>
""")
write(xml_dir / "device_admin.xml", """<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
<disable-keyguard-features />
</uses-policies>
</device-admin>
""")
write(xml_dir / "device_admin_policies.xml", """<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
<disable-keyguard-features />
</uses-policies>
</device-admin>
""")
write(xml_dir / "file_paths.xml", """<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="apk_updates" path="updates/"/>
</paths>
""")
strings = main / "res" / "values" / "strings.xml"
s = read(strings)
if "a11y_desc" not in s:
s = s.replace("</resources>", ' <string name="a11y_desc">Blocks adult sites and selected apps, scans the screen for blocked keywords, and protects Blocker settings from tampering.</string>\n</resources>')
write(strings, s)
# App name is always "Blocker", regardless of what name the project was initialized with.
s = read(strings)
s = re.sub(r'(<string name="app_name">)[^<]*(</string>)', r"\1Blocker\2", s, count=1)
if "app_name" not in s:
s = s.replace("<resources>", '<resources>\n <string name="app_name">Blocker</string>', 1)
write(strings, s)
# 3b. App icon, generated from assets/app-icon-source.png by generate_icons.py. Only the legacy
# per-density PNGs are used (both ic_launcher.png and ic_launcher_round.png are the same uncropped,
# unmasked artwork) \u2014 any adaptive-icon XML from the RN template is removed so Android doesn't
# ignore them in favor of the template's own foreground/background icon on API 26+.
icons_dir = here / "android_icons"
if icons_dir.exists():
res_dir = main / "res"
anydpi = res_dir / "mipmap-anydpi-v26"
if anydpi.exists():
shutil.rmtree(anydpi)
for mipmap_dir in icons_dir.glob("mipmap-*"):
dest = res_dir / mipmap_dir.name
dest.mkdir(parents=True, exist_ok=True)
for f in mipmap_dir.iterdir():
shutil.copy(f, dest / f.name)
# remove any leftover RN-template foreground/background files for this density
for stale in ("ic_launcher_foreground.png", "ic_launcher_foreground.webp", "ic_launcher_background.webp"):
(dest / stale).unlink(missing_ok=True)
# Legacy per-density folders may still have the RN default mipmap in a flat "mipmap" folder on
# some template versions; remove it so ours is used everywhere.
for legacy in (res_dir / "mipmap").glob("ic_launcher*.png"):
legacy.unlink()
else:
warnings.append("No android_icons/ found \u2014 run ./generate_icons.py first to build the app icon from assets/app-icon-source.png.")
# 4. Manifest
mf = main / "AndroidManifest.xml"
t = read(mf)
if "BlockerAccessibilityService" not in t:
if "xmlns:tools" not in t:
t = t.replace('xmlns:android="http://schemas.android.com/apk/res/android"',
'xmlns:android="http://schemas.android.com/apk/res/android"\n xmlns:tools="http://schemas.android.com/tools"', 1)
head = """<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<queries>
<intent>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent>
<intent>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.HOME"/>
</intent>
<intent>
<action android:name="android.settings.SETTINGS"/>
</intent>
<intent>
<action android:name="android.settings.APPLICATION_DETAILS_SETTINGS"/>
<data android:scheme="package"/>
</intent>
</queries>
"""
tail = """ <service
android:name=".BlockerAccessibilityService"
android:label="@string/app_name"
android:exported="false"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibility_service_config"/>
</service>
<receiver
android:name=".BlockerDeviceAdminReceiver"
android:label="@string/app_name"
android:exported="true"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin_policies"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
</intent-filter>
</receiver>
<service
android:name=".BlockerForegroundService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Distraction and adult content protection"/>
</service>
<receiver
android:name=".BootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
"""
if "<application" not in t or "</application>" not in t:
sys.exit("ERROR: unexpected AndroidManifest.xml layout")
t = t.replace("<application", head + "<application", 1)
t = t.replace("</application>", tail + "</application>", 1)
write(mf, t)
# 4b. Permissions added after the first release. Kept apart from the block above (which only runs once per
# manifest) so re-running this script upgrades a manifest that was already patched.
t = read(mf)
extra = []
for perm, attrs in (
("android.permission.WRITE_SECURE_SETTINGS", ' tools:ignore="ProtectedPermissions"'),
("android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS", ""),
("android.permission.REQUEST_INSTALL_PACKAGES", ""),
("android.permission.FOREGROUND_SERVICE", ""),
("android.permission.FOREGROUND_SERVICE_SPECIAL_USE", ' tools:ignore="ProtectedPermissions"'),
("android.permission.RECEIVE_BOOT_COMPLETED", ""),
("android.permission.ACCESS_WIFI_STATE", ""),
("android.permission.CHANGE_WIFI_STATE", ""),
("android.permission.ACCESS_NETWORK_STATE", ""),
("android.permission.ACCESS_NOTIFICATION_POLICY", ""),
("android.permission.EXPAND_STATUS_BAR", ""),
("android.permission.KILL_BACKGROUND_PROCESSES", ""),
):
if perm not in t:
extra.append(f'<uses-permission android:name="{perm}"{attrs}/>')
if extra:
if "xmlns:tools" not in t:
t = t.replace('xmlns:android="http://schemas.android.com/apk/res/android"',
'xmlns:android="http://schemas.android.com/apk/res/android"\n xmlns:tools="http://schemas.android.com/tools"', 1)
t = t.replace("<application", "\n ".join(extra) + "\n <application", 1)
write(mf, t)
# Ensure BlockerForegroundService and BootReceiver exist if manifest was previously patched
t = read(mf)
extra_components = []
if "BlockerForegroundService" not in t:
extra_components.append(""" <service
android:name=".BlockerForegroundService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Distraction and adult content protection"/>
</service>""")
if "BootReceiver" not in t:
extra_components.append(""" <receiver
android:name=".BootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>""")
if "BlockerVpnService" not in t:
extra_components.append(""" <service
android:name=".BlockerVpnService"
android:exported="false"
android:permission="android.permission.BIND_VPN_SERVICE">
<intent-filter>
<action android:name="android.net.VpnService"/>
</intent-filter>
</service>""")
if extra_components:
t = t.replace("</application>", "\n".join(extra_components) + "\n</application>", 1)
write(mf, t)
# FileProvider for in-app APK installer
t = read(mf)
if "androidx.core.content.FileProvider" not in t:
provider_xml = """ <provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
"""
t = t.replace("</application>", provider_xml + "</application>", 1)
write(mf, t)
# 4c. Set excludeFromRecents, autoRemoveFromRecents, singleTask and resizeableActivity=false on MainActivity
t = read(mf)
if 'android:name=".MainActivity"' in t:
if 'android:windowSoftInputMode="adjustResize"' not in t:
t = t.replace('android:name=".MainActivity"', 'android:name=".MainActivity"\n android:windowSoftInputMode="adjustResize"', 1)
if 'android:excludeFromRecents="true"' not in t:
t = t.replace('android:name=".MainActivity"', 'android:name=".MainActivity"\n android:excludeFromRecents="true"', 1)
if 'android:autoRemoveFromRecents="true"' not in t:
t = t.replace('android:name=".MainActivity"', 'android:name=".MainActivity"\n android:autoRemoveFromRecents="true"', 1)
if 'android:resizeableActivity="false"' not in t:
t = t.replace('android:name=".MainActivity"', 'android:name=".MainActivity"\n android:resizeableActivity="false"', 1)
if 'android:noHistory="true"' in t:
t = t.replace(' android:noHistory="true"\n', '')
# Clean up duplicate/legacy DeviceAdminReceiver entries so strictly one exists
for legacy_rec in [r"\.PrachirDeviceAdminReceiver", r"\.MyDeviceAdminReceiver"]:
t = re.sub(rf'\s*<receiver[^>]*android:name="{legacy_rec}"[^>]*>.*?</receiver>', '', t, flags=re.DOTALL)
if 'android:name=".BlockerDeviceAdminReceiver"' not in t:
blocker_rec = """ <receiver
android:name=".BlockerDeviceAdminReceiver"
android:label="@string/app_name"
android:exported="true"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin_policies"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
</intent-filter>
</receiver>
"""
t = t.replace("</application>", blocker_rec + "</application>", 1)
write(mf, t)
# 5. app/build.gradle
gr = proj / "android" / "app" / "build.gradle"
g = read(gr)
if "core-ktx" not in g:
g, n = re.subn(r"dependencies\s*\{", 'dependencies {\n implementation("androidx.core:core-ktx:1.12.0")', g, count=1)
if not n:
warnings.append("Could not add core-ktx to android/app/build.gradle (add: implementation(\"androidx.core:core-ktx:1.12.0\"))")
if "react {" in g and "debuggableVariants = []" not in g:
g, n = re.subn(r"^react\s*\{", "react {\n debuggableVariants = []", g, count=1, flags=re.M)
if not n:
warnings.append("Could not bundle JS into debug builds (add 'debuggableVariants = []' inside the react { } block)")
# versionCode/versionName, from VERSION and .build_number (set_version.py keeps these current)
version_file = here / "VERSION"
build_file = here / ".build_number"
app_version = version_file.read_text(encoding="utf-8").strip() if version_file.exists() else "1.0.0"
try:
build_number = int(build_file.read_text(encoding="utf-8").strip()) if build_file.exists() else 0
except ValueError:
build_number = 0
# Android requires versionCode to strictly monotonically increase across releases to prevent
# INSTALL_FAILED_VERSION_DOWNGRADE ("App not installed as package appears to be invalid").
# We derive a deterministic base versionCode from the semantic marketing version (MAJOR.MINOR.PATCH.HOTFIX),
# guaranteeing that any higher marketing version will always have a higher versionCode than older versions
# regardless of whether .build_number is reset.
digits = [int(p) for p in re.findall(r"\d+", app_version)]
major = digits[0] if len(digits) > 0 else 1
minor = digits[1] if len(digits) > 1 else 0
patch = digits[2] if len(digits) > 2 else 0
hotfix = digits[3] if len(digits) > 3 else 0
semver_base = (major * 1_000_000) + (minor * 100_000) + (patch * 1_000) + (hotfix * 100)
# Minimum 1006810 ensures monotonic increase over any previous v1.0.6.8 (1006805) build to prevent INSTALL_FAILED_VERSION_DOWNGRADE
version_code = max(1006810, semver_base + (build_number % 100) + 100)
g, n1 = re.subn(r"versionCode\s+\d+", f"versionCode {version_code}", g, count=1)
g, n2 = re.subn(r'versionName\s+"[^"]*"', f'versionName "{app_version}"', g, count=1)
if not n1 or not n2:
warnings.append(
f"Could not find versionCode/versionName in android/app/build.gradle to set them to "
f"{build_number}/\"{app_version}\" \u2014 set them there by hand."
)
if "versionCodeOverride" not in g:
variant_hook = """
applicationVariants.all { variant ->
if (variant.buildType.name == "release") {
variant.outputs.each { output ->
output.versionCodeOverride = defaultConfig.versionCode + 100000
}
}
}
}
"""
g = re.sub(r"\n\}\s*\n(dependencies\s*\{)", variant_hook + r"\1", g, count=1)
if "externalNativeBuild" not in g:
cmake_block = """
externalNativeBuild {
cmake {
arguments "-DANDROID_STL=c++_shared"
}
}
ndk {
abiFilters "armeabi-v7a", "arm64-v8a", "x86_64"
}
"""
g = re.sub(r"(defaultConfig\s*\{)", r"\1" + cmake_block, g, count=1)
cmake_root = """
externalNativeBuild {
cmake {
path file("src/main/cpp/CMakeLists.txt")
version "3.22.1"
}
}
"""
g = re.sub(r"(buildTypes\s*\{)", cmake_root + r"\1", g, count=1)
g = re.sub(r'abiFilters\s+"armeabi-v7a",\s*"arm64-v8a"(?!,\s*"x86_64")', 'abiFilters "armeabi-v7a", "arm64-v8a", "x86_64"', g)
if "buildConfig true" not in g:
g = re.sub(r"(buildFeatures\s*\{[^}]*)", r'\1\n buildConfig true', g, count=1)
if 'buildConfigField "boolean", "IS_DEBUG_TIMER"' not in g:
g = re.sub(r"(debug\s*\{[^}]*)", r'\1\n buildConfigField "boolean", "IS_DEBUG_TIMER", "true"\n buildConfigField "long", "DEBUG_UNLOCK_DURATION_MS", "60000L"', g, count=1)
g = re.sub(r"(release\s*\{[^}]*)", r'\1\n buildConfigField "boolean", "IS_DEBUG_TIMER", "false"\n buildConfigField "long", "DEBUG_UNLOCK_DURATION_MS", "60000L"', g, count=1)
write(gr, g)
# 6. Decouple React Native in MainApplication.kt and register native package
a = read(app_kt)
if "val reactNativeHost: ReactNativeHost =" in a:
a = re.sub(
r"override\s+val\s+reactNativeHost:\s*ReactNativeHost\s*=\s*(object\s*:\s*DefaultReactNativeHost\(this\)\s*\{[\s\S]*?\n\s*\})",
r"override val reactNativeHost: ReactNativeHost by lazy {\n \1\n }",
a,
count=1
)
if "ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)" in a:
a = a.replace("ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)", "// ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)")
if "NativeBlockerBridge.load" not in a:
a = re.sub(
r"(super\.onCreate\(\))",
r'\1\n val binFile = java.io.File(filesDir, "blocklist.bin")\n if (!binFile.exists()) { runCatching { assets.open("blocklist.bin").use { it.copyTo(binFile.outputStream()) } } }\n if (binFile.exists()) { NativeBlockerBridge.load(binFile) }',
a,
count=1
)
if "PackageList" in a and "BlockerPackage()" not in a:
a, n = re.subn(r"//\s*add\(MyReactNativePackage\(\)\)", "add(BlockerPackage())", a, count=1)
if n:
write(app_kt, a)
else:
warnings.append(f"Add `add(BlockerPackage())` inside PackageList(this).packages.apply {{ ... }} in {app_kt}")
else:
write(app_kt, a)
print("Patched project:", proj)
for w in warnings:
print("WARNING:", w)
sys.exit(2 if warnings else 0)