262 Commits

Author SHA1 Message Date
CherretGit
35b0068b8c optimize libbyedpi 2025-12-08 23:11:49 +07:00
cheesedroid
cdcd8b85b5 Update build.gradle.kts 2025-12-08 18:11:45 +03:00
CherretGit
2dd181494a remove unnecessary modifier 2025-12-08 16:19:47 +07:00
white
77823252f2 add autostop on strategy testing error 2025-12-08 12:07:38 +03:00
CherretGit
87a9740aad remove unused import 2025-12-08 16:04:52 +07:00
CherretGit
efb60d0c93 fix shadow 2025-12-08 16:02:44 +07:00
white
f0c3baa3bd change NoHostsCard and it's logic, added getAllStrategies(prefs).isEmpty() testing 2025-12-08 11:44:15 +03:00
white
57217bbe1c add module error handling (and showing) in HostsScreen.kt, IpsetsScreen.kt, StrategyScreen.kt, StrategySelectionScreen.kt 2025-12-04 17:43:04 +03:00
white
6f9bd86d70 update agp 2025-12-04 16:45:32 +03:00
white
80f5934060 remove unwanted popBackStack() in error dialog 2025-12-04 16:25:56 +03:00
white
0065b8a92b added module errors handling on service start, stop, restart, added automated service status updating on start, stop, restart 2025-12-04 16:08:05 +03:00
CherretGit
b5e3d256a6 Merge remote-tracking branch 'origin/main' 2025-11-29 17:33:31 +07:00
CherretGit
77bbd41609 fix strings 2025-11-29 17:33:22 +07:00
CherretGit
4e1568b405 Update workflow.yml 2025-11-26 19:26:13 +07:00
CherretGit
b8844c8cca add reset settings option 2025-11-22 17:53:14 +07:00
CherretGit
1d6eb32473 Update changelog.md 2025-11-04 02:46:33 +07:00
CherretGit
ded89165dc Update changelog.md 2025-11-04 02:46:16 +07:00
CherretGit
ed7452b7cb Update update.json 2025-11-04 02:43:59 +07:00
CherretGit
717368b4e9 bump version 2025-11-03 18:03:43 +07:00
CherretGit
36885a8410 fix some crashed from firebase crashlytics 2025-11-03 17:59:27 +07:00
CherretGit
ad614b3b4a fix ByeDpiVpnService 2025-11-03 02:19:06 +07:00
CherretGit
5c8425573a change commands in ZaprettManager 2025-11-03 02:05:14 +07:00
CherretGit
59e30206f7 Merge remote-tracking branch 'origin/main' 2025-10-30 21:42:50 +07:00
CherretGit
c4dcf934aa Config to json 2025-10-30 21:42:43 +07:00
egor-white
1bbeb4e987 Update README.md 2025-10-27 16:49:10 +03:00
egor-white
003a4c57a3 update changelog 2025-10-18 15:57:54 +03:00
egor-white
432873409c Update update.json 2025-10-18 15:57:20 +03:00
CherretGit
c5b60b1ee9 use card onClick in settings items 2025-10-18 19:41:51 +07:00
CherretGit
2f349e5108 bump app version 2025-10-18 19:29:27 +07:00
CherretGit
e8a8fa69db fix JNI seg fault 2025-10-18 19:21:51 +07:00
CherretGit
c094a072b8 fix app list mode 2025-10-18 18:46:40 +07:00
white
786321d852 edit strings.xml 2025-10-18 12:57:21 +03:00
white
7a17c93622 change selection screen title font size 2025-10-18 12:55:56 +03:00
white
cf38ef7ac2 some strategy selection interface changes 2025-10-18 12:20:30 +03:00
CherretGit
94979d2b2e fix testDomain 2025-10-18 12:42:06 +07:00
CherretGit
bd1bdf8298 Merge remote-tracking branch 'origin/main' 2025-10-18 01:56:19 +07:00
CherretGit
adc98db3f1 add info in strategy selection 2025-10-18 01:56:11 +07:00
CherretGit
9bbc3b771f filter list/ipset/strategy files to only .txt 2025-10-17 15:37:59 +07:00
egor-white
51356e63eb Update update.json 2025-10-16 16:43:08 +03:00
egor-white
f3f2cf999c Update changelog.md 2025-10-16 16:42:32 +03:00
white
69f395275e change build.gradle version 2025-10-16 16:18:03 +03:00
CherretGit
39dc2baad3 Merge remote-tracking branch 'origin/main' 2025-10-16 19:46:05 +07:00
CherretGit
ad5c556241 fix ipsets loading 2025-10-16 19:45:57 +07:00
white
48e7497e79 add no hosts dialog, optimize imports 2025-10-16 15:45:19 +03:00
white
2954cef0a6 small fixes, added vpn permission request before selection 2025-10-14 20:31:05 +03:00
CherretGit
c49cce1de4 fix JNI 2025-10-14 23:05:49 +07:00
white
4786ef8faf optimise sum imports, fix two active strategies 2025-10-12 19:48:44 +03:00
white
0b69d2bf4d add automatic strategy selection, remove phantom switch in settings, add ipset repository url setting, made some refactoring, disable analytics and autoupdate in debug releases by default, etc 2025-10-12 19:01:22 +03:00
CherretGit
9208885de4 Merge remote-tracking branch 'origin/main' 2025-10-10 16:51:45 +07:00
CherretGit
44fbb5fa98 useModule to view model 2025-10-10 16:51:37 +07:00
CherretGit
7c2fba684d Update workflow.yml 2025-10-09 23:19:20 +07:00
CherretGit
3ac0ca73e1 Update workflow.yml 2025-10-09 23:07:12 +07:00
CherretGit
abb3a8e4e4 Update workflow.yml 2025-10-09 22:57:43 +07:00
CherretGit
73cbd89390 Update workflow.yml 2025-10-09 22:49:55 +07:00
CherretGit
8cfe6f4389 Update workflow.yml 2025-10-09 22:39:42 +07:00
CherretGit
9a89fcccae Update workflow.yml 2025-10-09 22:38:50 +07:00
CherretGit
cd44a09cfc git submodule fix 2025-10-09 01:05:33 +07:00
CherretGit
14d6ea6caa rewrite JNI to Rust 2025-10-09 00:31:05 +07:00
white
6caff9b611 change repo source to ipsets, add ipset parsing to byedpi 2025-09-30 19:24:15 +03:00
white
5eba2461dd add ipsets screen 2025-09-30 19:00:55 +03:00
CherretGit
5a6bf9780b ipset repo and autostart 2025-09-30 20:35:46 +07:00
CherretGit
ce6e1f07b8 Merge remote-tracking branch 'origin/main' 2025-09-30 18:40:25 +07:00
CherretGit
1e985807d9 micro bug fix 2025-09-30 18:40:12 +07:00
CherretGit
80d885167e Update update.json 2025-08-31 22:38:42 +07:00
CherretGit
01f4333fee Update changelog.md 2025-08-31 22:38:21 +07:00
CherretGit
c67846a7e4 bump version 2025-08-31 22:19:48 +07:00
white
c4da9d1c29 add updater error handling 2025-08-31 17:58:10 +03:00
CherretGit
0386fbbccd Merge remote-tracking branch 'origin/main' 2025-08-31 03:08:49 +07:00
CherretGit
109042d5e7 add DebugScreen, markdown in update dialog 2025-08-31 03:08:42 +07:00
CherretGit
34595512d0 Update README.md 2025-08-30 12:59:54 +07:00
CherretGit
7d2b969337 Merge remote-tracking branch 'origin/main' 2025-08-30 02:18:57 +07:00
CherretGit
da66743014 move UI elements to components 2025-08-30 02:18:49 +07:00
CherretGit
6146504125 Update update.json 2025-08-28 02:54:12 +07:00
CherretGit
0d8deb2e9f Update changelog.md 2025-08-28 02:54:04 +07:00
CherretGit
fd06b6c75b navigationBarsPadding in repo screen 2025-08-28 02:35:33 +07:00
CherretGit
ce91b578b8 bump version 2025-08-28 02:31:53 +07:00
CherretGit
68b25d8efa edit button in settings 2025-08-28 02:26:50 +07:00
CherretGit
b8d26a1a57 handle file download error 2025-08-28 02:18:38 +07:00
CherretGit
e6ffe78eb1 fix byedpi blacklist (again) 2025-08-28 01:08:27 +07:00
CherretGit
d754abf794 move card status update to ViewModel 2025-08-28 01:03:32 +07:00
CherretGit
2bdc69b1ba move card status update to ViewModel 2025-08-28 01:03:28 +07:00
CherretGit
902b2939cd remove spacer 2025-08-27 19:11:16 +07:00
CherretGit
c70752f8c5 Fix UI errors 2025-08-27 19:05:17 +07:00
CherretGit
a385e498ea fix repo 2025-08-27 17:43:33 +07:00
CherretGit
3f6086c11f add repository error handling, fix Byedpi blacklist, possible UI error fix 2025-08-27 04:18:49 +07:00
white
f7f8d3e3b9 fix list repo crash 2025-08-22 00:17:25 +03:00
CherretGit
6095a3d485 Merge remote-tracking branch 'origin/main' 2025-08-21 20:17:43 +07:00
CherretGit
8771c8fd1b Fix crashes 2025-08-21 20:16:28 +07:00
CherretGit
51d774b6aa Revert "some refactoring + creating config on every change"
This reverts commit ef04471a
2025-08-21 19:43:27 +07:00
CherretGit
879bf98ed1 Update update.json 2025-08-21 18:11:39 +07:00
CherretGit
cb283b7d62 Update changelog.md 2025-08-21 18:11:22 +07:00
CherretGit
e988bfdd2e and one more 2025-08-21 16:44:03 +07:00
CherretGit
49f61892da one more fix 2025-08-21 16:35:56 +07:00
white
2aa831baa5 way more refactoring 2025-08-21 12:22:32 +03:00
white
ef04471a05 some refactoring + creating config on every change 2025-08-21 12:10:14 +03:00
CherretGit
baec0f3838 fix 2025-08-21 15:30:15 +07:00
white
8101c44dc1 update version, change repository urls 2025-08-21 11:09:21 +03:00
white
aef5b962b5 rename parametres 2025-08-21 10:53:16 +03:00
white
28dca0716a rename parametres 2025-08-21 10:52:07 +03:00
white
0807eebeb2 fix non-root exclude switches state saving 2025-08-20 22:50:23 +03:00
CherretGit
b17a0dc4cb implement hostlist excluded 2025-08-21 01:57:22 +07:00
white
1ada6304a4 add black/white hostlist division in ui and config 2025-08-20 18:09:41 +03:00
CherretGit
e16e8e3bbe update dependencies 2025-08-20 16:34:39 +07:00
white
1e0368e467 Merge remote-tracking branch 'origin/main' 2025-08-16 15:49:24 +03:00
white
4dcf90dcfc draft of new ui 2025-08-16 15:49:03 +03:00
CherretGit
94ff869bd5 update some dependencies 2025-08-05 21:11:23 +07:00
CherretGit
435f548698 fix lags 2025-07-26 03:37:02 +07:00
CherretGit
660c3b509a fix lags 2025-07-26 03:35:28 +07:00
CherretGit
6e8960a707 links 2025-07-26 03:11:46 +07:00
CherretGit
c5f836d65c Update update.json 2025-07-17 21:32:52 +07:00
CherretGit
3f46872fec Update changelog.md 2025-07-17 21:32:05 +07:00
CherretGit
8192490e93 fix new feature 2025-07-17 20:56:20 +07:00
egor-white
53510746a6 refreshApplications() is now public 2025-07-17 11:49:43 +03:00
egor-white
0a71c725bb Merge branch 'main' of github.com:CherretGit/zaprett-app 2025-07-17 11:37:59 +03:00
egor-white
2d95cee5a6 add system apps filter 2025-07-17 11:37:43 +03:00
CherretGit
d1904901b1 update submodule(again) 2025-07-17 13:23:45 +07:00
CherretGit
fc9f12d102 fix 2025-07-17 13:17:15 +07:00
egor-white
dc53b433f6 Update update.json 2025-07-16 23:59:05 +03:00
egor-white
8331a44d15 Update changelog.md 2025-07-16 23:58:35 +03:00
egor-white
307b0e1736 update byedpi version in homescreen 2025-07-16 23:44:15 +03:00
egor-white
2fb0987de3 implement black and white lists for apps (split tunneling) for byedpi and module; fix typos 2025-07-16 23:37:52 +03:00
CherretGit
27bc84bac9 fix root request 2025-07-14 19:58:01 +07:00
CherretGit
e1179e3144 implement prepareList 2025-07-14 18:55:44 +07:00
CherretGit
032c1bc797 implement prepareList 2025-07-14 18:55:26 +07:00
egor-white
b83b0db7a5 Merge remote-tracking branch 'origin/main' 2025-07-14 12:45:06 +03:00
egor-white
6723a0732b trying to implement prepareList 2025-07-14 12:44:48 +03:00
egor-white
efba165546 Create LICENSE 2025-07-13 12:17:24 +03:00
egor-white
4e3fbb70ef qs tile long tap now opening app 2025-07-12 14:22:42 +03:00
egor-white
e3331119a0 fix QS tile, change root detection method 2025-07-11 18:21:52 +03:00
egor-white
4addc7245d Merge remote-tracking branch 'origin/main' 2025-07-09 14:24:05 +03:00
egor-white
0c6a31f4e6 disable test repo 2025-07-09 14:23:04 +03:00
CherretGit
7e783104c9 Update update.json 2025-07-09 18:16:16 +07:00
CherretGit
486e6a337a Update update.json 2025-07-09 18:09:05 +07:00
CherretGit
c13a9d7815 Update changelog.md 2025-07-09 18:07:02 +07:00
egor-white
c49d7858c3 change ver 2025-07-09 13:54:23 +03:00
egor-white
578ca0f38f fix crashes after Likchach42's PR 2025-07-09 13:10:11 +03:00
egor-white
bd5bd798c1 fix package name empty on activity start 2025-07-09 10:44:18 +03:00
egor-white
91e627ced6 fix startActivity() crashes 2025-07-08 19:44:10 +03:00
CherretGit
0819cbab73 Update update.json 2025-07-08 21:47:24 +07:00
egor-white
dddac71bc6 Merge remote-tracking branch 'origin/main' 2025-07-08 17:31:18 +03:00
egor-white
2d4850c0e8 add Updater.kt mediastore if sdk < 30 2025-07-08 17:31:00 +03:00
CherretGit
a466ad8bcd Update update.json 2025-07-08 21:11:58 +07:00
CherretGit
1121365dfb Update changelog.md 2025-07-08 21:10:10 +07:00
egor-white
212df7fa9b Android 10 Storage crashes fix 2025-07-08 16:48:46 +03:00
egor-white
5e01ebae7d Merge pull request #3 from CherretGit/revert-1-main
Revert "Android 10 fix & update libs"
2025-07-08 14:57:44 +03:00
egor-white
2e2b33ca55 Revert "Android 10 fix & update libs" 2025-07-08 14:57:06 +03:00
egor-white
2d1a25bbc3 Merge pull request #1 from Likhach42/main
Android 10 fix
2025-07-08 14:47:39 +03:00
egor-white
4737e763ea Merge remote-tracking branch 'origin/main' into a10
# Conflicts:
#	app/build.gradle.kts
#	app/src/main/java/com/cherret/zaprett/MainActivity.kt
#	app/src/main/java/com/cherret/zaprett/ui/viewmodel/BaseListsViewModel.kt
#	app/src/main/java/com/cherret/zaprett/ui/viewmodel/HomeViewModel.kt
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values/strings.xml
#	gradle/libs.versions.toml
2025-07-08 14:39:23 +03:00
egor-white
8c93093b6b Update README.md 2025-07-08 09:44:43 +03:00
egor-white
0977d30729 Add files via upload 2025-07-08 09:43:43 +03:00
egor-white
f02b22d8bd Merge remote-tracking branch 'origin/main' 2025-07-07 14:14:59 +03:00
egor-white
6cf4a067fb fix status card text out of card 2025-07-07 14:14:37 +03:00
CherretGit
3fa009d3e9 Update update.json 2025-07-07 17:59:23 +07:00
CherretGit
0222ee5cfc Update update.json 2025-07-07 17:53:13 +07:00
CherretGit
e8c8a2a6c1 Update Updater.kt 2025-07-07 17:41:27 +07:00
egor-white
7c75174e26 fix installApk crashes 2025-07-07 13:40:00 +03:00
egor-white
c687d912b3 Update update.json 2025-07-07 12:47:07 +03:00
egor-white
6b017d116f Update changelog.md 2025-07-07 12:46:36 +03:00
egor-white
c8c3b6de96 change ver 2025-07-07 12:25:46 +03:00
egor-white
b832be9556 add icon to status card 2025-07-07 12:22:38 +03:00
egor-white
817f3a0e7d move setupProxy checks to HomeViewModel.kt 2025-07-07 11:18:20 +03:00
egor-white
7d25f7e600 fix startVpn crashes 2025-07-06 20:48:35 +03:00
egor-white
8dcb4d1997 fix startVpn crashes 2025-07-06 12:34:39 +03:00
egor-white
ba2cf523bd Merge remote-tracking branch 'origin/main' 2025-07-05 14:35:51 +03:00
egor-white
c268ee8ccd get install unknown apps permission before loading, add module installation check on up startup 2025-07-05 14:30:23 +03:00
egor-white
72905f4180 change navbar icons 2025-07-05 13:19:38 +03:00
egor-white
a7bb250a64 move utils to com.cherret.zaprett.utils 2025-07-05 12:57:44 +03:00
CherretGit
cf15ed7559 Update workflow.yml 2025-07-04 18:38:21 +07:00
egor-white
77f6135f6a update ByeDpiVpnService.kt 2025-07-04 14:27:20 +03:00
egor-white
1997bb8403 Merge remote-tracking branch 'origin/main' 2025-07-04 14:17:03 +03:00
CherretGit
b266976a08 Update workflow.yml 2025-07-04 18:06:13 +07:00
egor-white
b5d9ec6f19 remove unused imports 2025-07-04 14:05:48 +03:00
egor-white
b0a4c3d2f5 move byedpi classes to package org.cherret.zaprett.byedpi 2025-07-04 14:04:48 +03:00
egor-white
8f2e7030d8 Update update.json 2025-07-04 12:23:25 +03:00
egor-white
aeb1c6123b Update changelog.md 2025-07-04 12:22:57 +03:00
egor-white
5a423f39c0 Update workflow.yml 2025-07-04 12:08:32 +03:00
egor-white
efeab387af change ver 2025-07-04 11:54:07 +03:00
egor-white
747a4b2052 bug fix 2025-07-04 11:53:16 +03:00
egor-white
6c6eeefcf1 add icon and module info card 2025-07-03 21:00:45 +03:00
CherretGit
0983262919 Update README.md 2025-06-30 12:31:03 +07:00
CherretGit
078c0085bb Update README.md 2025-06-30 12:30:13 +07:00
CherretGit
e87a0434de Update update.json 2025-06-30 01:16:34 +07:00
CherretGit
57d56cb5f2 Update changelog.md 2025-06-30 01:15:29 +07:00
CherretGit
26dfba1dda ciadpi version 2025-06-30 01:01:14 +07:00
CherretGit
e59a4ad75c Merge remote-tracking branch 'origin/main' 2025-06-30 00:48:41 +07:00
CherretGit
df38f29b55 remove unused imports 2025-06-30 00:47:10 +07:00
CherretGit
693f93e297 non root and etc 2025-06-30 00:42:04 +07:00
maksim
c153b582e7 Android 10 fix & update libs 2025-06-27 20:19:48 +03:00
egor-white
7dff7ac36a update readmme 2025-06-21 20:25:01 +00:00
CherretGit
45a6e10fb5 Update README.md 2025-06-20 01:31:01 +07:00
CherretGit
353bb169f3 Merge remote-tracking branch 'origin/main' 2025-06-03 21:07:46 +07:00
CherretGit
aba5d650d8 Refactor: migrate to MVVM architecture 2025-06-03 21:05:18 +07:00
CherretGit
6b0e86a5cf Update README.md 2025-05-10 21:08:35 +07:00
CherretGit
67e14b32be Add files via upload 2025-05-10 21:06:31 +07:00
CherretGit
f1f3963137 Update update.json 2025-05-10 21:04:32 +07:00
CherretGit
c54ee5c22d Update changelog.md 2025-05-10 21:04:27 +07:00
Cherret
87ff9c5164 Merge remote-tracking branch 'origin/main' 2025-05-10 20:46:12 +07:00
Cherret
c61937a4b0 Update version 2025-05-10 20:45:56 +07:00
Cherret
edf54851ae Add strategies 2025-05-10 20:43:35 +07:00
CherretGit
b766deafa5 Update update.json 2025-05-05 23:40:11 +07:00
CherretGit
7974066105 Update changelog.md 2025-05-05 23:40:06 +07:00
Cherret
dc096ae3ed Merge remote-tracking branch 'origin/main' 2025-05-05 23:21:34 +07:00
Cherret
23172b1cd8 enable shrink 2025-05-05 23:21:24 +07:00
CherretGit
a9ed6a5e67 Update README.md 2025-05-05 23:01:45 +07:00
CherretGit
00b5334273 Update README.md 2025-05-05 14:25:50 +07:00
CherretGit
f11071fd4d Update README.md 2025-05-05 14:10:43 +07:00
CherretGit
82e28c1620 Update changelog.md 2025-05-01 21:12:47 +07:00
CherretGit
9ea170a2b2 Update update.json 2025-05-01 21:12:42 +07:00
Cherret
2d82aec1eb Merge remote-tracking branch 'origin/main' 2025-05-01 21:04:08 +07:00
Cherret
4ee72db907 disable shrink 2025-05-01 21:03:45 +07:00
CherretGit
96a1455ebc Update README.md 2025-05-01 20:43:42 +07:00
CherretGit
e5ed91e90d Add files via upload 2025-05-01 20:38:14 +07:00
Cherret
de65eaea5a Merge remote-tracking branch 'origin/main' 2025-05-01 20:23:16 +07:00
Cherret
e5f82030fd update settings 2025-05-01 20:22:11 +07:00
Cherret
10eeb2c9d5 update settings 2025-05-01 20:20:16 +07:00
CherretGit
cb475ac8c9 Update README.md 2025-04-29 09:21:30 +07:00
CherretGit
66ff70e728 Update update.json 2025-04-28 16:37:58 +07:00
CherretGit
2aa26a9b35 Update update.json 2025-04-28 00:17:31 +07:00
CherretGit
9a3e8d8cee Update changelog.md 2025-04-28 00:17:14 +07:00
Cherret
458741485b hosts repo and code refactor 2025-04-27 23:55:30 +07:00
CherretGit
ca51cb1e81 Update update.json 2025-04-07 20:27:25 +07:00
CherretGit
542b14ddd2 Update changelog.md 2025-04-07 20:27:15 +07:00
Cherret
c88687882e Merge remote-tracking branch 'origin/main' 2025-04-07 20:17:57 +07:00
Cherret
355987fddb QS Button 2025-04-07 20:17:07 +07:00
CherretGit
b43b197233 Update update.json 2025-04-07 01:27:49 +07:00
CherretGit
eec81a32d9 Update changelog.md 2025-04-07 01:27:38 +07:00
Cherret
3e5b96b562 Update version 2025-04-07 01:19:22 +07:00
Cherret
acf579da89 Merge remote-tracking branch 'origin/main' 2025-04-07 01:17:28 +07:00
Cherret
180922699c Remove host button 2025-04-07 01:15:41 +07:00
CherretGit
3fdd68ca55 Update update.json 2025-04-05 02:58:28 +07:00
CherretGit
20bdcac931 Update changelog.md 2025-04-05 02:58:05 +07:00
Cherret
76e7fb8310 Merge remote-tracking branch 'origin/main' 2025-04-05 02:41:14 +07:00
Cherret
4ed064ff9c Bug Fixing, Firebase Analytics 2025-04-05 02:40:49 +07:00
Cherret
b758decd6b Bug Fixing, Firebase Analytics 2025-04-05 02:38:25 +07:00
CherretGit
4a74050ec6 Update update.json 2025-04-02 13:39:07 +07:00
CherretGit
d9aa02a436 Update update.json 2025-03-31 02:58:36 +07:00
CherretGit
18b3c0e3c6 Update update.json 2025-03-31 02:56:02 +07:00
CherretGit
1870edfb5c Update changelog.md 2025-03-31 02:55:44 +07:00
Cherret
9b138d55ee Merge remote-tracking branch 'origin/main' 2025-03-31 02:54:43 +07:00
Cherret
03e1ea4f06 Minor Update 2025-03-31 02:47:08 +07:00
CherretGit
9e95ba9922 Update workflow.yml 2025-03-30 17:44:25 +07:00
CherretGit
aac80da9a7 Update workflow.yml 2025-03-30 17:25:59 +07:00
CherretGit
2b611ce8cd Update workflow.yml 2025-03-30 16:43:35 +07:00
CherretGit
6967ee286c Update workflow.yml 2025-03-30 16:02:44 +07:00
CherretGit
83737d5df9 Update workflow.yml 2025-03-30 15:55:00 +07:00
CherretGit
a05c6af2c1 Update workflow.yml 2025-03-30 15:47:35 +07:00
CherretGit
7b7f94f0e2 Create workflow.yml 2025-03-30 15:40:41 +07:00
CherretGit
8367eac9bc Update README.md 2025-03-30 14:43:20 +07:00
CherretGit
e95792b8c9 Update README.md 2025-03-30 14:42:02 +07:00
CherretGit
7352943bb3 Update README.md 2025-03-30 14:41:22 +07:00
CherretGit
b4da6bda5a Update README.md 2025-03-28 21:16:46 +07:00
Cherret
4ecc9a40d4 Merge remote-tracking branch 'origin/main' 2025-03-28 17:27:31 +07:00
Cherret
96dc70473e Auto Update 2025-03-28 17:26:11 +07:00
CherretGit
b05616d7ef Update changelog.md 2025-03-28 17:25:48 +07:00
CherretGit
316bdea986 Create update.json 2025-03-28 17:18:41 +07:00
CherretGit
de22bb048c Create changelog.md 2025-03-28 17:18:22 +07:00
Cherret
56d3c95f07 Merge remote-tracking branch 'origin/main' 2025-03-25 21:21:28 +07:00
Cherret
df4e7f9658 Fix App Freeze 2025-03-25 21:21:15 +07:00
CherretGit
3c44a449c3 README.md 2025-03-25 12:31:43 +07:00
CherretGit
e46b0e7d4f Delete images/1 2025-03-25 12:28:11 +07:00
CherretGit
136340949d Images 2025-03-25 12:27:39 +07:00
CherretGit
894899bfc9 1 2025-03-25 12:26:26 +07:00
83 changed files with 7425 additions and 979 deletions

82
.github/workflows/workflow.yml vendored Normal file
View File

