code_widget.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. // ignore_for_file: public_member_api_docs, sort_constructors_first
  2. import 'dart:async';
  3. import 'dart:io';
  4. import 'package:clipboard/clipboard.dart';
  5. import 'package:ente_auth/core/configuration.dart';
  6. import 'package:ente_auth/ente_theme_data.dart';
  7. import 'package:ente_auth/l10n/l10n.dart';
  8. import 'package:ente_auth/models/code.dart';
  9. import 'package:ente_auth/onboarding/view/setup_enter_secret_key_page.dart';
  10. import 'package:ente_auth/onboarding/view/view_qr_page.dart';
  11. import 'package:ente_auth/services/local_authentication_service.dart';
  12. import 'package:ente_auth/services/preference_service.dart';
  13. import 'package:ente_auth/store/code_store.dart';
  14. import 'package:ente_auth/ui/code_timer_progress.dart';
  15. import 'package:ente_auth/ui/utils/icon_utils.dart';
  16. import 'package:ente_auth/utils/dialog_util.dart';
  17. import 'package:ente_auth/utils/platform_util.dart';
  18. import 'package:ente_auth/utils/toast_util.dart';
  19. import 'package:ente_auth/utils/totp_util.dart';
  20. import 'package:flutter/gestures.dart';
  21. import 'package:flutter/material.dart';
  22. import 'package:flutter_slidable/flutter_slidable.dart';
  23. import 'package:logging/logging.dart';
  24. import 'package:move_to_background/move_to_background.dart';
  25. class CodeWidget extends StatefulWidget {
  26. final Code code;
  27. const CodeWidget(this.code, {super.key});
  28. @override
  29. State<CodeWidget> createState() => _CodeWidgetState();
  30. }
  31. class _CodeWidgetState extends State<CodeWidget> {
  32. Timer? _everySecondTimer;
  33. final ValueNotifier<String> _currentCode = ValueNotifier<String>("");
  34. final ValueNotifier<String> _nextCode = ValueNotifier<String>("");
  35. final Logger logger = Logger("_CodeWidgetState");
  36. bool _isInitialized = false;
  37. late bool hasConfiguredAccount;
  38. late bool _shouldShowLargeIcon;
  39. late bool _hideCode;
  40. bool isMaskingEnabled = false;
  41. @override
  42. void initState() {
  43. super.initState();
  44. isMaskingEnabled = PreferenceService.instance.shouldHideCodes();
  45. _hideCode = isMaskingEnabled;
  46. _everySecondTimer =
  47. Timer.periodic(const Duration(milliseconds: 500), (Timer t) {
  48. String newCode = _getCurrentOTP();
  49. if (newCode != _currentCode.value) {
  50. _currentCode.value = newCode;
  51. if (widget.code.type == Type.totp) {
  52. _nextCode.value = _getNextTotp();
  53. }
  54. }
  55. });
  56. hasConfiguredAccount = Configuration.instance.hasConfiguredAccount();
  57. }
  58. @override
  59. void dispose() {
  60. _everySecondTimer?.cancel();
  61. _currentCode.dispose();
  62. _nextCode.dispose();
  63. super.dispose();
  64. }
  65. @override
  66. Widget build(BuildContext context) {
  67. if (isMaskingEnabled != PreferenceService.instance.shouldHideCodes()) {
  68. isMaskingEnabled = PreferenceService.instance.shouldHideCodes();
  69. _hideCode = isMaskingEnabled;
  70. }
  71. _shouldShowLargeIcon = PreferenceService.instance.shouldShowLargeIcons();
  72. if (!_isInitialized) {
  73. _currentCode.value = _getCurrentOTP();
  74. if (widget.code.type == Type.totp) {
  75. _nextCode.value = _getNextTotp();
  76. }
  77. _isInitialized = true;
  78. }
  79. final l10n = context.l10n;
  80. return Container(
  81. margin: const EdgeInsets.only(left: 16, right: 16, bottom: 8, top: 8),
  82. child: Slidable(
  83. enabled: PlatformUtil.isMobile(),
  84. key: ValueKey(widget.code.hashCode),
  85. endActionPane: ActionPane(
  86. extentRatio: 0.60,
  87. motion: const ScrollMotion(),
  88. children: [
  89. const SizedBox(
  90. width: 4,
  91. ),
  92. SlidableAction(
  93. onPressed: _onShowQrPressed,
  94. backgroundColor: Colors.grey.withOpacity(0.1),
  95. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  96. foregroundColor:
  97. Theme.of(context).colorScheme.inverseBackgroundColor,
  98. icon: Icons.qr_code_2_outlined,
  99. label: "QR",
  100. padding: const EdgeInsets.only(left: 4, right: 0),
  101. spacing: 8,
  102. ),
  103. const SizedBox(
  104. width: 4,
  105. ),
  106. SlidableAction(
  107. onPressed: _onEditPressed,
  108. backgroundColor: Colors.grey.withOpacity(0.1),
  109. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  110. foregroundColor:
  111. Theme.of(context).colorScheme.inverseBackgroundColor,
  112. icon: Icons.edit_outlined,
  113. label: l10n.edit,
  114. padding: const EdgeInsets.only(left: 4, right: 0),
  115. spacing: 8,
  116. ),
  117. const SizedBox(
  118. width: 4,
  119. ),
  120. SlidableAction(
  121. onPressed: _onDeletePressed,
  122. backgroundColor: Colors.grey.withOpacity(0.1),
  123. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  124. foregroundColor: const Color(0xFFFE4A49),
  125. icon: Icons.delete,
  126. label: l10n.delete,
  127. padding: const EdgeInsets.only(left: 0, right: 0),
  128. spacing: 8,
  129. ),
  130. ],
  131. ),
  132. child: Builder(
  133. builder: (context) => RawGestureDetector(
  134. gestures: {
  135. PanGestureRecognizer:
  136. GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
  137. () => PanGestureRecognizer(
  138. debugOwner: this,
  139. // This recognizer accepts any button press made with a secondary button.
  140. allowedButtonsFilter: (int buttons) =>
  141. buttons & kSecondaryButton != 0,
  142. ),
  143. (PanGestureRecognizer instance) {
  144. instance
  145. ..dragStartBehavior = DragStartBehavior.down
  146. ..onEnd = (DragEndDetails details) {
  147. Slidable.of(context)?.openEndActionPane();
  148. };
  149. },
  150. ),
  151. },
  152. child: ClipRRect(
  153. borderRadius: BorderRadius.circular(8),
  154. child: Container(
  155. color: Theme.of(context).colorScheme.codeCardBackgroundColor,
  156. child: Material(
  157. color: Colors.transparent,
  158. child: InkWell(
  159. customBorder: RoundedRectangleBorder(
  160. borderRadius: BorderRadius.circular(10),
  161. ),
  162. onTap: () {
  163. _copyCurrentOTPToClipboard();
  164. },
  165. onDoubleTap: isMaskingEnabled
  166. ? () {
  167. setState(
  168. () {
  169. _hideCode = !_hideCode;
  170. },
  171. );
  172. }
  173. : null,
  174. onLongPress: () {
  175. _copyCurrentOTPToClipboard();
  176. },
  177. child: _getCardContents(l10n),
  178. ),
  179. ),
  180. ),
  181. ),
  182. ),
  183. ),
  184. ),
  185. );
  186. }
  187. Widget _getCardContents(AppLocalizations l10n) {
  188. return SizedBox(
  189. child: Column(
  190. crossAxisAlignment: CrossAxisAlignment.start,
  191. mainAxisAlignment: MainAxisAlignment.center,
  192. children: [
  193. if (widget.code.type == Type.totp)
  194. CodeTimerProgress(
  195. period: widget.code.period,
  196. ),
  197. const SizedBox(
  198. height: 16,
  199. ),
  200. Row(
  201. children: [
  202. _shouldShowLargeIcon ? _getIcon() : const SizedBox.shrink(),
  203. Expanded(
  204. child: Column(
  205. children: [
  206. _getTopRow(),
  207. const SizedBox(height: 4),
  208. _getBottomRow(l10n),
  209. ],
  210. ),
  211. ),
  212. ],
  213. ),
  214. const SizedBox(
  215. height: 20,
  216. ),
  217. if (PlatformUtil.isDesktop())
  218. Row(
  219. mainAxisAlignment: MainAxisAlignment.end,
  220. children: [
  221. SlideAction(
  222. onPressed: _onShowQrPressed,
  223. backgroundColor: Colors.grey.withOpacity(0.1),
  224. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  225. foregroundColor:
  226. Theme.of(context).colorScheme.inverseBackgroundColor,
  227. icon: Icons.qr_code_2_outlined,
  228. label: "QR",
  229. padding: const EdgeInsets.only(left: 4, right: 0),
  230. spacing: 8,
  231. ),
  232. const SizedBox(
  233. width: 4,
  234. ),
  235. SlideAction(
  236. onPressed: _onEditPressed,
  237. backgroundColor: Colors.grey.withOpacity(0.1),
  238. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  239. foregroundColor:
  240. Theme.of(context).colorScheme.inverseBackgroundColor,
  241. icon: Icons.edit_outlined,
  242. label: l10n.edit,
  243. padding: const EdgeInsets.only(left: 4, right: 0),
  244. spacing: 8,
  245. ),
  246. const SizedBox(
  247. width: 4,
  248. ),
  249. SlideAction(
  250. onPressed: _onDeletePressed,
  251. backgroundColor: Colors.grey.withOpacity(0.1),
  252. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  253. foregroundColor: const Color(0xFFFE4A49),
  254. icon: Icons.delete,
  255. label: l10n.delete,
  256. padding: const EdgeInsets.only(left: 0, right: 0),
  257. spacing: 8,
  258. ),
  259. ],
  260. ),
  261. ],
  262. ),
  263. );
  264. }
  265. Widget _getBottomRow(AppLocalizations l10n) {
  266. return Container(
  267. padding: const EdgeInsets.only(left: 16, right: 16),
  268. child: Row(
  269. mainAxisAlignment: MainAxisAlignment.start,
  270. crossAxisAlignment: CrossAxisAlignment.end,
  271. children: [
  272. Expanded(
  273. child: ValueListenableBuilder<String>(
  274. valueListenable: _currentCode,
  275. builder: (context, value, child) {
  276. return Material(
  277. type: MaterialType.transparency,
  278. child: Text(
  279. _getFormattedCode(value),
  280. style: const TextStyle(fontSize: 24),
  281. ),
  282. );
  283. },
  284. ),
  285. ),
  286. widget.code.type == Type.totp
  287. ? GestureDetector(
  288. onTap: () {
  289. _copyNextToClipboard();
  290. },
  291. child: Column(
  292. crossAxisAlignment: CrossAxisAlignment.end,
  293. children: [
  294. Text(
  295. l10n.nextTotpTitle,
  296. style: Theme.of(context).textTheme.bodySmall,
  297. ),
  298. ValueListenableBuilder<String>(
  299. valueListenable: _nextCode,
  300. builder: (context, value, child) {
  301. return Material(
  302. type: MaterialType.transparency,
  303. child: Text(
  304. _getFormattedCode(value),
  305. style: const TextStyle(
  306. fontSize: 18,
  307. color: Colors.grey,
  308. ),
  309. ),
  310. );
  311. },
  312. ),
  313. ],
  314. ),
  315. )
  316. : Column(
  317. crossAxisAlignment: CrossAxisAlignment.end,
  318. children: [
  319. Text(
  320. l10n.nextTotpTitle,
  321. style: Theme.of(context).textTheme.bodySmall,
  322. ),
  323. InkWell(
  324. onTap: _onNextHotpTapped,
  325. child: const Icon(
  326. Icons.forward_outlined,
  327. size: 32,
  328. color: Colors.grey,
  329. ),
  330. ),
  331. ],
  332. ),
  333. ],
  334. ),
  335. );
  336. }
  337. Widget _getTopRow() {
  338. return Padding(
  339. padding: const EdgeInsets.only(left: 16, right: 16),
  340. child: Row(
  341. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  342. crossAxisAlignment: CrossAxisAlignment.start,
  343. children: [
  344. Column(
  345. crossAxisAlignment: CrossAxisAlignment.start,
  346. children: [
  347. Text(
  348. safeDecode(widget.code.issuer).trim(),
  349. style: Theme.of(context).textTheme.titleLarge,
  350. ),
  351. const SizedBox(height: 2),
  352. Text(
  353. safeDecode(widget.code.account).trim(),
  354. style: Theme.of(context).textTheme.bodySmall?.copyWith(
  355. fontSize: 12,
  356. color: Colors.grey,
  357. ),
  358. ),
  359. ],
  360. ),
  361. Row(
  362. mainAxisAlignment: MainAxisAlignment.end,
  363. children: [
  364. (widget.code.hasSynced != null && widget.code.hasSynced!) ||
  365. !hasConfiguredAccount
  366. ? const SizedBox.shrink()
  367. : const Icon(
  368. Icons.sync_disabled,
  369. size: 20,
  370. color: Colors.amber,
  371. ),
  372. const SizedBox(width: 12),
  373. _shouldShowLargeIcon ? const SizedBox.shrink() : _getIcon(),
  374. ],
  375. ),
  376. ],
  377. ),
  378. );
  379. }
  380. Widget _getIcon() {
  381. return Padding(
  382. padding: _shouldShowLargeIcon
  383. ? const EdgeInsets.only(left: 16)
  384. : const EdgeInsets.all(0),
  385. child: IconUtils.instance.getIcon(
  386. context,
  387. safeDecode(widget.code.issuer).trim(),
  388. width: _shouldShowLargeIcon ? 42 : 24,
  389. ),
  390. );
  391. }
  392. void _copyCurrentOTPToClipboard() async {
  393. _copyToClipboard(
  394. _getCurrentOTP(),
  395. confirmationMessage: context.l10n.copiedToClipboard,
  396. );
  397. }
  398. void _copyNextToClipboard() {
  399. _copyToClipboard(
  400. _getNextTotp(),
  401. confirmationMessage: context.l10n.copiedNextToClipboard,
  402. );
  403. }
  404. void _copyToClipboard(
  405. String content, {
  406. required String confirmationMessage,
  407. }) async {
  408. final shouldMinimizeOnCopy =
  409. PreferenceService.instance.shouldMinimizeOnCopy();
  410. await FlutterClipboard.copy(content);
  411. showToast(context, confirmationMessage);
  412. if (Platform.isAndroid && shouldMinimizeOnCopy) {
  413. // ignore: unawaited_futures
  414. MoveToBackground.moveTaskToBack();
  415. }
  416. }
  417. void _onNextHotpTapped() {
  418. if (widget.code.type == Type.hotp) {
  419. CodeStore.instance
  420. .addCode(
  421. widget.code.copyWith(counter: widget.code.counter + 1),
  422. shouldSync: true,
  423. )
  424. .ignore();
  425. }
  426. }
  427. Future<void> _onEditPressed(_) async {
  428. bool isAuthSuccessful = await LocalAuthenticationService.instance
  429. .requestLocalAuthentication(context, context.l10n.editCodeAuthMessage);
  430. await PlatformUtil.refocusWindows();
  431. if (!isAuthSuccessful) {
  432. return;
  433. }
  434. final Code? code = await Navigator.of(context).push(
  435. MaterialPageRoute(
  436. builder: (BuildContext context) {
  437. return SetupEnterSecretKeyPage(code: widget.code);
  438. },
  439. ),
  440. );
  441. if (code != null) {
  442. await CodeStore.instance.addCode(code);
  443. }
  444. }
  445. Future<void> _onShowQrPressed(_) async {
  446. bool isAuthSuccessful = await LocalAuthenticationService.instance
  447. .requestLocalAuthentication(context, context.l10n.showQRAuthMessage);
  448. await PlatformUtil.refocusWindows();
  449. if (!isAuthSuccessful) {
  450. return;
  451. }
  452. // ignore: unused_local_variable
  453. final Code? code = await Navigator.of(context).push(
  454. MaterialPageRoute(
  455. builder: (BuildContext context) {
  456. return ViewQrPage(code: widget.code);
  457. },
  458. ),
  459. );
  460. }
  461. void _onDeletePressed(_) async {
  462. bool isAuthSuccessful =
  463. await LocalAuthenticationService.instance.requestLocalAuthentication(
  464. context,
  465. context.l10n.deleteCodeAuthMessage,
  466. );
  467. if (!isAuthSuccessful) {
  468. return;
  469. }
  470. FocusScope.of(context).requestFocus();
  471. final l10n = context.l10n;
  472. await showChoiceActionSheet(
  473. context,
  474. title: l10n.deleteCodeTitle,
  475. body: l10n.deleteCodeMessage,
  476. firstButtonLabel: l10n.delete,
  477. isCritical: true,
  478. firstButtonOnTap: () async {
  479. await CodeStore.instance.removeCode(widget.code);
  480. },
  481. );
  482. }
  483. String _getCurrentOTP() {
  484. try {
  485. return getOTP(widget.code);
  486. } catch (e) {
  487. return context.l10n.error;
  488. }
  489. }
  490. String _getNextTotp() {
  491. try {
  492. assert(widget.code.type == Type.totp);
  493. return getNextTotp(widget.code);
  494. } catch (e) {
  495. return context.l10n.error;
  496. }
  497. }
  498. String _getFormattedCode(String code) {
  499. if (_hideCode) {
  500. // replace all digits with •
  501. code = code.replaceAll(RegExp(r'\d'), '•');
  502. }
  503. if (code.length == 6) {
  504. return "${code.substring(0, 3)} ${code.substring(3, 6)}";
  505. }
  506. return code;
  507. }
  508. }
  509. class SlideAction extends StatelessWidget {
  510. const SlideAction({
  511. super.key,
  512. required this.onPressed,
  513. required this.backgroundColor,
  514. required this.borderRadius,
  515. required this.foregroundColor,
  516. required this.icon,
  517. required this.label,
  518. required this.padding,
  519. required this.spacing,
  520. });
  521. final void Function(dynamic) onPressed;
  522. final Color backgroundColor;
  523. final BorderRadius borderRadius;
  524. final Color foregroundColor;
  525. final IconData icon;
  526. final String label;
  527. final EdgeInsets padding;
  528. final double spacing;
  529. @override
  530. Widget build(BuildContext context) {
  531. return InkWell(
  532. onTap: () => onPressed(0),
  533. child: Container(
  534. color: backgroundColor,
  535. height: 52,
  536. width: 52,
  537. child: Column(
  538. mainAxisAlignment: MainAxisAlignment.center,
  539. children: [
  540. Icon(
  541. icon,
  542. size: 16,
  543. color: foregroundColor,
  544. ),
  545. const SizedBox(
  546. height: 4,
  547. ),
  548. Text(
  549. label,
  550. style: Theme.of(context).textTheme.bodySmall?.copyWith(
  551. color: foregroundColor,
  552. ),
  553. ),
  554. ],
  555. ),
  556. ),
  557. );
  558. }
  559. }