code_widget.dart 14 KB

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