account_repository.dart 9.0 KB

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