persistence.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import 'dart:async';
  2. import 'dart:convert'; // 导入 json 编码解码
  3. import 'dart:io';
  4. import 'package:puzzleweave/models/items.dart';
  5. import 'package:package_info_plus/package_info_plus.dart';
  6. import 'package:rate_my_app/rate_my_app.dart';
  7. import 'package:shared_preferences/shared_preferences.dart';
  8. import 'package:uuid/uuid.dart';
  9. ///持久化存储数据
  10. ///全局类
  11. class Persistence {
  12. late final SharedPreferences _prefs;
  13. Persistence._internal();
  14. static final Persistence _instance = Persistence._internal();
  15. factory Persistence() => _instance;
  16. int get projectId {
  17. if (Platform.isAndroid) {
  18. return 19; // 暂定,需要跟阿淼确认
  19. } else if (Platform.isIOS) {
  20. return 20;
  21. }
  22. return 0;
  23. }
  24. String get libraryName {
  25. if (Platform.isAndroid) {
  26. return "android";
  27. } else if (Platform.isIOS) {
  28. return "ios";
  29. }
  30. return "unkown";
  31. }
  32. late String packageVersion;
  33. ///初始化并给各参数分配默认值
  34. Future<void> initialize() async {
  35. PackageInfo packageInfo = await PackageInfo.fromPlatform();
  36. packageVersion = packageInfo.version;
  37. _prefs = await SharedPreferences.getInstance();
  38. //系统
  39. _uuid = PreferencesValue<String>('uuid', const Uuid().v4(), _prefs);
  40. _firstRun = PreferencesValue<bool>('first_run', true, _prefs);
  41. _firstRunTime = PreferencesValue<DateTime>('first_run_time', DateTime.now(), _prefs, saveDefault: true);
  42. _lastRunTime = PreferencesValue<DateTime>('last_run_time', DateTime.now(), _prefs, saveDefault: true);
  43. _lastDailyRewardTime = PreferencesValue<DateTime>('last_daily_reward_time', DateTime.now().subtract(const Duration(days: 1)), _prefs);
  44. //评分
  45. _rating = PreferencesValue<double>('rating', 0, _prefs);
  46. _rateShowTimes = PreferencesValue<int>('rate_show_times', 0, _prefs);
  47. _rateLastShowTime = PreferencesValue<DateTime>('last_rate_show_time', DateTime.now().subtract(const Duration(days: 1)), _prefs);
  48. //settings
  49. _sound = PreferencesValue<bool>('sound', true, _prefs);
  50. _music = PreferencesValue<bool>('music', true, _prefs);
  51. _vibrate = PreferencesValue<bool>('vibrate', true, _prefs);
  52. _skin = PreferencesValue<int>('skin', 0, _prefs);
  53. //banner 广告收益
  54. _lastBannerPaidReportTimestamp = PreferencesValue<int>('last_banner_paid_report_timestamp', DateTime.now().millisecondsSinceEpoch, _prefs);
  55. _bannerPaidValueMicros = PreferencesValue<double>('banner_paid_value_micros', 0, _prefs);
  56. _allPaidValueMicros = PreferencesValue<double>('all_paid_value_micros', 0, _prefs);
  57. _tRoasCache = PreferencesValue<double>('troas_cache', 0, _prefs);
  58. // !!! 改造点:完成作品集 - 存储 Work 对象列表
  59. _completedWorks = PreferencesValue<List<Work>>(
  60. 'completed_works',
  61. [],
  62. _prefs,
  63. encoder: (list) => list.map((w) => jsonEncode(w.toJson())).toList(), // 序列化
  64. decoder: (jsonList) => jsonList.map((jsonStr) => Work.fromJson(jsonDecode(jsonStr))).toList(), // 反序列化
  65. );
  66. // !!! 改造点:完成收藏图集 - 存储 Work 对象列表
  67. _completedCollections = PreferencesValue<List<Work>>(
  68. 'completed_collections',
  69. [],
  70. _prefs,
  71. encoder: (list) => list.map((c) => jsonEncode(c.toJson())).toList(), // 序列化
  72. decoder: (jsonList) => jsonList.map((jsonStr) => Work.fromJson(jsonDecode(jsonStr))).toList(), // 反序列化
  73. );
  74. }
  75. // uuid
  76. late PreferencesValue<String> _uuid;
  77. String get uuid => _uuid.value;
  78. set uuid(String value) => _uuid.value = value;
  79. // firstRun
  80. late PreferencesValue<bool> _firstRun;
  81. bool get firstRun => _firstRun.value;
  82. set firstRun(bool value) => _firstRun.value = value;
  83. // 程序第一次运行
  84. late PreferencesValue<DateTime> _firstRunTime;
  85. DateTime get firstRunTime => _firstRunTime.value;
  86. set firstRunTime(DateTime value) => _firstRunTime.value = value;
  87. //程序最后一次运行时间
  88. late PreferencesValue<DateTime> _lastRunTime;
  89. DateTime get lastRunTime => _lastRunTime.value;
  90. set lastRunTime(DateTime value) => _lastRunTime.value = value;
  91. //上一次 daily reward 时间
  92. late PreferencesValue<DateTime> _lastDailyRewardTime;
  93. DateTime get lastDailyRewardTime => _lastDailyRewardTime.value;
  94. set lastDailyRewardTime(DateTime value) => _lastDailyRewardTime.value = value;
  95. //评分
  96. late PreferencesValue<double> _rating;
  97. double get rating => _rating.value;
  98. set rating(double value) => _rating.value = value;
  99. //评分弹框次数
  100. late PreferencesValue<int> _rateShowTimes;
  101. int get rateShowTimes => _rateShowTimes.value;
  102. set rateShowTimes(int value) => _rateShowTimes.value = value;
  103. //评分上次弹框时间
  104. late PreferencesValue<DateTime> _rateLastShowTime;
  105. DateTime get rateLastShowTime => _rateLastShowTime.value;
  106. set rateLastShowTime(DateTime value) => _rateLastShowTime.value = value;
  107. // 各种按键声音效果
  108. late PreferencesValue<bool> _sound;
  109. bool get sound => _sound.value;
  110. set sound(bool value) => _sound.value = value;
  111. // 背景音乐
  112. late PreferencesValue<bool> _music;
  113. bool get music => _music.value;
  114. set music(bool value) => _music.value = value;
  115. // 振动
  116. late PreferencesValue<bool> _vibrate;
  117. bool get vibrate => _vibrate.value;
  118. set vibrate(bool value) => _vibrate.value = value;
  119. // 皮肤方案
  120. late PreferencesValue<int> _skin;
  121. int get skin => _skin.value;
  122. set skin(int value) => _skin.value = value;
  123. // banner 上一次广告收益上报时间
  124. late PreferencesValue<int> _lastBannerPaidReportTimestamp;
  125. int get lastBannerPaidReportTimestamp => _lastBannerPaidReportTimestamp.value;
  126. set lastBannerPaidReportTimestamp(int value) => _lastBannerPaidReportTimestamp.value = value;
  127. // banner 广告收益累积金额
  128. late PreferencesValue<double> _bannerPaidValueMicros;
  129. double get bannerPaidValueMicros => _bannerPaidValueMicros.value;
  130. set bannerPaidValueMicros(double value) => _bannerPaidValueMicros.value = value;
  131. // 所有广告收益累积金额
  132. late PreferencesValue<double> _allPaidValueMicros;
  133. double get allPaidValueMicros => _allPaidValueMicros.value;
  134. set allPaidValueMicros(double value) => _allPaidValueMicros.value = value;
  135. // 广告收益缓存,单位美元
  136. late PreferencesValue<double> _tRoasCache;
  137. double get tRoasCache => _tRoasCache.value;
  138. set tRoasCache(double value) => _tRoasCache.value = value;
  139. // !!! 改造点:已完成作品集合
  140. late PreferencesValue<List<Work>> _completedWorks;
  141. List<Work> get completedWorks => _completedWorks.value;
  142. set completedWorks(List<Work> value) => _completedWorks.value = value;
  143. // !!! 改造点:已完成收藏集合
  144. late PreferencesValue<List<Work>> _completedCollections;
  145. List<Work> get completedCollections => _completedCollections.value;
  146. set completedCollections(List<Work> value) => _completedCollections.value = value;
  147. }
  148. ///----------------------------
  149. class PreferencesValue<T> {
  150. final String key;
  151. final T defaultValue;
  152. final SharedPreferences prefs;
  153. // 新增:用于自定义对象列表的编码和解码函数
  154. final List<String> Function(T value)? encoder;
  155. final T Function(List<String> jsonList)? decoder;
  156. late T _value;
  157. T get value => _value;
  158. set value(T v) {
  159. _value = v;
  160. if (_value is bool) {
  161. unawaited(prefs.setBool(key, _value as bool));
  162. } else if (_value is int) {
  163. unawaited(prefs.setInt(key, _value as int));
  164. } else if (_value is String) {
  165. unawaited(prefs.setString(key, _value as String));
  166. } else if (_value is double) {
  167. unawaited(prefs.setDouble(key, _value as double));
  168. } else if (_value is DateTime) {
  169. unawaited(prefs.setInt(key, (_value as DateTime).millisecondsSinceEpoch));
  170. } // !!! 改造点:处理 List<CompletedWork> 或 List<CompletedCollection>
  171. else if (_value is List<String> && encoder == null) {
  172. // 兼容旧的List<String>
  173. unawaited(prefs.setStringList(key, _value as List<String>));
  174. } else if (_value is List && encoder != null) {
  175. // 针对自定义对象列表
  176. unawaited(prefs.setStringList(key, encoder!(_value))); // 使用 encoder 编码
  177. }
  178. // 注意:这里没有对List<T> (非List<String>) 和非列表的自定义T进行处理,
  179. // 如果有其他非List<String>的自定义T需要持久化,需要在这里添加逻辑,
  180. // 例如通过 jsonEncode(value.toJson()) / T.fromJson(jsonDecode(string))
  181. }
  182. PreferencesValue(this.key, this.defaultValue, this.prefs, {bool saveDefault = false, this.encoder, this.decoder}) {
  183. _value = defaultValue;
  184. bool isExist = prefs.containsKey(key);
  185. if (_value is bool) {
  186. _value = (prefs.getBool(key) ?? defaultValue) as T;
  187. if (!isExist && saveDefault) unawaited(prefs.setBool(key, _value as bool));
  188. } else if (_value is int) {
  189. _value = (prefs.getInt(key) ?? defaultValue) as T;
  190. if (!isExist && saveDefault) unawaited(prefs.setInt(key, _value as int));
  191. } else if (_value is String) {
  192. _value = (prefs.getString(key) ?? defaultValue) as T;
  193. if (!isExist && saveDefault) unawaited(prefs.setString(key, _value as String));
  194. } else if (_value is double) {
  195. _value = (prefs.getDouble(key) ?? defaultValue) as T;
  196. if (!isExist && saveDefault) unawaited(prefs.setDouble(key, _value as double));
  197. } else if (_value is DateTime) {
  198. int? tmp = prefs.getInt(key);
  199. _value = (tmp == null ? defaultValue : DateTime.fromMillisecondsSinceEpoch(tmp)) as T;
  200. if (!isExist && saveDefault) unawaited(prefs.setInt(key, (_value as DateTime).millisecondsSinceEpoch));
  201. } // !!! 改造点:处理 List<CompletedWork> 或 List<CompletedCollection>
  202. else if (_value is List<String> && decoder == null) {
  203. // 兼容旧的List<String>
  204. _value = (prefs.getStringList(key) ?? defaultValue) as T;
  205. if (!isExist && saveDefault) unawaited(prefs.setStringList(key, _value as List<String>));
  206. } else if (_value is List && decoder != null) {
  207. // 针对自定义对象列表
  208. final List<String>? jsonList = prefs.getStringList(key);
  209. if (jsonList != null && jsonList.isNotEmpty) {
  210. _value = decoder!(jsonList); // 使用 decoder 反序列化
  211. } else {
  212. _value = defaultValue;
  213. }
  214. if (!isExist && saveDefault) unawaited(prefs.setStringList(key, encoder!(_value))); // 保存默认值
  215. }
  216. }
  217. }