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
package com.vauth.foxyvpn.ui.screens
import com.vauth.foxyvpn.ui.l10n.s
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
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.draw.clip
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.vauth.foxyvpn.data.FxaAuthRepository
import com.vauth.foxyvpn.data.GUARDIAN_ENDPOINT_DEFAULT
import com.vauth.foxyvpn.data.GuardianClient
import com.vauth.foxyvpn.data.TokenStore
import com.vauth.foxyvpn.data.formatBytes
import com.vauth.foxyvpn.data.formatBytesPerSecond
import com.vauth.foxyvpn.data.model.AccountLiveStats
import com.vauth.foxyvpn.data.model.BatchImportItemResult
import com.vauth.foxyvpn.data.model.VpnAccount
import com.vauth.foxyvpn.ui.theme.AppearanceController
import com.vauth.foxyvpn.vpn.FoxyVpnService
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun AccountScreen(
authRepository: FxaAuthRepository,
tokenStore: TokenStore,
appearance: AppearanceController,
onBack: () -> Unit,
) {
val scope = rememberCoroutineScope()
val accounts by tokenStore.accountsFlow.collectAsState()
val liveStats by FoxyVpnService.multiAccountStats.collectAsState()
val usage by tokenStore.usageFlow.collectAsState()
val statsById = remember(liveStats) { liveStats.associateBy { it.accountId } }
var showImportSheet by remember { mutableStateOf(false) }
var showLoginDialog by remember { mutableStateOf(false) }
var refreshingQuotas by remember { mutableStateOf(false) }
var banner by remember { mutableStateOf<String?>(null) }
var pendingDelete by remember { mutableStateOf<VpnAccount?>(null) }
fun doDelete(account: VpnAccount) {
tokenStore.removeAccount(account.id)
}
fun refreshQuotas() {
refreshingQuotas = true
banner = null
scope.launch {
var ok = 0
for (account in tokenStore.getAccounts()) {
val renewed = runCatching {
authRepository.ensureFreshAccessTokenForAccount(account, force = false)
}.getOrNull() ?: account.auth
val entitlement = runCatching {
GuardianClient().fetchUserInfo(GUARDIAN_ENDPOINT_DEFAULT, renewed.accessToken)
}.getOrNull()
if (entitlement != null) {
tokenStore.updateAccount(
account.copy(
auth = renewed,
quotaRemaining = entitlement.quotaRemaining,
uid = entitlement.uid.ifBlank { null },
lastError = null,
),
)
// Server quota is authoritative — drop locally counted usage.
tokenStore.resetUsedBytes(account.id)
ok++
} else {
tokenStore.updateAccount(account.copy(lastError = "Quota refresh failed"))
}
}
banner = "Updated $ok of ${tokenStore.getAccounts().size} account(s)."
refreshingQuotas = false
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(s("Accounts"), style = MaterialTheme.typography.titleLargeEmphasized) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = { refreshQuotas() }, enabled = !refreshingQuotas) {
if (refreshingQuotas) {
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
} else {
Icon(Icons.Filled.Refresh, contentDescription = "Refresh quotas")
}
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(horizontal = 16.dp)
.widthIn(max = 560.dp),
) {
banner?.let {
Spacer(Modifier.height(8.dp))
Surface(
shape = RoundedCornerShape(20.dp),
color = MaterialTheme.colorScheme.secondaryContainer,
modifier = Modifier.fillMaxWidth(),
) {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
)
}
}
Spacer(Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(
onClick = { showImportSheet = true },
modifier = Modifier.weight(1f),
) {
Icon(Icons.Filled.ContentPaste, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(s("Batch import"))
}
FilledTonalButton(
onClick = { showLoginDialog = true },
modifier = Modifier.weight(1f),
) {
Icon(Icons.Filled.Add, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(s("Add account"))
}
}
Spacer(Modifier.height(12.dp))
if (accounts.isEmpty()) {
EmptyAccountsHint()
} else {
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(accounts, key = { it.id }) { account ->
AccountCard(
account = account,
stats = statsById[account.id],
usedBytes = usage[account.id] ?: 0L,
corner = appearance.personalization.cornerStyle.cardDp.dp,
onToggle = { tokenStore.toggleAccount(account.id, !account.isEnabled) },
onDelete = {
if (appearance.confirmRemove) pendingDelete = account
else doDelete(account)
},
)
}
item { Spacer(Modifier.height(16.dp)) }
}
}
}
}
pendingDelete?.let { account ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { pendingDelete = null },
title = { Text(s("Remove account?")) },
text = { Text("Remove ${account.email.ifBlank { "this account" }} from the app?") },
confirmButton = {
TextButton(
onClick = {
doDelete(account)
pendingDelete = null
},
) { Text(s("Remove"), color = MaterialTheme.colorScheme.error) }
},
dismissButton = {
TextButton(onClick = { pendingDelete = null }) { Text(s("Cancel")) }
},
)
}
if (showImportSheet) {
BatchImportBottomSheet(
authRepository = authRepository,
onDismiss = { showImportSheet = false },
)
}
if (showLoginDialog) {
SingleAccountLoginDialog(
authRepository = authRepository,
onDismiss = { showLoginDialog = false },
)
}
}
@Composable
private fun EmptyAccountsHint() {
val cs = MaterialTheme.colorScheme
Surface(
shape = RoundedCornerShape(28.dp),
color = cs.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth(),
) {
Column(
Modifier.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
Icons.Filled.AccountCircle,
contentDescription = null,
modifier = Modifier.size(48.dp),
tint = cs.primary,
)
Spacer(Modifier.height(12.dp))
Text(
"No accounts yet",
style = MaterialTheme.typography.titleMediumEmphasized,
)
Spacer(Modifier.height(4.dp))
Text(
"Add one account or paste a whole list — each gets its own VPN session and they share the load.",
style = MaterialTheme.typography.bodyMedium,
color = cs.onSurfaceVariant,
textAlign = TextAlign.Center,
)
}
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun AccountCard(
account: VpnAccount,
stats: AccountLiveStats?,
usedBytes: Long,
corner: androidx.compose.ui.unit.Dp,
onToggle: () -> Unit,
onDelete: () -> Unit,
) {
val cs = MaterialTheme.colorScheme
val dotTarget = when {
!account.isEnabled -> cs.outlineVariant
stats?.isExhausted == true -> cs.error
stats?.isConnected == true -> cs.primary
else -> cs.outline
}
val dot by animateColorAsState(dotTarget, tween(300), label = "card-dot")
Surface(
shape = RoundedCornerShape(corner),
color = cs.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(
Modifier
.size(12.dp)
.clip(CircleShape)
.background(dot),
)
Spacer(Modifier.width(10.dp))
Text(
account.email.ifBlank { "Account" },
style = MaterialTheme.typography.titleSmallEmphasized,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Switch(checked = account.isEnabled, onCheckedChange = { onToggle() })
IconButton(onClick = onDelete, modifier = Modifier.size(36.dp)) {
Icon(
Icons.Filled.Delete,
contentDescription = "Remove account",
tint = cs.error,
modifier = Modifier.size(20.dp),
)
}
}
// Quota bar — always visible (Bug 2). Server-reported remaining
// when known, otherwise estimated from this device's usage.
Spacer(Modifier.height(8.dp))
val base = account.quotaRemaining ?: account.quotaMax
val remaining = (base - usedBytes).coerceAtLeast(0L)
val fraction = (remaining.toFloat() / account.quotaMax.toFloat()).coerceIn(0f, 1f)
LinearProgressIndicator(
progress = { fraction },
modifier = Modifier
.fillMaxWidth()
.height(8.dp)
.clip(RoundedCornerShape(4.dp)),
color = when {
fraction <= 0.1f -> cs.error
fraction <= 0.25f -> cs.tertiary
else -> cs.primary
},
)
Spacer(Modifier.height(4.dp))
Text(
buildString {
append("${formatBytes(remaining)} left of ${formatBytes(account.quotaMax)}")
if (account.quotaRemaining == null) append(" · on this device")
},
style = MaterialTheme.typography.labelSmall,
color = cs.onSurfaceVariant,
)
// Live per-account stats.
if (stats != null && account.isEnabled) {
Spacer(Modifier.height(6.dp))
Text(
when {
stats.isExhausted -> "Quota exhausted"
!stats.isConnected -> "Not connected"
else -> "↓ ${formatBytesPerSecond(stats.speedDownBytesPerSec)} · " +
"↑ ${formatBytesPerSecond(stats.speedUpBytesPerSec)} · " +
"${stats.activeStreams} streams"
},
style = MaterialTheme.typography.labelMedium,
color = cs.onSurfaceVariant,
)
}
account.lastError?.let {
Spacer(Modifier.height(6.dp))
Text(it, style = MaterialTheme.typography.labelSmall, color = cs.error, maxLines = 2)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun BatchImportBottomSheet(
authRepository: FxaAuthRepository,
onDismiss: () -> Unit,
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
.padding(bottom = 32.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Text(s("Batch import"), style = MaterialTheme.typography.titleLargeEmphasized)
GuidedBatchImport(authRepository = authRepository)
}
}
}
@Composable
private fun SingleAccountLoginDialog(
authRepository: FxaAuthRepository,
onDismiss: () -> Unit,
) {
val scope = rememberCoroutineScope()
// If an account sign-in is still pending its email code (e.g. the app was
// killed mid-flow), reopen straight at the code step for that account.
val restoredPending = remember {
authRepository.pendingLogin()?.takeIf { it.kind == FxaAuthRepository.PendingKind.ACCOUNT }
}
var email by remember { mutableStateOf(restoredPending?.email ?: "") }
var password by remember { mutableStateOf("") }
var code by remember { mutableStateOf("") }
var awaitingCode by remember { mutableStateOf(restoredPending != null) }
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
var notice by remember { mutableStateOf<String?>(null) }
Dialog(onDismissRequest = onDismiss) {
Surface(shape = RoundedCornerShape(28.dp), color = MaterialTheme.colorScheme.surfaceContainerHigh) {
Column(
Modifier.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(s("Add account"), style = MaterialTheme.typography.titleLargeEmphasized)
if (!awaitingCode) {
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text(s("Email")) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text(s("Password")) },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier.fillMaxWidth(),
)
} else {
Text(s("Enter the confirmation code sent to your email"), style = MaterialTheme.typography.bodyMedium)
Text(
email,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = code,
onValueChange = { code = it.replace(Regex("[\\s]+"), "") },
label = { Text(s("Confirmation code")) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
modifier = Modifier.fillMaxWidth(),
)
}
error?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
notice?.let {
Text(it, color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.bodySmall)
}
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
) {
if (awaitingCode) {
TextButton(
onClick = {
scope.launch {
authRepository.resendPendingCode()
.onSuccess { notice = "A new code was sent." }
.onFailure { error = it.message ?: "Could not resend the code" }
}
},
enabled = !busy,
) { Text(s("Resend code")) }
Spacer(Modifier.width(8.dp))
}
TextButton(onClick = onDismiss) { Text(s("Cancel")) }
Spacer(Modifier.width(8.dp))
Button(
onClick = {
busy = true
error = null
notice = null
scope.launch {
if (!awaitingCode) {
authRepository.beginAccountLogin(email.trim(), password)
.onSuccess { step ->
when (step) {
is FxaAuthRepository.AccountLoginStep.Completed -> onDismiss()
is FxaAuthRepository.AccountLoginStep.NeedsCode -> awaitingCode = true
}
}
.onFailure { error = it.message ?: "Sign-in failed" }
} else {
authRepository.submitPendingAccountCode(code)
.onSuccess { onDismiss() }
.onFailure { error = it.message ?: "Verification failed" }
}
busy = false
}
},
enabled = !busy &&
(if (awaitingCode) code.isNotBlank() else email.isNotBlank() && password.isNotBlank()),
) {
if (busy) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
else Text(if (awaitingCode) s("Verify") else s("Sign in"))
}
}
if (!awaitingCode) {
AccountHelpRow()
}
}
}
}
}