code_widget.dart 15 KB

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