forked from starifly/NekoBoxForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigurationFragment.kt
More file actions
2088 lines (1837 loc) · 84.4 KB
/
Copy pathConfigurationFragment.kt
File metadata and controls
2088 lines (1837 loc) · 84.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.nekohasekai.sagernet.ui
import android.content.DialogInterface
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import android.provider.OpenableColumns
import android.text.SpannableStringBuilder
import android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.format.Formatter
import android.text.style.ForegroundColorSpan
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.core.graphics.ColorUtils
import androidx.core.net.toUri
import androidx.core.os.BundleCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.size
import kotlinx.coroutines.delay
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceDataStore
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.card.MaterialCardView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import io.nekohasekai.sagernet.GroupOrder
import io.nekohasekai.sagernet.GroupType
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.TrafficData
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.proto.UrlTest
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProfileManager
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.database.preference.OnPreferenceDataStoreChangeListener
import io.nekohasekai.sagernet.databinding.LayoutProfileListBinding
import io.nekohasekai.sagernet.databinding.LayoutProgressListBinding
import io.nekohasekai.sagernet.fmt.AbstractBean
import io.nekohasekai.sagernet.fmt.toUniversalLink
import io.nekohasekai.sagernet.group.GroupUpdater
import io.nekohasekai.sagernet.group.RawUpdater
import io.nekohasekai.sagernet.ktx.FixedLinearLayoutManager
import io.nekohasekai.sagernet.ktx.FixedGridLayoutManager
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.SubscriptionFoundException
import io.nekohasekai.sagernet.ktx.alert
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.dp2px
import io.nekohasekai.sagernet.ktx.getColorAttr
import io.nekohasekai.sagernet.ktx.getColour
import io.nekohasekai.sagernet.ktx.isIpAddress
import io.nekohasekai.sagernet.ktx.onMainDispatcher
import io.nekohasekai.sagernet.ktx.readableMessage
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import io.nekohasekai.sagernet.ktx.runOnLifecycleDispatcher
import io.nekohasekai.sagernet.ktx.runOnMainDispatcher
import io.nekohasekai.sagernet.ktx.scrollTo
import io.nekohasekai.sagernet.ktx.showAllowingStateLoss
import io.nekohasekai.sagernet.ktx.snackbar
import io.nekohasekai.sagernet.ktx.startFilesForResult
import io.nekohasekai.sagernet.ktx.tryToShow
import io.nekohasekai.sagernet.plugin.PluginManager
import io.nekohasekai.sagernet.ui.profile.ChainSettingsActivity
import io.nekohasekai.sagernet.ui.profile.HttpSettingsActivity
import io.nekohasekai.sagernet.ui.profile.HysteriaSettingsActivity
import io.nekohasekai.sagernet.ui.profile.MasterDnsVpnSettingsActivity
import io.nekohasekai.sagernet.ui.profile.JuicitySettingsActivity
import io.nekohasekai.sagernet.ui.profile.MieruSettingsActivity
import io.nekohasekai.sagernet.ui.profile.NaiveSettingsActivity
import io.nekohasekai.sagernet.ui.profile.SSHSettingsActivity
import io.nekohasekai.sagernet.ui.profile.ShadowsocksSettingsActivity
import io.nekohasekai.sagernet.ui.profile.ShadowsocksRSettingsActivity
import io.nekohasekai.sagernet.ui.profile.SnellSettingsActivity
import io.nekohasekai.sagernet.ui.profile.SocksSettingsActivity
import io.nekohasekai.sagernet.ui.profile.TrojanGoSettingsActivity
import io.nekohasekai.sagernet.ui.profile.TrojanSettingsActivity
import io.nekohasekai.sagernet.ui.profile.TuicSettingsActivity
import io.nekohasekai.sagernet.ui.profile.VMessSettingsActivity
import io.nekohasekai.sagernet.ui.profile.WireGuardSettingsActivity
import io.nekohasekai.sagernet.ui.profile.AmneziaWGSettingsActivity
import io.nekohasekai.sagernet.widget.QRCodeDialog
import io.nekohasekai.sagernet.widget.UndoSnackbarManager
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import moe.matsuri.nb4a.Protocols
import moe.matsuri.nb4a.Protocols.getProtocolColor
import moe.matsuri.nb4a.proxy.anytls.AnyTLSSettingsActivity
import moe.matsuri.nb4a.proxy.config.ConfigSettingActivity
import moe.matsuri.nb4a.proxy.shadowtls.ShadowTLSSettingsActivity
import moe.matsuri.nb4a.ui.ConnectionTestNotification
import java.io.Closeable
import java.net.InetSocketAddress
import java.net.Socket
import java.net.UnknownHostException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
import java.util.zip.ZipInputStream
import kotlin.collections.set
import androidx.appcompat.app.AlertDialog
import io.nekohasekai.sagernet.database.SubscriptionBean
class ConfigurationFragment @JvmOverloads constructor(
val select: Boolean = false, val selectedItem: ProxyEntity? = null, val titleRes: Int = 0
) : ToolbarFragment(R.layout.layout_group_list),
PopupMenu.OnMenuItemClickListener,
Toolbar.OnMenuItemClickListener,
SearchView.OnQueryTextListener,
OnPreferenceDataStoreChangeListener {
interface SelectCallback {
fun returnProfile(profileId: Long)
}
lateinit var adapter: GroupPagerAdapter
lateinit var tabLayout: TabLayout
lateinit var groupPager: ViewPager2
val alwaysShowAddress by lazy { DataStore.alwaysShowAddress }
fun getCurrentGroupFragment(): GroupFragment? {
return try {
childFragmentManager.findFragmentByTag("f" + DataStore.selectedGroup) as GroupFragment?
} catch (e: Exception) {
Logs.e(e)
null
}
}
fun switchAllGroupFragmentsLayout() {
adapter.groupFragments.values.forEach { fragment ->
if (fragment.isAdded && fragment.view != null) {
fragment.switchLayoutMode()
}
}
}
val updateSelectedCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int, positionOffset: Float, positionOffsetPixels: Int
) {
if (adapter.groupList.size > position) {
DataStore.selectedGroup = adapter.groupList[position].id
}
}
}
override fun onQueryTextChange(query: String): Boolean {
getCurrentGroupFragment()?.adapter?.filter(query)
return false
}
override fun onQueryTextSubmit(query: String): Boolean = false
@SuppressLint("DetachAndAttachSameFragment")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
if (savedInstanceState != null) {
parentFragmentManager.beginTransaction()
.setReorderingAllowed(false)
.detach(this)
.attach(this)
.commit()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (!select) {
toolbar.inflateMenu(R.menu.add_profile_menu)
toolbar.menu.findItem(R.id.action_global_mode)?.isChecked = DataStore.globalMode
toolbar.setOnMenuItemClickListener(this)
} else {
toolbar.setTitle(titleRes)
toolbar.setNavigationIcon(R.drawable.ic_navigation_close)
toolbar.setNavigationOnClickListener {
requireActivity().finish()
}
}
val searchView = toolbar.findViewById<SearchView>(R.id.action_search)
if (searchView != null) {
searchView.setOnQueryTextListener(this)
searchView.maxWidth = Int.MAX_VALUE
searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
cancelSearch(searchView)
}
}
}
groupPager = view.findViewById(R.id.group_pager)
tabLayout = view.findViewById(R.id.group_tab)
adapter = GroupPagerAdapter()
ProfileManager.addListener(adapter)
GroupManager.addListener(adapter)
groupPager.adapter = adapter
groupPager.offscreenPageLimit = 2
TabLayoutMediator(tabLayout, groupPager) { tab, position ->
if (adapter.groupList.size > position) {
tab.text = adapter.groupList[position].displayName()
}
tab.view.setOnLongClickListener { // clear toast
true
}
}.attach()
toolbar.setOnClickListener {
val fragment = getCurrentGroupFragment()
if (fragment != null) {
val selectedProxy = selectedItem?.id ?: DataStore.selectedProxy
val selectedProfileIndex =
fragment.adapter!!.configurationIdList.indexOf(selectedProxy)
if (selectedProfileIndex != -1) {
val layoutManager = fragment.layoutManager
if (layoutManager is LinearLayoutManager) {
val first = layoutManager.findFirstVisibleItemPosition()
val last = layoutManager.findLastVisibleItemPosition()
if (selectedProfileIndex !in first..last) {
fragment.configurationListView.scrollTo(selectedProfileIndex, true)
return@setOnClickListener
}
} else {
fragment.configurationListView.scrollTo(selectedProfileIndex, true)
return@setOnClickListener
}
}
fragment.configurationListView.scrollTo(0)
}
}
DataStore.profileCacheStore.registerChangeListener(this)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.action_global_mode)?.isChecked = DataStore.globalMode
super.onPrepareOptionsMenu(menu)
}
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
runOnMainDispatcher {
// editingGroup
if (key == Key.PROFILE_GROUP) {
val targetId = DataStore.editingGroup
if (targetId > 0 && targetId != DataStore.selectedGroup) {
DataStore.selectedGroup = targetId
val targetIndex = adapter.groupList.indexOfFirst { it.id == targetId }
if (targetIndex >= 0) {
groupPager.setCurrentItem(targetIndex, false)
} else {
adapter.reload()
}
}
}
}
}
override fun onDestroy() {
DataStore.profileCacheStore.unregisterChangeListener(this)
if (::adapter.isInitialized) {
GroupManager.removeListener(adapter)
ProfileManager.removeListener(adapter)
}
super.onDestroy()
}
override fun onKeyDown(ketCode: Int, event: KeyEvent): Boolean {
val fragment = getCurrentGroupFragment()
fragment?.configurationListView?.apply {
if (!hasFocus()) requestFocus()
}
return super.onKeyDown(ketCode, event)
}
private val importFile =
registerForActivityResult(ActivityResultContracts.GetContent()) { file ->
if (file != null) runOnDefaultDispatcher {
try {
val fileName =
requireContext().contentResolver.query(file, null, null, null, null)
?.use { cursor ->
cursor.moveToFirst()
cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
.let(cursor::getString)
}
val proxies = mutableListOf<AbstractBean>()
if (fileName != null && fileName.endsWith(".zip")) {
// try parse wireguard zip
val zip =
ZipInputStream(requireContext().contentResolver.openInputStream(file)!!)
while (true) {
val entry = zip.nextEntry ?: break
if (entry.isDirectory) continue
val fileText = zip.bufferedReader().readText()
RawUpdater.parseRaw(fileText, entry.name)
?.let { pl -> proxies.addAll(pl) }
zip.closeEntry()
}
zip.closeQuietly()
} else {
val fileText =
requireContext().contentResolver.openInputStream(file)!!.use {
it.bufferedReader().readText()
}
RawUpdater.parseRaw(fileText, fileName ?: "")
?.let { pl -> proxies.addAll(pl) }
}
if (proxies.isEmpty()) onMainDispatcher {
snackbar(getString(R.string.no_proxies_found_in_file)).show()
} else import(proxies)
} catch (e: SubscriptionFoundException) {
(requireActivity() as MainActivity).importSubscription(e.link.toUri())
} catch (e: Exception) {
Logs.w(e)
onMainDispatcher {
snackbar(e.readableMessage).show()
}
}
}
}
suspend fun import(proxies: List<AbstractBean>) {
val targetId = DataStore.selectedGroupForImport()
for (proxy in proxies) {
ProfileManager.createProfile(targetId, proxy)
}
onMainDispatcher {
DataStore.editingGroup = targetId
snackbar(
requireContext().resources.getQuantityString(
R.plurals.added, proxies.size, proxies.size
)
).show()
}
}
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_scan_qr_code -> {
startActivity(Intent(context, ScannerActivity::class.java))
}
R.id.action_import_clipboard -> {
val text = SagerNet.getClipboardText()
if (text.isBlank()) {
snackbar(getString(R.string.clipboard_empty)).show()
} else runOnDefaultDispatcher {
try {
val proxies = RawUpdater.parseRaw(text)
if (proxies.isNullOrEmpty()) {
onMainDispatcher {
snackbar(getString(R.string.no_proxies_found_in_clipboard)).show()
}
} else {
import(proxies)
}
} catch (e: SubscriptionFoundException) {
onMainDispatcher {
if (e.link.startsWith("sn://")) {
(requireActivity() as MainActivity).importSubscription(e.link.toUri())
} else {
val subscriptionLink = Uri.parse(e.link).getQueryParameter("url") ?: e.link
val group = ProxyGroup(type = GroupType.SUBSCRIPTION)
val subscription = SubscriptionBean()
group.subscription = subscription
subscription.link = subscriptionLink
subscription.autoUpdate = false
group.name = ""
startActivity(Intent(requireContext(), GroupSettingsActivity::class.java).apply {
putExtra(GroupSettingsActivity.EXTRA_FROM_CLIPBOARD, true)
putExtra(GroupSettingsActivity.EXTRA_GROUP_SUBSCRIPTION_LINK, subscriptionLink)
})
}
}
} catch (e: Exception) {
Logs.w(e)
onMainDispatcher {
snackbar(e.readableMessage).show()
}
}
}
}
R.id.action_import_file -> {
startFilesForResult(importFile, "*/*")
}
R.id.action_new_socks -> {
startActivity(Intent(requireActivity(), SocksSettingsActivity::class.java))
}
R.id.action_new_http -> {
startActivity(Intent(requireActivity(), HttpSettingsActivity::class.java))
}
R.id.action_new_ss -> {
startActivity(Intent(requireActivity(), ShadowsocksSettingsActivity::class.java))
}
R.id.action_new_ssr -> {
startActivity(Intent(requireActivity(), ShadowsocksRSettingsActivity::class.java))
}
R.id.action_new_vmess -> {
startActivity(Intent(requireActivity(), VMessSettingsActivity::class.java))
}
R.id.action_new_vless -> {
startActivity(Intent(requireActivity(), VMessSettingsActivity::class.java).apply {
putExtra("vless", true)
})
}
R.id.action_new_trojan -> {
startActivity(Intent(requireActivity(), TrojanSettingsActivity::class.java))
}
R.id.action_new_trojan_go -> {
startActivity(Intent(requireActivity(), TrojanGoSettingsActivity::class.java))
}
R.id.action_new_mieru -> {
startActivity(Intent(requireActivity(), MieruSettingsActivity::class.java))
}
R.id.action_new_naive -> {
startActivity(Intent(requireActivity(), NaiveSettingsActivity::class.java))
}
R.id.action_new_hysteria -> {
startActivity(Intent(requireActivity(), HysteriaSettingsActivity::class.java))
}
R.id.action_new_tuic -> {
startActivity(Intent(requireActivity(), TuicSettingsActivity::class.java))
}
R.id.action_new_juicity -> {
startActivity(Intent(requireActivity(), JuicitySettingsActivity::class.java))
}
R.id.action_new_ssh -> {
startActivity(Intent(requireActivity(), SSHSettingsActivity::class.java))
}
R.id.action_new_snell -> {
startActivity(Intent(requireActivity(), SnellSettingsActivity::class.java))
}
R.id.action_new_masterdnsvpn -> {
startActivity(Intent(requireActivity(), MasterDnsVpnSettingsActivity::class.java))
}
R.id.action_new_wg -> {
startActivity(Intent(requireActivity(), WireGuardSettingsActivity::class.java))
}
R.id.action_new_awg -> {
startActivity(Intent(requireActivity(), AmneziaWGSettingsActivity::class.java))
}
R.id.action_new_shadowtls -> {
startActivity(Intent(requireActivity(), ShadowTLSSettingsActivity::class.java))
}
R.id.action_new_anytls -> {
startActivity(Intent(requireActivity(), AnyTLSSettingsActivity::class.java))
}
R.id.action_new_config -> {
startActivity(Intent(requireActivity(), ConfigSettingActivity::class.java))
}
R.id.action_new_chain -> {
startActivity(Intent(requireActivity(), ChainSettingsActivity::class.java))
}
R.id.action_update_subscription -> {
val group = DataStore.currentGroup()
if (group.type != GroupType.SUBSCRIPTION) {
snackbar(R.string.group_not_subscription).show()
Logs.e("onMenuItemClick: Group(${group.displayName()}) is not subscription")
} else {
runOnLifecycleDispatcher {
GroupUpdater.startUpdate(group, true)
}
}
}
R.id.action_clear_traffic_statistics -> {
runOnDefaultDispatcher {
val profiles = SagerDatabase.proxyDao.getByGroup(DataStore.currentGroupId())
val toClear = mutableListOf<ProxyEntity>()
if (profiles.isNotEmpty()) for (profile in profiles) {
if (profile.tx != 0L || profile.rx != 0L) {
profile.tx = 0
profile.rx = 0
toClear.add(profile)
}
}
if (toClear.isNotEmpty()) {
ProfileManager.updateProfile(toClear)
}
}
}
R.id.action_connection_test_clear_results -> {
runOnDefaultDispatcher {
val profiles = SagerDatabase.proxyDao.getByGroup(DataStore.currentGroupId())
val toClear = mutableListOf<ProxyEntity>()
if (profiles.isNotEmpty()) for (profile in profiles) {
if (profile.status != 0) {
profile.status = 0
profile.ping = 0
profile.error = null
toClear.add(profile)
}
}
if (toClear.isNotEmpty()) {
ProfileManager.updateProfile(toClear)
}
}
}
R.id.action_connection_test_delete_unavailable -> {
runOnDefaultDispatcher {
val profiles = SagerDatabase.proxyDao.getByGroup(DataStore.currentGroupId())
val toClear = mutableListOf<ProxyEntity>()
if (profiles.isNotEmpty()) for (profile in profiles) {
if (profile.status != 0 && profile.status != 1) {
toClear.add(profile)
}
}
if (toClear.isNotEmpty()) {
onMainDispatcher {
MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.confirm)
.setMessage(R.string.delete_confirm_prompt)
.setPositiveButton(R.string.yes) { _, _ ->
for (profile in toClear) {
adapter.groupFragments[DataStore.selectedGroup]?.adapter?.apply {
val index = configurationIdList.indexOf(profile.id)
if (index >= 0) {
configurationIdList.removeAt(index)
configurationList.remove(profile.id)
notifyItemRemoved(index)
}
}
}
runOnDefaultDispatcher {
for (profile in toClear) {
ProfileManager.deleteProfile2(
profile.groupId, profile.id
)
}
}
}
.setNegativeButton(R.string.no, null)
.show()
}
}
}
}
R.id.action_remove_duplicate -> {
runOnDefaultDispatcher {
val profiles = SagerDatabase.proxyDao.getByGroup(DataStore.currentGroupId())
val toClear = mutableListOf<ProxyEntity>()
val uniqueProxies = LinkedHashSet<Protocols.Deduplication>()
for (pf in profiles) {
val proxy = Protocols.Deduplication(pf.requireBean(), pf.displayType())
if (!uniqueProxies.add(proxy)) {
toClear += pf
}
}
if (toClear.isNotEmpty()) {
onMainDispatcher {
MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.confirm)
.setMessage(
getString(R.string.delete_confirm_prompt) + "\n" +
toClear.mapIndexedNotNull { index, proxyEntity ->
if (index < 20) {
proxyEntity.displayName()
} else if (index == 20) {
"......"
} else {
null
}
}.joinToString("\n")
)
.setPositiveButton(R.string.yes) { _, _ ->
for (profile in toClear) {
adapter.groupFragments[DataStore.selectedGroup]?.adapter?.apply {
val index = configurationIdList.indexOf(profile.id)
if (index >= 0) {
configurationIdList.removeAt(index)
configurationList.remove(profile.id)
notifyItemRemoved(index)
}
}
}
runOnDefaultDispatcher {
for (profile in toClear) {
ProfileManager.deleteProfile2(
profile.groupId, profile.id
)
}
}
}
.setNegativeButton(R.string.no, null)
.show()
}
}
}
}
R.id.action_connection_tcp_ping -> {
pingTest(false)
}
R.id.action_connection_url_test -> {
urlTest()
}
R.id.action_global_mode -> {
item.isChecked = !item.isChecked
DataStore.globalMode = item.isChecked
if (DataStore.serviceState.canStop) {
runOnDefaultDispatcher {
try {
// wait a while to ensure the config has been saved
delay(500)
snackbar(getString(R.string.need_reload)).setAction(R.string.apply) {
runOnDefaultDispatcher {
try {
// wait again to ensure the config has been saved
delay(100)
SagerNet.reloadService()
} catch (e: Exception) {
Logs.w(e)
onMainDispatcher {
snackbar(getString(R.string.service_failed)).show()
}
}
}
}.show()
} catch (e: Exception) {
Logs.w(e)
onMainDispatcher {
snackbar(getString(R.string.service_failed)).show()
}
}
}
}
return true
}
}
return false
}
inner class TestDialog {
val binding = LayoutProgressListBinding.inflate(layoutInflater)
val builder = MaterialAlertDialogBuilder(requireContext()).setView(binding.root)
.setPositiveButton(R.string.minimize) { _, _ ->
minimize()
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
cancel()
}
.setCancelable(false)
lateinit var cancel: () -> Unit
lateinit var minimize: () -> Unit
val dialogStatus = AtomicInteger(0) // 1: hidden 2: cancelled
var notification: ConnectionTestNotification? = null
val results: MutableSet<ProxyEntity> = ConcurrentHashMap.newKeySet()
var proxyN = 0
val finishedN = AtomicInteger(0)
fun update(profile: ProxyEntity) {
if (dialogStatus.get() != 2) {
results.add(profile)
}
runOnMainDispatcher {
val context = context ?: return@runOnMainDispatcher
val progress = finishedN.addAndGet(1)
val status = dialogStatus.get()
notification?.updateNotification(
progress,
proxyN,
progress >= proxyN || status == 2
)
if (status >= 1) return@runOnMainDispatcher
if (!isAdded) return@runOnMainDispatcher
// refresh dialog
var profileStatusText: String? = null
var profileStatusColor = 0
when (profile.status) {
-1 -> {
profileStatusText = profile.error
profileStatusColor = context.getColorAttr(android.R.attr.textColorSecondary)
}
0 -> {
profileStatusText = getString(R.string.connection_test_testing)
profileStatusColor = context.getColorAttr(android.R.attr.textColorSecondary)
}
1 -> {
profileStatusText = getString(R.string.available, profile.ping)
profileStatusColor = context.getColour(R.color.material_green_500)
}
2 -> {
profileStatusText = profile.error
profileStatusColor = context.getColorAttr(R.attr.testFailColor)
}
3 -> {
val err = profile.error ?: ""
val msg = Protocols.genFriendlyMsg(err)
profileStatusText = if (msg != err) msg else getString(R.string.unavailable)
profileStatusColor = context.getColorAttr(R.attr.testFailColor)
}
}
val text = SpannableStringBuilder().apply {
append("\n" + profile.displayName())
append("\n")
append(
profile.displayType(),
ForegroundColorSpan(context.getProtocolColor(profile.type)),
SPAN_EXCLUSIVE_EXCLUSIVE
)
append(" ")
append(
profileStatusText,
ForegroundColorSpan(profileStatusColor),
SPAN_EXCLUSIVE_EXCLUSIVE
)
append("\n")
}
binding.nowTesting.text = text
binding.progress.text = "$progress / $proxyN"
}
}
}
@OptIn(DelicateCoroutinesApi::class)
@Suppress("EXPERIMENTAL_API_USAGE")
fun pingTest(icmpPing: Boolean) {
if (DataStore.runningTest) return else DataStore.runningTest = true
val test = TestDialog()
val dialog = test.builder.show()
val testJobs = mutableListOf<Job>()
val group = DataStore.currentGroup()
val mainJob = runOnDefaultDispatcher {
val profilesList = SagerDatabase.proxyDao.getByGroup(group.id).filter {
if (icmpPing) {
if (it.requireBean().canICMPing()) {
return@filter true
}
} else {
if (it.requireBean().canTCPing()) {
return@filter true
}
}
return@filter false
}
test.proxyN = profilesList.size
val profiles = ConcurrentLinkedQueue(profilesList)
repeat(DataStore.connectionTestConcurrent) {
testJobs.add(launch(Dispatchers.IO) {
while (isActive) {
val profile = profiles.poll() ?: break
profile.status = 0
var address = profile.requireBean().serverAddress
if (!address.isIpAddress()) {
try {
SagerNet.underlyingNetwork!!.getAllByName(address).apply {
if (isNotEmpty()) {
address = this[0].hostAddress
}
}
} catch (ignored: UnknownHostException) {
}
}
if (!isActive) break
if (!address.isIpAddress()) {
profile.status = 2
profile.error = app.getString(R.string.connection_test_domain_not_found)
test.update(profile)
continue
}
try {
if (icmpPing) {
// removed
} else {
val socket =
SagerNet.underlyingNetwork?.socketFactory?.createSocket()
?: Socket()
try {
socket.soTimeout = 3000
socket.bind(InetSocketAddress(0))
val start = SystemClock.elapsedRealtime()
socket.connect(
InetSocketAddress(
address, profile.requireBean().serverPort
), 3000
)
if (!isActive) break
profile.status = 1
profile.ping = (SystemClock.elapsedRealtime() - start).toInt()
// Clear any stale error from a previous failed test.
profile.error = null
test.update(profile)
} finally {
socket.closeQuietly()
}
}
} catch (e: Exception) {
if (!isActive) break
val message = e.readableMessage
if (icmpPing) {
profile.status = 2
profile.error = getString(R.string.connection_test_unreachable)
} else {
profile.status = 2
when {
!message.contains("failed:") -> profile.error =
getString(R.string.connection_test_timeout_error)
else -> when {
message.contains("ECONNREFUSED") -> {
profile.error =
getString(R.string.connection_test_refused)
}
message.contains("ENETUNREACH") -> {
profile.error =
getString(R.string.connection_test_unreachable)
}
else -> {
profile.status = 3
profile.error = message
}
}
}
}
test.update(profile)
}
}
})
}
testJobs.joinAll()
runOnMainDispatcher {
test.cancel()
}
}
test.cancel = {
test.dialogStatus.set(2)
try { dialog.dismiss() } catch (e: IllegalStateException) { Logs.w(e) } // dialog window may be gone after rotation (#1141)
runOnDefaultDispatcher {
mainJob.cancel()
testJobs.forEach { it.cancel() }
test.results.forEach {
try {
ProfileManager.updateProfile(it)
} catch (e: Exception) {
Logs.w(e)
}
}
GroupManager.postReload(DataStore.currentGroupId())
DataStore.runningTest = false
}
}
test.minimize = {
test.dialogStatus.set(1)
test.notification = ConnectionTestNotification(
dialog.context,
"[${group.displayName()}] ${getString(R.string.connection_test)}"
)
dialog.hide()
}
}
@OptIn(DelicateCoroutinesApi::class)
fun urlTest() {
if (DataStore.runningTest) return else DataStore.runningTest = true
val test = TestDialog()
val dialog = test.builder.show()
val testJobs = mutableListOf<Job>()
val group = DataStore.currentGroup()
val mainJob = runOnDefaultDispatcher {
val profilesList = SagerDatabase.proxyDao.getByGroup(group.id)
test.proxyN = profilesList.size
val profiles = ConcurrentLinkedQueue(profilesList)
repeat(DataStore.connectionTestConcurrent) {
testJobs.add(launch(Dispatchers.IO) {
val urlTest = UrlTest() // note: this is NOT in bg process
while (isActive) {
val profile = profiles.poll() ?: break
profile.status = 0
try {
val result = urlTest.doTest(profile)
profile.status = 1
profile.ping = result
// Clear any stale error from a previous failed test so a now-passing
// profile doesn't keep showing an old failure message.
profile.error = null
} catch (e: PluginManager.PluginNotFoundException) {
if (!isActive) break
profile.status = 2
profile.error = e.readableMessage
} catch (e: Exception) {
// A cancelled test (dialog cancel / teardown) kills the sidecar
// mid-handshake and throws here. Don't record that as a profile
// failure — it isn't one. The pingTest path guards the same way.
if (!isActive) break
profile.status = 3
profile.error = e.readableMessage
}
if (!isActive) break
test.update(profile)
}
})
}
testJobs.joinAll()
runOnMainDispatcher {
test.cancel()
}
}
test.cancel = {
test.dialogStatus.set(2)
try { dialog.dismiss() } catch (e: IllegalStateException) { Logs.w(e) } // dialog window may be gone after rotation (#1141)
runOnDefaultDispatcher {
mainJob.cancel()