account_repository.dart 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import 'dart:async';
  2. import 'package:get/get.dart';
  3. import 'package:injectable/injectable.dart';
  4. import 'package:location/base/app_base_request.dart';
  5. import 'package:location/data/api/atmob_api.dart';
  6. import 'package:location/data/api/request/login_request.dart';
  7. import 'package:location/data/api/request/send_code_request.dart';
  8. import 'package:location/data/bean/location_info.dart';
  9. import 'package:location/data/bean/member_status_info.dart';
  10. import 'package:location/data/bean/user_info.dart';
  11. import 'package:location/data/consts/constants.dart';
  12. import 'package:location/data/consts/error_code.dart';
  13. import 'package:location/data/repositories/friends_repository.dart';
  14. import 'package:location/data/repositories/message_repository.dart';
  15. import 'package:location/data/repositories/urgent_contact_repository.dart';
  16. import 'package:location/di/get_it.dart';
  17. import 'package:location/resource/string.gen.dart';
  18. import 'package:location/socket/atmob_location_client.dart';
  19. import 'package:location/utils/async_util.dart';
  20. import 'package:location/utils/atmob_log.dart';
  21. import 'package:location/utils/http_handler.dart';
  22. import 'package:location/utils/mmkv_util.dart';
  23. import '../../sdk/map/map_helper.dart';
  24. import '../api/request/user_avatar_update_request.dart';
  25. import '../api/response/login_response.dart';
  26. import '../api/response/member_status_response.dart';
  27. @lazySingleton
  28. class AccountRepository {
  29. final AtmobApi atmobApi;
  30. final String tag = "AccountRepository";
  31. static final String keyAccountLoginPhoneNum = 'key_account_login_phone_num';
  32. static final String keyAccountLoginToken = 'key_account_login_token';
  33. static final String keyAccountLoginUserId = 'key_account_login_user_id';
  34. RxnString loginPhoneNum = RxnString();
  35. RxBool isLogin = RxBool(false);
  36. Rxn<MemberStatusInfo> memberStatusInfo = Rxn<MemberStatusInfo>();
  37. int? _lastRequestCodeTime;
  38. int _errorCodeTimes = 0;
  39. Timer? refreshMemberHandler;
  40. CancelableFuture? memberStatusFuture;
  41. static String? token = KVUtil.getString(keyAccountLoginToken, null);
  42. late final FriendsRepository friendsRepository;
  43. late final MessageRepository messageRepository;
  44. late final UrgentContactRepository urgentContactRepository;
  45. final Rx<UserInfo> mineUserInfo = Rx<UserInfo>(UserInfo(
  46. id: Constants.mineLocationId,
  47. phoneNumber: StringName.locationMine,
  48. isMine: true));
  49. AccountRepository(this.atmobApi) {
  50. AtmobLog.d(tag, '$tag....init');
  51. friendsRepository = FriendsRepository.getInstance();
  52. messageRepository = MessageRepository.getInstance();
  53. urgentContactRepository = UrgentContactRepository.getInstance();
  54. isLogin.bindStream(
  55. loginPhoneNum.map((value) {
  56. return value?.isNotEmpty == true;
  57. }),
  58. );
  59. loginPhoneNum.value = KVUtil.getString(keyAccountLoginPhoneNum, null);
  60. refreshMemberStatus();
  61. MapHelper.addLocationListener((location) {
  62. mineUserInfo.value.lastLocation.value =
  63. LocationInfo.fromMapLocation(location);
  64. });
  65. }
  66. static AccountRepository getInstance() {
  67. return getIt.get<AccountRepository>();
  68. }
  69. Future<void> loginSendCode(String phoneNum) {
  70. final currentTime = DateTime.now().millisecondsSinceEpoch;
  71. // 检查是否在 60 秒内重复请求
  72. if (currentTime - (_lastRequestCodeTime ?? 0) < 60 * 1000) {
  73. throw RequestCodeTooOftenException();
  74. }
  75. return atmobApi
  76. .loginSendCode(SendCodeRequest(phoneNum))
  77. .then(HttpHandler.handle(true))
  78. .then((value) {
  79. _lastRequestCodeTime = currentTime;
  80. _errorCodeTimes = 0;
  81. });
  82. }
  83. Future<LoginResponse> loginUserLogin(
  84. String phoneNum, String verificationCode) {
  85. if (_errorCodeTimes >= 5) {
  86. return Future.error(LoginTooOftenException());
  87. }
  88. return atmobApi
  89. .loginUserLogin(LoginRequest(phoneNum, verificationCode))
  90. .then(HttpHandler.handle(true))
  91. .then((response) {
  92. _errorCodeTimes = 0;
  93. onLoginSuccess(phoneNum, response.authToken);
  94. return response;
  95. }).catchError((error) {
  96. if (error is ServerErrorException &&
  97. error.code == ErrorCode.verificationCodeError) {
  98. _errorCodeTimes++;
  99. }
  100. throw error;
  101. });
  102. }
  103. void onLoginSuccess(String phoneNum, String authToken) {
  104. AccountRepository.token = authToken;
  105. loginPhoneNum.value = phoneNum;
  106. KVUtil.putString(keyAccountLoginPhoneNum, phoneNum);
  107. KVUtil.putString(keyAccountLoginToken, authToken);
  108. AtmobLocationClient.connectWebSocket();
  109. refreshMemberStatus();
  110. friendsRepository.refreshFriends();
  111. messageRepository.refreshFriendWaitingCount();
  112. messageRepository.refreshUnreadMessage();
  113. urgentContactRepository.requestUrgentContactList();
  114. }
  115. void logout() {
  116. token = null;
  117. refreshMemberHandler?.cancel();
  118. AtmobLocationClient.disConnectWebSocket();
  119. KVUtil.putString(keyAccountLoginPhoneNum, null);
  120. KVUtil.putString(keyAccountLoginToken, null);
  121. KVUtil.putString(keyAccountLoginUserId, null);
  122. KVUtil.putString(Constants.keyLastSelectFriendId, null);
  123. loginPhoneNum.value = null;
  124. memberStatusInfo.value = null;
  125. friendsRepository.clearFriends();
  126. messageRepository.clearMessage();
  127. urgentContactRepository.clearContactList();
  128. }
  129. void refreshMemberStatus() {
  130. memberStatusFuture?.cancel();
  131. memberStatusFuture = AsyncUtil.retryWithExponentialBackoff(
  132. () => getMemberStatus(), 10, predicate: (error) {
  133. if (error is ServerErrorException) {
  134. return error.code != ErrorCode.noLoginError;
  135. }
  136. return true;
  137. });
  138. memberStatusFuture?.then((data) {
  139. AtmobLog.d(tag, "getMemberStatus success: ${memberStatusInfo.value}");
  140. }).catchError((error) {
  141. AtmobLog.e(tag, "getMemberStatus error: $error");
  142. });
  143. }
  144. Future<MemberStatusResponse> getMemberStatus() {
  145. return atmobApi
  146. .getMemberStatus(AppBaseRequest())
  147. .then(HttpHandler.handle(false))
  148. .then((response) {
  149. refreshMemberHandler?.cancel();
  150. updateAvatar(response.avatar);
  151. KVUtil.putString(keyAccountLoginUserId, response.deviceId);
  152. if (!response.permanent && !response.expired) {
  153. refreshMemberHandler = Timer(
  154. Duration(
  155. milliseconds: response.endTimestamp - response.serverTimestamp),
  156. () => refreshMemberStatus());
  157. }
  158. return response;
  159. }).then((response) {
  160. MemberStatusInfo memberStatusInfo = MemberStatusInfo(
  161. level: response.level,
  162. endTimestamp: response.endTimestamp,
  163. expired: response.expired,
  164. permanent: response.permanent,
  165. trialed: response.trialed,
  166. avatar: response.avatar,
  167. trialEndTimestamp: response.trialEndTimestamp
  168. );
  169. this.memberStatusInfo.value = memberStatusInfo;
  170. return response;
  171. });
  172. }
  173. void updateAvatar(String? avatar) {
  174. mineUserInfo.value.avatar = avatar;
  175. mineUserInfo.refresh();
  176. }
  177. Future<bool> userAvatarUpdate(String avatar) {
  178. if (avatar == mineUserInfo.value.avatar) {
  179. return Future.value(true);
  180. }
  181. return atmobApi
  182. .userAvatarUpdate(UserAvatarUpdateRequest(avatar))
  183. .then(HttpHandler.handle(true))
  184. .then((_) {
  185. updateAvatar(avatar);
  186. AtmobLog.d(tag, "userAvatarUpdate success: $avatar");
  187. return true;
  188. });
  189. }
  190. bool memberIsExpired() {
  191. return memberStatusInfo.value == null ||
  192. memberStatusInfo.value?.expired == true;
  193. }
  194. Future<void> userClear() {
  195. return atmobApi.userClear(AppBaseRequest()).then(HttpHandler.handle(true));
  196. }
  197. }
  198. class RequestCodeTooOftenException implements Exception {
  199. final String message;
  200. /// 可选的构造函数,支持自定义错误信息
  201. RequestCodeTooOftenException([this.message = '请求验证码过于频繁']);
  202. @override
  203. String toString() => message;
  204. }
  205. class LoginTooOftenException implements Exception {
  206. final String message;
  207. /// 可选的构造函数,支持自定义错误信息
  208. LoginTooOftenException([this.message = '登录过于频繁']);
  209. @override
  210. String toString() => message;
  211. }