persistent.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // ignore_for_file: constant_identifier_names, non_constant_identifier_names
  2. import 'package:flutter/material.dart';
  3. import 'package:maxkey_flutter/totp.dart';
  4. import 'package:shared_preferences/shared_preferences.dart';
  5. class MaxKeyPersistent {
  6. static const String _CURR_USER_KEY = "CurrUser";
  7. static const String _THEME_MODE_KEY = "ThemeMode";
  8. /// 和用户绑定
  9. String get _TOKEN_KEY => "$_currUser.Token";
  10. /// 不和用户绑定
  11. static const String _HOST_KEY = "Host";
  12. static const String _DEFAULT_HOST = "192.168.1.66";
  13. /// 和用户绑定
  14. String get _TOTP_LIST_KEY => "$_currUser.TotpList";
  15. /// must call [init] first
  16. static final MaxKeyPersistent instance = MaxKeyPersistent();
  17. late SharedPreferences _sp;
  18. static Future<void> init() async {
  19. instance._sp = await SharedPreferences.getInstance();
  20. instance._readTotps();
  21. }
  22. ThemeMode get themeMode => switch (_sp.getString(_THEME_MODE_KEY)) {
  23. "light" => ThemeMode.light,
  24. "dark" => ThemeMode.dark,
  25. _ => ThemeMode.system,
  26. };
  27. late ValueNotifier<ThemeMode> themeModeListenable = ValueNotifier(themeMode);
  28. String? get _currUser => _sp.getString(_CURR_USER_KEY);
  29. String? get token => _sp.getString(_TOKEN_KEY);
  30. /// example: 192.168.220.26:9527
  31. String get host => _sp.getString(_HOST_KEY) ?? _DEFAULT_HOST;
  32. String get baseUrl => "http://$host/sign";
  33. final List<Totp> _totps = [];
  34. void _readTotps() {
  35. final totpUris = _sp.getStringList(_TOTP_LIST_KEY);
  36. if (totpUris == null) return;
  37. for (final uri in totpUris) {
  38. final parsed = Totp.fromUri(uri);
  39. if (parsed == null) continue;
  40. _totps.add(parsed);
  41. }
  42. }
  43. List<Totp> get totps => _totps;
  44. Future<bool> setThemeMode(ThemeMode themeMode) {
  45. themeModeListenable.value = themeMode;
  46. return _sp.setString(_THEME_MODE_KEY, themeMode.name);
  47. }
  48. Future<bool> setUser(String username) async {
  49. final result = await _sp.setString(_CURR_USER_KEY, username);
  50. _totps.clear();
  51. if (result) {
  52. instance._readTotps();
  53. }
  54. return result;
  55. }
  56. Future<bool> setToken(String token) => _sp.setString(_TOKEN_KEY, token);
  57. /// example: 192.168.220.26:9527
  58. Future<bool> setHost(String host) => _sp.setString(_HOST_KEY, host);
  59. Future<bool> saveTotps(List<Totp> totps) => _sp.setStringList(
  60. _TOTP_LIST_KEY,
  61. List.generate(totps.length, (i) => totps[i].uri),
  62. );
  63. Future<bool> clearToken() => _sp.remove(_TOKEN_KEY);
  64. }