account_repository.dart 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import 'dart:async';
  2. import 'package:get/get.dart';
  3. import 'package:injectable/injectable.dart';
  4. import 'package:keyboard/data/api/atmob_api.dart';
  5. import 'package:keyboard/data/api/request/user_info_setting_request.dart';
  6. import 'package:keyboard/data/api/request/wechat_login_request.dart';
  7. import 'package:keyboard/data/api/response/wechat_login_response.dart';
  8. import 'package:keyboard/data/bean/member_info.dart';
  9. import 'package:keyboard/data/repository/keyboard_repository.dart';
  10. import '../../base/app_base_request.dart';
  11. import '../../di/get_it.dart';
  12. import '../../plugins/keyboard_android_platform.dart';
  13. import '../../utils/async_util.dart';
  14. import '../../utils/atmob_log.dart';
  15. import '../../utils/daily_limiter_util.dart';
  16. import '../../utils/http_handler.dart';
  17. import '../../utils/mmkv_util.dart';
  18. import '../api/request/complaint_submit_request.dart';
  19. import '../api/request/login_request.dart';
  20. import '../api/request/send_code_request.dart';
  21. import '../api/response/login_response.dart';
  22. import '../api/response/user_info_response.dart';
  23. import '../consts/constants.dart';
  24. import '../consts/error_code.dart';
  25. @lazySingleton
  26. class AccountRepository {
  27. final AtmobApi atmobApi;
  28. final String tag = "AccountRepository";
  29. static final String keyAccountLoginPhoneNum = 'key_account_login_phone_num';
  30. static final String keyAccountLoginToken = 'key_account_login_token';
  31. final Rxn<UserInfoResponse> _userInfo = Rxn<UserInfoResponse>();
  32. Rxn<UserInfoResponse> get userInfo => _userInfo;
  33. RxnString loginPhoneNum = RxnString();
  34. final RxBool isLogin = false.obs;
  35. Rxn<MemberInfo> memberStatusInfo = Rxn<MemberInfo>();
  36. bool get isVipUser =>
  37. memberStatusInfo.value != null && memberStatusInfo.value!.isMember && isLogin.value;
  38. int? _lastRequestCodeTime;
  39. int _errorCodeTimes = 0;
  40. Timer? refreshUserInfoHandler;
  41. CancelableFuture? userInfoFuture;
  42. static String? token = KVUtil.getString(keyAccountLoginToken, null);
  43. RxnString get tokenRxn => RxnString(token);
  44. final KeyboardRepository keyboardRepository =
  45. KeyboardRepository.getInstance();
  46. AccountRepository(this.atmobApi) {
  47. AtmobLog.d(tag, '$tag....init $hashCode');
  48. loginPhoneNum.value = KVUtil.getString(keyAccountLoginPhoneNum, null);
  49. refreshUserInfo();
  50. }
  51. // 检查是否在 60 秒内重复请求
  52. Future<void> loginSendCode(String phoneNum) {
  53. final currentTime = DateTime.now().millisecondsSinceEpoch;
  54. if (currentTime - (_lastRequestCodeTime ?? 0) < 60 * 1000) {
  55. throw RequestCodeTooOftenException();
  56. }
  57. return atmobApi
  58. .loginSendCode(SendCodeRequest(phoneNum))
  59. .then(HttpHandler.handle(true))
  60. .then((value) {
  61. _lastRequestCodeTime = currentTime;
  62. _errorCodeTimes = 0;
  63. });
  64. }
  65. Future<LoginResponse> loginUserLogin(
  66. String phoneNum,
  67. String verificationCode,
  68. ) {
  69. if (_errorCodeTimes >= 5) {
  70. throw LoginTooOftenException();
  71. }
  72. return atmobApi
  73. .loginUserLogin(LoginRequest(phoneNum, verificationCode))
  74. .then(HttpHandler.handle(true))
  75. .then((response) {
  76. _errorCodeTimes = 0;
  77. onLoginSuccess(phoneNum, response.authToken);
  78. return response;
  79. })
  80. .catchError((error) {
  81. if (error is ServerErrorException &&
  82. error.code == ErrorCode.verificationCodeError) {
  83. _errorCodeTimes++;
  84. }
  85. throw error;
  86. });
  87. }
  88. Future<WechatLoginResponse> wechatLogin(String code) {
  89. if (_errorCodeTimes >= 5) {
  90. throw LoginTooOftenException();
  91. }
  92. return atmobApi
  93. .loginUserWechatLogin(WechatLoginRequest(code))
  94. .then(HttpHandler.handle(true))
  95. .then((response) {
  96. _errorCodeTimes = 0;
  97. onWechatLoginSuccess(response.authToken);
  98. return response;
  99. })
  100. .catchError((error) {
  101. if (error is ServerErrorException &&
  102. error.code == ErrorCode.verificationCodeError) {
  103. _errorCodeTimes++;
  104. }
  105. throw error;
  106. });
  107. }
  108. Future<void> deprecateAccount() {
  109. return atmobApi.deprecate(AppBaseRequest()).then(HttpHandler.handle(true));
  110. }
  111. void refreshUserInfo() {
  112. userInfoFuture?.cancel();
  113. userInfoFuture = AsyncUtil.retryWithExponentialBackoff(
  114. () => getUserInfo(),
  115. 10,
  116. predicate: (error) {
  117. if (error is ServerErrorException) {
  118. return error.code != ErrorCode.noLoginError;
  119. }
  120. return true;
  121. },
  122. );
  123. userInfoFuture
  124. ?.then((userInfo) {
  125. AtmobLog.d(tag, "refreshUserInfo success: ${memberStatusInfo.value}");
  126. })
  127. .catchError((error) {
  128. AtmobLog.e(tag, "refreshUserInfo error: $error");
  129. });
  130. }
  131. Future<UserInfoResponse> getUserInfo() {
  132. return atmobApi
  133. .getUserInfo(AppBaseRequest())
  134. .then(HttpHandler.handle(true))
  135. .then((response) {
  136. _userInfo.value = response;
  137. if (response.loginStatus != null) {
  138. if (response.loginStatus == 1) {
  139. print("loginStatus == 1");
  140. isLogin.value = true;
  141. KVUtil.putBool(Constants.keyIsLogin, true);
  142. }
  143. if (response.loginStatus == 0) {
  144. print("loginStatus == 0");
  145. isLogin.value = false;
  146. }
  147. }
  148. memberStatusInfo.value = response.memberInfo;
  149. if (response.memberInfo != null) {
  150. KVUtil.putBool(
  151. Constants.keyIsMember,
  152. response.memberInfo!.isMember,
  153. );
  154. }
  155. return response;
  156. });
  157. }
  158. Future<void> setUserInfo({
  159. String? name,
  160. String? birthday,
  161. int? gender,
  162. String? imageUrl,
  163. List<String>? hobbies,
  164. List<String>? characters,
  165. }) {
  166. return atmobApi
  167. .setUserInfo(
  168. UserInfoSettingRequest(
  169. name: name,
  170. birthday: birthday,
  171. gender: gender,
  172. imageUrl: imageUrl,
  173. hobbies: hobbies,
  174. characters: characters,
  175. ),
  176. )
  177. .then(HttpHandler.handle(true));
  178. }
  179. void onLoginSuccess(String phoneNum, String authToken) {
  180. AccountRepository.token = authToken;
  181. loginPhoneNum.value = phoneNum;
  182. refreshUserInfo();
  183. KVUtil.putString(keyAccountLoginPhoneNum, phoneNum);
  184. KVUtil.putString(keyAccountLoginToken, authToken);
  185. keyboardRepository.refreshData();
  186. // 登录登录,通知键盘刷新数据
  187. KeyboardAndroidPlatform.refreshData();
  188. }
  189. void onWechatLoginSuccess(String authToken) {
  190. AccountRepository.token = authToken;
  191. refreshUserInfo();
  192. KVUtil.putString(keyAccountLoginToken, authToken);
  193. keyboardRepository.refreshData();
  194. }
  195. void logout() {
  196. token = null;
  197. KVUtil.putString(keyAccountLoginPhoneNum, null);
  198. KVUtil.putString(keyAccountLoginToken, null);
  199. memberStatusInfo.value = null;
  200. KVUtil.putBool(Constants.keyIsLogin, false);
  201. KVUtil.putBool(Constants.keyIsMember, false);
  202. loginPhoneNum.value = null;
  203. isLogin.value = false;
  204. keyboardRepository.refreshData();
  205. KVUtil.putString(Constants.keyboardSelect, null);
  206. DailyLimiterUtil.clearDailyLimitData("SurpriseDialog");
  207. // 退出登录,通知键盘刷新数据
  208. KeyboardAndroidPlatform.refreshData();
  209. }
  210. // 意见反馈
  211. Future<void> complaintSubmit(String? phone, String content) {
  212. return atmobApi
  213. .complaintSubmit(ComplaintSubmitRequest(phone, content))
  214. .then(HttpHandler.handle(true));
  215. }
  216. static AccountRepository getInstance() {
  217. return getIt.get<AccountRepository>();
  218. }
  219. }
  220. class RequestCodeTooOftenException implements Exception {
  221. final String message;
  222. /// 可选的构造函数,支持自定义错误信息
  223. RequestCodeTooOftenException([this.message = '请求验证码过于频繁']);
  224. @override
  225. String toString() => message;
  226. }
  227. class LoginTooOftenException implements Exception {
  228. final String message;
  229. /// 可选的构造函数,支持自定义错误信息
  230. LoginTooOftenException([this.message = '登录过于频繁']);
  231. @override
  232. String toString() => message;
  233. }