profile_provider.dart 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import 'package:flutter/painting.dart';
  2. import 'package:flutter_cache_manager/flutter_cache_manager.dart';
  3. import 'package:flutter_riverpod/flutter_riverpod.dart';
  4. import 'package:path_provider/path_provider.dart';
  5. import '../core/config/app_config.dart';
  6. import '../core/utils/avatar_urls.dart';
  7. import '../data/repositories/auth_repository.dart';
  8. import '../data/repositories/copy_trading_repository.dart';
  9. import 'auth_provider.dart';
  10. // ── Domain Models ──────────────────────────────────────────
  11. class UserProfile {
  12. final String email;
  13. final String rawEmail;
  14. final String uid;
  15. final String avatarLetter;
  16. /// 与 Web 顶栏一致:优先 uc/member/my-info,可由跟单资料补全。
  17. final String? avatarUrl;
  18. final bool isLoggedIn;
  19. /// 是否为经纪商(superPartner == "1")
  20. final bool isBroker;
  21. const UserProfile({
  22. required this.email,
  23. String? rawEmail,
  24. required this.uid,
  25. required this.avatarLetter,
  26. this.avatarUrl,
  27. required this.isLoggedIn,
  28. this.isBroker = false,
  29. }) : rawEmail = rawEmail ?? email;
  30. UserProfile copyWith({
  31. String? email,
  32. String? rawEmail,
  33. String? uid,
  34. String? avatarLetter,
  35. String? avatarUrl,
  36. bool? isLoggedIn,
  37. bool? isBroker,
  38. }) =>
  39. UserProfile(
  40. email: email ?? this.email,
  41. rawEmail: rawEmail ?? this.rawEmail,
  42. uid: uid ?? this.uid,
  43. avatarLetter: avatarLetter ?? this.avatarLetter,
  44. avatarUrl: avatarUrl ?? this.avatarUrl,
  45. isLoggedIn: isLoggedIn ?? this.isLoggedIn,
  46. isBroker: isBroker ?? this.isBroker,
  47. );
  48. }
  49. class ProfileState {
  50. final UserProfile user;
  51. final String appVersion;
  52. final bool isLoadingProfile;
  53. const ProfileState({
  54. required this.user,
  55. this.appVersion = AppConfig.appVersion,
  56. this.isLoadingProfile = false,
  57. });
  58. ProfileState copyWith({
  59. UserProfile? user,
  60. String? appVersion,
  61. bool? isLoadingProfile,
  62. }) =>
  63. ProfileState(
  64. user: user ?? this.user,
  65. appVersion: appVersion ?? this.appVersion,
  66. isLoadingProfile: isLoadingProfile ?? this.isLoadingProfile,
  67. );
  68. }
  69. // ── Notifier ───────────────────────────────────────────────
  70. class ProfileNotifier extends Notifier<ProfileState> {
  71. static const _guest = UserProfile(
  72. email: '未登录',
  73. uid: '',
  74. avatarLetter: 'U',
  75. isLoggedIn: false,
  76. );
  77. @override
  78. ProfileState build() {
  79. // 监听登录状态变化,自动刷新用户信息
  80. ref.listen<bool>(isLoggedInProvider, (_, loggedIn) {
  81. if (loggedIn) {
  82. _fetchProfile();
  83. } else {
  84. state = state.copyWith(user: _guest, isLoadingProfile: false);
  85. }
  86. });
  87. final loggedIn = ref.read(isLoggedInProvider);
  88. if (loggedIn) Future.microtask(_fetchProfile);
  89. Future.microtask(_loadAppVersion);
  90. return ProfileState(
  91. // 已登录时标记 loading,等 _fetchProfile 完成后才变 false
  92. isLoadingProfile: loggedIn,
  93. user: loggedIn
  94. ? const UserProfile(
  95. email: '***@**.com',
  96. uid: '00000',
  97. avatarLetter: 'U',
  98. avatarUrl: null,
  99. isLoggedIn: true,
  100. )
  101. : _guest,
  102. );
  103. }
  104. Future<void> _loadAppVersion() async {
  105. // 版本号与 pubspec.yaml / ProfileState 默认值保持一致
  106. }
  107. Future<void> _fetchProfile() async {
  108. if (!ref.read(isLoggedInProvider)) {
  109. return;
  110. }
  111. state = state.copyWith(isLoadingProfile: true);
  112. try {
  113. final repo = ref.read(authRepositoryProvider);
  114. final data = await repo.getMyInfo();
  115. if (!ref.read(isLoggedInProvider)) {
  116. return;
  117. }
  118. final email = (data['email'] as String?) ??
  119. (data['username'] as String?) ??
  120. '***@**.com';
  121. final uid = data['id']?.toString() ?? data['uid']?.toString() ?? '';
  122. final masked = _maskIdentity(email);
  123. final brokerRaw =
  124. data['superPartner'] ?? data['isBroker'] ?? data['broker'];
  125. final isBroker = brokerRaw == true ||
  126. brokerRaw == 1 ||
  127. brokerRaw == '1' ||
  128. brokerRaw == 'true';
  129. var avatarUrl =
  130. resolvedAvatarUrlFromRecord(Map<String, dynamic>.from(data));
  131. if (avatarUrl == null || avatarUrl.isEmpty) {
  132. try {
  133. final follow =
  134. await ref.read(copyTradingRepositoryProvider).getFollowerInfo();
  135. if (!ref.read(isLoggedInProvider)) {
  136. return;
  137. }
  138. avatarUrl = resolvedAvatarUrlFromRecord(follow);
  139. } catch (_) {
  140. // 未开通跟单或接口不可用
  141. }
  142. }
  143. if (!ref.read(isLoggedInProvider)) {
  144. return;
  145. }
  146. state = state.copyWith(
  147. isLoadingProfile: false,
  148. user: UserProfile(
  149. email: masked,
  150. rawEmail: email,
  151. uid: uid,
  152. avatarLetter: masked.isNotEmpty ? masked[0].toUpperCase() : 'U',
  153. avatarUrl:
  154. avatarUrl != null && avatarUrl.isNotEmpty ? avatarUrl : null,
  155. isLoggedIn: true,
  156. isBroker: isBroker,
  157. ),
  158. );
  159. } catch (_) {
  160. if (!ref.read(isLoggedInProvider)) {
  161. return;
  162. }
  163. state = state.copyWith(isLoadingProfile: false);
  164. }
  165. }
  166. String _maskIdentity(String identity) {
  167. if (identity.isEmpty) return identity;
  168. final at = identity.indexOf('@');
  169. if (at > -1) {
  170. // 邮箱:本地部分首2位 + **** + @域名
  171. final local = identity.substring(0, at);
  172. if (local.length <= 2) return identity;
  173. return '${local.substring(0, 2)}****@${identity.substring(at + 1)}';
  174. } else {
  175. // 非邮箱用户名:首2位 + **** + 末2位
  176. if (identity.length <= 4) return identity;
  177. return '${identity.substring(0, 2)}****${identity.substring(identity.length - 2)}';
  178. }
  179. }
  180. Future<void> logout() async {
  181. await ref.read(authProvider.notifier).logout();
  182. state = state.copyWith(user: _guest);
  183. }
  184. /// 清除本地缓存(图片缓存 + 临时文件),不清除用户偏好和登录态
  185. Future<void> clearCache() async {
  186. // 1. 清除 Flutter 内存图片缓存
  187. PaintingBinding.instance.imageCache.clear();
  188. PaintingBinding.instance.imageCache.clearLiveImages();
  189. // 2. 清除 cached_network_image 磁盘缓存
  190. await DefaultCacheManager().emptyCache();
  191. // 3. 清除系统临时目录
  192. try {
  193. final tempDir = await getTemporaryDirectory();
  194. if (tempDir.existsSync()) {
  195. await for (final entity in tempDir.list()) {
  196. try {
  197. await entity.delete(recursive: true);
  198. } catch (_) {
  199. // 跳过正在使用的文件
  200. }
  201. }
  202. }
  203. } catch (_) {
  204. // 临时目录不可用时忽略
  205. }
  206. }
  207. }
  208. // ── Provider ───────────────────────────────────────────────
  209. final profileProvider = NotifierProvider<ProfileNotifier, ProfileState>(
  210. ProfileNotifier.new,
  211. );