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
import 'dart:async';
import 'package:flutter/material.dart';
import '../core/core_api.dart';
import '../core/core_controller.dart';
import '../core/models.dart';
import '../l10n/app_localizations.dart';
import 'widgets.dart';
/// One account read from a pasted line.
class BatchEntry {
const BatchEntry(this.line, this.email, this.password);
/// The line's number in the pasted text, from 1.
final int line;
final String email;
final String password;
}
/// Splits one line into its email and password, on the first separator
/// that leaves an address (an `@`, no spaces) before it and a password
/// after it: `----`, `:`, `,`, or whitespace.
(String, String)? _splitLine(String line) {
for (final sep in ['----', ':', ',']) {
final i = line.indexOf(sep);
if (i <= 0) continue;
final email = line.substring(0, i).trim();
final password = line.substring(i + sep.length).trim();
if (email.contains('@') && !email.contains(' ') && password.isNotEmpty) {
return (email, password);
}
}
final ws = RegExp(r'\s+').firstMatch(line);
if (ws != null) {
final email = line.substring(0, ws.start).trim();
final password = line.substring(ws.end).trim();
if (email.contains('@') && password.isNotEmpty) return (email, password);
}
return null;
}
/// Reads the pasted [text]: one account per non-empty line (see
/// [_splitLine]); the lines that are not accounts come back by number.
({List<BatchEntry> entries, List<int> badLines}) parseBatchImport(
String text,
) {
final entries = <BatchEntry>[];
final bad = <int>[];
final lines = text.split('\n');
for (var i = 0; i < lines.length; i++) {
final line = lines[i].trim();
if (line.isEmpty) continue;
final split = _splitLine(line);
if (split == null) {
bad.add(i + 1);
} else {
entries.add(BatchEntry(i + 1, split.$1, split.$2));
}
}
return (entries: entries, badLines: bad);
}
/// Adds many accounts from pasted text, one after another: the dialog of
/// the Foxy accounts page's Batch import button. Each account signs in
/// through the core like the single sign-in form; a sign-in Mozilla
/// interrupts with a question (a code, a CAPTCHA) is left for the single
/// form and marked, never answered here.
Future<void> showBatchImportDialog(BuildContext context, CoreController core) =>
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => _BatchImportDialog(core: core),
);
enum _LineState { waiting, adding, added, failed, manual, invalid }
class _Line {
_Line(this.number, this.label);
final int number;
/// The account's email; the pasted line itself for an unreadable one.
final String label;
_LineState state = _LineState.waiting;
String detail = '';
}
class _BatchImportDialog extends StatefulWidget {
const _BatchImportDialog({required this.core});
final CoreController core;
@override
State<_BatchImportDialog> createState() => _BatchImportDialogState();
}
class _BatchImportDialogState extends State<_BatchImportDialog> {
final _text = TextEditingController();
List<_Line> _lines = const [];
List<BatchEntry> _entries = const [];
bool _running = false;
bool _cancelled = false;
bool _done = false;
String? _error;
int _current = 0;
@override
void dispose() {
_text.dispose();
super.dispose();
}
void _start() {
final l = AppLocalizations.of(context);
final parsed = parseBatchImport(_text.text);
if (parsed.entries.isEmpty && parsed.badLines.isEmpty) {
setState(() => _error = l.batchImportEmpty);
return;
}
setState(() {
_error = null;
_entries = parsed.entries;
final raw = _text.text.split('\n');
_lines = [
for (final e in parsed.entries) _Line(e.line, e.email),
for (final n in parsed.badLines)
_Line(n, raw[n - 1].trim())..state = _LineState.invalid,
]..sort((a, b) => a.number.compareTo(b.number));
_running = true;
_cancelled = false;
_done = false;
_current = 0;
});
unawaited(_run());
}
Future<void> _run() async {
final l = AppLocalizations.of(context);
for (var i = 0; i < _entries.length; i++) {
if (_cancelled) break;
final entry = _entries[i];
final line = _lines.firstWhere((x) => x.number == entry.line);
setState(() {
_current = i + 1;
line.state = _LineState.adding;
});
final (state, detail) = await _importOne(l, entry);
if (!mounted) return;
setState(() {
line.state = state;
line.detail = detail;
});
}
if (!mounted) return;
setState(() {
_running = false;
_done = true;
});
widget.core.refresh(accountsToo: true);
}
/// Signs one account in through the core and follows it to its end:
/// done, failed, or a step only the person can answer (a code, a
/// CAPTCHA, a link in the email), which is marked and cancelled here.
Future<(_LineState, String)> _importOne(
AppLocalizations l,
BatchEntry entry,
) async {
final api = widget.core.api;
if (api == null) {
final problem = widget.core.unavailable;
return (
_LineState.failed,
problem == null ? '' : describeProblem(l, problem),
);
}
SignInState s;
try {
s = await api.startSignIn(entry.email, entry.password);
} on CoreApiException catch (e) {
return (_LineState.failed, e.message);
} on CoreUnavailable catch (e) {
return (_LineState.failed, describeProblem(l, e));
}
final deadline = DateTime.now().add(const Duration(seconds: 30));
var current = s;
while (true) {
switch (current.step) {
case SignInStep.done:
return (_LineState.added, '');
case SignInStep.failed:
return (_LineState.failed, _reason(l, current));
case SignInStep.cancelled:
return (_LineState.failed, l.signInCancelled);
}
if (current.needsAnswer || current.step == SignInStep.needEmailLink) {
unawaited(_cancel(api, current.id));
return (_LineState.manual, '');
}
if (DateTime.now().isAfter(deadline)) {
unawaited(_cancel(api, current.id));
return (_LineState.failed, l.signInTimedOut);
}
await Future<void>.delayed(const Duration(milliseconds: 1500));
try {
current = await api.signInState(current.id);
} on Exception {
// The next tick retries; the core may be busy.
}
}
}
Future<void> _cancel(CoreApi api, String id) async {
try {
await api.cancelSignIn(id);
} on Exception {
// The core ends abandoned sign-ins itself.
}
}
/// Why a sign-in failed, in the app's language where it knows the code;
/// the core's own text otherwise.
String _reason(AppLocalizations l, SignInState s) => switch (s.errorCode) {
SignInError.noAccount => l.signInNoAccount,
SignInError.wrongPassword => l.signInWrongPassword,
SignInError.noPassword => l.signInNoPassword,
SignInError.tooManyAttempts => l.signInTooManyAttempts,
SignInError.unblockCodeRejected => l.signInUnblockRejected,
SignInError.wrongCode => l.signInWrongCode,
SignInError.wrongTotp => l.signInWrongTotp,
SignInError.tooManyCodes => l.signInTooManyCodes,
SignInError.timedOut => l.signInTimedOut,
SignInError.network => l.signInNetwork,
_ => s.error.isNotEmpty ? s.error : l.signInFailed,
};
@override
Widget build(BuildContext context) {
final l = AppLocalizations.of(context);
final theme = Theme.of(context);
final added = _lines.where((x) => x.state == _LineState.added).length;
final notAdded = _lines
.where(
(x) =>
x.state == _LineState.failed || x.state == _LineState.manual,
)
.length;
return AlertDialog(
title: Text(l.batchImport),
content: SizedBox(
width: 460,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(l.batchImportHint, style: theme.textTheme.bodyMedium),
const SizedBox(height: 12),
TextField(
controller: _text,
enabled: !_running,
minLines: 5,
maxLines: 8,
textDirection: TextDirection.ltr,
style: theme.textTheme.bodyMedium?.copyWith(
fontFeatures: const [FontFeature.tabularFigures()],
),
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'email@example.com:password',
hintTextDirection: TextDirection.ltr,
),
),
if (_error != null) ...[
const SizedBox(height: 10),
Text(
_error!,
style: theme.textTheme.bodyMedium?.copyWith(
color: StatusColors.bad,
),
),
],
if (_lines.isNotEmpty) ...[
const SizedBox(height: 14),
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 190),
child: ListView(
shrinkWrap: true,
children: [
for (final line in _lines) _lineRow(theme, l, line),
],
),
),
const SizedBox(height: 10),
Text(
_running
? l.batchProgress(_current, _entries.length)
: l.batchSummary(added, notAdded),
style: theme.textTheme.bodyMedium,
),
],
],
),
),
actions: [
TextButton(
onPressed: _running
? () => setState(() => _cancelled = true)
: () => Navigator.of(context).pop(),
child: Text(_running || !_done ? l.cancel : l.close),
),
if (!_done)
FilledButton(
onPressed: _running ? null : _start,
child: Text(l.batchImportAction),
),
],
);
}
Widget _lineRow(ThemeData theme, AppLocalizations l, _Line line) {
final (icon, color, note) = switch (line.state) {
_LineState.waiting => (
Icons.schedule_rounded,
StatusColors.idle,
'',
),
_LineState.adding => (Icons.sync_rounded, StatusColors.busy, ''),
_LineState.added => (
Icons.check_circle_rounded,
StatusColors.good,
l.batchAdded,
),
_LineState.failed => (
Icons.error_rounded,
StatusColors.bad,
line.detail,
),
_LineState.manual => (
Icons.person_outline_rounded,
StatusColors.busy,
l.batchNeedsManual,
),
_LineState.invalid => (
Icons.warning_amber_rounded,
StatusColors.busy,
l.batchLineInvalid,
),
};
return Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
children: [
if (line.state == _LineState.adding)
const SizedBox.square(
dimension: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
Icon(icon, size: 18, color: color),
const SizedBox(width: 10),
Expanded(
child: Text(
line.label.isEmpty ? '${line.number}' : line.label,
textDirection: line.label.contains('@')
? TextDirection.ltr
: null,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodyMedium,
),
),
if (note.isNotEmpty) ...[
const SizedBox(width: 8),
Flexible(
child: Text(
note,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall?.copyWith(color: color),
),
),
],
],
),
);
}
}