@@ -0,0 +1,82 @@
name: Build and Release
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag for the release'
required: true
type: string
release_name:
description: 'Release Name'
required: true
type: string
release_notes:
description: 'Release Description'
required: true
type: string
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: gradle
- name: Setup Git submodules
run: git submodule update --init --recursive
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Set up Android SDK
uses: android-actions/setup-android@v2
- name: Setup NDK
run: sdkmanager "ndk;27.0.12077973" "cmake;3.22.1"
- name: Install toolchain
run: |
rustup default stable
rustup update stable
cargo install cargo-ndk
rustup target add armv7-linux-androideabi
rustup target add aarch64-linux-android
rustup target add i686-linux-android
rustup target add x86_64-linux-android
- name: Build APK
run: ./gradlew assembleRelease
- name: Decode Keystore
run: |
echo "${{ secrets.KEYSTORE }}" | base64 --decode > keystore.jks
- name: Sign the APK
run: |
$ANDROID_HOME/build-tools/$(ls $ANDROID_HOME/build-tools | sort -V | tail -1)/apksigner sign \
--ks keystore.jks \
--ks-pass "pass:${{ secrets.KEY_STORE_PASSWORD }}" \
--key-pass "pass:${{ secrets.KEY_PASSWORD }}" \
--out app/build/outputs/apk/release/app-release.apk \
app/build/outputs/apk/release/app-release-unsigned.apk
- name: Verify APK signature
run: |
$ANDROID_HOME/build-tools/$(ls $ANDROID_HOME/build-tools | sort -V | tail -1)/apksigner verify \
app/build/outputs/apk/release/app-release.apk
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.event.inputs.tag }}
name: ${{ github.event.inputs.release_name }}
body: ${{ github.event.inputs.release_notes }}
files: |
app/build/outputs/apk/release/app-release.apk

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "rust/byedpi"]
path = rust/byedpi
url = https://github.com/hufrea/byedpi
[submodule "app/src/main/jni/hev-socks5-tunnel"]
path = app/src/main/jni/hev-socks5-tunnel
url = https://github.com/heiher/hev-socks5-tunnel

27
.idea/appInsightsSettings.xml generated Normal file
View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AppInsightsSettings">
<option name="selectedTabId" value="Android Vitals" />
<option name="tabSettings">
<map>
<entry key="Firebase Crashlytics">
<value>
<InsightsFilterSettings>
<option name="connection">
<ConnectionSetting>
<option name="appId" value="com.cherret.zaprett" />
<option name="mobileSdkAppId" value="1:1005804036856:android:e7db5546b8bb4daf91510d" />
<option name="projectId" value="zaprett-app" />
<option name="projectNumber" value="1005804036856" />
</ConnectionSetting>
</option>
<option name="signal" value="SIGNAL_UNSPECIFIED" />
<option name="timeIntervalDays" value="THIRTY_DAYS" />
<option name="visibilityType" value="ALL" />
</InsightsFilterSettings>
</value>
</entry>
</map>
</option>
</component>
</project>

View File

@@ -1,5 +1,40 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="" withSubpackages="true" static="false" module="true" />
<package name="android" withSubpackages="true" static="true" />
<package name="androidx" withSubpackages="true" static="true" />
<package name="com" withSubpackages="true" static="true" />
<package name="junit" withSubpackages="true" static="true" />
<package name="net" withSubpackages="true" static="true" />
<package name="org" withSubpackages="true" static="true" />
<package name="java" withSubpackages="true" static="true" />
<package name="javax" withSubpackages="true" static="true" />
<package name="" withSubpackages="true" static="true" />
<emptyLine />
<package name="android" withSubpackages="true" static="false" />
<emptyLine />
<package name="androidx" withSubpackages="true" static="false" />
<emptyLine />
<package name="com" withSubpackages="true" static="false" />
<emptyLine />
<package name="junit" withSubpackages="true" static="false" />
<emptyLine />
<package name="net" withSubpackages="true" static="false" />
<emptyLine />
<package name="org" withSubpackages="true" static="false" />
<emptyLine />
<package name="java" withSubpackages="true" static="false" />
<emptyLine />
<package name="javax" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="false" />
<emptyLine />
</value>
</option>
</JavaCodeStyleSettings>
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>

View File

@@ -4,10 +4,10 @@
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2025-03-24T08:57:47.584581613Z">
<DropdownSelection timestamp="2025-10-03T07:21:08.712998131Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/home/dimap/.var/app/com.google.AndroidStudio/config/.android/avd/Medium_Phone.avd" />
<DeviceId pluginId="LocalEmulator" identifier="path=/home/dimap/.android/avd/Medium_Phone.avd" />
</handle>
</Target>
</DropdownSelection>

13
.idea/deviceManager.xml generated Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeviceTable">
<option name="columnSorters">
<list>
<ColumnSorterState>
<option name="column" value="Name" />
<option name="order" value="ASCENDING" />
</ColumnSorterState>
</list>
</option>
</component>
</project>

6
.idea/vcs.xml generated
View File

@@ -2,5 +2,11 @@
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/src/main/jni/hev-socks5-tunnel" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/src/main/jni/hev-socks5-tunnel/src/core" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/src/main/jni/hev-socks5-tunnel/third-part/hev-task-system" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/src/main/jni/hev-socks5-tunnel/third-part/lwip" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/src/main/jni/hev-socks5-tunnel/third-part/yaml" vcs="Git" />
<mapping directory="$PROJECT_DIR$/rust/byedpi" vcs="Git" />
</component>
</project>

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

42
README.md Normal file
View File

@@ -0,0 +1,42 @@
# zaprett
## О приложении
![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/CherretGit/zaprett-app/total)
![GitHub Downloads (all assets, latest release)](https://img.shields.io/github/downloads/CherretGit/zaprett-app/latest/total)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/CherretGit/zaprett-app/workflow.yml)
Приложение разработано для работы с модулем [zaprett](https://github.com/egor-white/zaprett)
> [!IMPORTANT]
> 📢 [Официальный Telegram-канал приложения](https://t.me/zaprett_module)
> [!CAUTION]
> ⚠️ Для корректной работы приложения **желательны root-права**, однако предусмотрен режим без root на основе **byedpi**
---
На данный момент приложение умеет:
* Запускать, останавливать и перезапускать сервис
* Работа с листами (добавление, включение и выключение, загрузка из репозитория)
* Работа с стратегиями (добавление, выбор, загрузка из репозитория)
* Авто обновление приложения
---
## [Репозиторий с хостами и стратегиями](https://github.com/CherretGit/zaprett-hosts-repo)
---
#### Данное приложение является ремейком [приложения](https://github.com/egor-white/zaprett-app) от [egor-white](https://github.com/egor-white), разработка которого была прекращена в пользу этого приложения
---
## Скриншоты:
<p align="center">
<img src="images/1.png" width="180">
<img src="images/2.png" width="180">
<img src="images/3.png" width="180"><br>
<img src="images/4.png" width="180">
<img src="images/5.png" width="180">
<img src="images/6.png" width="180"><br>
<img src="images/7.png" width="180">
</p>

View File

@@ -2,29 +2,39 @@ plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
id("com.google.gms.google-services")
id("com.google.firebase.crashlytics")
kotlin("plugin.serialization") version "2.1.20"
id("org.mozilla.rust-android-gradle.rust-android") version "0.9.6"
}
android {
namespace = "com.cherret.zaprett"
compileSdk = 35
compileSdk = 36
defaultConfig {
applicationId = "com.cherret.zaprett"
minSdk = 30
minSdk = 29
targetSdk = 35
versionCode = 1
versionName = "1.0"
versionCode = 25
versionName = "2.13"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
buildConfigField("boolean", "send_firebase_analytics", "true")
buildConfigField("boolean", "auto_update", "true")
}
debug {
buildConfigField("boolean", "send_firebase_analytics", "false")
buildConfigField("boolean", "auto_update", "false")
}
}
compileOptions {
@@ -36,16 +46,69 @@ android {
}
buildFeatures {
compose = true
buildConfig = true
}
}
tasks.register<Exec>("runNdkBuild") {
group = "build"
val ndkDir = android.ndkDirectory
executable = if (System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) {
"$ndkDir\\ndk-build.cmd"
} else {
"$ndkDir/ndk-build"
}
setArgs(listOf(
"NDK_PROJECT_PATH=build/intermediates/ndkBuild",
"NDK_LIBS_OUT=src/main/jniLibs",
"APP_BUILD_SCRIPT=src/main/jni/Android.mk",
"NDK_APPLICATION_MK=src/main/jni/Application.mk"
))
println("Command: $commandLine")
}
tasks.preBuild {
dependsOn("runNdkBuild")
}
cargo {
module = "../rust"
libname = "byedpi"
targets = listOf("arm", "arm64", "x86", "x86_64")
profile = "release"
}
tasks.preBuild {
dependsOn("cargoBuild")
}
tasks.register<Exec>("cargoClean") {
workingDir = file("../rust")
commandLine("cargo", "clean")
group = "build"
}
tasks.named("clean") {
dependsOn("cargoClean")
}
dependencies {
implementation("androidx.compose.material3:material3:1.3.1")
implementation("androidx.compose.material3:material3-window-size-class:1.3.1")
implementation("androidx.compose.material3:material3-adaptive-navigation-suite:1.4.0-alpha10")
implementation("androidx.navigation:navigation-compose:2.8.9")
implementation("androidx.compose.material:material-icons-extended:1.7.8")
implementation ("com.github.topjohnwu.libsu:core:6.0.0")
implementation(libs.compose.material3)
implementation(libs.compose.material3.window.size)
implementation(libs.compose.material3.adaptive.nav)
implementation(libs.navigation.compose)
implementation(libs.compose.icons)
implementation(libs.libsu.core)
implementation(libs.okhttp)
implementation(libs.serialization.json)
implementation(platform(libs.firebase.bom))
implementation(libs.firebase.analytics)
implementation(libs.firebase.crashlytics)
implementation(libs.fragment.compose)
implementation(libs.coil.compose)
implementation(libs.compose.markdown)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
@@ -61,4 +124,4 @@ dependencies {
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}
}

29
app/google-services.json Normal file
View File

@@ -0,0 +1,29 @@
{
"project_info": {
"project_number": "1005804036856",
"project_id": "zaprett-app",
"storage_bucket": "zaprett-app.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:1005804036856:android:e7db5546b8bb4daf91510d",
"android_client_info": {
"package_name": "com.cherret.zaprett"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyASt83pAMxMI4txNAXaHDpX1R9crfoZAMk"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}

View File

@@ -18,4 +18,10 @@
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
#-renamesourcefileattribute SourceFile
-keep class com.cherret.zaprett.byedpi.TProxyService {
native long[] TProxyGetStats();
native void TProxyStartService(java.lang.String, int);
native void TProxyStopService();
}

View File

@@ -7,7 +7,16 @@
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission" />
<application
android:requestLegacyExternalStorage="true"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
@@ -17,6 +26,16 @@
android:supportsRtl="true"
android:theme="@style/Theme.Zaprett"
tools:targetApi="31">
<meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
@@ -24,10 +43,33 @@
android:theme="@style/Theme.Zaprett">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<service
android:name=".utils.QSTileService"
android:exported="true"
android:label="@string/qs_name"
android:icon="@drawable/ic_launcher_monochrome"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
</service>
<service
android:name=".byedpi.ByeDpiVpnService"
android:exported="true"
android:permission="android.permission.BIND_VPN_SERVICE"
android:foregroundServiceType="specialUse">
<intent-filter>
<action android:name="android.net.VpnService" />
</intent-filter>
</service>
</application>
</manifest>

View File

@@ -1,20 +1,28 @@
package com.cherret.zaprett
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Dashboard
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Lan
import androidx.compose.material.icons.filled.MultipleStop
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SettingsInputComposite
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
@@ -23,76 +31,175 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.cherret.zaprett.ui.screens.HomeScreen
import com.cherret.zaprett.ui.screens.HostsScreen
import com.cherret.zaprett.ui.screens.SettingsScreen
import androidx.navigation.navArgument
import com.cherret.zaprett.ui.screen.DebugScreen
import com.cherret.zaprett.ui.screen.HomeScreen
import com.cherret.zaprett.ui.screen.HostsScreen
import com.cherret.zaprett.ui.screen.IpsetsScreen
import com.cherret.zaprett.ui.screen.RepoScreen
import com.cherret.zaprett.ui.screen.SettingsScreen
import com.cherret.zaprett.ui.screen.StrategyScreen
import com.cherret.zaprett.ui.screen.StrategySelectionScreen
import com.cherret.zaprett.ui.theme.ZaprettTheme
import com.topjohnwu.superuser.Shell
import com.cherret.zaprett.ui.viewmodel.HomeViewModel
import com.cherret.zaprett.ui.viewmodel.HostRepoViewModel
import com.cherret.zaprett.ui.viewmodel.IpsetRepoViewModel
import com.cherret.zaprett.ui.viewmodel.StrategyRepoViewModel
import com.cherret.zaprett.utils.checkModuleInstallation
import com.cherret.zaprett.utils.checkStoragePermission
import com.google.firebase.Firebase
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.analytics
sealed class Screen(val route: String, @StringRes val nameResId: Int, val icon: androidx.compose.ui.graphics.vector.ImageVector) {
sealed class Screen(val route: String, @StringRes val nameResId: Int, val icon: ImageVector) {
object home : Screen("home", R.string.title_home, Icons.Default.Home)
object hosts : Screen("hosts", R.string.title_hosts, Icons.Default.Dashboard)
object hosts : Screen("hosts", R.string.title_hosts, Icons.Default.Lan)
object strategies : Screen("strategies", R.string.title_strategies, Icons.Default.MultipleStop)
object ipsets : Screen("ipsets", R.string.title_ipset, Icons.Default.SettingsInputComposite)
object settings : Screen("settings", R.string.title_settings, Icons.Default.Settings)
}
val topLevelRoutes = listOf(Screen.home, Screen.hosts, Screen.settings)
val topLevelRoutes = listOf(Screen.home, Screen.hosts, Screen.strategies, Screen.ipsets, Screen.settings)
val hideNavBar = listOf("repo?source={source}", "debugScreen", "selectionScreen")
class MainActivity : ComponentActivity() {
private val viewModel: HomeViewModel by viewModels()
private lateinit var notificationPermissionLauncher: ActivityResultLauncher<String>
private lateinit var firebaseAnalytics: FirebaseAnalytics
private lateinit var vpnPermissionLauncher: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPreferences = getSharedPreferences("settings", MODE_PRIVATE)
Shell.setDefaultBuilder(Shell.Builder.create()
.setTimeout(10))
vpnPermissionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
viewModel.startVpn()
viewModel.clearVpnPermissionRequest()
}
}
notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> }
firebaseAnalytics = Firebase.analytics
enableEdgeToEdge()
setContent {
ZaprettTheme {
BottomBar()
if (!Environment.isExternalStorageManager()) {
permissionDialog()
val sharedPreferences = remember { getSharedPreferences("settings", MODE_PRIVATE) }
LaunchedEffect(Unit) {
if (sharedPreferences.getBoolean("use_module", false)) {
checkModuleInstallation { result ->
if (getSharedPreferences(
"settings",
Context.MODE_PRIVATE
).getBoolean("use_module", false) && !result
) sharedPreferences.edit {
putBoolean(
"use_module",
false
)
}
}
}
}
if (sharedPreferences.getBoolean("welcome_dialog", true)) {
welcomeDialog()
var showStoragePermissionDialog by remember {
mutableStateOf(!checkStoragePermission(this))
}
var showNotificationPermissionDialog by remember {
mutableStateOf(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
)
}
var showWelcomeDialog by remember { mutableStateOf(sharedPreferences.getBoolean("welcome_dialog", true)) }
firebaseAnalytics.setAnalyticsCollectionEnabled(sharedPreferences.getBoolean("send_firebase_analytics", BuildConfig.send_firebase_analytics))
BottomBar()
if (showStoragePermissionDialog) {
PermissionDialog(
title = stringResource(R.string.error_no_storage_title),
message = stringResource(R.string.error_no_storage_message),
onConfirm = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivity(intent)
} else {
requestPermissions(
arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
),
100
)
}
showStoragePermissionDialog = false
},
onDismiss = { showStoragePermissionDialog = false }
)
}
if (showNotificationPermissionDialog) {
PermissionDialog(
title = stringResource(R.string.notification_permission_title),
message = stringResource(R.string.notification_permission_message),
onConfirm = {
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
showNotificationPermissionDialog = false
},
onDismiss = { showNotificationPermissionDialog = false }
)
}
if (showWelcomeDialog) {
WelcomeDialog {
sharedPreferences.edit { putBoolean("welcome_dialog", false) }
showWelcomeDialog = false
}
}
}
}
}
@Composable
fun BottomBar() {
val navController = rememberNavController()
Scaffold(
bottomBar = {
NavigationBar {
val navBackStackEntry = navController.currentBackStackEntryAsState().value
val currentDestination = navBackStackEntry?.destination
topLevelRoutes.forEach { topLevelRoute ->
NavigationBarItem(
icon = {
Icon(
topLevelRoute.icon,
contentDescription = stringResource(id = topLevelRoute.nameResId)
)
},
label = { Text(text = stringResource(id = topLevelRoute.nameResId)) },
selected = currentDestination?.route == topLevelRoute.route,
onClick = {
navController.navigate(topLevelRoute.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
val navBackStackEntry = navController.currentBackStackEntryAsState().value
val currentDestination = navBackStackEntry?.destination
if (currentDestination?.route !in hideNavBar) {
NavigationBar {
topLevelRoutes.forEach { topLevelRoute ->
NavigationBarItem(
icon = {
Icon(
topLevelRoute.icon,
contentDescription = stringResource(id = topLevelRoute.nameResId)
)
},
label = { Text(text = stringResource(id = topLevelRoute.nameResId)) }, alwaysShowLabel = false,
selected = currentDestination?.route == topLevelRoute.route,
onClick = {
navController.navigate(topLevelRoute.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
launchSingleTop = true
restoreState = true
}
}
)
)
}
}
}
}
@@ -102,77 +209,59 @@ class MainActivity : ComponentActivity() {
startDestination = Screen.home.route,
Modifier.padding(innerPadding)
) {
composable(Screen.home.route) { HomeScreen() }
composable(Screen.hosts.route) { HostsScreen() }
composable(Screen.settings.route) { SettingsScreen() }
composable(Screen.home.route) { HomeScreen(viewModel = viewModel,vpnPermissionLauncher) }
composable(Screen.hosts.route) { HostsScreen(navController) }
composable(Screen.strategies.route) { StrategyScreen(navController) }
composable(Screen.ipsets.route) { IpsetsScreen(navController) }
composable(Screen.settings.route) { SettingsScreen(navController) }
composable(route = "repo?source={source}",arguments = listOf(navArgument("source") {})) { backStackEntry ->
val source = backStackEntry.arguments?.getString("source")
when (source) {
"hosts" -> {
val viewModel: HostRepoViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
RepoScreen(navController, viewModel)
}
"ipsets" -> {
val viewModel: IpsetRepoViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
RepoScreen(navController, viewModel)
}
"strategies" -> {
val viewModel: StrategyRepoViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
RepoScreen(navController, viewModel)
}
}
}
composable("debugScreen") { DebugScreen(navController) }
composable("selectionScreen") { StrategySelectionScreen(navController, vpnPermissionLauncher) }
}
}
}
@Composable
fun welcomeDialog() {
val sharedPreferences =
LocalContext.current.getSharedPreferences("settings", MODE_PRIVATE)
val editor = sharedPreferences.edit()
val openDialog = remember { mutableStateOf(true) }
if (openDialog.value) {
AlertDialog(
title = {
Text(text = stringResource(R.string.app_name))
},
text = {
Text(text = stringResource(R.string.text_welcome))
},
onDismissRequest = {
editor.putBoolean("welcome_dialog", false).apply()
openDialog.value = false
},
confirmButton = {
TextButton(
onClick = {
editor.putBoolean("welcome_dialog", false).apply()
openDialog.value = false
}
) {
Text(stringResource(R.string.btn_continue))
}
},
)
}
fun WelcomeDialog(onDismiss: () -> Unit) {
AlertDialog(
title = { Text(text = stringResource(R.string.app_name)) },
text = { Text(text = stringResource(R.string.text_welcome)) },
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
@Composable
fun permissionDialog() {
val openDialog = remember { mutableStateOf(true) }
if (openDialog.value) {
AlertDialog(
title = {
Text(text = stringResource(R.string.error_no_storage_title))
},
text = {
Text(text = stringResource(R.string.error_no_storage_message))
},
onDismissRequest = {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
val uri = Uri.fromParts("package", packageName, null)
intent.setData(uri)
startActivity(intent)
openDialog.value = false
},
confirmButton = {
TextButton(
onClick = {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
val uri = Uri.fromParts("package", packageName, null)
intent.setData(uri)
startActivity(intent)
openDialog.value = false
}
) {
Text(stringResource(R.string.btn_continue))
}
},
)
}
fun PermissionDialog(title: String, message: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
title = { Text(title) },
text = { Text(message) },
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onConfirm) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
}

View File

@@ -1,170 +0,0 @@
package com.cherret.zaprett
import android.os.Environment
import android.util.Log
import com.topjohnwu.superuser.Shell
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.util.Properties
fun checkRoot(): Boolean {
val result = Shell.cmd("ls /").exec()
Shell.getShell().close()
return result.isSuccess
}
fun checkModuleInstallation(): Boolean {
val result = Shell.cmd("zaprett").exec()
Shell.getShell().close()
return result.out.toString().contains("zaprett")
}
fun getStatus(): Boolean {
val result = Shell.cmd("zaprett status").exec()
Shell.getShell().close()
return result.out.toString().contains("working")
}
fun startService() {
Shell.cmd("zaprett start").exec()
Shell.getShell().close()
}
fun stopService() {
Shell.cmd("zaprett stop").exec()
Shell.getShell().close()
}
fun restartService() {
Shell.cmd("zaprett restart").exec()
Shell.getShell().close()
}
fun getConfigFile(): File {
return File(Environment.getExternalStorageDirectory(), "zaprett/config")
}
fun setStartOnBoot(startOnBoot: Boolean) {
val configFile = getConfigFile()
if (configFile.exists()) {
val props = Properties()
try {
FileInputStream(configFile).use { input ->
props.load(input)
}
props.setProperty("autorestart", startOnBoot.toString())
FileOutputStream(configFile).use { output ->
props.store(output, "Don't place '/' in end of directory! Example: /sdcard")
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
fun getStartOnBoot(): Boolean {
val configFile = getConfigFile()
val props = Properties()
return try {
if (configFile.exists()) {
FileInputStream(configFile).use { input ->
props.load(input)
}
props.getProperty("autorestart", "false").toBoolean()
} else {
false
}
} catch (e: IOException) {
false
}
}
fun getZaprettPath(): String {
val props = Properties()
val configFile = getConfigFile()
if (configFile.exists()) {
return try {
FileInputStream(configFile).use { input ->
props.load(input)
}
props.getProperty("zaprettdir", "/sdcard/zaprett")
} catch (e: IOException) {
throw RuntimeException(e)
}
}
return "/sdcard/zaprett"
}
fun getAllLists(): Array<String> {
val listsDir = File("${getZaprettPath()}/lists/")
if (listsDir.exists() && listsDir.isDirectory) {
val onlyNames = listsDir.list() ?: return emptyArray()
return onlyNames.map { "$listsDir/$it" }.toTypedArray()
}
return emptyArray()
}
fun getActiveLists(): Array<String> {
val configFile = File("${getZaprettPath()}/config")
if (configFile.exists()) {
val props = Properties()
return try {
FileInputStream(configFile).use { input ->
props.load(input)
}
val activeLists = props.getProperty("activelists", "")
Log.d("Active lists", activeLists)
if (activeLists.isNotEmpty()) activeLists.split(",").toTypedArray() else emptyArray()
} catch (e: IOException) {
throw RuntimeException(e)
}
}
return emptyArray()
}
fun enableList(path: String) {
val props = Properties()
val configFile = getConfigFile()
try {
if (configFile.exists()) {
FileInputStream(configFile).use { input ->
props.load(input)
}
}
val activeLists = props.getProperty("activelists", "").split(",").toMutableList()
if (path !in activeLists) {
activeLists.add(path)
}
props.setProperty("activelists", activeLists.joinToString(","))
FileOutputStream(configFile).use { output ->
props.store(output, "Don't place '/' in end of directory! Example: /sdcard")
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
fun disableList(path: String) {
val props = Properties()
val configFile = getConfigFile()
try {
if (configFile.exists()) {
FileInputStream(configFile).use { input ->
props.load(input)
}
}
val activeLists = props.getProperty("activelists", "").split(",").toMutableList()
if (path in activeLists) {
activeLists.remove(path)
}
props.setProperty("activelists", activeLists.joinToString(","))
FileOutputStream(configFile).use { output ->
props.store(output, "Don't place '/' in end of directory! Example: /sdcard")
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}

View File

@@ -0,0 +1,287 @@
package com.cherret.zaprett.byedpi
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.content.SharedPreferences
import android.net.VpnService
import android.os.ParcelFileDescriptor
import android.util.Log
import androidx.core.app.NotificationCompat
import com.cherret.zaprett.MainActivity
import com.cherret.zaprett.R
import com.cherret.zaprett.data.ServiceStatus
import com.cherret.zaprett.utils.disableList
import com.cherret.zaprett.utils.getActiveByeDPIStrategyContent
import com.cherret.zaprett.utils.getActiveExcludeIpsets
import com.cherret.zaprett.utils.getActiveExcludeLists
import com.cherret.zaprett.utils.getActiveIpsets
import com.cherret.zaprett.utils.getActiveLists
import com.cherret.zaprett.utils.getActiveStrategy
import com.cherret.zaprett.utils.getAppsListMode
import com.cherret.zaprett.utils.getHostListMode
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
class ByeDpiVpnService : VpnService() {
private var vpnInterface: ParcelFileDescriptor? = null
private lateinit var sharedPreferences: SharedPreferences
companion object {
private const val CHANNEL_ID = "zaprett_vpn_channel"
private const val NOTIFICATION_ID = 1
var status: ServiceStatus = ServiceStatus.Disconnected
}
@SuppressLint("ForegroundServiceType")
override fun onCreate() {
super.onCreate()
sharedPreferences = getSharedPreferences("settings", MODE_PRIVATE)
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return when (intent?.action) {
"START_VPN" -> {
startForeground(NOTIFICATION_ID, createNotification())
setupProxy()
START_STICKY
}
"STOP_VPN" -> {
stopProxy()
stopSelf()
START_NOT_STICKY
}
else -> {
START_NOT_STICKY
}
}
}
override fun onDestroy() {
super.onDestroy()
vpnInterface?.close()
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
CHANNEL_ID,
getString(R.string.notification_zaprett_proxy),
NotificationManager.IMPORTANCE_LOW
).apply {
description = getString(R.string.notification_zaprett_description)
}
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
private fun createNotification(): Notification {
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0,
notificationIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.notification_zaprett_proxy))
.setContentText(getString(R.string.notification_zaprett_description))
.setSmallIcon(R.drawable.ic_launcher_monochrome)
.setContentIntent(pendingIntent)
.addAction(0, getString(R.string.btn_stop_service),
PendingIntent.getService(
this,
0,
Intent(this, ByeDpiVpnService::class.java).setAction("STOP_VPN"),
PendingIntent.FLAG_IMMUTABLE,
)
)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setOngoing(true)
.build()
}
private fun setupProxy() {
try {
startSocksProxy()
startByeDpi()
status = ServiceStatus.Connected
} catch (e: Exception) {
Log.e("proxy", "Failed to start")
status = ServiceStatus.Failed
stopSelf()
}
}
private fun startSocksProxy() {
val dns = sharedPreferences.getString("dns", "8.8.8.8")?: "8.8.8.8"
val ipv6 = sharedPreferences.getBoolean("ipv6", false)
val socksIp = sharedPreferences.getString("ip", "127.0.0.1")?: "127.0.0.1"
val socksPort = sharedPreferences.getString("port", "1080")?: "1080"
val builder = Builder()
builder.setSession(getString(R.string.notification_zaprett_proxy))
.setMtu(1500)
.addAddress("10.10.10.10", 32)
.addDnsServer(dns)
.addRoute("0.0.0.0", 0)
.setMetered(false)
if (ipv6) {
builder.addAddress("fd00::1", 128)
.addRoute("::", 0)
}
val appList = getAppsListMode(sharedPreferences)
when (appList) {
"blacklist" -> {
builder.addDisallowedApplication(applicationContext.packageName)
val blacklist = sharedPreferences.getStringSet("blacklist", emptySet())?: emptySet()
blacklist.forEach {
builder.addDisallowedApplication(it)
}
}
"whitelist" -> {
val whitelist = sharedPreferences.getStringSet("whitelist", emptySet())?: emptySet()
whitelist.forEach {
builder.addAllowedApplication(it)
}
}
else -> {
builder.addDisallowedApplication(applicationContext.packageName)
}
}
Log.d("builder", builder.toString())
vpnInterface = builder.establish()
val tun2socksConfig = """
| misc:
| task-stack-size: 81920
| socks5:
| mtu: 8500
| address: $socksIp
| port: $socksPort
| udp: udp
""".trimMargin("| ")
val configPath = File.createTempFile("config", "tmp", cacheDir).apply {
writeText(tun2socksConfig)
deleteOnExit()
}
vpnInterface?.fd?.let { fd ->
TProxyService.TProxyStartService(configPath.absolutePath, fd)
}
}
private fun stopProxy() {
try {
vpnInterface?.close()
vpnInterface = null
NativeBridge().jniStopProxy()
TProxyService.TProxyStopService()
status = ServiceStatus.Disconnected
} catch (e: Exception) {
Log.e("proxy", "error stop proxy")
}
}
private fun startByeDpi() {
val socksIp = sharedPreferences.getString("ip", "127.0.0.1")?: "127.0.0.1"
val socksPort = sharedPreferences.getString("port", "1080")?: "1080"
val listSet = if (getHostListMode(sharedPreferences) == "whitelist") getActiveLists(sharedPreferences) else getActiveExcludeLists(sharedPreferences)
val ipsetSet = if (getHostListMode(sharedPreferences) == "whitelist") getActiveIpsets(sharedPreferences) else getActiveExcludeIpsets(sharedPreferences)
CoroutineScope(Dispatchers.IO).launch {
val args = parseArgs(
socksIp,
socksPort,
getActiveByeDPIStrategyContent(sharedPreferences),
prepareList(listSet),
prepareIpset(ipsetSet),
sharedPreferences)
val result = NativeBridge().jniStartProxy(args)
if (result < 0) {
Log.d("proxy","Failed to start byedpi proxy")
} else {
Log.d("proxy", "Byedpi proxy started successfully")
}
}
}
private suspend fun prepareList(actlists: Array<String>): String {
if (actlists.isNotEmpty()) {
val lists: Array<File> = actlists.map { File(it) }.toTypedArray()
val hostlist = withContext(Dispatchers.IO) {
File.createTempFile("hostlist", ".txt", cacheDir)
}.apply { deleteOnExit() }
withContext(Dispatchers.IO) {
hostlist.printWriter().use { out ->
lists.forEach {
if (it.exists()) {
it.bufferedReader().useLines {
it.forEach {
out.println(it)
}
}
} else {
disableList(it.name, sharedPreferences)
}
}
}
}
return hostlist.absolutePath
}
return ""
}
private suspend fun prepareIpset(actsets: Array<String>): String {
if (actsets.isNotEmpty()) {
val lists: Array<File> = actsets.map { File(it) }.toTypedArray()
val hostlist = withContext(Dispatchers.IO) {
File.createTempFile("ipset", ".txt", cacheDir)
}.apply { deleteOnExit() }
withContext(Dispatchers.IO) {
hostlist.printWriter().use { out ->
lists.forEach {
if (it.exists()) {
it.bufferedReader().useLines {
it.forEach {
out.println(it)
}
}
} else {
disableList(it.name, sharedPreferences)
}
}
}
}
return hostlist.absolutePath
}
return ""
}
private fun parseArgs(ip: String, port: String, rawArgs: List<String>, list : String, ipset : String, sharedPreferences: SharedPreferences): Array<String> {
val regex = Regex("""--?\S+(?:=(?:[^"'\s]+|"[^"]*"|'[^']*'))?|[^\s]+""")
val parsedArgs = rawArgs
.flatMap { args -> regex.findAll(args).map { it.value } }
.flatMap { arg ->
if (getHostListMode(sharedPreferences) == "whitelist") {
when {
arg == "\$hostlist" && list.isNotEmpty() -> listOf("--hosts", list)
arg == "\$hostlist" && list.isEmpty() -> emptyList()
arg == "\$ipset" && list.isNotEmpty() -> listOf("--ipset", list)
arg == "\$ipset" && list.isEmpty() -> emptyList()
else -> listOf(arg)
}
} else {
when {
arg == "\$hostlist" && list.isNotEmpty() -> listOf("--hosts", list, "-An", list)
arg == "\$ipset" && ipset.isNotEmpty() -> listOf("--ipset", ipset, "-An", ipset)
arg == "\$hostlist" || arg == "\$ipset" -> emptyList()
else -> listOf(arg)
}
}
}
.toMutableList()
return arrayOf("ciadpi", "--ip", ip, "--port", port) + parsedArgs
}
}

View File

@@ -0,0 +1,12 @@
package com.cherret.zaprett.byedpi
class NativeBridge {
companion object {
init {
System.loadLibrary("byedpi")
}
}
external fun jniStartProxy(args: Array<String>): Int
external fun jniStopProxy(): Int
}

View File

@@ -0,0 +1,11 @@
package com.cherret.zaprett.byedpi
object TProxyService {
init {
System.loadLibrary("hev-socks5-tunnel")
}
external fun TProxyStartService(config: String, fd: Int)
external fun TProxyGetStats(): LongArray
external fun TProxyStopService()
}

View File

@@ -0,0 +1,5 @@
package com.cherret.zaprett.data;
enum class AppListType {
Blacklist,
Whitelist
}

View File

@@ -0,0 +1,5 @@
package com.cherret.zaprett.data
enum class ItemType {
byedpi, nfqws, list, list_exclude, ipset, ipset_exclude
}

View File

@@ -0,0 +1,7 @@
package com.cherret.zaprett.data
enum class ServiceStatus {
Disconnected,
Connected,
Failed,
}

View File

@@ -0,0 +1,11 @@
package com.cherret.zaprett.data
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Help
import androidx.compose.ui.graphics.vector.ImageVector
import com.cherret.zaprett.R
data class ServiceStatusUI(
val textRes: Int = R.string.status_not_availible,
val icon: ImageVector = Icons.AutoMirrored.Filled.Help
)

View File

@@ -0,0 +1,7 @@
package com.cherret.zaprett.data
sealed class Setting {
data class Toggle(val title: String, val checked: Boolean, val onToggle: (Boolean) -> Unit) : Setting()
data class Action(val title: String, val onClick: () -> Unit) : Setting()
data class Section(val title: String) : Setting()
}

View File

@@ -0,0 +1,8 @@
package com.cherret.zaprett.data
data class StrategyCheckResult (
val path : String,
val progress : Float,
var domains: List<String>,
val status : StrategyTestingStatus,
)

View File

@@ -0,0 +1,7 @@
package com.cherret.zaprett.data
import com.cherret.zaprett.R
enum class StrategyTestingStatus(val resId: Int) {
Waiting(R.string.strategy_status_waiting), Testing(R.string.strategy_status_testing), Completed(R.string.strategy_status_tested)
}

View File

@@ -0,0 +1,26 @@
package com.cherret.zaprett.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ZaprettConfig(
@SerialName("active_lists")
val activeLists: List<String> = emptyList(),
@SerialName("active_ipsets")
val activeIpsets: List<String> = emptyList(),
@SerialName("active_exclude_lists")
val activeExcludeLists: List<String> = emptyList(),
@SerialName("active_exclude_ipsets")
val activeExcludeIpsets: List<String> = emptyList(),
@SerialName("list_type")
val listType: String = "whitelist",
@SerialName("strategy")
val strategy: String = "",
@SerialName("app_list")
val appList: String = "none",
@SerialName("whitelist")
val whitelist: List<String> = emptyList(),
@SerialName("blacklist")
val blacklist: List<String> = emptyList()
)

View File

@@ -0,0 +1,308 @@
package com.cherret.zaprett.ui.component
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.InstallMobile
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProgressIndicatorDefaults
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cherret.zaprett.R
import com.cherret.zaprett.data.StrategyCheckResult
import com.cherret.zaprett.data.StrategyTestingStatus
import com.cherret.zaprett.ui.viewmodel.BaseRepoViewModel
import com.cherret.zaprett.utils.RepoItemInfo
import com.cherret.zaprett.utils.disableStrategy
import com.cherret.zaprett.utils.enableStrategy
import com.cherret.zaprett.utils.getActiveStrategy
import kotlinx.coroutines.launch
@Composable
fun ListSwitchItem(item: String, isChecked: Boolean, onCheckedChange: (Boolean) -> Unit, onDeleteClick: () -> Unit) {
ElevatedCard(
elevation = CardDefaults.cardElevation(defaultElevation = 6.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 25.dp, end = 10.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = item, modifier = Modifier.weight(1f))
Switch(checked = isChecked, onCheckedChange = onCheckedChange)
}
HorizontalDivider(thickness = Dp.Hairline)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
FilledTonalButton(
onClick = onDeleteClick,
modifier = Modifier.padding(horizontal = 5.dp)
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = stringResource(R.string.btn_remove_host),
modifier = Modifier.size(20.dp)
)
Text(stringResource(R.string.btn_remove_host))
}
}
}
}
@Composable
fun RepoItem(
item: RepoItemInfo,
viewModel: BaseRepoViewModel,
isInstalling: Map<String, Boolean>,
isUpdateInstalling: Map<String, Boolean>,
isUpdate: Map<String, Boolean>,
modifier: Modifier = Modifier
) {
val isInstalled = viewModel.isItemInstalled(item)
val installing = isInstalling[item.name] == true
val updating = isUpdateInstalling[item.name] == true
ElevatedCard(
elevation = CardDefaults.cardElevation(defaultElevation = 6.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
modifier = modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 25.dp, end = 10.dp)
) {
Column(Modifier.fillMaxWidth()) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = item.name, modifier = Modifier.weight(1f))
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp)
) {
Text(
text = stringResource(R.string.title_author, item.author),
modifier = Modifier.weight(1f)
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp)
) {
Text(
text = item.description,
modifier = Modifier.weight(1f)
)
}
HorizontalDivider(thickness = Dp.Hairline)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
if (isUpdate[item.name] == true && isInstalled) {
FilledTonalButton(
onClick = { viewModel.update(item) },
enabled = !updating,
modifier = Modifier.padding(horizontal = 5.dp)
) {
Icon(
imageVector = Icons.Default.Update,
contentDescription = stringResource(R.string.btn_remove_host),
modifier = Modifier.size(20.dp)
)
Text(
if (updating) stringResource(R.string.btn_updating_host)
else stringResource(R.string.btn_update_host)
)
}
}
FilledTonalButton(
onClick = { viewModel.install(item) },
enabled = !installing && !isInstalled,
modifier = Modifier.padding(horizontal = 5.dp)
) {
Icon(
imageVector = Icons.Default.InstallMobile,
contentDescription = stringResource(R.string.btn_remove_host),
modifier = Modifier.size(20.dp)
)
Text(
when {
installing -> stringResource(R.string.btn_installing_host)
isInstalled -> stringResource(R.string.btn_installed_host)
else -> stringResource(R.string.btn_install_host)
}
)
}
}
}
}
}
@Composable
fun StrategySelectionItem(strategy : StrategyCheckResult, prefs : SharedPreferences, context : Context, snackbarHostState : SnackbarHostState) {
val scope = rememberCoroutineScope()
var expanded by remember { mutableStateOf(false) }
ElevatedCard (
elevation = CardDefaults.cardElevation(defaultElevation = 6.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
onClick = {
if (strategy.status == StrategyTestingStatus.Completed && strategy.domains.isNotEmpty()) {
expanded = !expanded
}
},
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, end = 10.dp, top = 25.dp, bottom = 0.dp)
) {
Column (
Modifier
.fillMaxWidth()
.padding(16.dp)
)
{
Row {
Text(
text = strategy.path,
modifier = Modifier
.weight(1f)
)
FilledTonalIconButton(
onClick = {
if (getActiveStrategy(prefs).isNotEmpty()) disableStrategy(getActiveStrategy(prefs)[0], prefs)
enableStrategy(strategy.path, prefs)
scope.launch {
snackbarHostState.showSnackbar(
message = context.getString(R.string.strategy_applied)
)
}
},
enabled = strategy.status == StrategyTestingStatus.Completed
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = "apply"
)
}
}
Row {
Text(
text = stringResource(strategy.status.resId),
modifier = Modifier
.weight(1f),
fontSize = 12.sp,
)
}
Row (
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
) {
LinearProgressIndicator(
modifier = Modifier
.weight(1f),
progress = {
strategy.progress
},
color = ProgressIndicatorDefaults.linearColor,
trackColor = ProgressIndicatorDefaults.linearTrackColor,
strokeCap = ProgressIndicatorDefaults.LinearStrokeCap,
)
Text(
text = "${(strategy.progress*100).toInt()}%",
modifier = Modifier
.padding(start = 16.dp),
)
}
}
AnimatedVisibility(
visible = expanded,
enter = expandVertically(),
exit = shrinkVertically()
) {
Card (
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
modifier = Modifier
.padding(horizontal = 8.dp)
.fillMaxWidth()
) {
Text(
text = stringResource(R.string.selection_available_domains)
)
LazyColumn(modifier = Modifier.heightIn(max = 300.dp)) {
items(strategy.domains) { item ->
Card(
elevation = CardDefaults.cardElevation(4.dp),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Text(
text = item,
modifier = Modifier.padding(16.dp),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
}
}
}
}

View File

@@ -0,0 +1,146 @@
package com.cherret.zaprett.ui.component
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cherret.zaprett.R
@Composable
fun SettingsItem(title: String, checked: Boolean, onToggle: (Boolean) -> Unit, onCheckedChange: (Boolean) -> Unit) {
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.height(80.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
onClick = { onToggle(!checked) },
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = title,
modifier = Modifier.weight(1f)
)
Switch(
checked = checked,
onCheckedChange = onCheckedChange
)
}
}
}
@Composable
fun SettingsActionItem(title: String, onClick: () -> Unit) {
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.height(80.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
onClick = { onClick() },
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = title,
modifier = Modifier.weight(1f)
)
Icon(imageVector = Icons.AutoMirrored.Default.ArrowForward, contentDescription = null)
}
}
}
@Composable
fun SettingsSection(title: String) {
Text(
text = title,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(vertical = 8.dp, horizontal = 4.dp)
)
}
@Composable
fun InfoDialog(title: String, message: String, onDismiss: () -> Unit) {
AlertDialog(
title = { Text(text = title) },
text = { Text(text = message) },
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
@Composable
fun TextDialog(title: String, message: String, initialText: String, onConfirm: (String) -> Unit, onDismiss: () -> Unit) {
var inputText by remember { mutableStateOf(initialText) }
AlertDialog(
title = { Text(text = title) },
text = {
TextField(
value = inputText,
onValueChange = { inputText = it },
placeholder = { Text(message) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)},
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = {
if (inputText.isNotEmpty()) {
onConfirm(inputText)
onDismiss()
}
else {
onDismiss()
}
}
) {
Text(stringResource(R.string.btn_continue))
}
},
dismissButton = {
TextButton(
onClick = { onDismiss() }
) {
Text(stringResource(R.string.btn_dismiss))
}
}
)
}

View File

@@ -0,0 +1,155 @@
package com.cherret.zaprett.ui.screen
import android.app.Activity
import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.cherret.zaprett.R
import com.cherret.zaprett.data.Setting
import com.cherret.zaprett.ui.component.SettingsActionItem
import com.cherret.zaprett.ui.component.SettingsItem
import com.cherret.zaprett.ui.component.SettingsSection
import com.cherret.zaprett.ui.component.TextDialog
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DebugScreen(navController: NavController) {
val context = LocalContext.current
val sharedPreferences = remember { context.getSharedPreferences("settings", Context.MODE_PRIVATE) }
val editor = remember { sharedPreferences.edit() }
val showUpdateUrlDialog = remember { mutableStateOf(false) }
val textDialogValue = remember { mutableStateOf("") }
val showResetSettingsDialog = remember { mutableStateOf(false) }
val settingsList = listOf(
Setting.Action(
title = stringResource(R.string.btn_update_repository_url),
onClick = {
textDialogValue.value = sharedPreferences.getString("update_repo_url", "https://raw.githubusercontent.com/CherretGit/zaprett-app/refs/heads/main/update.json")?: "https://raw.githubusercontent.com/CherretGit/zaprett-app/refs/heads/main/update.json"
showUpdateUrlDialog.value = true
}
),
Setting.Action(
title = stringResource(R.string.reset_settings_title),
onClick = {
showResetSettingsDialog.value = true
}
)
)
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_debug),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.btn_back)
)
}
},
windowInsets = WindowInsets(0)
)
},
content = { paddingValues ->
LazyColumn(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize(),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 25.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(settingsList) { setting ->
when (setting) {
is Setting.Toggle -> {
SettingsItem(
title = setting.title,
onToggle = setting.onToggle,
checked = setting.checked,
onCheckedChange = setting.onToggle
)
}
is Setting.Action -> {
SettingsActionItem(
title = setting.title,
setting.onClick
)
}
is Setting.Section -> {
SettingsSection(setting.title)
}
}
}
}
}
)
if (showUpdateUrlDialog.value) {
TextDialog(stringResource(R.string.btn_update_repository_url), stringResource(R.string.hint_enter_update_repository_url), textDialogValue.value, onConfirm = {
editor.putString("update_repo_url", it).apply()
}, onDismiss = { showUpdateUrlDialog.value = false })
}
if (showResetSettingsDialog.value) {
AlertDialog(title = { Text(text = stringResource(R.string.reset_settings_title)) },
text = { Text(text = stringResource(R.string.reset_settings_message)) },
onDismissRequest = {
showResetSettingsDialog.value = false
},
dismissButton = {
TextButton(onClick = {
showResetSettingsDialog.value = false
}) {
Text(stringResource(R.string.btn_dismiss))
}
},
confirmButton = {
TextButton(onClick = {
context.deleteSharedPreferences("settings")
showResetSettingsDialog.value = false
val activity = context as Activity
val intent = activity.intent
activity.finish()
activity.startActivity(intent)
}) {
Text(text = stringResource(R.string.btn_continue))
}
})
}
}

