forked from starifly/NekoBoxForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupSettingsActivity.kt
More file actions
449 lines (395 loc) · 17.3 KB
/
Copy pathGroupSettingsActivity.kt
File metadata and controls
449 lines (395 loc) · 17.3 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
package io.nekohasekai.sagernet.ui
import android.annotation.SuppressLint
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AlertDialog
import androidx.core.view.ViewCompat
import androidx.preference.*
import com.github.shadowsocks.plugin.Empty
import com.github.shadowsocks.plugin.fragment.AlertDialogFragment
import io.nekohasekai.sagernet.GroupType
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.SubscriptionFilterMode
import io.nekohasekai.sagernet.database.*
import io.nekohasekai.sagernet.database.preference.OnPreferenceDataStoreChangeListener
import io.nekohasekai.sagernet.group.GroupUpdater
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.applyDefaultValues
import io.nekohasekai.sagernet.ktx.onMainDispatcher
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import io.nekohasekai.sagernet.widget.ListListener
import io.nekohasekai.sagernet.widget.OutboundPreference
import kotlinx.parcelize.Parcelize
import moe.matsuri.nb4a.ui.SimpleMenuPreference
@Suppress("UNCHECKED_CAST")
class GroupSettingsActivity(
@LayoutRes resId: Int = R.layout.layout_config_settings,
) : ThemedActivity(resId),
OnPreferenceDataStoreChangeListener {
private lateinit var frontProxyPreference: OutboundPreference
private lateinit var landingProxyPreference: OutboundPreference
fun ProxyGroup.init() {
DataStore.groupName = name ?: ""
DataStore.groupType = type
DataStore.groupOrder = order
DataStore.groupIsSelector = isSelector
DataStore.frontProxy = frontProxy
DataStore.landingProxy = landingProxy
DataStore.frontProxyTmp =
if (frontProxy >= 0) OutboundPreference.VALUE_SELECT_PROFILE.toInt() else 0
DataStore.landingProxyTmp =
if (landingProxy >= 0) OutboundPreference.VALUE_SELECT_PROFILE.toInt() else 0
val subscription = subscription ?: SubscriptionBean().applyDefaultValues()
DataStore.subscriptionLink = subscription.link
DataStore.subscriptionForceResolve = subscription.forceResolve
DataStore.subscriptionDeduplication = subscription.deduplication
DataStore.subscriptionUpdateWhenConnectedOnly = subscription.updateWhenConnectedOnly
DataStore.subscriptionUserAgent = subscription.customUserAgent
DataStore.subscriptionAutoUpdate = subscription.autoUpdate
DataStore.subscriptionAutoUpdateDelay = subscription.autoUpdateDelay
DataStore.subscriptionFilterMode = subscription.filterMode
DataStore.subscriptionFilterRegex = subscription.filterRegex
}
fun ProxyGroup.serialize() {
name = DataStore.groupName.takeIf { it.isNotBlank() } ?: "My group"
type = DataStore.groupType
order = DataStore.groupOrder
isSelector = DataStore.groupIsSelector
frontProxy =
if (DataStore.frontProxyTmp == OutboundPreference.VALUE_SELECT_PROFILE.toInt()) {
DataStore.frontProxy
} else {
-1
}
landingProxy =
if (DataStore.landingProxyTmp == OutboundPreference.VALUE_SELECT_PROFILE.toInt()) {
DataStore.landingProxy
} else {
-1
}
val isSubscription = type == GroupType.SUBSCRIPTION
if (isSubscription) {
subscription = (subscription ?: SubscriptionBean().applyDefaultValues()).apply {
link = DataStore.subscriptionLink
forceResolve = DataStore.subscriptionForceResolve
deduplication = DataStore.subscriptionDeduplication
updateWhenConnectedOnly = DataStore.subscriptionUpdateWhenConnectedOnly
customUserAgent = DataStore.subscriptionUserAgent
autoUpdate = DataStore.subscriptionAutoUpdate
autoUpdateDelay = DataStore.subscriptionAutoUpdateDelay
filterMode = DataStore.subscriptionFilterMode
filterRegex = DataStore.subscriptionFilterRegex
}
}
}
private var isFromClipboard = false
fun needSave(): Boolean {
return DataStore.dirty
}
fun PreferenceFragmentCompat.createPreferences(
savedInstanceState: Bundle?,
rootKey: String?,
) {
addPreferencesFromResource(R.xml.group_preferences)
frontProxyPreference = findPreference(Key.GROUP_FRONT_PROXY)!!
frontProxyPreference.apply {
setEntries(R.array.front_proxy_entry)
setEntryValues(R.array.front_proxy_value)
setOnPreferenceChangeListener { _, newValue ->
if (newValue.toString() == OutboundPreference.VALUE_SELECT_PROFILE) {
selectProfileForAddFront.launch(
Intent(
this@GroupSettingsActivity, ProfileSelectActivity::class.java
).apply {
ProfileManager.getProfile(DataStore.frontProxy)?.let {
putExtra(ProfileSelectActivity.EXTRA_SELECTED, it)
}
}
)
false
} else {
true
}
}
}
landingProxyPreference = findPreference(Key.GROUP_LANDING_PROXY)!!
landingProxyPreference.apply {
setEntries(R.array.front_proxy_entry)
setEntryValues(R.array.front_proxy_value)
setOnPreferenceChangeListener { _, newValue ->
if (newValue.toString() == OutboundPreference.VALUE_SELECT_PROFILE) {
selectProfileForAddLanding.launch(
Intent(
this@GroupSettingsActivity, ProfileSelectActivity::class.java
).apply {
ProfileManager.getProfile(DataStore.landingProxy)?.let {
putExtra(ProfileSelectActivity.EXTRA_SELECTED, it)
}
}
)
false
} else {
true
}
}
}
val groupType = findPreference<SimpleMenuPreference>(Key.GROUP_TYPE)!!
val groupSubscription = findPreference<PreferenceCategory>(Key.GROUP_SUBSCRIPTION)!!
val subscriptionUpdate = findPreference<PreferenceCategory>(Key.SUBSCRIPTION_UPDATE)!!
fun updateGroupType(groupType: Int = DataStore.groupType) {
val isSubscription = groupType == GroupType.SUBSCRIPTION
groupSubscription.isVisible = isSubscription
subscriptionUpdate.isVisible = isSubscription
}
updateGroupType()
groupType.setOnPreferenceChangeListener { _, newValue ->
updateGroupType((newValue as String).toInt())
true
}
val subscriptionAutoUpdate =
findPreference<SwitchPreference>(Key.SUBSCRIPTION_AUTO_UPDATE)!!
val subscriptionAutoUpdateDelay =
findPreference<EditTextPreference>(Key.SUBSCRIPTION_AUTO_UPDATE_DELAY)!!
subscriptionAutoUpdateDelay.isEnabled = subscriptionAutoUpdate.isChecked
subscriptionAutoUpdateDelay.setOnPreferenceChangeListener { _, newValue ->
val delay = (newValue as String).toIntOrNull()
if (delay == null) {
false
} else {
delay >= 15
}
}
subscriptionAutoUpdate.setOnPreferenceChangeListener { _, newValue ->
subscriptionAutoUpdateDelay.isEnabled = (newValue as Boolean)
true
}
val subscriptionFilterMode =
findPreference<SimpleMenuPreference>(Key.SUBSCRIPTION_FILTER_MODE)!!
val subscriptionFilterRegex =
findPreference<EditTextPreference>(Key.SUBSCRIPTION_FILTER_REGEX)!!
fun updateFilterMode(filterMode: Int = DataStore.subscriptionFilterMode) {
subscriptionFilterRegex.isVisible = filterMode != SubscriptionFilterMode.DISABLED
}
updateFilterMode()
subscriptionFilterMode.setOnPreferenceChangeListener { _, newValue ->
updateFilterMode((newValue as String).toInt())
true
}
}
class UnsavedChangesDialogFragment : AlertDialogFragment<Empty, Empty>() {
override fun AlertDialog.Builder.prepare(listener: DialogInterface.OnClickListener) {
setTitle(R.string.unsaved_changes_prompt)
setPositiveButton(R.string.yes) { _, _ ->
runOnDefaultDispatcher {
(requireActivity() as GroupSettingsActivity).saveAndExit()
}
}
setNegativeButton(R.string.no) { _, _ ->
requireActivity().finish()
}
setNeutralButton(android.R.string.cancel, null)
}
}
@Parcelize
data class GroupIdArg(val groupId: Long) : Parcelable
class DeleteConfirmationDialogFragment : AlertDialogFragment<GroupIdArg, Empty>() {
override fun AlertDialog.Builder.prepare(listener: DialogInterface.OnClickListener) {
setTitle(R.string.delete_group_prompt)
setPositiveButton(R.string.yes) { _, _ ->
runOnDefaultDispatcher {
GroupManager.deleteGroup(arg.groupId)
}
requireActivity().finish()
}
setNegativeButton(R.string.no, null)
}
}
companion object {
const val EXTRA_GROUP_ID = "id"
const val EXTRA_FROM_CLIPBOARD = "fromClipboard"
const val EXTRA_GROUP_SUBSCRIPTION_LINK = "subscription_link"
}
@SuppressLint("CommitTransaction")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onBackPressedDispatcher.addCallback(this) {
if (needSave()) {
UnsavedChangesDialogFragment().apply { key() }.show(supportFragmentManager, null)
} else finish()
}
setSupportActionBar(findViewById(R.id.toolbar))
supportActionBar?.apply {
setTitle(R.string.group_settings)
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_navigation_close)
}
if (savedInstanceState == null) {
val editingId = intent.getLongExtra(EXTRA_GROUP_ID, 0L)
isFromClipboard = intent.getBooleanExtra(EXTRA_FROM_CLIPBOARD, false)
val subscriptionLink = intent.getStringExtra(EXTRA_GROUP_SUBSCRIPTION_LINK)
DataStore.editingId = editingId
runOnDefaultDispatcher {
if (editingId == 0L) {
val group = ProxyGroup()
group.init()
// if there's a subscription link, set it to subscription type and fill in the link
if (!subscriptionLink.isNullOrEmpty()) {
DataStore.groupType = GroupType.SUBSCRIPTION
DataStore.subscriptionLink = subscriptionLink
DataStore.dirty = true
}
} else {
val entity = SagerDatabase.groupDao.getById(editingId)
if (entity == null) {
onMainDispatcher {
finish()
}
return@runOnDefaultDispatcher
}
entity.init()
}
onMainDispatcher {
supportFragmentManager.beginTransaction()
.replace(R.id.settings, MyPreferenceFragmentCompat())
.commit()
DataStore.dirty = false
DataStore.profileCacheStore.registerChangeListener(this@GroupSettingsActivity)
}
}
}
}
suspend fun saveAndExit() {
val editingId = DataStore.editingId
if (editingId == 0L) {
val newGroup = GroupManager.createGroup(ProxyGroup().apply { serialize() })
if (isFromClipboard && newGroup.type == GroupType.SUBSCRIPTION && !newGroup.subscription?.link.isNullOrEmpty()) {
GroupUpdater.startUpdate(newGroup, true)
}
} else if (needSave()) {
val entity = SagerDatabase.groupDao.getById(DataStore.editingId)
if (entity == null) {
finish()
return
}
val keepUserInfo = (entity.type == GroupType.SUBSCRIPTION &&
DataStore.groupType == GroupType.SUBSCRIPTION &&
entity.subscription?.link == DataStore.subscriptionLink)
if (!keepUserInfo) {
entity.subscription?.subscriptionUserinfo = "";
}
GroupManager.updateGroup(entity.apply { serialize() })
}
finish()
}
val child by lazy { supportFragmentManager.findFragmentById(R.id.settings) as MyPreferenceFragmentCompat }
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.profile_config_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = child.onOptionsItemSelected(item)
override fun onSupportNavigateUp(): Boolean {
// Route the action-bar up button through the back dispatcher so it honors the
// unsaved-changes guard instead of finishing directly (avoids data loss).
onBackPressedDispatcher.onBackPressed()
return true
}
override fun onDestroy() {
DataStore.profileCacheStore.unregisterChangeListener(this)
super.onDestroy()
}
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
if (key != Key.PROFILE_DIRTY) {
DataStore.dirty = true
}
}
class MyPreferenceFragmentCompat : PreferenceFragmentCompat() {
var activity: GroupSettingsActivity? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
preferenceManager.preferenceDataStore = DataStore.profileCacheStore
try {
activity = (requireActivity() as GroupSettingsActivity).apply {
createPreferences(savedInstanceState, rootKey)
}
} catch (e: Exception) {
Toast.makeText(
SagerNet.application,
"Error on createPreferences, please try again.",
Toast.LENGTH_SHORT
).show()
Logs.e(e)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ViewCompat.setOnApplyWindowInsetsListener(listView, ListListener)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_delete -> {
if (DataStore.editingId == 0L) {
requireActivity().finish()
} else {
DeleteConfirmationDialogFragment().apply {
arg(GroupIdArg(DataStore.editingId))
key()
}.show(parentFragmentManager, null)
}
true
}
R.id.action_apply -> {
runOnDefaultDispatcher {
activity?.saveAndExit()
}
true
}
else -> false
}
}
object PasswordSummaryProvider : Preference.SummaryProvider<EditTextPreference> {
override fun provideSummary(preference: EditTextPreference): CharSequence {
val text = preference.text
return if (text.isNullOrBlank()) {
preference.context.getString(androidx.preference.R.string.not_set)
} else {
"\u2022".repeat(text.length)
}
}
}
val selectProfileForAddFront = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode == Activity.RESULT_OK) runOnDefaultDispatcher {
val profile = ProfileManager.getProfile(
it.data!!.getLongExtra(ProfileSelectActivity.EXTRA_PROFILE_ID, 0)
) ?: return@runOnDefaultDispatcher
DataStore.frontProxy = profile.id
onMainDispatcher {
frontProxyPreference.value = OutboundPreference.VALUE_SELECT_PROFILE
}
}
}
val selectProfileForAddLanding = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode == Activity.RESULT_OK) runOnDefaultDispatcher {
val profile = ProfileManager.getProfile(
it.data!!.getLongExtra(ProfileSelectActivity.EXTRA_PROFILE_ID, 0)
) ?: return@runOnDefaultDispatcher
DataStore.landingProxy = profile.id
onMainDispatcher {
landingProxyPreference.value = OutboundPreference.VALUE_SELECT_PROFILE
}
}
}
}