code_widget.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:clipboard/clipboard.dart';
  4. import 'package:ente_auth/core/configuration.dart';
  5. import 'package:ente_auth/ente_theme_data.dart';
  6. import 'package:ente_auth/l10n/l10n.dart';
  7. import 'package:ente_auth/models/code.dart';
  8. import 'package:ente_auth/models/code_display.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/material.dart';
  21. import 'package:flutter_context_menu/flutter_context_menu.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: Builder(
  83. builder: (context) {
  84. if (PlatformUtil.isDesktop()) {
  85. return ContextMenuRegion(
  86. contextMenu: ContextMenu(
  87. entries: <ContextMenuEntry>[
  88. MenuItem(
  89. label: 'QR',
  90. icon: Icons.qr_code_2_outlined,
  91. onSelected: () => _onShowQrPressed(null),
  92. ),
  93. MenuItem(
  94. label: l10n.pinText,
  95. icon: widget.code.isPinned
  96. ? Icons.push_pin
  97. : Icons.push_pin_outlined,
  98. onSelected: () => _onShowQrPressed(null),
  99. ),
  100. MenuItem(
  101. label: l10n.edit,
  102. icon: Icons.edit,
  103. onSelected: () => _onEditPressed(null),
  104. ),
  105. const MenuDivider(),
  106. MenuItem(
  107. label: l10n.delete,
  108. value: "Delete",
  109. icon: Icons.delete,
  110. onSelected: () => _onDeletePressed(null),
  111. ),
  112. ],
  113. padding: const EdgeInsets.all(8.0),
  114. ),
  115. child: _clippedCard(l10n),
  116. );
  117. }
  118. return Slidable(
  119. key: ValueKey(widget.code.hashCode),
  120. endActionPane: ActionPane(
  121. extentRatio: 0.60,
  122. motion: const ScrollMotion(),
  123. children: [
  124. const SizedBox(
  125. width: 4,
  126. ),
  127. SlidableAction(
  128. onPressed: _onShowQrPressed,
  129. backgroundColor: Colors.grey.withOpacity(0.1),
  130. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  131. foregroundColor:
  132. Theme.of(context).colorScheme.inverseBackgroundColor,
  133. icon: Icons.qr_code_2_outlined,
  134. label: "QR",
  135. padding: const EdgeInsets.only(left: 4, right: 0),
  136. spacing: 8,
  137. ),
  138. const SizedBox(
  139. width: 4,
  140. ),
  141. SlidableAction(
  142. onPressed: _onPinPressed,
  143. backgroundColor: Colors.grey.withOpacity(0.1),
  144. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  145. foregroundColor:
  146. Theme.of(context).colorScheme.inverseBackgroundColor,
  147. icon: widget.code.isPinned
  148. ? Icons.push_pin
  149. : Icons.push_pin_outlined,
  150. label: l10n.pinText,
  151. padding: const EdgeInsets.only(left: 4, right: 0),
  152. spacing: 8,
  153. ),
  154. const SizedBox(
  155. width: 4,
  156. ),
  157. SlidableAction(
  158. onPressed: _onEditPressed,
  159. backgroundColor: Colors.grey.withOpacity(0.1),
  160. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  161. foregroundColor:
  162. Theme.of(context).colorScheme.inverseBackgroundColor,
  163. icon: Icons.edit_outlined,
  164. label: l10n.edit,
  165. padding: const EdgeInsets.only(left: 4, right: 0),
  166. spacing: 8,
  167. ),
  168. const SizedBox(
  169. width: 4,
  170. ),
  171. SlidableAction(
  172. onPressed: _onDeletePressed,
  173. backgroundColor: Colors.grey.withOpacity(0.1),
  174. borderRadius: const BorderRadius.all(Radius.circular(12.0)),
  175. foregroundColor: const Color(0xFFFE4A49),
  176. icon: Icons.delete,
  177. label: l10n.delete,
  178. padding: const EdgeInsets.only(left: 0, right: 0),
  179. spacing: 8,
  180. ),
  181. ],
  182. ),
  183. child: Builder(
  184. builder: (context) => _clippedCard(l10n),
  185. ),
  186. );
  187. },
  188. ),
  189. );
  190. }
  191. Widget _clippedCard(AppLocalizations l10n) {
  192. return ClipRRect(
  193. borderRadius: BorderRadius.circular(8),
  194. child: Container(
  195. color: Theme.of(context).colorScheme.codeCardBackgroundColor,
  196. child: Material(
  197. color: Colors.transparent,
  198. child: InkWell(
  199. customBorder: RoundedRectangleBorder(
  200. borderRadius: BorderRadius.circular(10),
  201. ),
  202. onTap: () {
  203. _copyCurrentOTPToClipboard();
  204. },
  205. onDoubleTap: isMaskingEnabled
  206. ? () {
  207. setState(
  208. () {
  209. _hideCode = !_hideCode;
  210. },
  211. );
  212. }
  213. : null,
  214. onLongPress: () {
  215. _copyCurrentOTPToClipboard();
  216. },
  217. child: _getCardContents(l10n),
  218. ),
  219. ),
  220. ),
  221. );
  222. }
  223. Widget _getCardContents(AppLocalizations l10n) {
  224. return SizedBox(
  225. child: Column(
  226. crossAxisAlignment: CrossAxisAlignment.start,
  227. mainAxisAlignment: MainAxisAlignment.center,
  228. children: [
  229. if (widget.code.type == Type.totp)
  230. CodeTimerProgress(
  231. period: widget.code.period,
  232. ),
  233. const SizedBox(
  234. height: 16,
  235. ),
  236. Row(
  237. children: [
  238. _shouldShowLargeIcon ? _getIcon() : const SizedBox.shrink(),
  239. Expanded(
  240. child: Column(
  241. children: [
  242. _getTopRow(),
  243. const SizedBox(height: 4),
  244. _getBottomRow(l10n),
  245. ],
  246. ),
  247. ),
  248. ],
  249. ),
  250. const SizedBox(
  251. height: 20,
  252. ),
  253. ],
  254. ),
  255. );
  256. }
  257. Widget _getBottomRow(AppLocalizations l10n) {
  258. return Container(
  259. padding: const EdgeInsets.only(left: 16, right: 16),
  260. child: Row(
  261. mainAxisAlignment: MainAxisAlignment.start,
  262. crossAxisAlignment: CrossAxisAlignment.end,
  263. children: [
  264. Expanded(
  265. child: ValueListenableBuilder<String>(
  266. valueListenable: _currentCode,
  267. builder: (context, value, child) {
  268. return Material(
  269. type: MaterialType.transparency,
  270. child: Text(
  271. _getFormattedCode(value),
  272. style: const TextStyle(fontSize: 24),
  273. ),
  274. );
  275. },
  276. ),
  277. ),
  278. widget.code.type == Type.totp
  279. ? GestureDetector(
  280. onTap: () {
  281. _copyNextToClipboard();
  282. },
  283. child: Column(
  284. crossAxisAlignment: CrossAxisAlignment.end,
  285. children: [
  286. Text(
  287. l10n.nextTotpTitle,
  288. style: Theme.of(context).textTheme.bodySmall,
  289. ),
  290. ValueListenableBuilder<String>(
  291. valueListenable: _nextCode,
  292. builder: (context, value, child) {
  293. return Material(
  294. type: MaterialType.transparency,
  295. child: Text(
  296. _getFormattedCode(value),
  297. style: const TextStyle(
  298. fontSize: 18,
  299. color: Colors.grey,
  300. ),
  301. ),
  302. );
  303. },
  304. ),
  305. ],
  306. ),
  307. )
  308. : Column(
  309. crossAxisAlignment: CrossAxisAlignment.end,
  310. children: [
  311. Text(
  312. l10n.nextTotpTitle,
  313. style: Theme.of(context).textTheme.bodySmall,
  314. ),
  315. InkWell(
  316. onTap: _onNextHotpTapped,
  317. child: const Icon(
  318. Icons.forward_outlined,
  319. size: 32,
  320. color: Colors.grey,
  321. ),
  322. ),
  323. ],
  324. ),
  325. ],
  326. ),
  327. );
  328. }
  329. Widget _getTopRow() {
  330. return Padding(
  331. padding: const EdgeInsets.only(left: 16, right: 16),
  332. child: Row(
  333. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  334. crossAxisAlignment: CrossAxisAlignment.start,
  335. children: [
  336. Column(
  337. crossAxisAlignment: CrossAxisAlignment.start,
  338. children: [
  339. Text(
  340. safeDecode(widget.code.issuer).trim(),
  341. style: Theme.of(context).textTheme.titleLarge,
  342. ),
  343. const SizedBox(height: 2),
  344. Text(
  345. safeDecode(widget.code.account).trim(),
  346. style: Theme.of(context).textTheme.bodySmall?.copyWith(
  347. fontSize: 12,
  348. color: Colors.grey,
  349. ),
  350. ),
  351. ],
  352. ),
  353. Row(
  354. mainAxisAlignment: MainAxisAlignment.end,
  355. children: [
  356. (widget.code.hasSynced != null && widget.code.hasSynced!) ||
  357. !hasConfiguredAccount
  358. ? const SizedBox.shrink()
  359. : const Icon(
  360. Icons.sync_disabled,
  361. size: 20,
  362. color: Colors.amber,
  363. ),
  364. const SizedBox(width: 12),
  365. _shouldShowLargeIcon ? const SizedBox.shrink() : _getIcon(),
  366. ],
  367. ),
  368. ],
  369. ),
  370. );
  371. }
  372. Widget _getIcon() {
  373. return Padding(
  374. padding: _shouldShowLargeIcon
  375. ? const EdgeInsets.only(left: 16)
  376. : const EdgeInsets.all(0),
  377. child: IconUtils.instance.getIcon(
  378. context,
  379. safeDecode(widget.code.issuer).trim(),
  380. width: _shouldShowLargeIcon ? 42 : 24,
  381. ),
  382. );
  383. }
  384. void _copyCurrentOTPToClipboard() async {
  385. _copyToClipboard(
  386. _getCurrentOTP(),
  387. confirmationMessage: context.l10n.copiedToClipboard,
  388. );
  389. }
  390. void _copyNextToClipboard() {
  391. _copyToClipboard(
  392. _getNextTotp(),
  393. confirmationMessage: context.l10n.copiedNextToClipboard,
  394. );
  395. }
  396. void _copyToClipboard(
  397. String content, {
  398. required String confirmationMessage,
  399. }) async {
  400. final shouldMinimizeOnCopy =
  401. PreferenceService.instance.shouldMinimizeOnCopy();
  402. await FlutterClipboard.copy(content);
  403. showToast(context, confirmationMessage);
  404. if (Platform.isAndroid && shouldMinimizeOnCopy) {
  405. // ignore: unawaited_futures
  406. MoveToBackground.moveTaskToBack();
  407. }
  408. }
  409. void _onNextHotpTapped() {
  410. if (widget.code.type == Type.hotp) {
  411. CodeStore.instance
  412. .addCode(
  413. widget.code.copyWith(counter: widget.code.counter + 1),
  414. shouldSync: true,
  415. )
  416. .ignore();
  417. }
  418. }
  419. Future<void> _onEditPressed(_) async {
  420. bool isAuthSuccessful = await LocalAuthenticationService.instance
  421. .requestLocalAuthentication(context, context.l10n.editCodeAuthMessage);
  422. await PlatformUtil.refocusWindows();
  423. if (!isAuthSuccessful) {
  424. return;
  425. }
  426. final Code? code = await Navigator.of(context).push(
  427. MaterialPageRoute(
  428. builder: (BuildContext context) {
  429. return SetupEnterSecretKeyPage(code: widget.code);
  430. },
  431. ),
  432. );
  433. if (code != null) {
  434. await CodeStore.instance.addCode(code);
  435. }
  436. }
  437. Future<void> _onShowQrPressed(_) async {
  438. bool isAuthSuccessful = await LocalAuthenticationService.instance
  439. .requestLocalAuthentication(context, context.l10n.showQRAuthMessage);
  440. await PlatformUtil.refocusWindows();
  441. if (!isAuthSuccessful) {
  442. return;
  443. }
  444. // ignore: unused_local_variable
  445. final Code? code = await Navigator.of(context).push(
  446. MaterialPageRoute(
  447. builder: (BuildContext context) {
  448. return ViewQrPage(code: widget.code);
  449. },
  450. ),
  451. );
  452. }
  453. Future<void> _onPinPressed(_) async {
  454. bool currentlyPinned = widget.code.isPinned;
  455. final display = widget.code.display ?? CodeDisplay();
  456. final Code code = widget.code.copyWith(
  457. display: display.copyWith(pinned: !currentlyPinned),
  458. );
  459. unawaited(CodeStore.instance.addCode(code));
  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. }