View File

@@ -0,0 +1,381 @@
package com.cherret.zaprett.ui.screen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.VpnService
import android.os.Build
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Dangerous
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.WavingHand
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.cherret.zaprett.BuildConfig
import com.cherret.zaprett.R
import com.cherret.zaprett.data.ServiceStatusUI
import com.cherret.zaprett.ui.viewmodel.HomeViewModel
import dev.jeziellago.compose.markdowntext.MarkdownText
import kotlinx.coroutines.CoroutineScope
import kotlinx.serialization.SerializationException
import java.io.IOException
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(viewModel: HomeViewModel = viewModel(), vpnLauncher: ActivityResultLauncher<Intent>) {
val context = LocalContext.current
val sharedPreferences: SharedPreferences = remember { context.getSharedPreferences("settings", Context.MODE_PRIVATE) }
val requestVpnPermission by viewModel.requestVpnPermission.collectAsState()
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val status by viewModel.serviceStatus.collectAsState()
val changeLog = viewModel.changeLog
val newVersion = viewModel.newVersion
val updateAvailable = viewModel.updateAvailable
val showUpdateDialog = viewModel.showUpdateDialog.value
val moduleVer = viewModel.moduleVer;
val nfqwsVer = viewModel.nfqwsVer;
val byedpiVer = viewModel.byedpiVer;
val serviceMode = viewModel.serviceMode
val error by viewModel.errorFlow.collectAsState()
LaunchedEffect(Unit) {
viewModel.checkForUpdate()
viewModel.checkServiceStatus()
viewModel.checkModuleInfo()
}
LaunchedEffect(requestVpnPermission) {
if (requestVpnPermission) {
val intent = VpnService.prepare(context)
if (intent != null) {
vpnLauncher.launch(intent)
} else {
viewModel.startVpn()
viewModel.clearVpnPermissionRequest()
}
}
}
if (error.isNotEmpty()) {
AlertDialog(
onDismissRequest = {
viewModel.clearError()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(stringResource(R.string.error_unknown))
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", error)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearError()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.app_name),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
windowInsets = WindowInsets(0)
)
},
snackbarHost = { SnackbarHost(snackbarHostState) },
content = { paddingValues ->
Column(modifier = Modifier
.padding(paddingValues)
.verticalScroll(rememberScrollState())) {
ServiceStatusCard(viewModel, status, snackbarHostState, scope)
UpdateCard(updateAvailable) { viewModel.showUpdateDialog() }
if (showUpdateDialog) {
UpdateDialog(viewModel, changeLog.value.orEmpty(), newVersion) { viewModel.dismissUpdateDialog() }
}
ServiceControlButtons(
viewModel,
sharedPreferences,
snackbarHostState,
scope
)
ModuleInfoCard(moduleVer, nfqwsVer, byedpiVer, serviceMode)
}
}
)
}
@Composable
private fun ServiceStatusCard(viewModel: HomeViewModel, status: ServiceStatusUI, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
ElevatedCard(
elevation = CardDefaults.cardElevation(6.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primary),
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 25.dp, end = 10.dp)
//.height(150.dp)
.wrapContentHeight(),
onClick = { viewModel.onCardClick() }
) {
Row (
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
)
{
Icon(
painter = rememberVectorPainter(status.icon),
modifier = Modifier
.width(60.dp)
.height(60.dp),
contentDescription = "icon"
)
Text(
text = stringResource(status.textRes),
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal)),
fontSize = 16.sp,
//maxLines = 3,
//overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textAlign = TextAlign.Center
)
}
}
}
@Composable
private fun UpdateCard(updateAvailable: MutableState<Boolean>, onClick: () -> Unit) {
AnimatedVisibility(
visible = updateAvailable.value,
enter = fadeIn() + expandVertically(),
exit = shrinkVertically() + fadeOut()
) {
ElevatedCard(
elevation = CardDefaults.cardElevation(6.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 10.dp, end = 10.dp),
onClick = onClick
) {
Text(
text = stringResource(R.string.update_available),
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal)),
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textAlign = TextAlign.Center
)
}
}
}
@Composable
private fun ServiceControlButtons(viewModel: HomeViewModel, sharedPreferences: SharedPreferences, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
FilledTonalButton(
onClick = { viewModel.onBtnStartService(snackbarHostState, scope) },
modifier = Modifier
.padding(horizontal = 5.dp, vertical = 8.dp)
.fillMaxWidth()
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = stringResource(R.string.btn_start_service),
modifier = Modifier.size(20.dp)
)
Text(stringResource(R.string.btn_start_service))
}
FilledTonalButton(
onClick = { viewModel.onBtnStopService(snackbarHostState, scope) },
modifier = Modifier
.padding(horizontal = 5.dp, vertical = 8.dp)
.fillMaxWidth()
) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.btn_stop_service),
modifier = Modifier.size(20.dp)
)
Text(stringResource(R.string.btn_stop_service))
}
if (sharedPreferences.getBoolean("use_module", false)) {
FilledTonalButton(
onClick = { viewModel.onBtnRestart(snackbarHostState, scope) },
modifier = Modifier
.padding(horizontal = 5.dp, vertical = 8.dp)
.fillMaxWidth()
) {
Icon(
imageVector = Icons.Default.RestartAlt,
contentDescription = stringResource(R.string.btn_restart_service),
modifier = Modifier.size(20.dp)
)
Text(stringResource(R.string.btn_restart_service))
}
}
}
@Composable
private fun ModuleInfoCard(
moduleVer: MutableState<String>,
nfqwsVer: MutableState<String>,
byedpiVer: MutableState<String>,
serviceMode: MutableState<Int>
) {
ElevatedCard(
elevation = CardDefaults.cardElevation(6.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp)
) {
ModuleInfoItem(Icons.Default.Build, stringResource(R.string.service_mode), stringResource(serviceMode.value))
HorizontalDivider()
ModuleInfoItem(Icons.Default.Extension, stringResource(R.string.module_version), moduleVer.value)
HorizontalDivider()
ModuleInfoItem(Icons.Default.Dangerous, stringResource(R.string.nfqws_version), nfqwsVer.value)
HorizontalDivider()
ModuleInfoItem(Icons.Default.WavingHand, stringResource(R.string.ciadpi_version), byedpiVer.value)
}
}
@Composable
private fun ModuleInfoItem(
icon: ImageVector, header : String, value : String
) {
Row (
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Icon(
painter = rememberVectorPainter(icon),
modifier = Modifier
.size(50.dp)
.padding(16.dp),
contentDescription = "icon"
)
Column (
modifier = Modifier
.padding(horizontal = 16.dp)
){
Text(
text = header,
modifier = Modifier
.fillMaxWidth(),
fontSize = 18.sp,
textAlign = TextAlign.Justify,
)
Text(
text = value
)
}
}
}
@Composable
fun UpdateDialog(viewModel: HomeViewModel, changeLog: String, newVersion: MutableState<String?>, onDismiss: () -> Unit) {
AlertDialog(
title = { Text(text = stringResource(R.string.update_available)) },
text = {
MarkdownText(
markdown = stringResource(R.string.alert_version, BuildConfig.VERSION_NAME, newVersion.value.toString(), changeLog)
)
},
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = {
onDismiss()
viewModel.onUpdateConfirm()
}) {
Text(stringResource(R.string.btn_update))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.btn_dismiss))
}
}
)
}

View File

