account_repository.dart 8.9 KB

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