forked from j-hc/revanced-magisk-module
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.sh
More file actions
executable file
·984 lines (917 loc) · 34.7 KB
/
Copy pathutils.sh
File metadata and controls
executable file
·984 lines (917 loc) · 34.7 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
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
#!/usr/bin/env bash
# Shared helpers for Morphe Module Builder.
#
# This file is sourced by build.sh. Keep it free of commands which only make
# sense in an interactive shell: build.sh also sources it from CI and from
# Termux.
PROJECT_NAME="Morphe Module Builder"
MODULE_TEMPLATE_DIR="morphe-module"
CWD="${CWD:-$(pwd)}"
TEMP_DIR="${TEMP_DIR:-temp}"
BIN_DIR="${BIN_DIR:-bin}"
BUILD_DIR="${BUILD_DIR:-build}"
GH_AUTH_TOKEN="${GITHUB_TOKEN:-${GH_TOKEN-}}"
if [ -n "$GH_AUTH_TOKEN" ]; then
GH_HEADER="Authorization: Bearer ${GH_AUTH_TOKEN}"
else
GH_HEADER=""
fi
NEXT_VER_CODE="${NEXT_VER_CODE:-$(date +'%Y%m%d')}"
OS="$(uname -o 2>/dev/null || uname -s)"
###############################################################################
# Small shell helpers
###############################################################################
is_android() { [ "$OS" = "Android" ] || [ -d /data/adb ]; }
isoneof() {
local needle="${1-}" value
shift || true
for value; do
[ "$value" = "$needle" ] && return 0
done
return 1
}
vtf() {
if ! isoneof "${1-}" true false; then
abort "ERROR: '${1-}' is not a valid option for '${2-}': only true or false is allowed"
fi
}
slugify() {
local value="${1-}"
value="${value,,}"
value="${value// /-}"
value="${value//[^a-z0-9._-]/-}"
value="${value##-}"
value="${value%%-}"
printf '%s' "${value:-app}"
}
path_from_cwd() {
case "${1-}" in
/*) printf '%s' "$1" ;;
*) printf '%s/%s' "$CWD" "${1-}" ;;
esac
}
# Print a human-readable progress line. Error output goes to stderr so command
# substitutions can safely consume paths and API responses.
pr() { echo -e "\033[0;32m[+] ${1-}\033[0m"; }
epr() {
echo >&2 -e "\033[0;31m[-] ${1-}\033[0m"
if [ -n "${GITHUB_REPOSITORY-}" ]; then
echo -e "::error::${PROJECT_NAME} [-] ${1-}\n"
fi
}
abort() {
epr "ABORT: ${1-}"
exit 1
}
###############################################################################
# Lightweight TOML reader
###############################################################################
# The project configuration deliberately uses a small, documented subset of
# TOML: tables, comments, booleans, numbers and strings. These helpers keep
# the builder dependency-free on Android/Termux. Quoted '#' characters are
# preserved and table names may contain spaces.
toml_prep() {
__TOML__=$(awk '
{
line = $0
quote = ""
escaped = 0
out = ""
for (i = 1; i <= length(line); i++) {
c = substr(line, i, 1)
if (quote != "") {
out = out c
if (c == quote && !escaped) quote = ""
if (c == "\\" && !escaped) escaped = 1
else escaped = 0
} else if (c == "\"" || c == "\047") {
quote = c
out = out c
} else if (c == "#") {
break
} else {
out = out c
}
}
gsub(/^[[:space:]]+|[[:space:]]+$/, "", out)
if (out != "") print out
}
' <<<"${1-}" | sed -E 's/[[:space:]]*=[[:space:]]*/=/')
}
toml_get_table_names() {
local names
names=$(awk '/^\[[^][]+\]$/ { gsub(/^\[|\]$/, ""); print }' <<<"${__TOML__-}") || return 1
[ -n "$names" ] || return 0
if [ "$(sort <<<"$names" | uniq -d | wc -l)" -ne 0 ]; then
abort "ERROR: duplicate tables in TOML"
fi
printf '%s\n' "$names"
}
toml_get_table() {
local wanted="${1-}"
awk -v wanted="$wanted" '
BEGIN { in_table = (wanted == "") }
/^[[][^][]+[]]$/ {
name = $0
gsub(/^\[|\]$/, "", name)
if (wanted == "") exit
in_table = (name == wanted)
next
}
in_table { print }
' <<<"${__TOML__-}"
}
toml_get() {
local table="${1-}" key="${2-}" value
value=$(awk -F= -v key="$key" '
$1 == key {
value = substr($0, index($0, "=") + 1)
gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
print value
exit
}
' <<<"$table") || return 1
[ -n "$value" ] || return 1
case "$value" in
\"*\") value="${value:1:${#value}-2}" ;;
\'*\') value="${value:1:${#value}-2}" ;;
esac
printf '%s' "$value"
}
# Turn a whitespace-separated list of quoted patch names into one name per
# line. Both single and double quotes are accepted in config values, e.g.
# 'Remove ads' 'Custom icon'.
list_args() {
local input="${1-}" token="" quote="" escaped=false c i
for ((i = 0; i < ${#input}; i++)); do
c="${input:i:1}"
if [ -n "$quote" ]; then
if [ "$c" = "\\" ] && [ "$escaped" = false ]; then
escaped=true
continue
fi
if [ "$c" = "$quote" ] && [ "$escaped" = false ]; then
quote=""
else
token+="$c"
fi
escaped=false
elif [ "$c" = "\"" ] || [ "$c" = "'" ]; then
quote="$c"
elif [[ "$c" =~ [[:space:]] ]]; then
if [ -n "$token" ]; then
printf '%s\n' "$token"
token=""
fi
else
token+="$c"
fi
done
[ -n "$token" ] && printf '%s\n' "$token"
}
append_patch_names() {
local selection="${1-}" flag="${2-}" name
while IFS= read -r name; do
[ -n "$name" ] && PATCH_ARGS+=("$flag" "$name")
done < <(list_args "$selection")
}
###############################################################################
# HTTP and GitHub release helpers
###############################################################################
_req() {
local input_url="${1-}" output="${2-}"
shift 2
if [ "$output" = "-" ]; then
wget -qO- --timeout=30 --tries=3 "$@" "$input_url"
return
fi
if [ -s "$output" ]; then return 0; fi
mkdir -p "$(dirname "$output")"
local temporary="$(dirname "$output")/tmp.$(basename "$output")"
if [ -e "$temporary" ]; then
# Another parallel app may already be downloading this asset.
while [ -e "$temporary" ]; do sleep 1; done
[ -s "$output" ]
return
fi
if ! wget -nv -O "$temporary" --timeout=60 --tries=3 "$@" "$input_url"; then
rm -f "$temporary"
return 1
fi
[ -s "$temporary" ] || { rm -f "$temporary"; return 1; }
mv -f "$temporary" "$output"
}
req() {
_req "$1" "$2" \
--header="User-Agent: Morphe-Module-Builder/1.0 (https://github.com/iamsmmh/morphe-module-builder)"
}
gh_req() {
if [ -n "$GH_HEADER" ]; then
_req "$1" "$2" --header="$GH_HEADER" --header="Accept: application/vnd.github+json"
else
_req "$1" "$2" --header="Accept: application/vnd.github+json"
fi
}
gh_dl() {
local output="${1-}" url="${2-}"
if [ ! -s "$output" ]; then
pr "Getting '$output'" >&2
if [ -n "$GH_HEADER" ]; then
_req "$url" "$output" --header="$GH_HEADER" --header="Accept: application/octet-stream" || return 1
else
_req "$url" "$output" --header="Accept: application/octet-stream" || return 1
fi
fi
}
repo_cache_name() {
printf '%s' "${1,,}" | sed 's#[^a-z0-9._-]#-#g'
}
# Resolve one asset from a Morphe-compatible GitHub release. The result is a
# local path. `version` accepts latest, dev, or an exact release tag.
get_release_asset() {
local repo="$1" version="$2" suffix="$3" label="$4"
local release_url="https://api.github.com/repos/${repo}/releases" response release tag asset
case "$version" in
latest) release_url+="/latest" ;;
dev) ;;
*) release_url+="/tags/${version}" ;;
esac
response=$(gh_req "$release_url" -) || return 1
if [ "$version" = dev ]; then
response=$(jq -e -c 'map(select(.draft == false and .prerelease == true))[0]' <<<"$response") || return 1
fi
[ "$response" != null ] || return 1
tag=$(jq -e -r '.tag_name' <<<"$response") || return 1
asset=$(jq -e -r --arg suffix "$suffix" \
'[.assets[] | select(.name | endswith($suffix))] |
if length == 0 then error("release asset not found") else .[0] | [.name, .url] | @tsv end' \
<<<"$response") || return 1
local asset_name="${asset%%$'\t'*}" api_url="${asset#*$'\t'}"
local cache_dir="${TEMP_DIR}/morphe/$(repo_cache_name "$repo")"
local target="${cache_dir}/${asset_name}"
mkdir -p "$cache_dir"
if [ ! -s "$target" ]; then
pr "Getting ${label} ${repo}@${tag}" >&2
gh_dl "$target" "$api_url" || return 1
fi
printf '%s' "$target"
}
get_morphe_prebuilts() {
local desktop_source="$1" desktop_version="$2" patches_source="$3" patches_version="$4"
local desktop patches
desktop=$(get_release_asset "$desktop_source" "$desktop_version" "-all.jar" "Morphe Desktop") || return 1
patches=$(get_release_asset "$patches_source" "$patches_version" ".mpp" "Morphe patches") || return 1
printf '%s\t%s\n' "$desktop" "$patches"
}
###############################################################################
# Download helper binaries
###############################################################################
get_prebuilts() {
APKSIGNER="${BIN_DIR}/apksigner.jar"
if is_android; then
if [ "$(uname -m)" = aarch64 ]; then
HTMLQ="${BIN_DIR}/htmlq/htmlq-arm64"
else
HTMLQ="${BIN_DIR}/htmlq/htmlq-arm"
fi
else
if [ "$(uname -m)" = aarch64 ]; then HTMLQ="${BIN_DIR}/htmlq/htmlq-arm64"; else HTMLQ="${BIN_DIR}/htmlq/htmlq-x86_64"; fi
fi
[ -x "$HTMLQ" ] || abort "htmlq helper is missing or not executable: $HTMLQ"
}
get_module_prebuilts() {
# cmpr is executed on the Android device by the generated module. Keep the
# four architecture-specific copies in the template, but fetch them only
# when a build actually needs to package a module.
[ "${MODULE_PREBUILTS_READY:-false}" = true ] && return 0
mkdir -p "${MODULE_TEMPLATE_DIR}/bin/arm64" "${MODULE_TEMPLATE_DIR}/bin/arm" \
"${MODULE_TEMPLATE_DIR}/bin/x86" "${MODULE_TEMPLATE_DIR}/bin/x64"
gh_dl "${MODULE_TEMPLATE_DIR}/bin/arm64/cmpr" "https://github.com/j-hc/cmpr/releases/latest/download/cmpr-arm64-v8a"
gh_dl "${MODULE_TEMPLATE_DIR}/bin/arm/cmpr" "https://github.com/j-hc/cmpr/releases/latest/download/cmpr-armeabi-v7a"
gh_dl "${MODULE_TEMPLATE_DIR}/bin/x86/cmpr" "https://github.com/j-hc/cmpr/releases/latest/download/cmpr-x86"
gh_dl "${MODULE_TEMPLATE_DIR}/bin/x64/cmpr" "https://github.com/j-hc/cmpr/releases/latest/download/cmpr-x86_64"
chmod 0755 "${MODULE_TEMPLATE_DIR}"/bin/*/cmpr 2>/dev/null || true
MODULE_PREBUILTS_READY=true
}
###############################################################################
# Release/update bookkeeping
###############################################################################
log() { printf '%b \n' "${1-}" >>"build.md"; }
get_highest_ver() {
local versions
versions=$(awk 'NF { print $1 }' | sort -u)
[ -n "$versions" ] || return 1
# sort -V handles normal Android version names and Morphe's occasional
# prerelease suffixes. If the first item is not version-shaped, keep it.
local first="$(head -n 1 <<<"$versions")"
if semver_validate "$first"; then
sort -rV <<<"$versions" | head -n 1
else
printf '%s\n' "$first"
fi
}
semver_validate() {
[[ "${1-}" =~ ^v?[0-9]+([.][0-9]+)*([_-][A-Za-z0-9.+_-]+)?$ ]]
}
# Morphe Desktop prints, for example:
# Package name: com.google.android.youtube
# Most common compatible versions:
# 20.10.40 (8 patches)
# Read only the requested package and choose the newest compatible version.
get_patch_last_supported_ver() {
local morphe_jar="$1" patches_file="$2" pkg_name="$3"
local included="$4" exclusive="$5" output versions
local version_args=(list-versions --patches "$patches_file" --filter-package-names "$pkg_name")
# Explicitly selected patches may not be enabled by default. Ask Morphe to
# count those too; the final patch command still performs the exact selection.
if [ -n "$included" ] || [ "$exclusive" = true ]; then
version_args+=(--count-unused-patches)
fi
if ! output=$(java -jar "$morphe_jar" "${version_args[@]}" 2>&1); then
epr "Morphe list-versions failed for '$pkg_name': $output"
return 1
fi
versions=$(awk -v package="$pkg_name" '
index($0, "Package name: " package) { inside = 1; next }
inside && /Package name:/ { exit }
inside && /(^|[^0-9])Any([^A-Za-z0-9]|$)/ { print "Any"; exit }
inside {
line = $0
# Ignore logger prefixes and capture the first Android-like version.
if (match(line, /v?[0-9]+([.][0-9]+)+([_-][A-Za-z0-9.+_-]+)?/)) print substr(line, RSTART, RLENGTH)
}
' <<<"$output" | sort -u)
[ -n "$versions" ] || return 0
if grep -qx Any <<<"$versions"; then return 0; fi
get_highest_ver <<<"$versions"
}
###############################################################################
# APK downloads
###############################################################################
merge_splits() {
local bundle="$1" output="$2"
local apkeditor="${TEMP_DIR}/apkeditor.jar"
pr "Merging split APK bundle"
if [ ! -s "$apkeditor" ]; then
gh_dl "$apkeditor" "https://github.com/REAndroid/APKEditor/releases/download/V1.4.9/APKEditor-1.4.9.jar" || return 1
fi
local merged="${bundle}.mzip" unpack="${bundle}-zip"
rm -rf "$merged" "$unpack"
if ! OP=$(java -jar "$apkeditor" merge -i "$bundle" -o "$merged" -clean-meta -f 2>&1); then
epr "APKEditor merge failed: $OP"
return 1
fi
mkdir -p "$unpack"
unzip -qo "$merged" -d "$unpack" || return 1
(
cd "$unpack" || exit 1
zip -0rq "$(path_from_cwd "$output")" .
) || return 1
rm -rf "$merged" "$unpack"
[ -s "$output" ]
}
# -------------------- APKMirror --------------------
# APKMirror sits behind Cloudflare and intermittently answers rate-limit or
# challenge pages; retry page fetches briefly before treating them as failures.
apkmirror_req() {
local url="$1" response attempt
for attempt in 1 2 3; do
if response=$(req "$url" -); then
printf '%s' "$response"
return 0
fi
[ "$attempt" -eq 3 ] || sleep 5
done
return 1
}
# APKMirror labels a variant's DPI as 'nodpi', 'anydpi', a single density such
# as '420dpi', or a density range such as '120-640dpi' (common for universal
# BUNDLE variants). The default configuration asks for 'nodpi' (any density),
# so numeric/range variants must be accepted too; otherwise releases such as
# Reddit's would have no matching variant at all. A configured numeric dpi only
# matches when it equals the variant or falls inside its range.
apkmirror_dpi_matches() {
local actual="${1-}" cfg="${2:-nodpi}" lo hi num
case "$actual" in
nodpi|anydpi) return 0 ;;
esac
if [[ "$actual" =~ ^([0-9]+)-([0-9]+)dpi$ ]]; then
lo="${BASH_REMATCH[1]}" hi="${BASH_REMATCH[2]}"
case "$cfg" in
nodpi|anydpi|'') return 0 ;;
*dpi)
[[ "$cfg" =~ ^[0-9]+dpi$ ]] || return 1
num="${cfg%dpi}"
((num >= 10#$lo && num <= 10#$hi)) && return 0
return 1
;;
esac
fi
if [[ "$actual" =~ ^[0-9]+dpi$ ]]; then
case "$cfg" in
nodpi|anydpi|'') return 0 ;;
*dpi) [ "$actual" = "$cfg" ] && return 0 ;;
esac
fi
return 1
}
apk_mirror_search() {
local response="$1" dpi="$2" arch="$3" apk_bundle="$4"
local dlurl="" node app_table emptyCheck candidates=""
local -a apparch
if [ "$arch" = all ]; then
apparch=(universal noarch 'arm64-v8a + armeabi-v7a')
else
apparch=("$arch" universal noarch 'arm64-v8a + armeabi-v7a')
fi
local n
for ((n = 1; n < 40; n++)); do
node=$("$HTMLQ" "div.table-row.headerFont:nth-last-child($n)" -r "span:nth-child(n+3)" <<<"$response")
[ -n "$node" ] || break
# Skip non-download rows (ads, headers) which have no link in the first cell.
emptyCheck=$("$HTMLQ" -t -w "div.table-cell:nth-child(1) > a:nth-child(1)" <<<"$node" | xargs)
[ -n "$emptyCheck" ] || break
app_table=$("$HTMLQ" --text --ignore-whitespace <<<"$node")
[ "$(sed -n 3p <<<"$app_table")" = "$apk_bundle" ] || continue
[ -n "$candidates" ] && candidates+="; "
candidates+="$(sed -n 1,8p <<<"$app_table" | awk 'NR > 1 { printf " | " } { printf "%s", $0 }')"
dlurl=$("$HTMLQ" --base https://www.apkmirror.com --attribute href \
"div:nth-child(1) > a:nth-child(1)" <<<"$node")
if apkmirror_dpi_matches "$(sed -n 6p <<<"$app_table")" "$dpi" &&
isoneof "$(sed -n 4p <<<"$app_table")" "${apparch[@]}"; then
printf '%s\n' "$dlurl"
return 0
fi
done
if [ "$n" -eq 2 ] && [ -n "${dlurl:-}" ]; then
# The release page lists a single variant; accept it even when its
# dpi/arch columns do not match the configured values.
printf '%s\n' "$dlurl"
return 0
fi
# Keep diagnostics actionable: print the rows of the requested kind so a
# future APKMirror markup or variant change is easy to see in CI.
if [ -n "$candidates" ]; then
epr "APKMirror '$apk_bundle' rows found but none matched arch '$arch' dpi '$dpi': $candidates"
fi
return 1
}
dl_apkmirror() {
local base_url="${1%/}" version="${2// /-}" output="$3" arch="$4" dpi="$5"
if [ -f "${output}.apkm" ]; then
# A previous run already fetched the bundle; verification and merging
# happen in build_morphe once all sources have been tried.
return 0
fi
[ "$arch" = arm-v7a ] && arch=armeabi-v7a
local page_url="${base_url}/${base_url##*/}-${version//./-}-release/"
local response node download_page download_url bundle=false
if ! response=$(apkmirror_req "$page_url"); then
epr "APKMirror release page not reachable: $page_url"
return 1
fi
node=$("$HTMLQ" "div.table-row.headerFont:nth-last-child(1)" -r "span:nth-child(n+3)" <<<"$response")
if [ -n "$node" ]; then
if ! download_page=$(apk_mirror_search "$response" "$dpi" "$arch" APK); then
if download_page=$(apk_mirror_search "$response" "$dpi" "$arch" BUNDLE); then
bundle=true
else
epr "APKMirror has no matching variant for arch='$arch' dpi='$dpi' at: $page_url"
return 1
fi
fi
if ! response=$(apkmirror_req "$download_page"); then
epr "APKMirror variant page not reachable: $download_page"
return 1
fi
fi
download_url=$("$HTMLQ" --base https://www.apkmirror.com --attribute href "a.btn" <<<"$response") || return 1
download_url=$(req "$download_url" - | "$HTMLQ" --base https://www.apkmirror.com \
--attribute href "span > a[rel = nofollow]") || return 1
[ -n "$download_url" ] || return 1
if [ "$bundle" = true ]; then
# Keep the raw bundle next to the output. Signature verification must run
# against the original signed splits; merging happens afterwards.
req "$download_url" "${output}.apkm" || return 1
else
req "$download_url" "$output"
fi
}
get_apkmirror_resp() {
local url="${1%/}"
__APKMIRROR_RESP__=$(req "$url" -) || return 1
__APKMIRROR_CAT__="${url##*/}"
}
get_apkmirror_pkg_name() {
sed -n 's;.*id=\([^" ]*\)" class="accent_color.*;\1;p' <<<"${__APKMIRROR_RESP__-}" | head -n 1
}
get_apkmirror_vers() {
local response
response=$(req "https://www.apkmirror.com/uploads/?appcategory=${__APKMIRROR_CAT__}" -) || return 1
local versions
versions=$(sed -n 's;.*Version:</span><span class="infoSlide-value">\(.*\) </span>.*;\1;p' <<<"$response" | awk '{$1=$1}1')
if [ "${__AAV__:-false}" = false ]; then
versions=$(grep -Eiv '(beta|alpha)' <<<"$versions" || true)
fi
printf '%s\n' "$versions"
}
# -------------------- Uptodown --------------------
get_uptodown_resp() {
local url="${1%/}"
__UPTODOWN_RESP__=$(req "${url}/versions" -) || return 1
__UPTODOWN_RESP_PKG__=$(req "${url}/download" -) || return 1
__UPTODOWN_URL__="$url"
}
get_uptodown_pkg_name() { "$HTMLQ" --text "tr.full:nth-child(1) > td:nth-child(3)" <<<"${__UPTODOWN_RESP_PKG__-}"; }
get_uptodown_vers() { "$HTMLQ" --text ".version" <<<"${__UPTODOWN_RESP__-}"; }
dl_uptodown() {
local uptodown_url="${1%/}" version="$2" output="$3" arch="$4" _dpi="$5" latest="$6"
local url=""
if [ "$latest" = false ]; then
url=$(grep -F "${version}</span>" -B 2 <<<"${__UPTODOWN_RESP__-}" | head -n 1 | \
sed -n 's;.*data-url=".*download/\(.*\)".*;\1;p') || return 1
url="/${url#/}"
fi
if [ "$arch" != all ]; then
local response app_code data_version files node_arch content n
if [ "$latest" = false ]; then response=$(req "${uptodown_url}/download${url}" -); else response="${__UPTODOWN_RESP_PKG__}"; fi
app_code=$("$HTMLQ" "#detail-app-name" --attribute code <<<"$response")
data_version=$("$HTMLQ" "button.button:nth-child(2)" --attribute data-version <<<"$response")
files=$(req "${uptodown_url%/*}/app/${app_code}/version/${data_version}/files" - | jq -r .content) || return 1
for ((n = 1; n < 40; n++)); do
node_arch=$("$HTMLQ" ".content > p:nth-child($n)" --text <<<"$files" | xargs) || return 1
[ -n "$node_arch" ] || return 1
[ "$node_arch" = "$arch" ] || continue
content=$("$HTMLQ" "div.variant:nth-child($((n + 1)))" <<<"$files")
url=$(sed -n "s;.*'.*android/post-download/\(.*\)'.*;\1;p" <<<"$content" | head -n 1)
url="/${url#/}"
break
done
fi
local token
token=$(req "${uptodown_url}/post-download${url}" - | \
sed -n 's;.*class="post-download" data-url="\([^"]*\)".*;\1;p') || return 1
[ -n "$token" ] || return 1
req "https://dw.uptodown.com/dwn/${token}" "$output"
}
# -------------------- Internet Archive --------------------
get_archive_resp() {
local url="${1%/}" response
response=$(req "$url" -) || return 1
__ARCHIVE_RESP__=$(sed -n 's;^<a href="\([^"]*\.apk\)"[^>]*>.*;\1;p' <<<"$response")
[ -n "$__ARCHIVE_RESP__" ] || return 1
__ARCHIVE_URL__="$url"
__ARCHIVE_PKG_NAME__="${url##*/}"
}
get_archive_pkg_name() { printf '%s\n' "${__ARCHIVE_PKG_NAME__-}"; }
get_archive_vers() {
sed -E 's/^[^-]*-//; s/-((all|arm64-v8a|arm-v7a|armeabi-v7a))\.apk$//' <<<"${__ARCHIVE_RESP__-}"
}
dl_archive() {
local url="${1%/}" version="${2// /}" output="$3" arch="$4"
local archive_arch="$arch"
[ "$archive_arch" = all ] && archive_arch=all
local path
path=$(grep -E "${version//./\.}-${archive_arch//./\.}\.apk$" <<<"${__ARCHIVE_RESP__-}" | head -n 1) || return 1
path="${path##*/}"
req "${url}/${path}" "$output"
}
###############################################################################
# Morphe patching and output packaging
###############################################################################
check_sig() {
local file="$1" pkg_name="$2" expected signature
expected=$(awk -v pkg="$pkg_name" '$2 == pkg { print tolower($1); exit }' source-signatures.txt 2>/dev/null || true)
[ -z "$expected" ] && return 0
signature=$(java -jar "$APKSIGNER" verify --print-certs "$file" 2>/dev/null | \
grep -E '^Signer.*SHA-256' | tail -n 1 | awk '{print tolower($NF)}')
if [ -z "$signature" ] || [ "$signature" != "$expected" ]; then
epr "source signature mismatch for '$pkg_name' (expected $expected, got ${signature:-unknown})"
return 1
fi
return 0
}
# Verify every split inside an .apkm/.xapk bundle against source-signatures.txt.
# The individual splits keep the original signing certificate, while a merged
# APK does not, so bundles must be verified before they are merged.
verify_splits() {
local bundle="$1" pkg_name="$2" extract="$1-splits" a ok=true
rm -rf "$extract"
mkdir -p "$extract"
if ! unzip -qo "$bundle" -d "$extract"; then
epr "could not unpack bundle '$bundle' for signature verification"
rm -rf "$extract"
return 1
fi
for a in "$extract"/*.apk; do
[ -e "$a" ] || continue
if ! check_sig "$a" "$pkg_name"; then
ok=false
break
fi
done
rm -rf "$extract"
[ "$ok" = true ]
}
patch_apk() {
local input="$1" output="$2" morphe_jar="$3" patches_file="$4" key_store="$5" store_password="$6"
local key_alias="$7" entry_password="$8" signer="$9" temporary="${10}" result_file="${11}"
shift 11
local -a patch_args=("$@")
local -a command=(java -jar "$morphe_jar" patch --patches "$patches_file" --out "$output" \
--temporary-files-path "$temporary" --result-file "$result_file")
if [ -n "$key_store" ]; then
[ -f "$key_store" ] || { epr "keystore not found: $key_store"; return 1; }
command+=(--keystore "$key_store")
fi
[ -n "$store_password" ] && command+=(--keystore-password "$store_password")
[ -n "$key_alias" ] && command+=(--keystore-entry-alias "$key_alias")
[ -n "$entry_password" ] && command+=(--keystore-entry-password "$entry_password")
[ -n "$signer" ] && command+=(--signer "$signer")
command+=("${patch_args[@]}" "$input")
pr "Patching $(basename "$input") with Morphe Desktop"
# The data directory keeps CI/Termux runs self-contained and prevents the
# desktop CLI from writing into a read-only home directory. The full CLI
# output is kept next to the result file and echoed on failure so the
# annotation carries the underlying error instead of a generic message.
local run_log="${result_file%.json}.log"
if ! MORPHE_DATA_DIR="${TEMP_DIR}/morphe-data" "${command[@]}" >"$run_log" 2>&1; then
local reason fatal frames
# Morphe Desktop reports unexpected crashes as
# "SEVERE: An unexpected error occurred: <message>" followed by the
# stack trace. Include the exception class and the first frames so the
# CI annotation shows the actual cause instead of just "null".
fatal=$(grep -m1 -E '^SEVERE: An unexpected error occurred' "$run_log" || true)
if [ -n "$fatal" ]; then
reason="$fatal"
frames=$(grep -A8 '^SEVERE: An unexpected error occurred' "$run_log" \
| grep -m4 -E '^(java|kotlin|[a-zA-Z_$][a-zA-Z0-9_$.]*(\$[a-zA-Z0-9_$]+)?(Exception|Error))|\s+at ' \
| sed 's/^[[:space:]]*//' | awk 'NR > 1 { printf " | " } { printf "%s", $0 }')
[ -n "$frames" ] && reason+=" | $frames"
else
reason=$(grep -m1 -iE 'error|exception|failed|aborted|invalid|unsupported|not (found|exist)' "$run_log" \
|| sed '/^[[:space:]]*$/d' "$run_log" | tail -n 1)
fi
cat "$run_log" >&2
epr "Morphe patching failed for '$(basename "$input")': ${reason:-Morphe Desktop exited non-zero, see output above}"
return 1
fi
if ! [ -s "$output" ]; then
cat "$run_log" >&2 || true
epr "Morphe Desktop produced no output for '$(basename "$input")'"
return 1
fi
}
build_morphe() {
eval "declare -A args=${1#*=}"
local table="${args[table]}" app_name="${args[app_name]}" app_slug
app_slug=$(slugify "$app_name")
local app_name_l="$app_slug"
local arch="${args[arch]}"
local arch_f="${arch// /}"
local mode_arg="${args[build_mode]}" version_mode="${args[version]}"
local morphe_jar="${args[morphe_jar]}" patches_file="${args[patches_file]}"
local download_source="" pkg_name="" version="" latest=false force_version=false
local -a tried_sources=()
case "$mode_arg" in
apk) build_mode_arr=(apk) ;;
module) build_mode_arr=(module) ;;
both) build_mode_arr=(apk module) ;;
*) epr "invalid build mode '$mode_arg' for '$table'"; return 1 ;;
esac
# Locate the package and retain the first working source for version lookup.
local source
for source in apkmirror uptodown archive; do
[ -n "${args[${source}_dlurl]-}" ] || continue
if ! get_${source}_resp "${args[${source}_dlurl]}" || ! pkg_name=$(get_${source}_pkg_name); then
epr "Could not find '$table' in $source"
continue
fi
tried_sources+=("$source")
download_source="$source"
break
done
if [ -z "$pkg_name" ]; then
epr "empty package name; skipping '$table'"
return 1
fi
case "$version_mode" in
auto)
version=$(get_patch_last_supported_ver "$morphe_jar" "$patches_file" "$pkg_name" \
"${args[included_patches]}" "${args[exclusive_patches]}") || return 1
[ -n "$version" ] || latest=true
;;
latest|beta)
latest=true
force_version=true
[ "$version_mode" = beta ] && __AAV__=true || __AAV__=false
;;
*)
version="$version_mode"
;;
esac
if [ "$latest" = true ]; then
version=$(get_${download_source}_vers | get_highest_ver) || true
if [ -z "$version" ]; then
epr "could not determine latest version for '$table'"
return 1
fi
fi
[ -n "$version" ] || { epr "empty version for '$table'"; return 1; }
pr "Choosing version '$version' for $table"
local version_f="${version// /}"
version_f="${version_f#v}"
local stock_apk="${TEMP_DIR}/${pkg_name}-${version_f}-${arch_f}.apk"
if [ ! -s "$stock_apk" ]; then
for source in apkmirror uptodown archive; do
[ -n "${args[${source}_dlurl]-}" ] || continue
pr "Downloading '$table' from $source"
if ! isoneof "$source" "${tried_sources[@]}"; then
get_${source}_resp "${args[${source}_dlurl]}" || continue
fi
if dl_${source} "${args[${source}_dlurl]}" "$version" "$stock_apk" "$arch" \
"${args[dpi]}" "$latest"; then
download_source="$source"
break
fi
epr "Could not download '$table' from $source at version '$version'"
done
fi
[ -s "$stock_apk" ] || [ -f "${stock_apk}.apkm" ] || return 1
local from_bundle=false
if [ -f "${stock_apk}.apkm" ]; then
from_bundle=true
# Splits inside the bundle keep the original signature; verify them
# before merging because the merged APK itself is not signed.
if [ "${args[verify_signature]}" = true ] && ! verify_splits "${stock_apk}.apkm" "$pkg_name"; then
return 1
fi
if ! merge_splits "${stock_apk}.apkm" "$stock_apk"; then
epr "could not merge split bundle for '$table'"
return 1
fi
rm -f "${stock_apk}.apkm"
fi
if [ "${args[verify_signature]}" = true ] && [ "$from_bundle" = false ] && \
! check_sig "$stock_apk" "$pkg_name"; then
return 1
fi
log "${table}: ${version}"
log "Morphe Desktop: $(basename "$morphe_jar")"
log "Morphe Patches: ${args[patches_source]}/$(basename "$patches_file")"
local key_store="${args[keystore]}" store_password="${args[keystore_password]}"
local key_alias="${args[keystore_alias]}" entry_password="${args[keystore_entry_password]}" signer="${args[signer]}"
if [ -n "${MORPHE_KEYSTORE-}" ]; then key_store="$MORPHE_KEYSTORE"; fi
if [ -n "$key_store" ] && [ ! -f "$key_store" ]; then
# Morphe can create and reuse its own default key when no explicit key is
# supplied. This is useful for clean clones; CI users should cache/export a
# key when they need APK updates to retain the same signature.
pr "Configured keystore '$key_store' is unavailable; using Morphe's default keystore"
key_store=""
store_password=""
key_alias="Morphe"
entry_password="Morphe"
fi
[[ "$key_store" = /* ]] || [ -z "$key_store" ] || key_store="${CWD}/${key_store}"
local -a base_patch_args=()
PATCH_ARGS=()
append_patch_names "${args[excluded_patches]}" --disable
append_patch_names "${args[included_patches]}" --enable
base_patch_args=("${PATCH_ARGS[@]}")
[ "${args[exclusive_patches]}" = true ] && base_patch_args+=(--exclusive)
if [ "${args[force]}" = true ] || [ "$force_version" = true ]; then base_patch_args+=(--force); fi
[ "${args[continue_on_error]}" = true ] && base_patch_args+=(--continue-on-error)
[ -n "${args[options_file]}" ] && base_patch_args+=(--options-file "${args[options_file]}")
[ "${args[options_update]}" = true ] && base_patch_args+=(--options-update)
[ -n "${args[bytecode_mode]}" ] && base_patch_args+=(--bytecode-mode "${args[bytecode_mode]}")
local keep_architectures="${args[keep_architectures]}"
if [ "${args[strip_libs]}" = true ]; then
if [ -z "$keep_architectures" ]; then
case "$arch" in
arm64-v8a) keep_architectures=arm64-v8a ;;
arm-v7a) keep_architectures=armeabi-v7a ;;
all) keep_architectures=arm64-v8a,armeabi-v7a ;;
*) keep_architectures="$arch" ;;
esac
fi
base_patch_args+=(--striplibs "$keep_architectures")
fi
local build_mode patched_apk apk_output module_output base_template update_json
local brand="${args[brand]}" brand_slug
brand_slug=$(slugify "${brand:-morphe}")
for build_mode in "${build_mode_arr[@]}"; do
patched_apk="${TEMP_DIR}/${app_name_l}-${brand_slug}-${version_f}-${arch_f}-${build_mode}.apk"
local -a patch_args=("${base_patch_args[@]}")
local run_temp="${TEMP_DIR}/morphe-tmp/${app_slug}-${arch_f}-${build_mode}"
local result_file="${TEMP_DIR}/${app_slug}-${arch_f}-${build_mode}-result.json"
mkdir -p "$run_temp"
if ! patch_apk "$stock_apk" "$patched_apk" "$morphe_jar" "$patches_file" "$key_store" \
"$store_password" "$key_alias" "$entry_password" \
"$signer" "$run_temp" "$result_file" "${patch_args[@]}"; then
epr "Morphe patching failed for '$table' ($build_mode)"
return 1
fi
if [ "$build_mode" = apk ]; then
apk_output="${BUILD_DIR}/${app_name_l}-${brand_slug}-v${version_f}-${arch_f}.apk"
mv -f "$patched_apk" "$apk_output"
pr "Built $table APK: '$apk_output'"
continue
fi
get_module_prebuilts || {
epr "could not download module update helper binaries for '$table'"
return 1
}
base_template=$(mktemp -d -p "$TEMP_DIR")
cp -a "${MODULE_TEMPLATE_DIR}/." "$base_template/"
update_json="${app_slug}-${arch_f}-update.json"
module_config "$base_template" "$pkg_name" "$version" "$arch"
module_prop \
"${args[module_prop_name]}" \
"${app_name} ${brand}" \
"$version" \
"${app_name} ${brand} Magisk/KernelSU module built by ${PROJECT_NAME}" \
"https://raw.githubusercontent.com/${GITHUB_REPOSITORY-}/update/${update_json}" \
"$base_template"
module_output="${BUILD_DIR}/${app_name_l}-${brand_slug}-module-v${version_f}-${arch_f}.zip"
cp -f "$patched_apk" "${base_template}/base.apk"
if [ "${args[include_stock]}" = true ]; then cp -f "$stock_apk" "${base_template}/${pkg_name}.apk"; fi
pr "Packing $table module"
(
cd "$base_template" || exit 1
zip -"$COMPRESSION_LEVEL" -FSqr "$(path_from_cwd "$module_output")" .
) || { rm -rf "$base_template"; return 1; }
rm -rf "$base_template"
pr "Built $table module: '$module_output'"
done
}
###############################################################################
# Generated module metadata
###############################################################################
module_config() {
local module_dir="$1" pkg="$2" version="$3" arch="$4" module_arch=""
case "$arch" in
arm64-v8a) module_arch=arm64 ;;
arm-v7a|armeabi-v7a) module_arch=arm ;;
x86) module_arch=x86 ;;
x86_64|x64) module_arch=x64 ;;
esac
cat >"${module_dir}/config" <<EOF
PKG_NAME=${pkg}
PKG_VER=${version}
MODULE_ARCH=${module_arch}
EOF
}
module_prop() {
local module_id="$1" name="$2" app_version="$3" description="$4" update_json="$5" module_dir="$6"
cat >"${module_dir}/module.prop" <<EOF
id=${module_id}
name=${name}
version=v${app_version} (${NEXT_VER_CODE})
versionCode=${NEXT_VER_CODE}
author=${PROJECT_NAME}
description=${description}
EOF
if [ "$ENABLE_MAGISK_UPDATE" = true ]; then
printf 'updateJson=%s\n' "$update_json" >>"${module_dir}/module.prop"
fi
}
config_update() {
[ -f build.md ] || return 0
local -A seen_patches=() seen_desktop=()
local table t enabled patches_source patches_version morphe_source morphe_version asset expected source_key
while IFS= read -r table; do
[ -n "$table" ] || continue
t=$(toml_get_table "$table")
enabled=$(toml_get "$t" enabled) || enabled=true
[ "$enabled" = false ] && continue
morphe_source=$(toml_get "$t" morphe-source) || morphe_source="$DEF_MORPHE_SRC"
morphe_version=$(toml_get "$t" morphe-version) || morphe_version="$DEF_MORPHE_VER"
source_key="${morphe_source}/${morphe_version}"
if [ -z "${seen_desktop[$source_key]+x}" ]; then
seen_desktop[$source_key]=1
asset=$(get_release_asset "$morphe_source" "$morphe_version" "-all.jar" "Morphe Desktop" 2>/dev/null) || asset=""
if [ -n "$asset" ]; then
expected="Morphe Desktop: $(basename "$asset")"
if ! grep -qF "$expected" build.md; then
pr "New Morphe Desktop release detected for ${morphe_source}" >&2
cat "${CONFIG_FILE:-config.toml}"
return 0
fi
fi
fi
patches_source=$(toml_get "$t" patches-source) || patches_source="$DEF_PATCHES_SRC"
patches_version=$(toml_get "$t" patches-version) || patches_version="$DEF_PATCHES_VER"
source_key="${patches_source}/${patches_version}"
[ -n "${seen_patches[$source_key]+x}" ] && continue
seen_patches[$source_key]=1
asset=$(get_release_asset "$patches_source" "$patches_version" ".mpp" "Morphe patches" 2>/dev/null) || continue
expected="Morphe Patches: ${patches_source}/$(basename "$asset")"
if ! grep -qF "$expected" build.md; then
pr "New Morphe patch release detected for ${patches_source}" >&2
# Returning the original config is enough to signal the scheduled CI
# workflow. It also preserves comments and disabled app tables.
cat "${CONFIG_FILE:-config.toml}"
return 0
fi
done < <(toml_get_table_names)
}