code_widget.dart 20 KB

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