@@ -0,0 +1,281 @@
package com.cherret.zaprett.ui.screen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.UploadFile
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.cherret.zaprett.R
import com.cherret.zaprett.ui.component.ListSwitchItem
import com.cherret.zaprett.ui.viewmodel.HostsViewModel
import com.cherret.zaprett.utils.getHostListMode
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HostsScreen(navController: NavController, viewModel: HostsViewModel = viewModel()) {
val context = LocalContext.current
val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val allLists = viewModel.allItems
val checked = viewModel.checked
val isRefreshing = viewModel.isRefreshing
val showPermissionDialog by viewModel.showNoPermissionDialog.collectAsState()
val filePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
uri?.let {
if (getHostListMode(prefs) == "whitelist") viewModel.copySelectedFile(context, "/lists/include", it)
else viewModel.copySelectedFile(context, "/lists/exclude", it) }
}
val error by viewModel.errorFlow.collectAsState()
LaunchedEffect(Unit) {
viewModel.refresh()
}
if (error.isNotEmpty()) {
AlertDialog(
onDismissRequest = {
viewModel.clearError()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(stringResource(R.string.error_unknown))
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", error)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearError()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_hosts),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
windowInsets = WindowInsets(0)
)
},
content = { paddingValues ->
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = {
viewModel.refresh()
},
modifier = Modifier.fillMaxSize()
) {
LazyColumn(
contentPadding = PaddingValues(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding() + 80.dp
),
modifier = Modifier.navigationBarsPadding().fillMaxSize()
) {
item {
ListTypeChoose(viewModel, prefs)
}
when {
allLists.isEmpty() -> {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.empty_list),
textAlign = TextAlign.Center
)
}
}
}
else -> {
items(allLists) { item ->
ListSwitchItem (
item = item,
isChecked = checked[item] == true,
onCheckedChange = { isChecked ->
viewModel.onCheckedChange(item, isChecked, snackbarHostState, scope)
},
onDeleteClick = {
viewModel.deleteItem(item, snackbarHostState, scope)
}
)
}
}
}
}
}
},
floatingActionButton = {
FloatingMenu(navController, filePickerLauncher)
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
)
if (showPermissionDialog) {
AlertDialog(
title = { Text(text = stringResource(R.string.error_no_storage_title)) },
text = { Text(text = stringResource(R.string.no_storage_permission_message)) },
onDismissRequest = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
},
confirmButton = {
TextButton(onClick = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
}
@Composable
private fun FloatingMenu(navController: NavController, launcher: ActivityResultLauncher<Array<String>>) {
var expanded by remember { mutableStateOf(false) }
FloatingActionButton(
modifier = Modifier.size(80.dp),
onClick = { expanded = !expanded }
) {
Icon(Icons.Default.Add, contentDescription = stringResource(R.string.btn_add_host))
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.btn_download_host)) },
onClick = {
expanded = false
navController.navigate("repo?source=hosts") { launchSingleTop = true }
},
leadingIcon = {
Icon(Icons.Default.Download, contentDescription = stringResource(R.string.btn_download_host))
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.btn_add_host)) },
onClick = {
expanded = false
addHost(launcher)
},
leadingIcon = {
Icon(Icons.Default.UploadFile, contentDescription = stringResource(R.string.btn_add_host))
}
)
}
}
@Composable
fun ListTypeChoose(viewModel: HostsViewModel, prefs : SharedPreferences) {
val listType = remember { mutableStateOf(getHostListMode(prefs))}
val options = listOf(stringResource(R.string.title_whitelist), stringResource(R.string.title_blacklist))
val selectedIndex = if (listType.value == "whitelist") 0 else 1
SingleChoiceSegmentedButtonRow (
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
options.forEachIndexed { index, label ->
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = options.size
),
onClick = {
listType.value = if (index == 0) "whitelist" else "blacklist"
viewModel.setListType(listType.value)
},
selected = index == selectedIndex,
label = {
Text(
label
)
}
)
}
}
}
private fun addHost(launcher: ActivityResultLauncher<Array<String>>) {
launcher.launch(arrayOf("text/plain"))
}

View File

@@ -0,0 +1,279 @@
package com.cherret.zaprett.ui.screen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.UploadFile
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.cherret.zaprett.R
import com.cherret.zaprett.ui.component.ListSwitchItem
import com.cherret.zaprett.ui.viewmodel.HostsViewModel
import com.cherret.zaprett.ui.viewmodel.IpsetViewModel
import com.cherret.zaprett.utils.getHostListMode
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IpsetsScreen(navController: NavController, viewModel: IpsetViewModel = viewModel()) {
val context = LocalContext.current
val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val allLists = viewModel.allItems
val checked = viewModel.checked
val isRefreshing = viewModel.isRefreshing
val showPermissionDialog by viewModel.showNoPermissionDialog.collectAsState()
val filePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
uri?.let {
if (getHostListMode(prefs) == "whitelist") viewModel.copySelectedFile(context, "/ipset/include", it)
else viewModel.copySelectedFile(context, "/ipset/exclude", it) }
}
val error by viewModel.errorFlow.collectAsState()
LaunchedEffect(Unit) {
viewModel.refresh()
}
if (error.isNotEmpty()) {
AlertDialog(
onDismissRequest = {
viewModel.clearError()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(stringResource(R.string.error_unknown))
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", error)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearError()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_ipset),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
windowInsets = WindowInsets(0)
)
},
content = { paddingValues ->
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = {
viewModel.refresh()
},
modifier = Modifier.fillMaxSize()
) {
LazyColumn(
contentPadding = PaddingValues(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding() + 80.dp
),
modifier = Modifier.navigationBarsPadding().fillMaxSize()
) {
item {
IpsetTypeChoose(viewModel, prefs)
}
when {
allLists.isEmpty() -> {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.empty_list),
textAlign = TextAlign.Center
)
}
}
}
else -> {
items(allLists) { item ->
ListSwitchItem (
item = item,
isChecked = checked[item] == true,
onCheckedChange = { isChecked ->
viewModel.onCheckedChange(item, isChecked, snackbarHostState, scope)
},
onDeleteClick = {
viewModel.deleteItem(item, snackbarHostState, scope)
}
)
}
}
}
}
}
},
floatingActionButton = {
FloatingMenu(navController, filePickerLauncher)
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
)
if (showPermissionDialog) {
AlertDialog(
title = { Text(text = stringResource(R.string.error_no_storage_title)) },
text = { Text(text = stringResource(R.string.no_storage_permission_message)) },
onDismissRequest = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
},
confirmButton = {
TextButton(onClick = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
}
@Composable
private fun FloatingMenu(navController: NavController, launcher: ActivityResultLauncher<Array<String>>) {
var expanded by remember { mutableStateOf(false) }
FloatingActionButton(
modifier = Modifier.size(80.dp),
onClick = { expanded = !expanded }
) {
Icon(Icons.Default.Add, contentDescription = stringResource(R.string.btn_add_host))
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.btn_download_host)) },
onClick = {
expanded = false
navController.navigate("repo?source=ipsets") { launchSingleTop = true }
},
leadingIcon = {
Icon(Icons.Default.Download, contentDescription = stringResource(R.string.btn_download_host))
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.btn_add_host)) },
onClick = {
expanded = false
addHost(launcher)
},
leadingIcon = {
Icon(Icons.Default.UploadFile, contentDescription = stringResource(R.string.btn_add_host))
}
)
}
}
@Composable
fun IpsetTypeChoose(viewModel: IpsetViewModel, prefs : SharedPreferences) {
val listType = remember { mutableStateOf(getHostListMode(prefs))}
val options = listOf(stringResource(R.string.title_whitelist), stringResource(R.string.title_blacklist))
val selectedIndex = if (listType.value == "whitelist") 0 else 1
SingleChoiceSegmentedButtonRow (
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
options.forEachIndexed { index, label ->
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = options.size
),
onClick = {
listType.value = if (index == 0) "whitelist" else "blacklist"
viewModel.setListType(listType.value)
},
selected = index == selectedIndex,
label = {
Text(
label
)
}
)
}
}
}
private fun addHost(launcher: ActivityResultLauncher<Array<String>>) {
launcher.launch(arrayOf("text/plain"))
}

View File

@@ -0,0 +1,213 @@
package com.cherret.zaprett.ui.screen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.cherret.zaprett.R
import com.cherret.zaprett.ui.component.RepoItem
import com.cherret.zaprett.ui.viewmodel.BaseRepoViewModel
import kotlinx.serialization.SerializationException
import java.io.IOException
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RepoScreen(navController: NavController, viewModel: BaseRepoViewModel) {
val context = LocalContext.current
val hostLists = viewModel.hostLists.value
val isUpdate = viewModel.isUpdate
val isInstalling = viewModel.isInstalling
val isUpdateInstalling = viewModel.isUpdateInstalling
val isRefreshing = viewModel.isRefreshing.value
val snackbarHostState = remember { SnackbarHostState() }
val error by viewModel.errorFlow.collectAsState()
val downloadError by viewModel.downloadErrorFlow.collectAsState()
val showPermissionDialog by viewModel.showPermissionDialog.collectAsState()
LaunchedEffect(Unit) {
viewModel.refresh()
}
if (error != null) {
AlertDialog(
onDismissRequest = {
viewModel.clearError()
navController.popBackStack()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(
when (error) {
is IOException -> stringResource(R.string.error_server_data)
is SerializationException -> stringResource(R.string.error_processing_data)
else -> stringResource(R.string.error_unknown)
}
)
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", error?.message)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearError()
navController.popBackStack()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
if (downloadError != null) {
AlertDialog(
onDismissRequest = {
viewModel.clearDownloadError()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(stringResource(R.string.download_error))
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", downloadError)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearDownloadError()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
if (showPermissionDialog) {
AlertDialog(
title = { Text(text = stringResource(R.string.error_no_storage_title)) },
text = { Text(text = stringResource(R.string.no_storage_permission_message)) },
onDismissRequest = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
},
confirmButton = {
TextButton(onClick = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_repo),
fontSize = 30.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.btn_back)
)
}
},
windowInsets = WindowInsets(0)
)
},
content = { paddingValues ->
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = { viewModel.refresh() },
modifier = Modifier.fillMaxSize()
) {
LazyColumn(
contentPadding = paddingValues,
modifier = Modifier.navigationBarsPadding().fillMaxSize()
) {
if (hostLists.isEmpty()) {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.empty_list),
textAlign = TextAlign.Center
)
}
}
} else {
items(hostLists) { item ->
RepoItem(
item = item,
viewModel = viewModel,
isInstalling = isInstalling,
isUpdateInstalling = isUpdateInstalling,
isUpdate = isUpdate
)
}
}
}
}
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
)
}

View File

@@ -0,0 +1,711 @@
package com.cherret.zaprett.ui.screen
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.drawable.Drawable
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AttachMoney
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.core.content.edit
import androidx.core.net.toUri
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil3.compose.AsyncImage
import com.cherret.zaprett.BuildConfig
import com.cherret.zaprett.R
import com.cherret.zaprett.byedpi.ByeDpiVpnService
import com.cherret.zaprett.ui.component.SettingsActionItem
import com.cherret.zaprett.ui.component.SettingsItem
import com.cherret.zaprett.ui.component.SettingsSection
import com.cherret.zaprett.data.AppListType
import com.cherret.zaprett.data.ServiceStatus
import com.cherret.zaprett.ui.component.InfoDialog
import com.cherret.zaprett.data.Setting
import com.cherret.zaprett.ui.component.TextDialog
import com.cherret.zaprett.ui.viewmodel.SettingsViewModel
import com.cherret.zaprett.utils.checkModuleInstallation
import com.cherret.zaprett.utils.checkRoot
import com.cherret.zaprett.utils.getAppsListMode
import com.cherret.zaprett.utils.getStartOnBoot
import com.cherret.zaprett.utils.setAppsListMode
import com.cherret.zaprett.utils.setStartOnBoot
import com.cherret.zaprett.utils.stopService
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(navController: NavController, viewModel : SettingsViewModel = viewModel()) {
val context = LocalContext.current
val sharedPreferences = remember { context.getSharedPreferences("settings", Context.MODE_PRIVATE) }
val editor = remember { sharedPreferences.edit() }
val useModule = viewModel.useModule.collectAsState()
val updateOnBoot = remember { mutableStateOf(sharedPreferences.getBoolean("update_on_boot", true)) }
val autoRestart = viewModel.autoRestart.collectAsState()
val autoUpdate = remember { mutableStateOf(sharedPreferences.getBoolean("auto_update", BuildConfig.auto_update)) }
val sendFirebaseAnalytics = remember { mutableStateOf(sharedPreferences.getBoolean("send_firebase_analytics", BuildConfig.send_firebase_analytics)) }
val ipv6 = remember { mutableStateOf(sharedPreferences.getBoolean("ipv6",false)) }
val openNoRootDialog = remember { mutableStateOf(false) }
val openNoModuleDialog = remember { mutableStateOf(false) }
val showAboutDialog = remember { mutableStateOf(false) }
val showHostsRepoUrlDialog = remember { mutableStateOf(false) }
val showIpsetRepoUrlDialog = remember { mutableStateOf(false) }
val showStrategyRepoUrlDialog = remember { mutableStateOf(false) }
val showIPDialog = remember { mutableStateOf(false) }
val showPortDialog = remember { mutableStateOf(false) }
val showDNSDialog = remember { mutableStateOf(false) }
val textDialogValue = remember { mutableStateOf("") }
val showWhiteDialog = remember { mutableStateOf(false) }
val showBlackDialog = remember { mutableStateOf(false) }
val showAppsListsSheet = remember { mutableStateOf(false) }
val showSystemApps = remember { mutableStateOf(sharedPreferences.getBoolean("show_system_apps", false)) }
val showChangeProbeTimeout = remember { mutableStateOf(false) }
val settingsList = listOf(
Setting.Section(stringResource(R.string.general_section)),
Setting.Toggle(
title = stringResource(R.string.btn_use_root),
checked = useModule.value,
onToggle = { isChecked ->
viewModel.useModule(
context = context,
checked = isChecked,
openNoRootDialog = openNoRootDialog,
openNoModuleDialog = openNoModuleDialog)
}
),
Setting.Toggle(
title = stringResource(R.string.btn_update_on_boot),
checked = updateOnBoot.value,
onToggle = {
updateOnBoot.value = it
editor.putBoolean("update_on_boot", it).apply()
}
),
Setting.Toggle(
title = stringResource(R.string.btn_autoupdate),
checked = autoUpdate.value,
onToggle = {
autoUpdate.value = it
editor.putBoolean("auto_update", it).apply()
}
),
Setting.Toggle(
title = stringResource(R.string.btn_send_firebase_analytics),
checked = sendFirebaseAnalytics.value,
onToggle = {
sendFirebaseAnalytics.value = it
editor.putBoolean("send_firebase_analytics", it).apply()
}
),
Setting.Action(
title = stringResource(R.string.btn_repository_url_lists),
onClick = {
textDialogValue.value = sharedPreferences.getString("hosts_repo_url", "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/hosts.json") ?: "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/hosts.json"
showHostsRepoUrlDialog.value = true
}
),
Setting.Action(
title = stringResource(R.string.ipset_repo_url),
onClick = {
textDialogValue.value = sharedPreferences.getString("ipset_repo_url", "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/ipsets.json") ?: "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/ipsets.json"
showIpsetRepoUrlDialog.value = true
}
),
Setting.Action(
title = stringResource(R.string.btn_repository_url_strategies),
onClick = {
textDialogValue.value = sharedPreferences.getString("strategy_repo_url", "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/strategies.json") ?: "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/strategies.json"
showStrategyRepoUrlDialog.value = true
}
),
Setting.Section(title = stringResource(R.string.shared_section)),
Setting.Action(
title = stringResource(R.string.btn_applist),
onClick = {
showAppsListsSheet.value = true
}
),
Setting.Action(
title = stringResource(R.string.btn_whitelist),
onClick = {
showWhiteDialog.value = true
}
),
Setting.Action(
title = stringResource(R.string.btn_blacklist),
onClick = {
showBlackDialog.value = true
}
),
Setting.Section(stringResource(R.string.title_selection)),
Setting.Action(
title = stringResource(R.string.begin_selection),
onClick = {
navController.navigate("selectionScreen")
}
),
Setting.Action(
title = stringResource(R.string.change_probe_timeout),
onClick = {
textDialogValue.value = sharedPreferences.getLong("probe_timeout", 1000L).toString()
showChangeProbeTimeout.value = true
}
),
Setting.Section(stringResource(R.string.byedpi_section)),
Setting.Toggle(
title = stringResource(R.string.btn_ipv6),
checked = ipv6.value,
onToggle = {
ipv6.value = it
editor.putBoolean("ipv6", it).apply()
}
),
Setting.Action(
title = stringResource(R.string.btn_ip),
onClick = {
textDialogValue.value = sharedPreferences.getString("ip", "127.0.0.1") ?: "127.0.0.1"
showIPDialog.value = true
}
),
Setting.Action(
title = stringResource(R.string.btn_port),
onClick = {
textDialogValue.value = sharedPreferences.getString("port", "1080") ?: "1080"
showPortDialog.value = true
}
),
Setting.Action(
title = stringResource(R.string.btn_dns),
onClick = {
textDialogValue.value = sharedPreferences.getString("dns", "8.8.8.8") ?: "8.8.8.8"
showDNSDialog.value = true
}
),
Setting.Section(title = stringResource(R.string.zapret_section)),
Setting.Toggle(
title = stringResource(R.string.btn_autorestart),
checked = autoRestart.value,
onToggle = {
viewModel.handleAutoRestart(context)
}
)
)
if (openNoRootDialog.value) {
InfoDialog(
title = stringResource(R.string.error_root_title),
message = stringResource(R.string.error_root_message),
onDismiss = { openNoRootDialog.value = false }
)
}
if (openNoModuleDialog.value) {
InfoDialog(
title = stringResource(R.string.error_no_module_title),
message = stringResource(R.string.error_no_module_message),
onDismiss = { openNoModuleDialog.value = false }
)
}
if (showAboutDialog.value) {
AboutDialog(navController, onDismiss = { showAboutDialog.value = false })
}
if (showHostsRepoUrlDialog.value) {
TextDialog(stringResource(R.string.btn_repository_url_lists), stringResource(R.string.hint_enter_repository_url_lists), textDialogValue.value, onConfirm = {
editor.putString("hosts_repo_url", it).apply()
}, onDismiss = { showHostsRepoUrlDialog.value = false })
}
if (showIpsetRepoUrlDialog.value) {
TextDialog(stringResource(R.string.btn_repository_url_ipsets), stringResource(R.string.hint_enter_repository_url_ipsets), textDialogValue.value, onConfirm = {
editor.putString("ipsets_repo_url", it).apply()
}, onDismiss = { showIpsetRepoUrlDialog.value = false })
}
if (showStrategyRepoUrlDialog.value) {
TextDialog(stringResource(R.string.btn_repository_url_strategies), stringResource(R.string.hint_enter_repository_url_strategies), textDialogValue.value, onConfirm = {
editor.putString("strategies_repo_url", it).apply()
}, onDismiss = { showStrategyRepoUrlDialog.value = false })
}
if (showIPDialog.value) {
TextDialog(stringResource(R.string.btn_ip), stringResource(R.string.hint_ip), textDialogValue.value, onConfirm = {
editor.putString("ip", it).apply()
}, onDismiss = { showIPDialog.value = false })
}
if (showPortDialog.value) {
TextDialog(stringResource(R.string.btn_port), stringResource(R.string.hint_port), textDialogValue.value, onConfirm = {
editor.putString("port", it).apply()
}, onDismiss = { showPortDialog.value = false })
}
if (showDNSDialog.value) {
TextDialog(stringResource(R.string.btn_dns), stringResource(R.string.hint_dns), textDialogValue.value, onConfirm = {
editor.putString("dns", it).apply()
}, onDismiss = { showDNSDialog.value = false })
}
if (showWhiteDialog.value) {
ChooseAppsDialog(
onDismissRequest = {
showWhiteDialog.value = false
viewModel.clearList()
},
viewModel = viewModel,
listType = AppListType.Whitelist,
sharedPreferences,
showSystemApps
)
}
if (showBlackDialog.value) {
ChooseAppsDialog(
onDismissRequest = {
showBlackDialog.value = false
viewModel.clearList()
},
viewModel = viewModel,
listType = AppListType.Blacklist,
sharedPreferences,
showSystemApps
)
}
if (showAppsListsSheet.value) {
ListBottomSheet(
onDismissRequest = {
showAppsListsSheet.value = false
},
prefs = sharedPreferences,
context
)
}
if (showChangeProbeTimeout.value) {
TextDialog(stringResource(R.string.probe_timeout), stringResource(R.string.hint_enter_probe_timeout), textDialogValue.value, onConfirm = {
editor.putLong("probe_timeout", it.toLong()).apply()
}, onDismiss = { showChangeProbeTimeout.value = false })
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_settings),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
actions = {
var expanded by remember { mutableStateOf(false) }
IconButton(onClick = { expanded = !expanded }) {
Icon(Icons.Default.MoreVert, contentDescription = null)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.about_title)) },
onClick = {
expanded = false
showAboutDialog.value = true
}
)
}
},
windowInsets = WindowInsets(0)
)
},
content = { paddingValues ->
LazyColumn(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize(),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 25.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(settingsList) { setting ->
when (setting) {
is Setting.Toggle -> {
SettingsItem(
title = setting.title,
onToggle = setting.onToggle,
checked = setting.checked,
onCheckedChange = setting.onToggle
)
}
is Setting.Action -> {
SettingsActionItem(
title = setting.title,
setting.onClick
)
}
is Setting.Section -> {
SettingsSection(setting.title)
}
}
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ListBottomSheet(
onDismissRequest: () -> Unit,
prefs : SharedPreferences,
context: Context
){
val selectedOption = remember { mutableStateOf(getAppsListMode(prefs)) }
ModalBottomSheet(
onDismissRequest = { onDismissRequest() }
) {
Column(
modifier = Modifier
.fillMaxWidth()
.height(200.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Row(
Modifier
.fillMaxWidth()
.padding(8.dp)
.selectable(
selected = selectedOption.value=="none",
onClick = {
setAppsListMode(prefs, "none")
selectedOption.value = "none"
},
role = Role.RadioButton
),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selectedOption.value.equals("none"),
onClick = null
)
Text(stringResource(R.string.radio_disabed), modifier = Modifier.padding(start = 8.dp))
}
Row(
Modifier
.fillMaxWidth()
.padding(8.dp)
.selectable(
selected = selectedOption.value=="whitelist",
onClick = {
setAppsListMode(prefs, "whitelist")
selectedOption.value = "whitelist"
},
role = Role.RadioButton
),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selectedOption.value.equals("whitelist"),
onClick = null
)
Text(stringResource(R.string.title_whitelist), modifier = Modifier.padding(start = 8.dp))
}
Row(
Modifier
.fillMaxWidth()
.padding(8.dp)
.selectable(
selected = selectedOption.value=="blacklist",
onClick = {
setAppsListMode(prefs, "blacklist")
selectedOption.value = "blacklist"
},
role = Role.RadioButton
),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selectedOption.value.equals("blacklist"),
onClick = null
)
Text(stringResource(R.string.title_blacklist), modifier = Modifier.padding(start = 8.dp))
}
}
}
}
@Composable
private fun AboutDialog(navController: NavController, onDismiss: () -> Unit) {
val context = LocalContext.current
val interactionSource = remember { MutableInteractionSource() }
var clickCount by remember { mutableIntStateOf(0) }
AlertDialog(
title = { Text(text = stringResource(R.string.about_title)) },
icon = {Icon(painterResource(R.drawable.ic_launcher_monochrome), contentDescription = stringResource(R.string.app_name), modifier = Modifier
.size(64.dp))},
text = {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = stringResource(R.string.about_text, BuildConfig.VERSION_NAME), modifier = Modifier.clickable(interactionSource = interactionSource, null) {
clickCount++
if (clickCount == 7) {
onDismiss()
navController.navigate("debugScreen") { launchSingleTop = true }
}
})
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
IconButton(onClick = {
val intent = Intent(Intent.ACTION_VIEW,
"https://github.com/CherretGit/zaprett-app".toUri())
context.startActivity(intent)
}) {
Icon(painterResource(R.drawable.github), "GitHub")
}
IconButton(onClick = {
val intent = Intent(Intent.ACTION_VIEW,
"https://t.me/zaprett_module".toUri())
context.startActivity(intent)
}) {
Icon(painterResource(R.drawable.telegram), "Telegram")
}
IconButton(onClick = {
val intent = Intent(Intent.ACTION_VIEW,
"https://matrix.to/#/#zaprett-group:matrix.cherret.ru".toUri())
context.startActivity(intent)
}) {
Icon(painterResource(R.drawable.matrix), "Matrix")
}
IconButton(onClick = {
val intent = Intent(Intent.ACTION_VIEW,
"https://pay.cloudtips.ru/p/672192fd".toUri())
context.startActivity(intent)
}) {
Icon(Icons.Default.AttachMoney, "Donate")
}
}
}
},
onDismissRequest = onDismiss,
confirmButton = { }
)
}
@Composable
private fun ChooseAppsDialog(
onDismissRequest: () -> Unit,
viewModel: SettingsViewModel,
listType: AppListType,
prefs: SharedPreferences,
showSystemApps : MutableState<Boolean>
) {
val appsList by viewModel.appsList.collectAsState()
val selectedPackages by viewModel.selectedPackages.collectAsState()
var searchQuery by remember { mutableStateOf("") }
val filteredList = remember(searchQuery, appsList) {
if (searchQuery.isBlank()) appsList
else appsList.filter { it.contains(searchQuery, ignoreCase = true) }
}
var expanded by remember { mutableStateOf(false) }
val title = if (listType == AppListType.Whitelist) stringResource(R.string.title_whitelist) else stringResource(R.string.title_blacklist)
LaunchedEffect(listType) {
viewModel.setListType(listType)
}
Dialog(onDismissRequest = onDismissRequest) {
Card(
modifier = Modifier
.wrapContentHeight()
.padding(16.dp),
shape = RoundedCornerShape(16.dp),
) {
Column(
modifier = Modifier
.wrapContentHeight()
.fillMaxWidth()) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
modifier = Modifier.weight(1f),
fontWeight = FontWeight.Bold,
fontSize = 24.sp
)
Box {
IconButton(onClick = { expanded = !expanded }) {
Icon(Icons.Default.MoreVert, contentDescription = "More options")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.btn_show_system_apps),
fontSize = 12.sp,
textAlign = TextAlign.Center
)
Checkbox(
checked = showSystemApps.value,
onCheckedChange = null
)
}
},
onClick = {
prefs.edit { putBoolean("show_system_apps", !showSystemApps.value) }
showSystemApps.value = !showSystemApps.value
viewModel.refreshApplications()
expanded = false
}
)
}
}
}
Row {
OutlinedTextField(
value = searchQuery,
onValueChange = { searchQuery = it },
placeholder = { Text(stringResource(R.string.search_field)) },
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 400.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
items(filteredList) {
AppItem(viewModel(), it, selectedPackages.contains(it), { isChecked ->
if (isChecked){ viewModel.addToList(listType, it) }
else { viewModel.removeFromList(listType, it) }
}
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp, end = 8.dp),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(
onClick = { onDismissRequest() },
modifier = Modifier.padding(8.dp, top = 4.dp),
) {
Text(text = stringResource(R.string.btn_continue))
}
}
}
}
}
}
@Composable
private fun AppItem(viewModel: SettingsViewModel, packageName : String, enabled : Boolean, onCheckedChange: (Boolean) -> Unit) {
var bitmap by remember { mutableStateOf<Drawable?>(null) }
LaunchedEffect(packageName) {
bitmap = viewModel.getAppIconBitmap(packageName)
}
Row (
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
AsyncImage(
model = bitmap,
contentDescription = null,
modifier = Modifier
.padding(4.dp)
)
Text(
text = viewModel.getApplicationName(packageName) ?: "unknown",
modifier = Modifier
.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontSize = 18.sp
)
Switch(
checked = enabled,
onCheckedChange = onCheckedChange
)
}
}

View File

@@ -0,0 +1,240 @@
package com.cherret.zaprett.ui.screen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.UploadFile
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.cherret.zaprett.R
import com.cherret.zaprett.ui.component.ListSwitchItem
import com.cherret.zaprett.ui.viewmodel.StrategyViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StrategyScreen(navController: NavController, viewModel: StrategyViewModel = viewModel()) {
val context = LocalContext.current
val sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val allLists = viewModel.allItems
val checked = viewModel.checked
val isRefreshing = viewModel.isRefreshing
val showPermissionDialog by viewModel.showNoPermissionDialog.collectAsState()
val filePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
uri?.let { viewModel.copySelectedFile(
context,
if (sharedPreferences.getBoolean("use_module", false)) "/strategies/nfqws" else "/strategies/byedpi",
it
) }
}
val error by viewModel.errorFlow.collectAsState()
LaunchedEffect(Unit) {
viewModel.refresh()
}
if (error.isNotEmpty()) {
AlertDialog(
onDismissRequest = {
viewModel.clearError()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(stringResource(R.string.error_unknown))
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", error)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearError()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_strategies),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
windowInsets = WindowInsets(0)
)
},
content = { paddingValues ->
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = {
viewModel.refresh()
},
modifier = Modifier.fillMaxSize()
) {
LazyColumn(
contentPadding = PaddingValues(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding() + 80.dp
),
modifier = Modifier.navigationBarsPadding().fillMaxSize()
) {
when {
allLists.isEmpty() -> {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.empty_list),
textAlign = TextAlign.Center
)
}
}
}
else -> {
items(allLists) { item ->
ListSwitchItem(
item = item,
isChecked = checked[item] == true,
onCheckedChange = { isChecked ->
viewModel.onCheckedChange(item, isChecked, snackbarHostState, scope)
},
onDeleteClick = {
viewModel.deleteItem(item, snackbarHostState, scope)
}
)
}
}
}
}
}
},
floatingActionButton = {
FloatingMenu(navController, filePickerLauncher)
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
)
if (showPermissionDialog) {
AlertDialog(
title = { Text(text = stringResource(R.string.error_no_storage_title)) },
text = { Text(text = stringResource(R.string.no_storage_permission_message)) },
onDismissRequest = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
},
confirmButton = {
TextButton(onClick = {
viewModel.hideNoPermissionDialog()
navController.popBackStack()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
}
@Composable
private fun FloatingMenu(navController: NavController, launcher: ActivityResultLauncher<Array<String>>) {
var expanded by remember { mutableStateOf(false) }
FloatingActionButton(
modifier = Modifier.size(80.dp),
onClick = { expanded = !expanded }
) {
Icon(Icons.Default.Add, contentDescription = stringResource(R.string.btn_add_host))
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.btn_download_host)) },
onClick = {
expanded = false
navController.navigate("repo?source=strategies") { launchSingleTop = true }
},
leadingIcon = {
Icon(Icons.Default.Download, contentDescription = stringResource(R.string.btn_download_host))
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.btn_add_host)) },
onClick = {
expanded = false
addStrategy(launcher)
},
leadingIcon = {
Icon(Icons.Default.UploadFile, contentDescription = stringResource(R.string.btn_add_host))
}
)
}
}
private fun addStrategy(launcher: ActivityResultLauncher<Array<String>>) {
launcher.launch(arrayOf("text/plain"))
}

View File

@@ -0,0 +1,238 @@
package com.cherret.zaprett.ui.screen
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.cherret.zaprett.R
import com.cherret.zaprett.ui.component.StrategySelectionItem
import com.cherret.zaprett.ui.viewmodel.StrategySelectionViewModel
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StrategySelectionScreen(navController: NavController, vpnLauncher: ActivityResultLauncher<Intent>, viewModel : StrategySelectionViewModel = viewModel()){
val snackbarHostState = remember { SnackbarHostState() }
val strategyStates = viewModel.strategyStates
val context = LocalContext.current
val prefs = context.getSharedPreferences("settings", MODE_PRIVATE)
var showDialog = remember { mutableStateOf(false) }
val requestVpnPermission by viewModel.requestVpnPermission.collectAsState()
val error by viewModel.errorFlow.collectAsState()
if (showDialog.value) {
InfoAlert { showDialog.value = false }
}
LaunchedEffect(requestVpnPermission) {
if (requestVpnPermission) {
val intent = VpnService.prepare(context)
if (intent != null) {
vpnLauncher.launch(intent)
} else {
viewModel.startVpn()
viewModel.clearVpnPermissionRequest()
}
}
}
if (error.isNotEmpty()) {
AlertDialog(
onDismissRequest = {
viewModel.clearError()
},
title = { Text(stringResource(R.string.error_text)) },
text = {
Text(stringResource(R.string.error_unknown))
},
dismissButton = {
TextButton(onClick = {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Error log", error)
clipboard.setPrimaryClip(clip)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
Toast.makeText(context, context.getString(R.string.log_copied), Toast.LENGTH_SHORT).show()
}
}) {
Text(stringResource(R.string.btn_copy_log))
}
},
confirmButton = {
TextButton(onClick = {
viewModel.clearError()
}) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(R.string.title_selection),
fontSize = 30.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
},
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.btn_back)
)
}
},
actions = {
IconButton(
onClick = {
showDialog.value = true
}
) {
Icon(
imageVector = Icons.Default.Info,
contentDescription = "info"
)
}
},
windowInsets = WindowInsets(0)
)
},
snackbarHost = { SnackbarHost(snackbarHostState) },
content = { paddingValues ->
LazyColumn (
contentPadding = PaddingValues(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding() + 40.dp
),
modifier = Modifier.fillMaxSize()
) {
item {
Row (
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
)
{
NoHostsCard(viewModel.noHostsCard)
FilledTonalButton(
onClick = {
viewModel.viewModelScope.launch {
snackbarHostState.showSnackbar(
context.getString(R.string.begin_selection_snack)
)
viewModel.performTest()
}
}
) {
Text(stringResource(R.string.begin_selection))
}
}
}
when {
strategyStates.isEmpty() -> {
item {
Box(
modifier = Modifier.fillParentMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
stringResource(R.string.empty_list),
textAlign = TextAlign.Center
)
}
}
}
else -> {
items(strategyStates, key = { it.path }) { item ->
StrategySelectionItem(item, prefs, context, snackbarHostState)
}
}
}
}
}
)
}
@Composable
fun InfoAlert(onDismiss: () -> Unit) {
AlertDialog(
title = { Text(text = stringResource(R.string.strategy_selection_info_title)) },
text = { Text(text = stringResource(R.string.strategy_selection_info_msg)) },
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
@Composable
private fun NoHostsCard(noHostsCard: MutableState<Boolean>) {
if (noHostsCard.value) {
AlertDialog(
title = { Text(text = stringResource(R.string.selection_no_hosts_title)) },
text = { Text(text = stringResource(R.string.selection_no_hosts_message)) },
onDismissRequest = {
noHostsCard.value = false
},
confirmButton = {
TextButton(onClick = { noHostsCard.value = false }) {
Text(stringResource(R.string.btn_continue))
}
}
)
}
}

View File

@@ -1,233 +0,0 @@
package com.cherret.zaprett.ui.screens
import android.content.Context
import android.content.Context.MODE_PRIVATE
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cherret.zaprett.R
import com.cherret.zaprett.getStatus
import com.cherret.zaprett.restartService
import com.cherret.zaprett.startService
import com.cherret.zaprett.stopService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Composable
fun HomeScreen() {
val context = LocalContext.current
val sharedPreferences = remember { context.getSharedPreferences("settings", MODE_PRIVATE) }
val cardText = remember { mutableStateOf(R.string.status_not_availible) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(Unit) {
if (sharedPreferences.getBoolean("use_module", false) && sharedPreferences.getBoolean("update_on_boot", false)) {
if (getStatus()) {
cardText.value = R.string.status_enabled
}
else {
cardText.value = R.string.status_disabled
}
}
}
Scaffold(
topBar = {
val primaryColor = MaterialTheme.colorScheme.surfaceVariant
Box(modifier = Modifier.padding(start = 20.dp, top = 10.dp)) {
Canvas(modifier = Modifier.size(100.dp, 50.dp)) {
rotate(degrees = -30f) {
drawOval(
color = primaryColor,
size = Size(200f, 140f),
topLeft = Offset(-20f, -20f)
)
}
}
Text(
text = stringResource(R.string.app_name),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
}
},
content = { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
) {
ElevatedCard(
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primary,
),
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 25.dp, end = 10.dp)
.size(width = 240.dp, height = 150.dp),
onClick = { onCardClick(context, cardText, snackbarHostState, scope) }
) {
Text(
text = stringResource(cardText.value),
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal)),
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textAlign = TextAlign.Center,
)
}
FilledTonalButton(
onClick = { onBtnStartService(context, snackbarHostState, scope) },
modifier = Modifier
.padding(start = 5.dp, top = 8.dp, end = 5.dp)
.fillMaxWidth()
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = stringResource(R.string.btn_start_service),
modifier = Modifier.size(20.dp)
)
Text(
stringResource(R.string.btn_start_service)
)
}
FilledTonalButton(
onClick = { onBtnStopService(context, snackbarHostState, scope) },
modifier = Modifier
.padding(start = 5.dp, top = 8.dp, end = 5.dp)
.fillMaxWidth()
) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.btn_stop_service),
modifier = Modifier.size(20.dp)
)
Text(
stringResource(R.string.btn_stop_service)
)
}
FilledTonalButton(
onClick = { onBtnRestart(context, snackbarHostState, scope) },
modifier = Modifier
.padding(start = 5.dp, top = 8.dp, end = 5.dp)
.fillMaxWidth()
) {
Icon(
imageVector = Icons.Default.RestartAlt,
contentDescription = stringResource(R.string.btn_restart_service),
modifier = Modifier.size(20.dp)
)
Text(
stringResource(R.string.btn_restart_service)
)
}
}
},
snackbarHost = {SnackbarHost(hostState = snackbarHostState)}
)
}
fun onCardClick(context: Context, cardText: MutableState<Int>, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
val sharedPreferences = context.getSharedPreferences("settings", MODE_PRIVATE)
if (sharedPreferences.getBoolean("use_module", false)) {
if (getStatus()) {
cardText.value = R.string.status_enabled
}
else {
cardText.value = R.string.status_disabled
}
}
else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_module_disabled))
}
}
}
fun onBtnStartService(context: Context, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (context.getSharedPreferences("settings", MODE_PRIVATE).getBoolean("use_module", false)) {
if (getStatus()) {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_already_started))
}
} else {
startService()
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.btn_start_service))
}
}
} else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_module_disabled))
}
}
}
fun onBtnStopService(context: Context, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (context.getSharedPreferences("settings", MODE_PRIVATE).getBoolean("use_module", false)) {
if (getStatus()) {
stopService()
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.btn_stop_service))
}
}
else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_no_service))
}
}
}
else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_module_disabled))
}
}
}
fun onBtnRestart(context: Context, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (context.getSharedPreferences("settings", MODE_PRIVATE).getBoolean("use_module", false)) {
restartService()
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_reload))
}
}
else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_module_disabled))
}
}
}

View File

@@ -1,210 +0,0 @@
package com.cherret.zaprett.ui.screens
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.OpenableColumns
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cherret.zaprett.R
import com.cherret.zaprett.disableList
import com.cherret.zaprett.enableList
import com.cherret.zaprett.getActiveLists
import com.cherret.zaprett.getAllLists
import com.cherret.zaprett.getZaprettPath
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HostsScreen() {
val context = LocalContext.current
var allLists by remember { mutableStateOf(getAllLists()) }
var activeLists by remember { mutableStateOf(getActiveLists()) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
var isRefreshing by remember { mutableStateOf(false) }
val checked = remember {
mutableStateMapOf<String, Boolean>().apply {
allLists.forEach { list ->
this[list] = activeLists.contains(list)
}
}
}
val filePickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument(),
onResult = { uri: Uri? ->
uri?.let {
copySelectedFile(context, it, snackbarHostState, scope)
}
}
)
Scaffold(
topBar = {
val primaryColor = MaterialTheme.colorScheme.surfaceVariant
Box(modifier = Modifier.padding(start = 20.dp, top = 10.dp)) {
Canvas(modifier = Modifier.size(100.dp, 50.dp)) {
rotate(degrees = -30f) {
drawOval(
color = primaryColor,
size = Size(200f, 140f),
topLeft = Offset(-30f, -30f)
)
}
}
Text(
text = stringResource(R.string.title_hosts),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
}
},
content = { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
) {
PullToRefreshBox(
isRefreshing = isRefreshing,
onRefresh = {
isRefreshing = true
allLists = getAllLists()
activeLists = getActiveLists()
checked.clear()
allLists.forEach { list ->
checked[list] = activeLists.contains(list)
}
isRefreshing = false
},
modifier = Modifier
) {
LazyColumn {
items(allLists) { item ->
ElevatedCard(
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 25.dp, end = 10.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = item,
modifier = Modifier.weight(1f)
)
Switch(
checked = checked[item] == true,
onCheckedChange = { isChecked ->
checked[item] = isChecked
if (isChecked) {
enableList(item)
} else {
disableList(item)
}
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.pls_restart_snack))
}
}
)
}
}
}
}
}
}
},
floatingActionButton = {
FloatingActionButton(modifier = Modifier
.size(80.dp, 80.dp),
onClick = {addHost(filePickerLauncher)}) {
Icon(Icons.Default.Add, contentDescription = "Restart")
}
},
snackbarHost = {SnackbarHost(hostState = snackbarHostState)}
)
}
fun addHost(launcher: ActivityResultLauncher<Array<String>>) {
launcher.launch(arrayOf("*/*"))
}
fun copySelectedFile(context: Context, uri: Uri?, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (Environment.isExternalStorageManager()) {
if (uri == null) return
val contentResolver = context.contentResolver
val fileName = contentResolver.query(uri, null, null, null, null)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (cursor.moveToFirst() && nameIndex != -1) cursor.getString(nameIndex) else "copied_file"
} ?: "copied_file"
val outputFile = File(getZaprettPath() + "/lists", fileName)
try {
contentResolver.openInputStream(uri)?.use { inputStream ->
FileOutputStream(outputFile).use { outputStream ->
inputStream.copyTo(outputStream)
}
}
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.pls_restart_snack))
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}

View File

@@ -1,224 +0,0 @@
package com.cherret.zaprett.ui.screens
import android.content.Context
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.cherret.zaprett.R
import com.cherret.zaprett.checkModuleInstallation
import com.cherret.zaprett.checkRoot
import com.cherret.zaprett.getStartOnBoot
import com.cherret.zaprett.setStartOnBoot
@Composable
fun SettingsScreen() {
val context = LocalContext.current
val sharedPreferences = remember { context.getSharedPreferences("settings", Context.MODE_PRIVATE) }
val editor = remember { sharedPreferences.edit() }
val useModule = remember { mutableStateOf(sharedPreferences.getBoolean("use_module", false)) }
val updateOnBoot = remember { mutableStateOf(sharedPreferences.getBoolean("update_on_boot", false)) }
val autoRestart = remember { mutableStateOf(getStartOnBoot()) }
val openNoRootDialog = remember { mutableStateOf(false) }
val openNoModuleDialog = remember { mutableStateOf(false) }
showNoRootDialog(openNoRootDialog)
showNoModuleDialog(openNoModuleDialog)
Scaffold(
topBar = {
val primaryColor = MaterialTheme.colorScheme.surfaceVariant
Box(modifier = Modifier.padding(start = 20.dp, top = 10.dp)) {
Canvas(modifier = Modifier.size(100.dp, 50.dp)) {
rotate(degrees = -30f) {
drawOval(
color = primaryColor,
size = Size(200f, 140f),
topLeft = Offset(-30f, -30f)
)
}
}
Text(
text = stringResource(R.string.title_settings),
fontSize = 40.sp,
fontFamily = FontFamily(Font(R.font.unbounded, FontWeight.Normal))
)
}
},
content = { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
) {
ElevatedCard(
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
),
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp, top = 25.dp, end = 10.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = stringResource(R.string.btn_use_root),
modifier = Modifier.weight(1f)
)
Switch(
checked = useModule.value,
onCheckedChange = { if (useModule(context, it, updateOnBoot, openNoRootDialog, openNoModuleDialog)) useModule.value = it}
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = stringResource(R.string.btn_update_on_boot),
modifier = Modifier.weight(1f)
)
Switch(
checked = updateOnBoot.value,
onCheckedChange = { updateOnBoot.value = it; editor.putBoolean("update_on_boot", it).apply()}
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = stringResource(R.string.btn_autorestart),
modifier = Modifier.weight(1f)
)
Switch(
checked = autoRestart.value,
onCheckedChange = { if (autoRestart(context, it)) autoRestart.value = it;}
)
}
}
}
}
)
}
fun useModule(context: Context, checked: Boolean, updateOnBoot: MutableState<Boolean>, openNoRootDialog: MutableState<Boolean>, openNoModuleDialog: MutableState<Boolean>): Boolean {
val sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
if (checked) {
if (checkRoot()) {
if (checkModuleInstallation()) {
editor.putBoolean("use_module", true).putBoolean("update_on_boot", true).apply()
updateOnBoot.value = true
return true
}
else {
openNoModuleDialog.value = true
}
} else {
openNoRootDialog.value = true
}
}
else {
editor.putBoolean("use_module", false).putBoolean("update_on_boot", false)
.apply()
return true
}
return false
}
fun autoRestart(context: Context, checked: Boolean): Boolean {
if (context.getSharedPreferences("settings", Context.MODE_PRIVATE).getBoolean("use_module", false)) {
setStartOnBoot(checked)
return true
}
return false
}
@Composable
fun showNoRootDialog(openDialog: MutableState<Boolean>) {
if (openDialog.value) {
AlertDialog(
title = {
Text(text = stringResource(R.string.error_root_title))
},
text = {
Text(text = stringResource(R.string.error_root_message))
},
onDismissRequest = {
openDialog.value = false
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text(stringResource(R.string.btn_continue))
}
},
)
}
}
@Composable
fun showNoModuleDialog(openDialog: MutableState<Boolean>) {
if (openDialog.value) {
AlertDialog(
title = {
Text(text = stringResource(R.string.error_no_module_title))
},
text = {
Text(text = stringResource(R.string.error_no_module_message))
},
onDismissRequest = {
openDialog.value = false
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text(stringResource(R.string.btn_continue))
}
},
)
}
}

View File

@@ -1,6 +1,5 @@
package com.cherret.zaprett.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme

View File

@@ -0,0 +1,140 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.OpenableColumns
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import com.cherret.zaprett.R
import com.cherret.zaprett.utils.checkStoragePermission
import com.cherret.zaprett.utils.getZaprettPath
import com.cherret.zaprett.utils.restartService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
abstract class BaseListsViewModel(application: Application) : AndroidViewModel(application) {
val context = application
var allItems by mutableStateOf<List<String>>(emptyList())
private set
var activeItems by mutableStateOf<List<String>>(emptyList())
private set
val checked = mutableStateMapOf<String, Boolean>()
var isRefreshing by mutableStateOf(false)
private set
private val _errorFlow = MutableStateFlow("")
val errorFlow = _errorFlow.asStateFlow()
private var _showNoPermissionDialog = MutableStateFlow(false)
val showNoPermissionDialog: StateFlow<Boolean> = _showNoPermissionDialog
abstract fun loadAllItems(): Array<String>
abstract fun loadActiveItems(): Array<String>
abstract fun onCheckedChange(item: String, isChecked: Boolean, snackbarHostState: SnackbarHostState, scope: CoroutineScope)
abstract fun deleteItem(item: String, snackbarHostState: SnackbarHostState, scope: CoroutineScope)
fun refresh() {
when (checkStoragePermission(context)) {
true -> {
isRefreshing = true
allItems = loadAllItems().toList()
activeItems = loadActiveItems().toList()
checked.clear()
allItems.forEach { list ->
checked[list] = activeItems.contains(list)
}
isRefreshing = false
}
false -> _showNoPermissionDialog.value = true
}
}
fun hideNoPermissionDialog() {
_showNoPermissionDialog.value = false
}
fun showRestartSnackbar(context: Context, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
scope.launch {
val result = snackbarHostState.showSnackbar(
context.getString(R.string.pls_restart_snack),
actionLabel = context.getString(R.string.btn_restart_service)
)
if (result == SnackbarResult.ActionPerformed) {
restartService { error ->
_errorFlow.value = error
}
snackbarHostState.showSnackbar(context.getString(R.string.snack_reload))
}
}
}
fun clearError() {
_errorFlow.value = ""
}
fun copySelectedFile(context: Context, path: String, uri: Uri) {
//if (!Environment.isExternalStorageManager()) return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
if (!Environment.isExternalStorageManager()) return
}
else if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) return
val contentResolver = context.contentResolver
val fileName = contentResolver.query(uri, null, null, null, null)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (cursor.moveToFirst() && nameIndex != -1) cursor.getString(nameIndex) else "copied_file"
} ?: "copied_file"
val directory = File(getZaprettPath() + path)
if (!directory.exists()) {
directory.mkdirs()
}
try {
val outputFile = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
val outputDir = File(getZaprettPath() + path)
if (!outputDir.exists()) {
outputDir.mkdirs()
}
File(outputDir, fileName)
} else {
val outputDir = File(context.filesDir, path)
if (!outputDir.exists()) {
outputDir.mkdirs()
}
File(outputDir, fileName)
}
} else {
val outputDir = File(context.filesDir, path)
if (!outputDir.exists()) {
outputDir.mkdirs()
}
File(outputDir, fileName)
}
contentResolver.openInputStream(uri)?.use { inputStream ->
FileOutputStream(outputFile).use { outputStream ->
inputStream.copyTo(outputStream)
}
}
refresh()
} catch (e: IOException) {
e.printStackTrace()
}
}
}

View File

@@ -0,0 +1,185 @@
package com.cherret.zaprett.ui.viewmodel
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cherret.zaprett.utils.RepoItemInfo
import com.cherret.zaprett.R
import com.cherret.zaprett.data.ItemType
import com.cherret.zaprett.utils.checkStoragePermission
import com.cherret.zaprett.utils.download
import com.cherret.zaprett.utils.getFileSha256
import com.cherret.zaprett.utils.getHostListMode
import com.cherret.zaprett.utils.getZaprettPath
import com.cherret.zaprett.utils.registerDownloadListener
import com.cherret.zaprett.utils.restartService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.io.File
abstract class BaseRepoViewModel(application: Application) : AndroidViewModel(application) {
@SuppressLint("StaticFieldLeak")
val context: Context = application.applicationContext
val sharedPreferences: SharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
private val _errorFlow = MutableStateFlow<Throwable?>(null)
val errorFlow: StateFlow<Throwable?> = _errorFlow
private val _downloadErrorFlow = MutableStateFlow<String?>(null)
val downloadErrorFlow: StateFlow<String?> = _downloadErrorFlow
private var _showPermissionDialog = MutableStateFlow(false)
val showPermissionDialog: StateFlow<Boolean> = _showPermissionDialog
var hostLists = mutableStateOf<List<RepoItemInfo>>(emptyList())
protected set
var isRefreshing = mutableStateOf(false)
protected set
val isUpdate = mutableStateMapOf<String, Boolean>()
val isInstalling = mutableStateMapOf<String, Boolean>()
val isUpdateInstalling = mutableStateMapOf<String, Boolean>()
abstract fun getInstalledLists(): Array<String>
abstract fun getRepoList(callback: (Result<List<RepoItemInfo>>) -> Unit)
fun refresh() {
isRefreshing.value = true
getRepoList { result ->
viewModelScope.launch(Dispatchers.IO) {
result
.onSuccess { safeList ->
val useModule = sharedPreferences.getBoolean("use_module", false)
val listType = getHostListMode(sharedPreferences)
val filteredList = safeList.filter { item ->
when (item.type) {
ItemType.list -> listType == "whitelist"
ItemType.list_exclude -> listType == "blacklist"
ItemType.ipset -> listType == "whitelist"
ItemType.ipset_exclude -> listType == "blacklist"
ItemType.nfqws -> useModule
ItemType.byedpi -> !useModule
}
}
hostLists.value = filteredList
isUpdate.clear()
val existingHashes = getInstalledLists().map { getFileSha256(File(it)) }
for (item in filteredList) {
isUpdate[item.name] = item.hash !in existingHashes
}
}
.onFailure { e ->
_errorFlow.value = e
}
}
isRefreshing.value = false
}
}
fun clearError() {
_errorFlow.value = null
}
fun clearDownloadError() {
_downloadErrorFlow.value = null
}
fun isItemInstalled(item: RepoItemInfo): Boolean {
return getInstalledLists().any { File(it).name == item.name }
}
fun install(item: RepoItemInfo) {
when (checkStoragePermission(context)) {
true -> {
isInstalling[item.name] = true
val downloadId = download(context, item.url)
registerDownloadListener(context, downloadId, { uri ->
viewModelScope.launch(Dispatchers.IO) {
val sourceFile = File(uri.path!!)
val targetDir = when (item.type) {
ItemType.byedpi -> File(getZaprettPath(), "strategies/byedpi")
ItemType.nfqws -> File(getZaprettPath(), "strategies/nfqws")
ItemType.list -> File(getZaprettPath(), "lists/include")
ItemType.list_exclude -> File(getZaprettPath(), "lists/exclude")
ItemType.ipset -> File(getZaprettPath(), "ipset/include")
ItemType.ipset_exclude -> File(getZaprettPath(), "ipset/exclude")
}
val targetFile = File(targetDir, uri.lastPathSegment!!)
sourceFile.copyTo(targetFile, overwrite = true)
sourceFile.delete()
isInstalling[item.name] = false
isUpdate[item.name] = false
refresh()
}
}, onError = {
isInstalling[item.name] = false
isUpdate[item.name] = false
refresh()
_downloadErrorFlow.value = it
})
}
false -> _showPermissionDialog.value = true
}
}
fun hideNoPermissionDialog() {
_showPermissionDialog.value = false
}
fun update(item: RepoItemInfo) {
isUpdateInstalling[item.name] = true
val downloadId = download(context, item.url)
registerDownloadListener(
context,
downloadId,
onDownloaded = { uri ->
viewModelScope.launch(Dispatchers.IO) {
val sourceFile = File(uri.path!!)
val targetDir = when (item.type) {
ItemType.byedpi -> File(getZaprettPath(), "strategies/byedpi")
ItemType.nfqws -> File(getZaprettPath(), "strategies/nfqws")
ItemType.list -> File(getZaprettPath(), "lists/include")
ItemType.list_exclude -> File(getZaprettPath(), "lists/exclude")
ItemType.ipset -> File(getZaprettPath(), "ipset/include")
ItemType.ipset_exclude -> File(getZaprettPath(), "ipset/exclude")
}
val targetFile = File(targetDir, uri.lastPathSegment!!)
sourceFile.copyTo(targetFile, overwrite = true)
sourceFile.delete()
isUpdateInstalling[item.name] = false
isUpdate[item.name] = false
refresh()
}
},
onError = { error ->
isUpdateInstalling[item.name] = false
isUpdate[item.name] = false
refresh()
_downloadErrorFlow.value = error
}
)
}
fun showRestartSnackbar(snackbarHostState: SnackbarHostState) {
viewModelScope.launch {
val result = snackbarHostState.showSnackbar(
context.getString(R.string.pls_restart_snack),
actionLabel = context.getString(R.string.btn_restart_service)
)
if (result == SnackbarResult.ActionPerformed) {
restartService {}
snackbarHostState.showSnackbar(context.getString(R.string.snack_reload))
}
}
}
}

View File

@@ -0,0 +1,268 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import com.cherret.zaprett.BuildConfig
import com.cherret.zaprett.R
import com.cherret.zaprett.byedpi.ByeDpiVpnService
import com.cherret.zaprett.data.ServiceStatus
import com.cherret.zaprett.data.ServiceStatusUI
import com.cherret.zaprett.utils.download
import com.cherret.zaprett.utils.getActiveStrategy
import com.cherret.zaprett.utils.getBinVersion
import com.cherret.zaprett.utils.getChangelog
import com.cherret.zaprett.utils.getModuleVersion
import com.cherret.zaprett.utils.getStatus
import com.cherret.zaprett.utils.getUpdate
import com.cherret.zaprett.utils.installApk
import com.cherret.zaprett.utils.registerDownloadListener
import com.cherret.zaprett.utils.restartService
import com.cherret.zaprett.utils.startService
import com.cherret.zaprett.utils.stopService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class HomeViewModel(application: Application) : AndroidViewModel(application) {
private val context = application
private val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
private val _requestVpnPermission = MutableStateFlow(false)
val requestVpnPermission = _requestVpnPermission.asStateFlow()
private val _serviceStatus = MutableStateFlow(ServiceStatusUI())
val serviceStatus: StateFlow<ServiceStatusUI> = _serviceStatus.asStateFlow()
private val _errorFlow = MutableStateFlow("")
val errorFlow = _errorFlow.asStateFlow()
var moduleVer = mutableStateOf(context.getString(R.string.unknown_text))
private set
var nfqwsVer = mutableStateOf(context.getString(R.string.unknown_text))
private set
var byedpiVer = mutableStateOf("0.17.3")
private set
var serviceMode = mutableIntStateOf(R.string.service_mode_ciadpi)
private set
var changeLog = mutableStateOf<String?>(null)
private set
var newVersion = mutableStateOf<String?>(null)
private set
var updateAvailable = mutableStateOf(false)
private set
var downloadUrl = mutableStateOf<String?>(null)
private set
var showUpdateDialog = mutableStateOf(false)
fun checkForUpdate() {
if (prefs.getBoolean("auto_update", BuildConfig.auto_update)) {
getUpdate(prefs) {
if (it != null) {
downloadUrl.value = it.downloadUrl.toString()
getChangelog(it.changelogUrl.toString()) { log -> changeLog.value = log }
newVersion.value = it.version
updateAvailable.value = true
}
}
}
}
private fun updateServiceStatus(useModule: Boolean) {
if (useModule) {
getStatus { isEnabled ->
_serviceStatus.value = if (isEnabled) {
ServiceStatusUI(R.string.status_enabled, Icons.Filled.CheckCircle)
} else {
ServiceStatusUI(R.string.status_disabled, Icons.Filled.Cancel)
}
}
} else {
_serviceStatus.value = if (ByeDpiVpnService.status == ServiceStatus.Connected) {
ServiceStatusUI(R.string.status_enabled, Icons.Filled.CheckCircle)
} else {
ServiceStatusUI(R.string.status_disabled, Icons.Filled.Cancel)
}
}
}
fun checkServiceStatus() {
val updateOnBoot = prefs.getBoolean("update_on_boot", true)
if (updateOnBoot) {
val useModule = prefs.getBoolean("use_module", false)
updateServiceStatus(useModule)
}
}
fun onCardClick() {
val useModule = prefs.getBoolean("use_module", false)
updateServiceStatus(useModule)
}
fun startVpn() {
ContextCompat.startForegroundService(context, Intent(context, ByeDpiVpnService::class.java).apply { action = "START_VPN" })
}
fun onBtnStartService(snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (prefs.getBoolean("use_module", false)) {
getStatus { isEnabled ->
scope.launch {
snackbarHostState.showSnackbar(
context.getString(
if (isEnabled) R.string.snack_already_started else R.string.snack_starting_service
)
)
}
if (!isEnabled) startService { error ->
_errorFlow.value = error
onCardClick()
}
}
} else {
if (ByeDpiVpnService.status == ServiceStatus.Disconnected || ByeDpiVpnService.status == ServiceStatus.Failed) {
if (getActiveStrategy(prefs).isNotEmpty()) {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_starting_service))
}
_requestVpnPermission.value = true
}
else {
Toast.makeText(
context,
context.getString(R.string.toast_no_strategy_selected),
Toast.LENGTH_SHORT
).show()
}
}
else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_already_started))
}
}
}
}
fun clearVpnPermissionRequest() {
_requestVpnPermission.value = false
}
fun onBtnStopService(snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (prefs.getBoolean("use_module", false)) {
getStatus { isEnabled ->
scope.launch {
snackbarHostState.showSnackbar(
context.getString(
if (isEnabled) R.string.snack_stopping_service else R.string.snack_no_service
)
)
}
if (isEnabled) stopService { error ->
_errorFlow.value = error
onCardClick()
}
}
} else {
if (ByeDpiVpnService.status == ServiceStatus.Connected) {
scope.launch {
snackbarHostState.showSnackbar(
context.getString(R.string.snack_stopping_service)
)
}
context.startService(Intent(context, ByeDpiVpnService::class.java).apply {
action = "STOP_VPN"
})
}
else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_no_service))
}
}
}
}
fun onBtnRestart(snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
if (prefs.getBoolean("use_module", false)) {
restartService { error ->
_errorFlow.value = error
onCardClick()
}
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_reload))
}
} else {
scope.launch {
snackbarHostState.showSnackbar(context.getString(R.string.snack_module_disabled))
}
}
}
fun checkModuleInfo() {
if (prefs.getBoolean("use_module", false)) {
getModuleVersion { value ->
moduleVer.value = value
}
getBinVersion { value ->
nfqwsVer.value = value
}
serviceMode.intValue = R.string.service_mode_nfqws;
}
}
fun showUpdateDialog() {
showUpdateDialog.value = true
}
fun dismissUpdateDialog() {
showUpdateDialog.value = false
}
fun onUpdateConfirm() {
showUpdateDialog.value = false
if (context.packageManager.canRequestPackageInstalls()){
val id = download(context, downloadUrl.value.orEmpty())
registerDownloadListener(context, id, { uri ->
installApk(context, uri)
},
onError = {
})
}
else {
val packageUri = Uri.fromParts("package", context.packageName, null)
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri).addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
// unused?
fun parseArgs(ip: String, port: String, lines: List<String>): Array<String> {
val regex = Regex("""--?\S+(?:=(?:[^"'\s]+|"[^"]*"|'[^']*'))?|[^\s]+""")
val parsedArgs = lines
.flatMap { line -> regex.findAll(line).map { it.value } }
return arrayOf("ciadpi", "--ip", ip, "--port", port) + parsedArgs
}
fun clearError() {
_errorFlow.value = ""
}
}

View File

@@ -0,0 +1,11 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import com.cherret.zaprett.utils.RepoItemInfo
import com.cherret.zaprett.utils.getAllLists
import com.cherret.zaprett.utils.getHostList
class HostRepoViewModel(application: Application): BaseRepoViewModel(application) {
override fun getInstalledLists(): Array<String> = getAllLists()
override fun getRepoList(callback: (Result<List<RepoItemInfo>>) -> Unit) = getHostList(sharedPreferences, callback)
}

View File

@@ -0,0 +1,63 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context
import androidx.compose.material3.SnackbarHostState
import com.cherret.zaprett.utils.disableList
import com.cherret.zaprett.utils.enableList
import com.cherret.zaprett.utils.getActiveExcludeLists
import com.cherret.zaprett.utils.getActiveLists
import com.cherret.zaprett.utils.getAllExcludeLists
import com.cherret.zaprett.utils.getAllLists
import com.cherret.zaprett.utils.getHostListMode
import com.cherret.zaprett.utils.getStatus
import com.cherret.zaprett.utils.setHostListMode
import kotlinx.coroutines.CoroutineScope
import java.io.File
class HostsViewModel(application: Application): BaseListsViewModel(application) {
private val sharedPreferences = application.getSharedPreferences("settings", Context.MODE_PRIVATE)
override fun loadAllItems(): Array<String> =
if (getHostListMode(sharedPreferences) == "whitelist") getAllLists()
else getAllExcludeLists()
override fun loadActiveItems(): Array<String> =
if (getHostListMode(sharedPreferences) == "whitelist") getActiveLists(sharedPreferences)
else getActiveExcludeLists(sharedPreferences)
override fun deleteItem(item: String, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
val wasChecked = checked[item] == true
disableList(item, sharedPreferences)
val success = File(item).delete()
if (success) refresh()
if (sharedPreferences.getBoolean("use_module", false)) {
getStatus { isEnabled ->
if (isEnabled && wasChecked) {
snackbarHostState.currentSnackbarData?.dismiss()
showRestartSnackbar(context, snackbarHostState, scope)
}
}
}
}
override fun onCheckedChange(item: String, isChecked: Boolean, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
checked[item] = isChecked
if (isChecked) enableList(item, sharedPreferences) else disableList(item, sharedPreferences)
if (sharedPreferences.getBoolean("use_module", false)) {
getStatus { isEnabled ->
if (isEnabled) {
snackbarHostState.currentSnackbarData?.dismiss()
showRestartSnackbar(
context,
snackbarHostState,
scope
)
}
}
}
}
fun setListType(type : String) {
setHostListMode(sharedPreferences, type)
refresh()
}
}

View File

@@ -0,0 +1,14 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import com.cherret.zaprett.utils.RepoItemInfo
import com.cherret.zaprett.utils.getAllIpsets
import com.cherret.zaprett.utils.getAllLists
import com.cherret.zaprett.utils.getHostList
import com.cherret.zaprett.utils.getIpsetList
class IpsetRepoViewModel(application: Application): BaseRepoViewModel(application) {
override fun getInstalledLists(): Array<String> = getAllIpsets()
override fun getRepoList(callback: (Result<List<RepoItemInfo>>) -> Unit) =
getIpsetList(sharedPreferences, callback)
}

View File

@@ -0,0 +1,65 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context
import androidx.compose.material3.SnackbarHostState
import com.cherret.zaprett.utils.disableIpset
import com.cherret.zaprett.utils.disableList
import com.cherret.zaprett.utils.enableIpset
import com.cherret.zaprett.utils.enableList
import com.cherret.zaprett.utils.getActiveExcludeIpsets
import com.cherret.zaprett.utils.getActiveExcludeLists
import com.cherret.zaprett.utils.getActiveIpsets
import com.cherret.zaprett.utils.getAllExcludeIpsets
import com.cherret.zaprett.utils.getAllIpsets
import com.cherret.zaprett.utils.getHostListMode
import com.cherret.zaprett.utils.getStatus
import com.cherret.zaprett.utils.setHostListMode
import kotlinx.coroutines.CoroutineScope
import java.io.File
class IpsetViewModel(application: Application): BaseListsViewModel(application) {
private val sharedPreferences = application.getSharedPreferences("settings", Context.MODE_PRIVATE)
override fun loadAllItems(): Array<String> =
if (getHostListMode(sharedPreferences) == "whitelist") getAllIpsets()
else getAllExcludeIpsets()
override fun loadActiveItems(): Array<String> =
if (getHostListMode(sharedPreferences) == "whitelist") getActiveIpsets(sharedPreferences)
else getActiveExcludeIpsets(sharedPreferences)
override fun deleteItem(item: String, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
val wasChecked = checked[item] == true
disableIpset(item, sharedPreferences)
val success = File(item).delete()
if (success) refresh()
if (sharedPreferences.getBoolean("use_module", false)) {
getStatus { isEnabled ->
if (isEnabled && wasChecked) {
snackbarHostState.currentSnackbarData?.dismiss()
showRestartSnackbar(context, snackbarHostState, scope)
}
}
}
}
override fun onCheckedChange(item: String, isChecked: Boolean, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
checked[item] = isChecked
if (isChecked) enableIpset(item, sharedPreferences) else disableIpset(item, sharedPreferences)
if (sharedPreferences.getBoolean("use_module", false)) {
getStatus { isEnabled ->
if (isEnabled) {
snackbarHostState.currentSnackbarData?.dismiss()
showRestartSnackbar(
context,
snackbarHostState,
scope
)
}
}
}
}
fun setListType(type : String) {
setHostListMode(sharedPreferences, type)
refresh()
}
}

View File

@@ -0,0 +1,163 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import androidx.compose.runtime.MutableState
import androidx.lifecycle.AndroidViewModel
import com.cherret.zaprett.byedpi.ByeDpiVpnService
import com.cherret.zaprett.data.AppListType
import com.cherret.zaprett.data.ServiceStatus
import com.cherret.zaprett.utils.addPackageToList
import com.cherret.zaprett.utils.checkModuleInstallation
import com.cherret.zaprett.utils.checkRoot
import com.cherret.zaprett.utils.getAppList
import com.cherret.zaprett.utils.getStartOnBoot
import com.cherret.zaprett.utils.removePackageFromList
import com.cherret.zaprett.utils.setStartOnBoot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
class SettingsViewModel(application: Application) : AndroidViewModel(application) {
private val context = application
private val prefs = context.getSharedPreferences("settings", MODE_PRIVATE)
private val _appsList = MutableStateFlow<List<String>>(emptyList())
val appsList: StateFlow<List<String>> = _appsList
private val _selectedPackages = MutableStateFlow<Set<String>>(emptySet())
val selectedPackages: StateFlow<Set<String>> = _selectedPackages.asStateFlow()
private val _currentListType = MutableStateFlow(AppListType.Whitelist)
private val _useModule = MutableStateFlow(false)
val useModule: StateFlow<Boolean> = _useModule
private val _autoRestart = MutableStateFlow(false)
val autoRestart: StateFlow<Boolean> = _autoRestart
init {
refreshApplications()
_useModule.value = context.getSharedPreferences("settings", MODE_PRIVATE).getBoolean("use_module", false)
getStartOnBoot(prefs) { value ->
_autoRestart.value = value
}
}
suspend fun getAppIconBitmap(packageName: String): Drawable? = withContext(Dispatchers.IO) {
val pm: PackageManager = context.packageManager
val drawable: Drawable = try {
pm.getApplicationIcon(packageName)
} catch (e: PackageManager.NameNotFoundException) {
return@withContext null
}
return@withContext drawable
}
fun getApplicationName(packageName: String) : String? {
val pm: PackageManager = context.packageManager
return try {
val applicationInfo = pm.getApplicationInfo(packageName, 0)
pm.getApplicationLabel(applicationInfo).toString()
} catch (e: PackageManager.NameNotFoundException) {
null
}
}
fun setListType(type: AppListType) {
_currentListType.value = type
refreshApplications()
}
fun clearList() {
_appsList.value = emptyList()
_selectedPackages.value = emptySet()
}
fun refreshApplications() {
val packages = if (prefs.getBoolean("show_system_apps", false)){
context.packageManager.getInstalledPackages(PackageManager.GET_META_DATA)
}
else {
context.packageManager.getInstalledPackages(PackageManager.GET_META_DATA).filter { pkgInfo ->
(pkgInfo.applicationInfo!!.flags and ApplicationInfo.FLAG_SYSTEM) == 0
}
}
val allPackages = packages.map { it.packageName }
val listType = _currentListType.value
val result = when (listType) {
AppListType.Whitelist -> {
val whitelistSet = getAppList(AppListType.Whitelist, prefs, context)
val (whitelisted, others) = allPackages.partition { it in whitelistSet }
_selectedPackages.value = whitelistSet
(whitelisted + others).filter { it != context.packageName }
}
AppListType.Blacklist -> {
val blacklistSet = getAppList(AppListType.Blacklist, prefs, context)
val (blacklisted, others) = allPackages.partition { it in blacklistSet }
_selectedPackages.value = blacklistSet
(blacklisted + others).filter { it != context.packageName }
}
}
_appsList.value = result
}
fun addToList(listType: AppListType, packageName: String) {
addPackageToList(listType, packageName, prefs, context)
selectedPackages.value.plus(packageName)
refreshApplications()
}
fun removeFromList(listType: AppListType, packageName: String) {
removePackageFromList(listType, packageName, prefs, context)
selectedPackages.value.minus(packageName)
refreshApplications()
}
fun useModule(context: Context, checked: Boolean, openNoRootDialog: MutableState<Boolean>, openNoModuleDialog: MutableState<Boolean>) {
val sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
if (checked) {
checkRoot { hasRoot ->
if (hasRoot) {
checkModuleInstallation { hasModule ->
if (hasModule) {
editor.putBoolean("use_module", true).apply()
if (ByeDpiVpnService.status == ServiceStatus.Connected) {
context.startService(Intent(context, ByeDpiVpnService::class.java).apply {
action = "STOP_VPN"
})
}
editor.remove("lists").apply()
editor.remove("active_strategy").apply()
editor.remove("applist").apply()
editor.remove("whitelist").apply()
editor.remove("blacklist").apply()
_useModule.value = true
} else {
openNoModuleDialog.value = true
}
}
} else {
openNoRootDialog.value = true
}
}
} else {
editor.putBoolean("use_module", false).apply()
_useModule.value = false
}
}
fun handleAutoRestart(context: Context) {
val sharedPreferences = context.getSharedPreferences("settings", MODE_PRIVATE)
if (sharedPreferences.getBoolean("use_module", false)) {
setStartOnBoot(prefs) { value ->
_autoRestart.value = value
}
}
}
}

View File

@@ -0,0 +1,17 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import com.cherret.zaprett.utils.RepoItemInfo
import com.cherret.zaprett.utils.getAllByeDPIStrategies
import com.cherret.zaprett.utils.getAllNfqwsStrategies
import com.cherret.zaprett.utils.getStrategiesList
class StrategyRepoViewModel(application: Application): BaseRepoViewModel(application) {
override fun getInstalledLists(): Array<String> =
if (sharedPreferences.getBoolean("use_module", false)) {
getAllNfqwsStrategies()
} else {
getAllByeDPIStrategies()
}
override fun getRepoList(callback: (Result<List<RepoItemInfo>>) -> Unit) = getStrategiesList(sharedPreferences, callback)
}

View File

@@ -0,0 +1,208 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.util.Log
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import com.cherret.zaprett.R
import com.cherret.zaprett.byedpi.ByeDpiVpnService
import com.cherret.zaprett.data.ServiceStatus
import com.cherret.zaprett.data.StrategyCheckResult
import com.cherret.zaprett.data.StrategyTestingStatus
import com.cherret.zaprett.utils.disableStrategy
import com.cherret.zaprett.utils.enableStrategy
import com.cherret.zaprett.utils.getActiveLists
import com.cherret.zaprett.utils.getActiveStrategy
import com.cherret.zaprett.utils.getAllStrategies
import com.cherret.zaprett.utils.getStatus
import com.cherret.zaprett.utils.startService
import com.cherret.zaprett.utils.stopService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
class StrategySelectionViewModel(application: Application) : AndroidViewModel(application) {
val prefs = application.getSharedPreferences("settings", MODE_PRIVATE)
val context = application
private val _requestVpnPermission = MutableStateFlow(false)
val requestVpnPermission = _requestVpnPermission.asStateFlow()
private val _errorFlow = MutableStateFlow("")
val errorFlow = _errorFlow.asStateFlow()
val strategyStates = mutableStateListOf<StrategyCheckResult>()
var noHostsCard = mutableStateOf(false)
private set
init {
loadStrategies()
checkHosts()
}
fun buildHttpClient(): OkHttpClient {
val builder = OkHttpClient.Builder()
.callTimeout(prefs.getLong("probe_timeout", 1000L), TimeUnit.MILLISECONDS)
.followRedirects(true)
.followSslRedirects(true)
if (!prefs.getBoolean("use_module", false)) {
val ip = prefs.getString("ip", "127.0.0.1") ?: "127.0.0.1"
val port = prefs.getString("port", "1080")?.toIntOrNull() ?: 1080
val proxy = Proxy(Proxy.Type.SOCKS, InetSocketAddress(ip, port))
builder.proxy(proxy)
}
return builder.build()
}
fun loadStrategies() {
val strategyList = getAllStrategies(prefs)
strategyStates.clear()
strategyList.forEach { name ->
strategyStates += StrategyCheckResult(
path = name,
status = StrategyTestingStatus.Waiting,
progress = 0f,
domains = emptyList()
)
}
}
suspend fun testDomain(domain : String) : Boolean = withContext(Dispatchers.IO) {
val request = Request.Builder()
.url("https://${domain}")
.build()
try {
buildHttpClient().newCall(request).execute().use { response ->
val body = response.body.byteStream().readBytes()
val contentLength = response.body.contentLength()
contentLength <= 0 || body.size.toLong() >= contentLength
}
} catch (e: Exception) {
false
}
}
suspend fun countReachable(index: Int, urls: List<String>): Float = coroutineScope {
if (urls.isEmpty()) return@coroutineScope 0f
val results: List<String> = urls.map { url ->
async { if (testDomain(url)) url else null }
}.awaitAll().filterNotNull()
strategyStates[index].domains = results
(results.size.toFloat() / urls.size.toFloat()).coerceIn(0f, 1f)
}
suspend fun readActiveListsLines(): List<String> = withContext(Dispatchers.IO) {
val result = mutableListOf<String>()
getActiveLists(prefs).forEach { path ->
runCatching {
File(path).useLines { lines ->
lines.forEach { line ->
result += line
}
}
}.onFailure {
Log.e("Error", "Occured error when creating list for check")
}
}
result
}
suspend fun performTest() {
val targets = readActiveListsLines()
var stopTest : Boolean = false;
for (index in strategyStates.indices) {
val current = strategyStates[index]
if (stopTest) break
strategyStates[index] = current.copy(status = StrategyTestingStatus.Testing)
enableStrategy(current.path, prefs)
if (prefs.getBoolean("use_module", false)) {
getStatus { if (it) stopService { error ->
_errorFlow.value = error
if (error.isNotEmpty()) stopTest = true
} }
startService { error ->
_errorFlow.value = error
if (error.isNotEmpty()) stopTest = true
}
try {
val progress = countReachable(index, targets)
val old = strategyStates[index]
strategyStates[index] = old.copy(
progress = progress,
status = StrategyTestingStatus.Completed
)
} finally {
stopService { error ->
_errorFlow.value = error
if (error.isNotEmpty()) stopTest = true
}
disableStrategy(current.path, prefs)
}
}
else {
if (ByeDpiVpnService.status == ServiceStatus.Connected) {
context.startService(Intent(context, ByeDpiVpnService::class.java).apply {
action = "STOP_VPN"
})
delay(300L)
}
_requestVpnPermission.value = true
/*context.startService(Intent(context, ByeDpiVpnService::class.java).apply {
action = "START_VPN"
})*/
val connected = withTimeoutOrNull(10_000L) {
while (ByeDpiVpnService.status != ServiceStatus.Connected) {
delay(100L)
}
true
} ?: false
if (connected) delay(150L)
try {
val progress = countReachable(index,targets)
val old = strategyStates[index]
strategyStates[index] = old.copy(
progress = progress,
status = StrategyTestingStatus.Completed
)
} finally {
context.startService(Intent(context, ByeDpiVpnService::class.java).apply {
action = "STOP_VPN"
})
delay(200L)
disableStrategy(current.path, prefs)
}
}
}
val sorted = strategyStates.sortedByDescending { it.progress }
strategyStates.clear()
strategyStates.addAll(sorted)
}
fun checkHosts() {
if (getActiveLists(prefs).isEmpty() || getAllStrategies(prefs).isEmpty()) noHostsCard.value = true
Log.d("getActiveLists.isEmpty || getAllStrategies.isEmpty", getActiveLists(prefs).isEmpty().toString())
}
fun startVpn() {
ContextCompat.startForegroundService(context, Intent(context, ByeDpiVpnService::class.java).apply { action = "START_VPN" })
}
fun clearVpnPermissionRequest() {
_requestVpnPermission.value = false
}
fun clearError() {
_errorFlow.value = ""
}
}

View File

@@ -0,0 +1,93 @@
package com.cherret.zaprett.ui.viewmodel
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.material3.SnackbarHostState
import com.cherret.zaprett.byedpi.ByeDpiVpnService
import com.cherret.zaprett.data.ServiceStatus
import com.cherret.zaprett.utils.disableStrategy
import com.cherret.zaprett.utils.enableStrategy
import com.cherret.zaprett.utils.getActiveByeDPIStrategy
import com.cherret.zaprett.utils.getActiveNfqwsStrategy
import com.cherret.zaprett.utils.getAllByeDPIStrategies
import com.cherret.zaprett.utils.getAllNfqwsStrategies
import com.cherret.zaprett.utils.getStatus
import kotlinx.coroutines.CoroutineScope
import java.io.File
class StrategyViewModel(application: Application): BaseListsViewModel(application) {
private val sharedPreferences = application.getSharedPreferences("settings", Context.MODE_PRIVATE)
private val strategyProvider: StrategyProvider
get() = if (sharedPreferences.getBoolean("use_module", false)) {
NfqwsStrategyProvider()
} else {
ByeDPIStrategyProvider(sharedPreferences)
}
override fun loadAllItems(): Array<String> = strategyProvider.getAll()
override fun loadActiveItems(): Array<String> = strategyProvider.getActive()
override fun deleteItem(item: String, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
val wasChecked = checked[item] == true
disableStrategy(item, sharedPreferences)
val success = File(item).delete()
if (success) refresh()
if (sharedPreferences.getBoolean("use_module", false)) {
getStatus { isEnabled ->
if (isEnabled && wasChecked) {
snackbarHostState.currentSnackbarData?.dismiss()
showRestartSnackbar(context, snackbarHostState, scope)
}
}
}
else {
if (ByeDpiVpnService.status == ServiceStatus.Connected && wasChecked) {
showRestartSnackbar(context, snackbarHostState, scope)
}
}
}
override fun onCheckedChange(item: String, isChecked: Boolean, snackbarHostState: SnackbarHostState, scope: CoroutineScope) {
checked[item] = isChecked
if (isChecked) {
checked.keys.forEach { key ->
checked[key] = false
disableStrategy(key, sharedPreferences)
}
checked[item] = true
enableStrategy(item, sharedPreferences)
}
else {
checked[item] = false
disableStrategy(item, sharedPreferences)
}
if (sharedPreferences.getBoolean("use_module", false)) {
getStatus { isEnabled ->
if (isEnabled) {
snackbarHostState.currentSnackbarData?.dismiss()
showRestartSnackbar(
context,
snackbarHostState,
scope
)
}
}
}
}
}
interface StrategyProvider {
fun getAll(): Array<String>
fun getActive(): Array<String>
}
class NfqwsStrategyProvider : StrategyProvider {
override fun getAll() = getAllNfqwsStrategies()
override fun getActive() = getActiveNfqwsStrategy()
}
class ByeDPIStrategyProvider(private val sharedPreferences: SharedPreferences) : StrategyProvider {
override fun getAll() = getAllByeDPIStrategies()
override fun getActive() = getActiveByeDPIStrategy(sharedPreferences)
}

View File

@@ -0,0 +1,86 @@
package com.cherret.zaprett.utils
import android.content.Intent
import android.content.SharedPreferences
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import androidx.core.content.ContextCompat
import com.cherret.zaprett.R
import com.cherret.zaprett.byedpi.ByeDpiVpnService
import com.cherret.zaprett.data.ServiceStatus
class QSTileService: TileService() {
private lateinit var prefs: SharedPreferences
override fun onCreate() {
super.onCreate()
prefs = applicationContext.getSharedPreferences("settings", MODE_PRIVATE)
}
override fun onTileAdded() {
super.onTileAdded()
updateStatus()
}
override fun onStartListening() {
super.onStartListening()
updateStatus()
}
override fun onClick() {
super.onClick()
if (qsTile.state == Tile.STATE_INACTIVE) {
qsTile.subtitle = getString(R.string.qs_starting)
qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile()
if (prefs.getBoolean("use_module", false)){
startService {}
}
else {
ContextCompat.startForegroundService(applicationContext, Intent(applicationContext, ByeDpiVpnService::class.java).apply { action = "START_VPN" })
}
}
else {
qsTile.subtitle = getString(R.string.qs_stopping)
qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile()
if (prefs.getBoolean("use_module", false)){
stopService {}
}
else {
applicationContext.startService(Intent(applicationContext, ByeDpiVpnService::class.java).apply { action = "STOP_VPN" })
}
}
updateStatus()
}
private fun updateStatus() {
if (prefs.getBoolean("use_module", false)) {
getStatus {
if (it) {
qsTile.label = getString(R.string.qs_name)
qsTile.subtitle = getString(R.string.qs_working)
qsTile.state = Tile.STATE_ACTIVE
qsTile.updateTile()
} else {
qsTile.label = getString(R.string.qs_name)
qsTile.subtitle = getString(R.string.qs_not_working)
qsTile.state = Tile.STATE_INACTIVE
qsTile.updateTile()
}
}
}
else {
if (ByeDpiVpnService.status == ServiceStatus.Connected) {
qsTile.label = getString(R.string.qs_name)
qsTile.subtitle = getString(R.string.qs_working)
qsTile.state = Tile.STATE_ACTIVE
qsTile.updateTile()
} else {
qsTile.label = getString(R.string.qs_name)
qsTile.subtitle = getString(R.string.qs_not_working)
qsTile.state = Tile.STATE_INACTIVE
qsTile.updateTile()
}
}
}
}

View File

@@ -0,0 +1,153 @@
package com.cherret.zaprett.utils
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.cherret.zaprett.data.ItemType
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.IOException
import java.io.File
import java.security.MessageDigest
private val client = OkHttpClient()
private val json = Json { ignoreUnknownKeys = true }
fun getHostList(sharedPreferences: SharedPreferences, callback: (Result<List<RepoItemInfo>>) -> Unit) {
getRepo(
sharedPreferences.getString(
"hosts_repo_url",
"https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/hosts.json"
) ?: "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/hosts.json",
callback
)
}
fun getIpsetList(sharedPreferences: SharedPreferences, callback: (Result<List<RepoItemInfo>>) -> Unit) {
getRepo(
sharedPreferences.getString(
"ipset_repo_url",
"https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/ipsets.json"
) ?: "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/ipsets.json",
callback
)
}
fun getStrategiesList(sharedPreferences: SharedPreferences, callback: (Result<List<RepoItemInfo>>) -> Unit) {
getRepo(
sharedPreferences.getString(
"strategies_repo_url",
"https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/strategies.json"
) ?: "https://raw.githubusercontent.com/CherretGit/zaprett-repo/refs/heads/main/strategies.json",
callback
)
}
fun getRepo(url: String, callback: (Result<List<RepoItemInfo>>) -> Unit) {
val request = Request.Builder().url(url).build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
callback(Result.failure(e))
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) {
callback(Result.failure(IOException("Unexpected HTTP code ${response.code}")))
return
}
val jsonString = response.body.string()
val result = runCatching {
json.decodeFromString<List<RepoItemInfo>>(jsonString)
}
callback(result)
}
}
})
}
fun registerDownloadListener(context: Context, downloadId: Long, onDownloaded: (Uri) -> Unit, onError: (String) -> Unit) {// AI Generated
val receiver = object : BroadcastReceiver() {
@SuppressLint("Range")
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action != DownloadManager.ACTION_DOWNLOAD_COMPLETE) return
if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) != downloadId) return
val dm = context?.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager ?: return
val query = DownloadManager.Query().setFilterById(downloadId)
dm.query(query)?.use { cursor ->
if (cursor.moveToFirst()) {
val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
val reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON))
when (status) {
DownloadManager.STATUS_SUCCESSFUL -> {
val uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
if (uriString != null) {
val uri = uriString.toUri()
context.unregisterReceiver(this)
onDownloaded(uri)
}
}
DownloadManager.STATUS_FAILED -> {
context.unregisterReceiver(this)
val errorMessage = when (reason) {
DownloadManager.ERROR_CANNOT_RESUME -> "Cannot resume download"
DownloadManager.ERROR_DEVICE_NOT_FOUND -> "Device not found"
DownloadManager.ERROR_FILE_ALREADY_EXISTS -> "File already exists"
DownloadManager.ERROR_FILE_ERROR -> "File error"
DownloadManager.ERROR_HTTP_DATA_ERROR -> "HTTP data error"
DownloadManager.ERROR_INSUFFICIENT_SPACE -> "Insufficient space"
DownloadManager.ERROR_TOO_MANY_REDIRECTS -> "Too many redirects"
DownloadManager.ERROR_UNHANDLED_HTTP_CODE -> "Unhandled HTTP code"
DownloadManager.ERROR_UNKNOWN -> "Unknown error"
else -> "Download failed: reason=$reason"
}
onError(errorMessage)
}
}
}
}
}
}
val intentFilter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(receiver, intentFilter, Context.RECEIVER_EXPORTED)
} else {
ContextCompat.registerReceiver(context, receiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE), ContextCompat.RECEIVER_EXPORTED)
}
}
fun getFileSha256(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
file.inputStream().use { input ->
val buffer = ByteArray(1024)
var bytesRead: Int
while (input.read(buffer).also { bytesRead = it } != -1) {
digest.update(buffer, 0, bytesRead)
}
}
return digest.digest().joinToString("") { "%02x".format(it) }
}
@Serializable
data class RepoItemInfo(
val name: String,
val author: String,
val description: String,
val type: ItemType,
val hash: String,
val url: String
)

View File

@@ -0,0 +1,104 @@
package com.cherret.zaprett.utils
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Environment
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import com.cherret.zaprett.BuildConfig
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.IOException
import java.io.File
private val client = OkHttpClient()
private val json = Json { ignoreUnknownKeys = true }
// PLS EGOR-WHITE REFACTOR THIS
fun getUpdate(sharedPreferences: SharedPreferences, callback: (UpdateInfo?) -> Unit) {
val request = Request.Builder().url(sharedPreferences.getString("update_repo_url", "https://raw.githubusercontent.com/CherretGit/zaprett-app/refs/heads/main/update.json")?: "https://raw.githubusercontent.com/CherretGit/zaprett-app/refs/heads/main/update.json").build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
callback(null)
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) {
throw IOException()
callback(null)
}
val jsonString = response.body.string()
val updateInfo = json.decodeFromString<UpdateInfo>(jsonString)
updateInfo?.versionCode?.let { versionCode ->
if (versionCode > BuildConfig.VERSION_CODE)
callback(updateInfo)
}
}
}
})
}
fun getChangelog(changelogUrl: String, callback: (String?) -> Unit) {
val request = Request.Builder().url(changelogUrl).build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
callback(null)
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) {
callback(null)
return
}
val changelogText = response.body.string()
callback(changelogText)
}
}
})
}
fun download(context: Context, url: String): Long {
val fileName = url.substringAfterLast("/")
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val request = DownloadManager.Request(url.toUri()).apply {
setTitle(fileName)
setDescription(fileName)
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
}
return downloadManager.enqueue(request)
}
fun installApk(context: Context, uri: Uri) {
val file = File(uri.path!!)
val apkUri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file)
if (context.packageManager.canRequestPackageInstalls()) {
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(apkUri, "application/vnd.android.package-archive")
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
context.startActivity(intent)
}
}
@Serializable
data class UpdateInfo(
val version: String?,
val versionCode: Int?,
val downloadUrl: String?,
val changelogUrl: String?
)

View File

@@ -0,0 +1,504 @@
package com.cherret.zaprett.utils
import android.Manifest
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import com.cherret.zaprett.data.AppListType
import com.cherret.zaprett.data.ZaprettConfig
import com.topjohnwu.superuser.Shell
import kotlinx.serialization.json.Json
import java.io.File
private val json = Json {
prettyPrint = true
ignoreUnknownKeys = true
coerceInputValues = true
encodeDefaults = true
}
private fun readConfig(): ZaprettConfig {
val configFile = getConfigFile()
if (!configFile.exists()) {
return ZaprettConfig()
}
return try {
val content = configFile.readText()
if (content.isBlank()) ZaprettConfig() else json.decodeFromString<ZaprettConfig>(content)
} catch (e: Exception) {
Log.e("ZaprettManager", "Error reading config, returning defaults", e)
ZaprettConfig()
}
}
private fun writeConfig(config: ZaprettConfig) {
val configFile = getConfigFile()
try {
configFile.parentFile?.mkdirs()
val content = json.encodeToString(config)
configFile.writeText(content)
} catch (e: Exception) {
Log.e("ZaprettManager", "Error writing config", e)
}
}
fun checkStoragePermission(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Environment.isExternalStorageManager()
} else {
ContextCompat.checkSelfPermission(
context,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
}
}
fun checkRoot(callback: (Boolean) -> Unit) {
Shell.getShell().isRoot.let { callback(it) }
}
fun checkModuleInstallation(callback: (Boolean) -> Unit) {
Shell.cmd("zaprett").submit { result ->
callback(result.out.toString().contains("zaprett"))
}
}
fun getStatus(callback: (Boolean) -> Unit) {
Shell.cmd("zaprett status").submit { result ->
callback(result.out.toString().contains("working"))
}
}
fun startService(callback: (String) -> Unit) {
Shell.cmd("zaprett start 2>&1").submit { result ->
callback(
if (result.isSuccess) ""
else result.out.joinToString("\n")
)
}
}
fun stopService(callback: (String) -> Unit) {
Shell.cmd("zaprett stop 2>&1").submit { result ->
callback(
if (result.isSuccess) ""
else result.out.joinToString("\n")
)
}
}
fun restartService(callback: (String) -> Unit) {
Shell.cmd("zaprett restart 2>&1").submit { result ->
callback(
if (result.isSuccess) ""
else result.out.joinToString("\n")
)
}
}
fun getModuleVersion(callback: (String) -> Unit) {
Shell.cmd("zaprett module-version").submit { result ->
if (result.out.isNotEmpty()) callback(result.out.first()) else "undefined"
}
}
fun getBinVersion(callback: (String) -> Unit) {
Shell.cmd("zaprett binary-version").submit { result ->
if (result.out.isNotEmpty()) callback(result.out.first()) else "undefined"
}
}
fun getConfigFile(): File {
return File(Environment.getExternalStorageDirectory(), "zaprett/config.json")
}
fun setStartOnBoot(prefs: SharedPreferences, callback: (Boolean) -> Unit) {
if (prefs.getBoolean("use_module", false)) {
Shell.cmd("zaprett set-autostart").submit { result ->
if (result.out.isNotEmpty() && result.out.toString().contains("true")) callback(true) else callback(false)
}
}
}
fun getStartOnBoot(prefs: SharedPreferences, callback: (Boolean) -> Unit) {
if (prefs.getBoolean("use_module", false)) {
Shell.cmd("zaprett get-autostart").submit { result ->
if (result.out.isNotEmpty() && result.out.toString().contains("true")) callback(true) else callback(false)
}
} else {
callback(false)
}
}
fun getZaprettPath(): String {
return Environment.getExternalStorageDirectory().path + "/zaprett"
}
fun getAllLists(): Array<String> {
val listsDir = File("${getZaprettPath()}/lists/include")
return listsDir.listFiles { file -> file.isFile && file.extension.lowercase() == "txt" }
?.map { it.absolutePath }
?.toTypedArray()
?: emptyArray()
}
fun getAllIpsets(): Array<String> {
val listsDir = File("${getZaprettPath()}/ipset/include")
return listsDir.listFiles { file -> file.isFile && file.extension.lowercase() == "txt" }
?.map { it.absolutePath }
?.toTypedArray()
?: emptyArray()
}
fun getAllExcludeLists(): Array<String> {
val listsDir = File("${getZaprettPath()}/lists/exclude/")
return listsDir.listFiles { file -> file.isFile && file.extension.lowercase() == "txt" }
?.map { it.absolutePath }
?.toTypedArray()
?: emptyArray()
}
fun getAllExcludeIpsets(): Array<String> {
val listsDir = File("${getZaprettPath()}/ipset/exclude/")
return listsDir.listFiles { file -> file.isFile && file.extension.lowercase() == "txt" }
?.map { it.absolutePath }
?.toTypedArray()
?: emptyArray()
}
fun getAllNfqwsStrategies(): Array<String> {
val listsDir = File("${getZaprettPath()}/strategies/nfqws")
return listsDir.listFiles { file -> file.isFile && file.extension.lowercase() == "txt" }
?.map { it.absolutePath }
?.toTypedArray()
?: emptyArray()
}
fun getAllByeDPIStrategies(): Array<String> {
val listsDir = File("${getZaprettPath()}/strategies/byedpi")
return listsDir.listFiles { file -> file.isFile && file.extension.lowercase() == "txt" }
?.map { it.absolutePath }
?.toTypedArray()
?: emptyArray()
}
fun getAllStrategies(sharedPreferences: SharedPreferences): Array<String> {
return if (sharedPreferences.getBoolean("use_module", false)) getAllNfqwsStrategies()
else getAllByeDPIStrategies()
}
fun getActiveLists(sharedPreferences: SharedPreferences): Array<String> {
if (sharedPreferences.getBoolean("use_module", false)) {
return readConfig().activeLists.toTypedArray()
} else {
return sharedPreferences.getStringSet("lists", emptySet())?.toTypedArray() ?: emptyArray()
}
}
fun getActiveIpsets(sharedPreferences: SharedPreferences): Array<String> {
if (sharedPreferences.getBoolean("use_module", false)) {
return readConfig().activeIpsets.toTypedArray()
} else return sharedPreferences.getStringSet("ipsets", emptySet())?.toTypedArray() ?: emptyArray()
}
fun getActiveExcludeLists(sharedPreferences: SharedPreferences): Array<String> {
if (sharedPreferences.getBoolean("use_module", false)) {
return readConfig().activeExcludeLists.toTypedArray()
} else {
return sharedPreferences.getStringSet("exclude_lists", emptySet())?.toTypedArray() ?: emptyArray()
}
}
fun getActiveExcludeIpsets(sharedPreferences: SharedPreferences): Array<String> {
if (sharedPreferences.getBoolean("use_module", false)) {
return readConfig().activeExcludeIpsets.toTypedArray()
} else return sharedPreferences.getStringSet("exclude_ipsets", emptySet())?.toTypedArray() ?: emptyArray()
}
fun getActiveNfqwsStrategy(): Array<String> {
val strategy = readConfig().strategy
return if (strategy.isNotBlank()) arrayOf(strategy) else emptyArray()
}
fun getActiveByeDPIStrategy(sharedPreferences: SharedPreferences): Array<String> {
val path = sharedPreferences.getString("active_strategy", "")
if (!path.isNullOrBlank() && File(path).exists()) {
return arrayOf(path)
}
return emptyArray()
}
fun getActiveByeDPIStrategyContent(sharedPreferences: SharedPreferences): List<String> {
val path = sharedPreferences.getString("active_strategy", "")
if (!path.isNullOrBlank() && File(path).exists()) {
return File(path).readLines()
}
return emptyList()
}
fun getActiveStrategy(sharedPreferences: SharedPreferences): Array<String> {
return if (sharedPreferences.getBoolean("use_module", false)) getActiveNfqwsStrategy()
else getActiveByeDPIStrategy(sharedPreferences)
}
fun enableList(path: String, sharedPreferences: SharedPreferences) {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
val isWhitelist = getHostListMode(sharedPreferences) == "whitelist"
val currentLists = if (isWhitelist) config.activeLists else config.activeExcludeLists
if (path !in currentLists) {
val updatedLists = currentLists + path
val newConfig = if (isWhitelist) {
config.copy(activeLists = updatedLists)
} else {
config.copy(activeExcludeLists = updatedLists)
}
writeConfig(newConfig)
}
} else {
val key = if (getHostListMode(sharedPreferences) == "whitelist") "lists" else "exclude_lists"
val currentSet = sharedPreferences.getStringSet(key, emptySet())?.toMutableSet() ?: mutableSetOf()
if (path !in currentSet) {
currentSet.add(path)
sharedPreferences.edit { putStringSet(key, currentSet) }
}
}
}
fun enableIpset(path: String, sharedPreferences: SharedPreferences) {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
val isWhitelist = getHostListMode(sharedPreferences) == "whitelist"
val currentIpsets = if (isWhitelist) config.activeIpsets else config.activeExcludeIpsets
if (path !in currentIpsets) {
val updatedIpsets = currentIpsets + path
val newConfig = if (isWhitelist) {
config.copy(activeIpsets = updatedIpsets)
} else {
config.copy(activeExcludeIpsets = updatedIpsets)
}
writeConfig(newConfig)
}
} else {
val key = if (getHostListMode(sharedPreferences) == "whitelist") "ipsets" else "exclude_ipsets"
val currentSet = sharedPreferences.getStringSet(key, emptySet())?.toMutableSet() ?: mutableSetOf()
if (path !in currentSet) {
currentSet.add(path)
sharedPreferences.edit { putStringSet(key, currentSet) }
}
}
}
fun enableStrategy(path: String, sharedPreferences: SharedPreferences) {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
if (config.strategy != path) {
writeConfig(config.copy(strategy = path))
}
} else {
sharedPreferences.edit { putString("active_strategy", path) }
}
}
fun disableList(path: String, sharedPreferences: SharedPreferences) {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
val isWhitelist = getHostListMode(sharedPreferences) == "whitelist"
val currentLists = if (isWhitelist) config.activeLists else config.activeExcludeLists
if (path in currentLists) {
val updatedLists = currentLists.filter { it != path }
val newConfig = if (isWhitelist) {
config.copy(activeLists = updatedLists)
} else {
config.copy(activeExcludeLists = updatedLists)
}
writeConfig(newConfig)
}
} else {
val key = if (getHostListMode(sharedPreferences) == "whitelist") "lists" else "exclude_lists"
val currentSet = sharedPreferences.getStringSet(key, emptySet())?.toMutableSet() ?: mutableSetOf()
if (path in currentSet) {
currentSet.remove(path)
sharedPreferences.edit { putStringSet(key, currentSet) }
}
if (currentSet.isEmpty()) {
sharedPreferences.edit { remove(key) }
}
}
}
fun disableIpset(path: String, sharedPreferences: SharedPreferences) {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
val isWhitelist = getHostListMode(sharedPreferences) == "whitelist"
val currentIpsets = if (isWhitelist) config.activeIpsets else config.activeExcludeIpsets
if (path in currentIpsets) {
val updatedIpsets = currentIpsets.filter { it != path }
val newConfig = if (isWhitelist) {
config.copy(activeIpsets = updatedIpsets)
} else {
config.copy(activeExcludeIpsets = updatedIpsets)
}
writeConfig(newConfig)
}
} else {
val key = if (getHostListMode(sharedPreferences) == "whitelist") "ipsets" else "exclude_ipsets"
val currentSet = sharedPreferences.getStringSet(key, emptySet())?.toMutableSet() ?: mutableSetOf()
if (path in currentSet) {
currentSet.remove(path)
sharedPreferences.edit { putStringSet(key, currentSet) }
}
if (currentSet.isEmpty()) {
sharedPreferences.edit { remove(key) }
}
}
}
fun disableStrategy(path: String, sharedPreferences: SharedPreferences) {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
if (config.strategy == path) {
writeConfig(config.copy(strategy = ""))
}
} else {
sharedPreferences.edit { remove("active_strategy") }
}
}
fun addPackageToList(listType: AppListType, packageName: String, prefs: SharedPreferences, context: Context) {
if (prefs.getBoolean("use_module", false)) {
val config = readConfig()
if (listType == AppListType.Whitelist) {
if (packageName !in config.whitelist) {
writeConfig(config.copy(whitelist = config.whitelist + packageName))
}
} else if (listType == AppListType.Blacklist) {
if (packageName !in config.blacklist) {
writeConfig(config.copy(blacklist = config.blacklist + packageName))
}
}
} else {
val prefs = context.getSharedPreferences("settings", MODE_PRIVATE)
if (listType == AppListType.Whitelist) {
val set = prefs.getStringSet("whitelist", emptySet())?.toMutableSet() ?: mutableSetOf()
set.add(packageName)
prefs.edit().putStringSet("whitelist", set).apply()
}
if (listType == AppListType.Blacklist) {
val set = prefs.getStringSet("blacklist", emptySet())?.toMutableSet() ?: mutableSetOf()
set.add(packageName)
prefs.edit().putStringSet("blacklist", set).apply()
}
}
}
fun removePackageFromList(listType: AppListType, packageName: String, prefs: SharedPreferences, context: Context) {
if (prefs.getBoolean("use_module", false)) {
val config = readConfig()
if (listType == AppListType.Whitelist) {
if (packageName in config.whitelist) {
writeConfig(config.copy(whitelist = config.whitelist.filter { it != packageName }))
}
} else if (listType == AppListType.Blacklist) {
if (packageName in config.blacklist) {
writeConfig(config.copy(blacklist = config.blacklist.filter { it != packageName }))
}
}
} else {
val prefs = context.getSharedPreferences("settings", MODE_PRIVATE)
if (listType == AppListType.Whitelist) {
val set = prefs.getStringSet("whitelist", emptySet())?.toMutableSet() ?: mutableSetOf()
set.remove(packageName)
prefs.edit().putStringSet("whitelist", set).apply()
}
if (listType == AppListType.Blacklist) {
val set = prefs.getStringSet("blacklist", emptySet())?.toMutableSet() ?: mutableSetOf()
set.remove(packageName)
prefs.edit().putStringSet("blacklist", set).apply()
}
}
}
fun isInList(listType: AppListType, packageName: String, prefs: SharedPreferences, context: Context): Boolean {
if (prefs.getBoolean("use_module", false)) {
val config = readConfig()
return if (listType == AppListType.Whitelist) {
packageName in config.whitelist
} else {
packageName in config.blacklist
}
} else {
val prefs = context.getSharedPreferences("settings", MODE_PRIVATE)
if (listType == AppListType.Whitelist) {
val whitelist = prefs.getStringSet("whitelist", emptySet()) ?: emptySet()
return packageName in whitelist
} else {
val blacklist = prefs.getStringSet("blacklist", emptySet()) ?: emptySet()
return packageName in blacklist
}
}
}
fun getAppList(listType: AppListType, sharedPreferences: SharedPreferences, context: Context): Set<String> {
if (sharedPreferences.getBoolean("use_module", false)) {
val config = readConfig()
return if (listType == AppListType.Whitelist) {
config.whitelist.toSet()
} else {
config.blacklist.toSet()
}
} else {
return if (listType == AppListType.Whitelist) context.getSharedPreferences("settings", MODE_PRIVATE)
.getStringSet("whitelist", emptySet()) ?: emptySet()
else context.getSharedPreferences("settings", MODE_PRIVATE)
.getStringSet("blacklist", emptySet()) ?: emptySet()
}
}
fun getAppsListMode(prefs: SharedPreferences): String {
if (prefs.getBoolean("use_module", false)) {
val applist = readConfig().appList
Log.d("App list", "Equals to $applist")
return if (applist == "whitelist" || applist == "blacklist" || applist == "none") applist
else "none"
} else {
return prefs.getString("app_list", "none")!!
}
}
fun setAppsListMode(prefs: SharedPreferences, mode: String) {
if (prefs.getBoolean("use_module", false)) {
val config = readConfig()
writeConfig(config.copy(appList = mode))
} else {
prefs.edit { putString("app_list", mode) }
}
Log.d("App List", "Changed to $mode")
}
fun setHostListMode(prefs: SharedPreferences, mode: String) {
if (prefs.getBoolean("use_module", false)) {
val config = readConfig()
writeConfig(config.copy(listType = mode))
} else {
prefs.edit { putString("list_type", mode) }
}
Log.d("App List", "Changed to $mode")
}
fun getHostListMode(prefs: SharedPreferences): String {
if (prefs.getBoolean("use_module", false)) {
val hostlist = readConfig().listType
return if (hostlist == "whitelist" || hostlist == "blacklist") hostlist
else "whitelist"
} else {
return prefs.getString("list_type", "whitelist")!!
}
}

View File

@@ -0,0 +1,16 @@
# Copyright (C) 2023 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include $(call all-subdir-makefiles)

View File

@@ -0,0 +1,21 @@
# Copyright (C) 2023 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
APP_OPTIM := release
APP_PLATFORM := android-21
APP_ABI := armeabi-v7a arm64-v8a x86 x86_64
APP_CFLAGS := -O3 -DPKGNAME=com/cherret/zaprett/byedpi
APP_CPPFLAGS := -O3 -std=c++11
NDK_TOOLCHAIN_VERSION := clang

View File

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M12,0.297c-6.63,0 -12,5.373 -12,12 0,5.303 3.438,9.8 8.205,11.385 0.6,0.113 0.82,-0.258 0.82,-0.577 0,-0.285 -0.01,-1.04 -0.015,-2.04 -3.338,0.724 -4.042,-1.61 -4.042,-1.61C4.422,18.07 3.633,17.7 3.633,17.7c-1.087,-0.744 0.084,-0.729 0.084,-0.729 1.205,0.084 1.838,1.236 1.838,1.236 1.07,1.835 2.809,1.305 3.495,0.998 0.108,-0.776 0.417,-1.305 0.76,-1.605 -2.665,-0.3 -5.466,-1.332 -5.466,-5.93 0,-1.31 0.465,-2.38 1.235,-3.22 -0.135,-0.303 -0.54,-1.523 0.105,-3.176 0,0 1.005,-0.322 3.3,1.23 0.96,-0.267 1.98,-0.399 3,-0.405 1.02,0.006 2.04,0.138 3,0.405 2.28,-1.552 3.285,-1.23 3.285,-1.23 0.645,1.653 0.24,2.873 0.12,3.176 0.765,0.84 1.23,1.91 1.23,3.22 0,4.61 -2.805,5.625 -5.475,5.92 0.42,0.36 0.81,1.096 0.81,2.22 0,1.606 -0.015,2.896 -0.015,3.286 0,0.315 0.21,0.69 0.825,0.57C20.565,22.092 24,17.592 24,12.297c0,-6.627 -5.373,-12 -12,-12"/>
</vector>

View File

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M0.632,0.55v22.9L2.28,23.45L2.28,24L0,24L0,0h2.28v0.55zM7.675,7.81v1.157h0.033c0.309,-0.443 0.683,-0.784 1.117,-1.024 0.433,-0.245 0.936,-0.365 1.5,-0.365 0.54,0 1.033,0.107 1.481,0.314 0.448,0.208 0.785,0.582 1.02,1.108 0.254,-0.374 0.6,-0.706 1.034,-0.992 0.434,-0.287 0.95,-0.43 1.546,-0.43 0.453,0 0.872,0.056 1.26,0.167 0.388,0.11 0.716,0.286 0.993,0.53 0.276,0.245 0.489,0.559 0.646,0.951 0.152,0.392 0.23,0.863 0.23,1.417v5.728h-2.349L16.186,11.52c0,-0.286 -0.01,-0.559 -0.032,-0.812a1.755,1.755 0,0 0,-0.18 -0.66,1.106 1.106,0 0,0 -0.438,-0.448c-0.194,-0.11 -0.457,-0.166 -0.785,-0.166 -0.332,0 -0.6,0.064 -0.803,0.189a1.38,1.38 0,0 0,-0.48 0.499,1.946 1.946,0 0,0 -0.231,0.696 5.56,5.56 0,0 0,-0.06 0.785v4.768h-2.35v-4.8c0,-0.254 -0.004,-0.503 -0.018,-0.752a2.074,2.074 0,0 0,-0.143 -0.688,1.052 1.052,0 0,0 -0.415,-0.503c-0.194,-0.125 -0.476,-0.19 -0.854,-0.19 -0.111,0 -0.259,0.024 -0.439,0.074 -0.18,0.051 -0.36,0.143 -0.53,0.282 -0.171,0.138 -0.319,0.337 -0.439,0.595 -0.12,0.259 -0.18,0.6 -0.18,1.02v4.966L5.46,16.375L5.46,7.81zM23.368,23.45L23.368,0.55L21.72,0.55L21.72,0L24,0v24h-2.28v-0.55z"/>
</vector>

View File

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M11.944,0A12,12 0,0 0,0 12a12,12 0,0 0,12 12,12 12,0 0,0 12,-12A12,12 0,0 0,12 0a12,12 0,0 0,-0.056 0zM16.906,7.224c0.1,-0.002 0.321,0.023 0.465,0.14a0.506,0.506 0,0 1,0.171 0.325c0.016,0.093 0.036,0.306 0.02,0.472 -0.18,1.898 -0.962,6.502 -1.36,8.627 -0.168,0.9 -0.499,1.201 -0.82,1.23 -0.696,0.065 -1.225,-0.46 -1.9,-0.902 -1.056,-0.693 -1.653,-1.124 -2.678,-1.8 -1.185,-0.78 -0.417,-1.21 0.258,-1.91 0.177,-0.184 3.247,-2.977 3.307,-3.23 0.007,-0.032 0.014,-0.15 -0.056,-0.212s-0.174,-0.041 -0.249,-0.024c-0.106,0.024 -1.793,1.14 -5.061,3.345 -0.48,0.33 -0.913,0.49 -1.302,0.48 -0.428,-0.008 -1.252,-0.241 -1.865,-0.44 -0.752,-0.245 -1.349,-0.374 -1.297,-0.789 0.027,-0.216 0.325,-0.437 0.893,-0.663 3.498,-1.524 5.83,-2.529 6.998,-3.014 3.332,-1.386 4.025,-1.627 4.476,-1.635z"/>
</vector>

View File

@@ -2,33 +2,122 @@
<resources>
<string name="title_home">Главная</string>
<string name="title_hosts">Хосты</string>
<string name="title_strategies">Стратегии</string>
<string name="title_repo">Репозиторий</string>
<string name="title_settings">Настройки</string>
<string name="title_debug">Отладка</string>
<string name="general_section">Основные настройки</string>
<string name="byedpi_section">Настройки ByeDPI</string>
<string name="btn_continue">Продолжить</string>
<string name="text_welcome">Привет в zaprett! Это приложение предназначено для обхода цензуры и иных блокировок. Для полноценной работоспособности необходимо установить Magisk модуль.</string>
<string name="btn_update">Обновить</string>
<string name="btn_dismiss">Отмена</string>
<string name="text_welcome">Добро пожаловать в zaprett! Это приложение предназначено для обхода цензуры и иных блокировок. Для полноценной работоспособности необходимо установить Magisk модуль.</string>
<string name="btn_use_root">Использовать модуль</string>
<string name="error_root_title">Root не получен</string>
<string name="error_root_message">Не получилось получить root доступ. Дайте права root для использования модуля Magisk</string>
<string name="error_no_module_title">Модуль не установлен</string>
<string name="error_no_module_message">Magisk модуль zaprett не найден. Пожалуйста, установите его</string>
<string name="snack_reload">Перезагружаем zaprett...</string>
<string name="snack_reload">Перезагружаем zaprett</string>
<string name="snack_module_disabled">Модуль Magisk отключен! Не получилось выполнить действие</string>
<string name="title_strategy">Стратегия</string>
<string name="status_not_availible">Состояние zaprett неизвестно. Нажми для обновления</string>
<string name="status_enabled">Сервис zaprett работает. Нажми для обновления состояния</string>
<string name="status_disabled">Сервис zaprett не работает. Нажми для обновления состояния</string>
<string name="status_crashed">Сервис zaprett вероятно крашнулся. Нажмите кнопку перезапуска ниже</string>
<string name="update_available">Доступно обновление</string>
<string name="btn_update_on_boot">Обновлять статус при запуске Главной страницы</string>
<string name="btn_start_service">Запустить сервис</string>
<string name="btn_stop_service">Остановить сервис</string>
<string name="btn_restart_service">Перезапустить сервис</string>
<string name="btn_autorestart">Переодически перезапускать сервис</string>
<string name="notification_zaprett_description">zaprett proxy запущен</string>
<string name="toast_no_strategy_selected">Стратегия не выбрана</string>
<string name="btn_remove_host">Удалить</string>
<string name="btn_download_host">Скачать</string>
<string name="btn_add_host">Добавить</string>
<string name="btn_back">Назад</string>
<string name="empty_list">Пусто :(</string>
<string name="title_author">Автор: %1$s</string>
<string name="btn_install_host">Установить</string>
<string name="btn_update_host">Обновить</string>
<string name="btn_installing_host">Установка</string>
<string name="btn_updating_host">Обновление</string>
<string name="btn_installed_host">Установлено</string>
<string name="btn_autorestart">Периодически перезапускать сервис</string>
<string name="btn_autoupdate">Автообновление</string>
<string name="btn_send_firebase_analytics">Отправлять аналитику Firebase</string>
<string name="btn_repository_url_lists">URL репозитория хостов</string>
<string name="hint_enter_repository_url_lists">Введите URL репозитория хостов</string>
<string name="btn_repository_url_strategies">URL репозитория стратегий</string>
<string name="hint_enter_repository_url_strategies">Введите URL репозитория стратегий</string>
<string name="btn_update_repository_url">URL репозитория обновлений</string>
<string name="hint_enter_update_repository_url">Введите URL репозитория обновлений</string>
<string name="btn_ipv6">IPv6</string>
<string name="btn_ip">IP-адрес</string>
<string name="hint_ip">Введите IP-адрес</string>
<string name="btn_port">Порт</string>
<string name="hint_port">Введите порт</string>
<string name="btn_dns">DNS</string>
<string name="hint_dns">Введите DNS</string>
<string name="alert_version">Версия: %1$s → %2$s\nСписок изменений:\n%3$s</string>
<string name="snack_already_started">Сервис уже запущен.</string>
<string name="snack_starting_service">Запускаем сервис...</string>
<string name="snack_starting_service">Запускаем сервис</string>
<string name="snack_no_service">Сервис не запущен</string>
<string name="snack_stopping_service">Останавливаем сервис...</string>
<string name="snack_stopping_service">Останавливаем сервис</string>
<string name="error_no_storage_title">Нет разрешения</string>
<string name="notification_permission_title">Разрешение на уведомления</string>
<string name="notification_permission_message">Приложению нужно разрешение на отправку уведомлений</string>
<string name="error_no_storage_message">Для правильной работы приложения необходимо разрешение на доступ к хранилищу</string>
<string name="btn_show_full_path">Показывать полный путь к листу</string>
<string name="pls_reboot_snack">Перезагрузите устройство для вступления изменений в силу</string>
<string name="pls_restart_snack">Перезапустите zaprett для вступления изменений в силу</string>
<string name="qs_starting">Запуск…</string>
<string name="qs_stopping">Остановка…</string>
<string name="module_version">Версия модуля</string>
<string name="nfqws_version">Версия nfqws</string>
<string name="ciadpi_version">Версия ciadpi</string>
<string name="unknown_text">неизвестно</string>
<string name="service_mode">Режим работы</string>
<string name="qs_not_available">Не доступно</string>
<string name="qs_working">Работает</string>
<string name="qs_not_working">Не работает</string>
<string name="about_title">О приложении</string>
<string name="about_text">zaprett app от Cherret, egor-white\nВерсия: %1$s</string>
<string name="btn_whitelist">Белый список приложений</string>
<string name="btn_blacklist">Чёрный список приложений</string>
<string name="shared_section">Общие настройки</string>
<string name="zapret_section">Настройки zapret</string>
<string name="title_whitelist">Белый список</string>
<string name="title_blacklist">Чёрный список</string>
<string name="btn_applist">Списки приложений</string>
<string name="radio_disabed">Выключено</string>
<string name="btn_show_system_apps">Показывать системные приложения</string>
<string name="search_field">Поиск…</string>
<string name="error_text">Ошибка</string>
<string name="error_server_data">Ошибка получения данных с сервера, пожалуйста проверьте интернет соединение</string>
<string name="error_processing_data">Ошибка при обработке данных</string>
<string name="error_unknown">Неизвестная ошибка</string>
<string name="btn_copy_log">Скопировать лог</string>
<string name="log_copied">Лог скопирован</string>
<string name="download_error">Произошла ошибка скачивания, пожалуйста, сообщите о ней разработчикам</string>
<string name="ipset_repo_url">URL репозитория ipset</string>
<string name="title_selection">Подбор стратегии</string>
<string name="btn_repository_url_ipsets">URL репозитория ipset</string>
<string name="hint_enter_repository_url_ipsets">Введите URL репозитория ipset</string>
<string name="strategy_status_waiting">ожидание...</string>
<string name="strategy_status_testing">проверка...</string>
<string name="strategy_status_tested">проверка завершена</string>
<string name="strategy_applied">Стратегия применена</string>
<string name="begin_selection">Начать подбор</string>
<string name="begin_selection_snack">Начат подбор стратегии. Не закрывайте эту вкладку</string>
<string name="change_probe_timeout">Изменить таймаут пробы</string>
<string name="probe_timeout">Таймаут пробы</string>
<string name="hint_enter_probe_timeout">Введите таймаут пробы</string>
<string name="strategy_selection_info_title">Информация</string>
<string name="strategy_selection_info_msg">"В этом разделе настроек приложения представлен перебор стратегий\n Подбор проходит среди скачанных стратегий, поэтому заранее скачайте из репозитория или добавьте из файловой системы интересующие вас стратегии для сравнения. \n Перед началом так же выберете один или несколько листов доменов на вкладке \"Листы\", затем нажмите на \"Начать подбор\". Не используйте для перебора списки с большим количеством доменов."</string>
<string name="selection_no_hosts_title">Нет включенных листов/стратегий</string>
<string name="selection_no_hosts_message">Не обнаружено активных списков хостов, либо доступных стратегий. Включите один или несколько, или скачайте стратегии для проверки, иначе подбор не сработает</string>
<string name="selection_available_domains">Доступные домены</string>
<string name="no_storage_permission_message">Нет разрешения на доступ к файлам</string>
<string name="reset_settings_title">Сброс настроек</string>
<string name="reset_settings_message">Вы действительно хотите сбросить настройки?</string>
</resources>

View File

@@ -2,33 +2,127 @@
<string name="app_name" translatable="false">zaprett</string>
<string name="title_home">Home</string>
<string name="title_hosts">Hosts</string>
<string name="title_strategies">Strategies</string>
<string name="title_repo">Repository</string>
<string name="title_settings">Settings</string>
<string name="title_debug">Debug</string>
<string name="general_section">General settings</string>
<string name="byedpi_section">ByeDPI settings</string>
<string name="btn_continue">Continue</string>
<string name="text_welcome">Hello to zaprett! This application is designed to bypass censorship and other blockages. For full functionality you need to install Magisk module.</string>
<string name="btn_update">Update</string>
<string name="btn_dismiss">Dismiss</string>
<string name="text_welcome">Welcome to zaprett! This application is designed to bypass censorship and other blockages. For full functionality you need to install Magisk module.</string>
<string name="btn_use_root">Use module</string>
<string name="error_root_title">Can\'t get root</string>
<string name="error_root_message">Couldn\'t get root access. Give root access to use the Magisk module</string>
<string name="error_no_module_title">Module is not installed</string>
<string name="error_no_module_message">Magisk module zaprett wasn\'t found. Please install it</string>
<string name="snack_reload">Reloading zaprett...</string>
<string name="snack_reload">Reloading zaprett</string>
<string name="snack_module_disabled">Magisk module disabled! Cant\'t execute action</string>
<string name="title_strategy">Strategy</string>
<string name="status_not_availible">Status of zaprett is unknown. Tap to update</string>
<string name="status_enabled">zaprett service is working. Tap to update</string>
<string name="status_disabled">zaprett service disabled.</string>
<string name="status_crashed">zaprett service crashed. Tap restart button below</string>
<string name="update_available">Update available</string>
<string name="btn_update_on_boot">Update the status when the Home page is launched</string>
<string name="btn_start_service">Start service</string>
<string name="btn_stop_service">Stop service</string>
<string name="btn_restart_service">Restart service</string>
<string name="btn_autorestart">Restart service periodicaly</string>
<string name="notification_zaprett_proxy" translatable="false">zaprett proxy</string>
<string name="notification_zaprett_description">zaprett proxy is running</string>
<string name="toast_no_strategy_selected">No strategy selected</string>
<string name="btn_remove_host">Remove</string>
<string name="btn_download_host">Download</string>
<string name="btn_add_host">Add</string>
<string name="btn_back">Back</string>
<string name="empty_list">Empty :(</string>
<string name="title_author">Author: %1$s</string>
<string name="btn_install_host">Install</string>
<string name="btn_update_host">Update</string>
<string name="btn_installing_host">Installing</string>
<string name="btn_updating_host">Updating</string>
<string name="btn_installed_host">Installed</string>
<string name="btn_autorestart">Restart service periodically</string>
<string name="btn_autoupdate">Autoupdate</string>
<string name="btn_send_firebase_analytics">Send Firebase Analytics</string>
<string name="btn_repository_url_lists">Hosts repository URL</string>
<string name="hint_enter_repository_url_lists">Enter hosts repository URL</string>
<string name="btn_repository_url_strategies">Strategies repository URL</string>
<string name="hint_enter_repository_url_strategies">Enter strategies repository URL</string>
<string name="btn_update_repository_url">Update repository URL</string>
<string name="hint_enter_update_repository_url">Enter update repository URL</string>
<string name="btn_ipv6">IPv6</string>
<string name="btn_ip">IP address</string>
<string name="hint_ip">Enter IP address</string>
<string name="btn_port">Port</string>
<string name="hint_port">Enter port</string>
<string name="btn_dns">DNS</string>
<string name="hint_dns">Enter DNS</string>
<string name="alert_version">Version: %1$s → %2$s\nChangelog:\n%3$s</string>
<string name="snack_already_started">Service already started.</string>
<string name="snack_starting_service">Starting service...</string>
<string name="snack_starting_service">Starting service</string>
<string name="snack_no_service">Service is not launched</string>
<string name="snack_stopping_service">Stopping service...</string>
<string name="snack_stopping_service">Stopping service</string>
<string name="error_no_storage_title">No permission</string>
<string name="error_no_storage_message">The application requires permission to acess the storage to work properly</string>
<string name="error_no_storage_message">The application requires permission to access the storage to work properly</string>
<string name="notification_permission_title">Notification Permission</string>
<string name="notification_permission_message">This app needs permission to send notifications</string>
<string name="btn_show_full_path">Show full list\'s path</string>
<string name="pls_reboot_snack">Reboot your device for the changes to take effect</string>
<string name="pls_restart_snack">Restart zaprett service for the changes to take effects</string>
<string name="qs_name" translatable="false">zaprett</string>
<string name="qs_starting">Starting…</string>
<string name="qs_stopping">Stopping…</string>
<string name="module_version">Module version</string>
<string name="nfqws_version">nfqws version</string>
<string name="ciadpi_version">ciadpi version</string>
<string name="unknown_text">unknown</string>
<string name="service_mode">Service mode</string>
<string name="service_mode_nfqws" translatable="false">nfqws</string>
<string name="service_mode_ciadpi" translatable="false">ciadpi</string>
<string name="qs_not_available">Not available</string>
<string name="qs_working">Working</string>
<string name="qs_not_working">Not working</string>
<string name="about_title">About app</string>
<string name="about_text">zaprett app by Cherret, egor-white\nVersion: %1$s</string>
<string name="btn_whitelist">App white list</string>
<string name="btn_blacklist">App black list</string>
<string name="shared_section">Shared settings</string>
<string name="zapret_section">zapret settings</string>
<string name="title_whitelist">White list</string>
<string name="title_blacklist">Black list</string>
<string name="btn_applist">Apps lists</string>
<string name="radio_disabed">Disabled</string>
<string name="btn_show_system_apps">Show system apps</string>
<string name="search_field">Search…</string>
<string name="error_text">Error</string>
<string name="error_server_data">Error retrieving data from the server, please check your internet connection</string>
<string name="error_processing_data">Error processing data</string>
<string name="error_unknown">Unknown error</string>
<string name="btn_copy_log">Copy log</string>
<string name="log_copied">Log copied</string>
<string name="download_error">Occurred a file download error, please report to developers</string>
<string name="ipset_repo_url">Ipset repository URL</string>
<string name="title_ipset" translatable="false">Ipset</string>
<string name="title_selection">Strategy selection</string>
<string name="btn_repository_url_ipsets">Ipsets repository url</string>
<string name="hint_enter_repository_url_ipsets">Enter ipsets repository URL</string>
<string name="strategy_status_waiting">waiting...</string>
<string name="strategy_status_testing">testing...</string>
<string name="strategy_status_tested">testing ended</string>
<string name="strategy_applied">Strategy applied</string>
<string name="begin_selection">Begin selection</string>
<string name="begin_selection_snack">Strategy selection has begun. Please keep this tab open.</string>
<string name="change_probe_timeout">Change probe timeout</string>
<string name="probe_timeout">Probe timeout</string>
<string name="hint_enter_probe_timeout">Enter probe timeout</string>
<string name="strategy_selection_info_title">Tip</string>
<string name="strategy_selection_info_msg">This section of the application settings allows you to iterate through strategies.\n The selection is based on downloaded strategies, so download the strategies you\'re interested in from the repository or add them from the file system for comparison.\n Before starting, select one or more domain lists in the \"Lists\" tab, then click \"Start selection\". Avoid using lists with a large number of domains.</string>
<string name="selection_no_hosts_title">No active hosts/strategies</string>
<string name="selection_no_hosts_message">No active host lists or available strategies were found. Please enable one or more, or download strategies for testing, otherwise the selection will not work.</string>
<string name="selection_available_domains">Available domains</string>
<string name="no_storage_permission_message">Missing permission to access files</string>
<string name="reset_settings_title">Reset settings</string>
<string name="reset_settings_message">Are you sure you want to reset the settings?</string>
</resources>

View File

@@ -1,5 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Zaprett" parent="android:Theme.Material.Light.NoActionBar" />
</resources>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="downloads" path="Download/" />
<external-files-path name="apk" path="zaprett/" />
</paths>

View File

@@ -3,4 +3,6 @@ plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
id("com.google.gms.google-services") version "4.4.2" apply false
id("com.google.firebase.crashlytics") version "3.0.3" apply false
}

3
changelog.md Normal file
View File

@@ -0,0 +1,3 @@
1. Изменения под новую версию модуля
2. Исправление работы ipset с byedpi
3. Исправление вылетов

View File

@@ -1,13 +1,24 @@
[versions]
agp = "8.9.0"
kotlin = "2.0.21"
coreKtx = "1.10.1"
agp = "8.13.1"
kotlin = "2.2.10"
coreKtx = "1.17.0"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
lifecycleRuntimeKtx = "2.6.1"
activityCompose = "1.8.0"
composeBom = "2024.09.00"
junitVersion = "1.3.0"
espressoCore = "3.7.0"
lifecycleRuntimeKtx = "2.9.2"
activityCompose = "1.10.1"
composeBom = "2025.08.00"
compose-material3 = "1.3.2"
compose-material3-adaptive = "1.4.0-beta02"
navigation = "2.9.3"
compose-icons = "1.7.8"
libsu = "6.0.0"
okhttp = "5.1.0"
serialization = "1.9.0"
firebase-bom = "34.1.0"
fragment-compose = "1.8.9"
coil3 = "3.3.0"
compose-markdown = "0.5.7"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
@@ -24,6 +35,21 @@ androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-toolin
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "compose-material3" }
compose-material3-window-size = { group = "androidx.compose.material3", name = "material3-window-size-class", version.ref = "compose-material3" }
compose-material3-adaptive-nav = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite", version.ref = "compose-material3-adaptive" }
navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigation" }
compose-icons = { group = "androidx.compose.material", name = "material-icons-extended", version.ref = "compose-icons" }
libsu-core = { group = "com.github.topjohnwu.libsu", name = "core", version.ref = "libsu" }
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebase-bom" }
firebase-analytics = { group = "com.google.firebase", name = "firebase-analytics" }
firebase-crashlytics = { group = "com.google.firebase", name = "firebase-crashlytics" }
fragment-compose = { group = "androidx.fragment", name = "fragment-compose", version.ref = "fragment-compose" }
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil3" }
compose-markdown = { module = "com.github.jeziellago:compose-markdown", version.ref = "compose-markdown" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }

View File

@@ -1,6 +1,6 @@
#Sat Mar 22 14:00:49 GMT+07:00 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

BIN
images/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

BIN
images/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

BIN
images/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

BIN
images/4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

BIN
images/5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

BIN
images/6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

BIN
images/7.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

14
rust/CMakeLists.txt Normal file
View File

@@ -0,0 +1,14 @@
cmake_minimum_required(VERSION 3.22.1)
project(byedpi_native)
file(GLOB BYE_DPI_SRC byedpi/*.c)
list(REMOVE_ITEM BYE_DPI_SRC ${CMAKE_CURRENT_SOURCE_DIR}/byedpi/win_service.c)
add_library(byedpi STATIC ${BYE_DPI_SRC})
target_include_directories(byedpi PRIVATE byedpi)
target_compile_options(byedpi PRIVATE -std=c99 -O2 -Wall -Wno-unused -Wextra -Wno-unused-parameter -pedantic)
target_compile_definitions(byedpi PRIVATE ANDROID_APP)
target_link_libraries(byedpi PRIVATE android log)

349
rust/Cargo.lock generated Normal file
View File

@@ -0,0 +1,349 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "android_log-sys"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d"
[[package]]
name = "android_logger"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3"
dependencies = [
"android_log-sys",
"env_filter",
"log",
]
[[package]]
name = "byedpi"
version = "0.1.0"
dependencies = [
"android_logger",
"cmake",
"jni",
"libc",
"log",
"once_cell",
]
[[package]]
name = "bytes"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "cc"
version = "1.2.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d05d92f4b1fd76aad469d46cdd858ca761576082cd37df81416691e50199fb"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cesu8"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
[[package]]
name = "cfg-if"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
[[package]]
name = "cmake"
version = "0.1.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0"
dependencies = [
"cc",
]
[[package]]
name = "combine"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"
dependencies = [
"bytes",
"memchr",
]
[[package]]
name = "env_filter"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
dependencies = [
"log",
"regex",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0399f9d26e5191ce32c498bebd31e7a3ceabc2745f0ac54af3f335126c3f24b3"
[[package]]
name = "jni"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
dependencies = [
"cesu8",
"cfg-if",
"combine",
"jni-sys",
"log",
"thiserror",
"walkdir",
"windows-sys 0.45.0",
]
[[package]]
name = "jni-sys"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
[[package]]
name = "libc"
version = "0.2.176"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
[[package]]
name = "log"
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
[[package]]
name = "memchr"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "proc-macro2"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
version = "2.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.1",
]
[[package]]
name = "windows-link"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65"
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.61.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f109e41dd4a3c848907eb83d5a42ea98b3769495597450cf6d153507b166f0f"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"

23
rust/Cargo.toml Normal file
View File

@@ -0,0 +1,23 @@
[package]
name = "byedpi"
version = "0.1.0"
edition = "2024"
[dependencies]
jni = "0.21.1"
libc = "0.2.0"
android_logger = "0.15.1"
log = "0.4"
once_cell = "1.21.3"
[lib]
crate-type = ["cdylib"]
[build-dependencies]
cmake = "0.1.49"
[profile.release]
opt-level = "z"
lto = true
strip = true
codegen-units = 1

8
rust/build.rs Normal file
View File

@@ -0,0 +1,8 @@
use cmake::Config;
fn main() {
let dst = Config::new(".").build_target("byedpi").build();
let lib_path = dst.join("build");
println!("cargo:rustc-link-search=native={}", lib_path.display());
println!("cargo:rustc-link-lib=static=byedpi");
}

1
rust/byedpi Submodule

Submodule rust/byedpi added at 7efde1b129

74
rust/src/lib.rs Normal file
View File

@@ -0,0 +1,74 @@
use android_logger::Config;
use jni::JNIEnv;
use jni::objects::{JClass, JObjectArray, JString};
use jni::sys::jint;
use libc::{SHUT_RDWR, shutdown};
use log::{LevelFilter, info};
use std::ffi::CString;
use std::os::raw::c_char;
use std::sync::atomic::{AtomicBool, Ordering};
static PROXY_RUNNING: AtomicBool = AtomicBool::new(false);
#[link(name = "byedpi", kind = "static")]
unsafe extern "C" {
static mut server_fd: i32;
static mut optind: i32;
static mut optreset: i32;
fn main(argc: libc::c_int, argv: *const *const c_char) -> libc::c_int;
fn clear_params();
}
fn init_logger() {
android_logger::init_once(Config::default().with_max_level(LevelFilter::Info));
}
#[unsafe(no_mangle)]
pub unsafe extern "system" fn Java_com_cherret_zaprett_byedpi_NativeBridge_jniStartProxy(
mut env: JNIEnv,
_class: JClass,
args: JObjectArray,
) -> jint {
init_logger();
if PROXY_RUNNING.swap(true, Ordering::SeqCst) {
info!("proxy already running");
return -1;
}
let argc = env.get_array_length(&args).unwrap_or(0) as usize;
let mut cstrings: Vec<CString> = Vec::with_capacity(argc);
for i in 0..argc {
let jstr: JString = env
.get_object_array_element(&args, i as i32)
.unwrap()
.into();
let rust_str: String = env.get_string(&jstr).unwrap().into();
cstrings.push(CString::new(rust_str).unwrap());
}
let mut argv: Vec<*const c_char> = cstrings.iter().map(|s| s.as_ptr()).collect();
argv.push(std::ptr::null());
info!("starting proxy");
unsafe {
optind = 1;
optreset = 1;
clear_params();
}
PROXY_RUNNING.store(true, Ordering::SeqCst);
let ret = unsafe { main(argc as i32, argv.as_ptr()) };
PROXY_RUNNING.store(false, Ordering::SeqCst);
ret as jint
}
#[unsafe(no_mangle)]
pub unsafe extern "system" fn Java_com_cherret_zaprett_byedpi_NativeBridge_jniStopProxy(
_env: JNIEnv,
_class: JClass,
) -> jint {
init_logger();
if !PROXY_RUNNING.load(Ordering::SeqCst) {
info!("failed to stop proxy");
return -1;
}
info!("stopping proxy");
let ret = unsafe { shutdown(server_fd, SHUT_RDWR) };
ret as jint
}

6
update.json Normal file
View File

@@ -0,0 +1,6 @@
{
"version": "2.12",
"versionCode": 24,
"downloadUrl": "https://github.com/CherretGit/zaprett-app/releases/download/2.12.0/app-release.apk",
"changelogUrl": "https://raw.githubusercontent.com/CherretGit/zaprett-app/refs/heads/main/changelog.md"
}