login_controller.dart
20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
import 'dart:async';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:doublefeel_flutter/app/modules/login/views/email_login_new_password_view.dart';
import 'package:doublefeel_flutter/app/modules/login/views/email_login_view.dart';
import 'package:doublefeel_flutter/core/config/app_environment_config.dart';
import 'package:doublefeel_flutter/core/constants/app_const.dart';
import 'package:doublefeel_flutter/core/logging/app_logger.dart';
import 'package:doublefeel_flutter/core/services/app_config_service.dart';
import 'package:doublefeel_flutter/core/services/thinking_data_service.dart';
import 'package:doublefeel_flutter/data/models/local/user_preferences.dart';
import 'package:doublefeel_flutter/l10n/gen/app_localizations.dart';
import 'package:doublefeel_flutter/l10n/l10n_extensions.dart';
import 'package:doublefeel_flutter/pigeon/platform_api.g.dart';
import 'package:doublefeel_flutter/pigeon/wechat_api.g.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:doublefeel_flutter/core/util/app_toast.dart';
import 'package:doublefeel_flutter/core/network/api/user_api.dart';
import 'package:doublefeel_flutter/core/network/api/vip_api.dart';
import 'package:doublefeel_flutter/core/services/user_state_service.dart';
import 'package:doublefeel_flutter/data/local/local_storage.dart';
import 'package:doublefeel_flutter/data/local/user_account_storage.dart';
import 'package:doublefeel_flutter/data/local/user_preferences_storage.dart';
import 'package:doublefeel_flutter/data/models/user/user_models.dart';
import 'package:doublefeel_flutter/data/models/vip/vip_info.dart';
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:doublefeel_flutter/app/routes/app_pages.dart';
import 'package:doublefeel_flutter/core/services/loading_service.dart';
class LoginController extends GetxController {
final UserApi _userApi = Get.find<UserApi>();
final VipApi _vipApi = Get.find<VipApi>();
final UserPreferencesStorage _userPrefs = Get.find<UserPreferencesStorage>();
final UserAccountStorage _userAccount = Get.find<UserAccountStorage>();
final UserStateService _userStateService = Get.find<UserStateService>();
final environmentConfig = Get.find<AppEnvironmentConfig>();
final phoneController = TextEditingController();
final emailController = TextEditingController();
final passwordController = TextEditingController();
final resetPasswordCodeController = TextEditingController();
final codeController = TextEditingController();
final codeFocusNode = FocusNode();
final phoneInput = ''.obs;
final codeInput = ''.obs;
final emailInput = ''.obs;
final passwordInput = ''.obs;
final isSendingCode = false.obs;
final countdownSeconds = 0.obs;
Timer? _countdownTimer;
final isLoggingIn = false.obs;
final hasSentCode = false.obs;
final termsChecked = false.obs;
final isPasswordObscured = true.obs;
/// 是否已经点击过「Continue」(用于控制提示文字是否变红)
final hasTriedEmailLogin = false.obs;
final hasTriedEmailPwd = false.obs;
final resetPasswordCode = ''.obs;
void togglePasswordVisibility() {
isPasswordObscured.value = !isPasswordObscured.value;
}
static final _emailRegex = RegExp(
r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$',
);
static final _passwordRegex = RegExp(
r'^(?=.*[0-9])(?=.*[A-Z]).{6,}$',
);
bool get isEmailValid =>
_emailRegex.hasMatch(emailInput.value.trim()) &&
emailInput.value.isNotEmpty;
bool get isPasswordValid =>
_passwordRegex.hasMatch(passwordInput.value) &&
passwordInput.value.isNotEmpty;
final resetPasswordError = false.obs;
/// 邮箱格式正确且密码符合要求时,按钮可点击
bool get canEmailLogin => isEmailValid && isPasswordValid;
AppleSignInModel? appleSignInModel;
GoogleSignInModel? googleSignInModel;
bool _isToggling = false;
void toggleTermsChecked() {
// 互斥锁:函数执行期间忽略所有重入调用(手势积压、快速连点)
if (_isToggling) return;
_isToggling = true;
final newValue = !termsChecked.value;
termsChecked.value = newValue;
// ① 写盘不 await,避免阻塞(SharedPrefs 写失败影响极小)
unawaited(Get.find<LocalStorage>().setTermsAgreed(newValue).catchError(
(e) => AppLogger.e('setTermsAgreed error: $e'),
));
if (newValue && !_userStateService.sdksInitialized) {
// ② SDK 初始化完全异步,不阻塞任何点击
unawaited(_initSdksAndTrack());
}
// 释放锁:推迟到下一帧,确保当前帧内积压的所有手势事件都已被忽略
WidgetsBinding.instance.addPostFrameCallback((_) {
_isToggling = false;
});
}
Future<void> _initSdksAndTrack() async {
try {
await _userStateService.initializeSdks();
if (needTrackWelcomepage) {
ta.track('enter_doublefeel_welcome_page');
needTrackWelcomepage = false;
}
unawaited(AppConfigService.to.fetch());
} catch (e) {
AppLogger.e('initializeSdks error: $e');
}
}
void onPhoneLoginPressed() {
if (!termsChecked.value &&
environmentConfig.region.value == AppRegion.china) {
AppToast.show(AppLocalizations.of(Get.context!)!.loginAgreeToTermsToast);
return;
}
ta.track('enter_doublefeel_telephone_login_page');
Get.toNamed(AppRoutes.phoneLogin);
}
void onEmailLoginPressed() {
ta.track('enter_doublefeel_email_login_page');
Get.to(() => const EmailLoginView());
}
void onAppleLoginPressed() async {
if (!termsChecked.value &&
environmentConfig.region.value == AppRegion.china) {
AppToast.show(AppLocalizations.of(Get.context!)!.loginAgreeToTermsToast);
return;
}
try {
final result = await LoadingService.instance.run(() async {
return await PlatformHostApi().requestAppleSignIn();
}, type: LoadingType.circular);
// result 为 null 或 identityToken 为空,说明用户取消或苹果授权失败
if (result == null ||
result.identityToken?.isNotEmpty != true ||
result.userId.isNotEmpty != true) {
appleSignInModel = null;
return;
}
appleSignInModel = result;
await _loginWithApple(result);
} catch (e) {
appleSignInModel = null;
AppToast.show(e.toString());
}
}
void onGoogleLoginPressed() async {
try {
final result = await LoadingService.instance.run(() async {
return await PlatformHostApi().requestGoogleSignIn();
}, type: LoadingType.circular);
// result 为 null 或 identityToken 为空,说明用户取消或苹果授权失败
if (result == null ||
result.idToken.isNotEmpty != true ||
result.clientID?.isNotEmpty != true) {
googleSignInModel = null;
return;
}
googleSignInModel = result;
await _loginWithGoogle(result);
} catch (e) {
googleSignInModel = null;
AppToast.show(e.toString());
}
}
void onWechatLoginPressed() async {
if (!termsChecked.value &&
environmentConfig.region.value == AppRegion.china) {
AppToast.show(AppLocalizations.of(Get.context!)!.loginAgreeToTermsToast);
return;
}
try {
final code = await LoadingService.instance.run(
() => WeChatHostApi().requestAuthorizationCode(),
type: LoadingType.circular,
);
if (code.isEmpty) return;
await _loginWithWechat(code);
} on PlatformException catch (e) {
AppToast.show(e.message?.isNotEmpty == true ? e.message! : '微信登录失败');
} catch (e) {
AppToast.show(e.toString());
}
}
void onDebugPressed() {
Get.toNamed(AppRoutes.debugEnvironment);
}
Future<void> selectServiceRegion(AppRegion region) async {
if (environmentConfig.region.value == region) return;
await environmentConfig.setRegion(region);
if (environmentConfig.region.value == AppRegion.china) {
if (termsChecked.value) toggleTermsChecked();
} else {
if (!termsChecked.value) toggleTermsChecked();
}
ta.setSuperProperties({
'app_region': environmentConfig.region.value == AppRegion.china
? 'mainland'
: 'overseas'
});
}
void openUserTerms() {
String url = environmentConfig.region.value == AppRegion.china
? AppConst.userTerms
: AppConst.userTermsGlobal;
Get.toNamed(
AppRoutes.webview,
parameters: {'url': url},
);
}
void openPrivacyPolicy() {
String url = environmentConfig.region.value == AppRegion.china
? AppConst.privacyPolicy
: AppConst.privacyPolicyGlobal;
Get.toNamed(
AppRoutes.webview,
parameters: {'url': url},
);
}
@override
void onInit() {
super.onInit();
termsChecked.value = Get.find<LocalStorage>().termsAgreed;
phoneController.addListener(() {
phoneInput.value = phoneController.text;
});
codeController.addListener(() {
codeInput.value = codeController.text;
});
emailController.addListener(() {
emailInput.value = emailController.text;
hasTriedEmailLogin.value = false;
});
passwordController.addListener(() {
hasTriedEmailPwd.value = false;
passwordInput.value = passwordController.text;
});
resetPasswordCodeController.addListener(() {
resetPasswordCode.value = resetPasswordCodeController.text.trim();
});
}
bool get canResetPassword =>
resetPasswordCode.value.isNotEmpty && isPasswordValid;
@override
void onClose() {
_countdownTimer?.cancel();
phoneController.dispose();
codeController.dispose();
passwordController.dispose();
resetPasswordCodeController.dispose();
codeFocusNode.dispose();
super.onClose();
}
@override
void onReady() {
super.onReady();
if (_userStateService.sdksInitialized) {
ta.track('enter_doublefeel_welcome_page');
needTrackWelcomepage = false;
} else {
needTrackWelcomepage = true;
}
}
bool needTrackWelcomepage = false;
String get cleanPhone => phoneInput.value.replaceAll(' ', '');
bool get canRequestCode =>
cleanPhone.length == 11 &&
!isSendingCode.value &&
countdownSeconds.value == 0;
bool get canLogin =>
cleanPhone.length == 11 &&
codeInput.value.isNotEmpty &&
!isLoggingIn.value;
Future<void> requestVerifyCode() async {
if (!canRequestCode) return;
if (cleanPhone.length < 11) {
AppToast.show(AppLocalizations.of(Get.context!)!.phoneLoginInvalidPhone);
return;
}
isSendingCode.value = true;
final request = VerifyCodeRequest.login(cleanPhone);
final result = await _userApi.requestVerifyCode(request);
isSendingCode.value = false;
if (result is AppSuccess<void>) {
AppToast.show(
AppLocalizations.of(Get.context!)!.phoneLoginCodeSentSuccess);
_startCountdown();
codeFocusNode.requestFocus();
}
}
void _startCountdown() {
hasSentCode.value = true;
_countdownTimer?.cancel();
countdownSeconds.value = 60;
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (countdownSeconds.value > 1) {
countdownSeconds.value--;
} else {
countdownSeconds.value = 0;
timer.cancel();
}
});
}
Future<void> login() async {
if (!canLogin) return;
if (cleanPhone.length < 11) {
AppToast.show(AppLocalizations.of(Get.context!)!.phoneLoginInvalidPhone);
return;
}
if (codeInput.value.isEmpty) {
AppToast.show(AppLocalizations.of(Get.context!)!.phoneLoginInvalidCode);
return;
}
isLoggingIn.value = true;
try {
await LoadingService.instance.run(() async {
final loginRes = await _userApi.login(
telephone: cleanPhone,
verifyCode: codeInput.value,
);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data);
await Get.find<LocalStorage>().setLastLoginMethod('phone');
await environmentConfig.updateHideChooseRegion(true);
}
});
} finally {
isLoggingIn.value = false;
}
}
/// 邮箱登录 Continue 按钮点击
Future<void> emailLogin() async {
hasTriedEmailLogin.value = true;
hasTriedEmailPwd.value = true;
if (!isEmailValid) {
// AppToast.show(l10n.invalidEmailFormat);
return;
}
if (!isPasswordValid) {
// AppToast.show(l10n.invalidPasswordFormat);
return;
}
isLoggingIn.value = true;
try {
final md5Password =
md5.convert(utf8.encode(passwordInput.value)).toString();
await LoadingService.instance.run(() async {
final loginRes = await _userApi.loginWithEmail(
email: emailInput.value.trim(),
password: md5Password,
);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data, emailPassword: md5Password);
await Get.find<LocalStorage>().setLastLoginMethod('email');
}
});
} finally {
isLoggingIn.value = false;
}
var success = true;
if (success) {
TextInput.finishAutofillContext();
}
}
Future<void> sendRestEmail() async {
if (!isEmailValid) {
AppToast.show(l10n.invalidEmailFormat);
return;
}
try {
await LoadingService.instance.run(() async {
final loginRes = await _userApi.forgetPasswordSendEmail(
email: emailInput.value.trim(),
);
if (loginRes is AppSuccess<LoginResponse>) {
Get.to(() => EmailLoginNewPasswordView());
} else {}
});
} catch (e) {}
}
Future<void> resetPassword() async {
if (!isEmailValid) {
// AppToast.show(l10n.invalidEmailFormat);
return;
}
if (resetPasswordCode.value.isEmpty) {
AppToast.show(l10n.invalidCode);
return;
}
if (!isPasswordValid) {
// AppToast.show(l10n.invalidPasswordFormat);
return;
}
try {
final md5Password =
md5.convert(utf8.encode(passwordInput.value)).toString();
await LoadingService.instance.run(() async {
final loginRes = await _userApi.forgetPasswordSetNewPassword(
email: emailInput.value.trim(),
verificationCode: resetPasswordCode.value,
newPassword: md5Password,
);
if (loginRes is AppSuccess<LoginResponse>) {
AppToast.show(l10n.paswordHasBeenChanged);
Get.back();
Get.back();
} else {}
});
} catch (e) {}
}
Future<void> _loginWithApple(AppleSignInModel appleModel) async {
isLoggingIn.value = true;
try {
await LoadingService.instance.run(() async {
final loginRes = await _userApi.loginWithApple(appleModel);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data, appleModel: appleModel);
await Get.find<LocalStorage>().setLastLoginMethod('apple');
await environmentConfig.updateHideChooseRegion(true);
}
});
} finally {
isLoggingIn.value = false;
}
}
Future<void> _loginWithWechat(String code) async {
isLoggingIn.value = true;
try {
await LoadingService.instance.run(() async {
final loginRes = await _userApi.loginWithWechat(code);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data, wechatCode: code);
await Get.find<LocalStorage>().setLastLoginMethod('wechat');
await environmentConfig.updateHideChooseRegion(true);
}
});
} finally {
isLoggingIn.value = false;
}
}
Future<void> _loginWithGoogle(GoogleSignInModel googleModel) async {
isLoggingIn.value = true;
try {
await LoadingService.instance.run(() async {
final loginRes = await _userApi.loginWithGoogle(googleModel);
if (loginRes is AppSuccess<LoginResponse>) {
await _handleLoginSuccess(loginRes.data, googleModel: googleModel);
await Get.find<LocalStorage>().setLastLoginMethod('google');
await environmentConfig.updateHideChooseRegion(true);
}
});
} finally {
isLoggingIn.value = false;
}
}
/// 登录/注册成功后的公共处理逻辑(手机号登录与苹果登录共用)
Future<void> _handleLoginSuccess(LoginResponse loginData,
{AppleSignInModel? appleModel,
GoogleSignInModel? googleModel,
String? emailPassword,
String? wechatCode}) async {
bool isApple = appleModel != null;
bool isGoogle = googleModel != null;
bool isEmail = emailPassword != null;
bool isWechat = wechatCode != null;
final isRegister = loginData.isNewUser == true;
String accessToken = loginData.accessToken;
if (isRegister) {
Map<String, dynamic>? registerData;
if (isApple) {
registerData = {
'login_type': 'apple',
'apple_user_id': appleModel.userId,
'identity_token': appleModel.identityToken,
};
} else if (isGoogle) {
registerData = {
'login_type': 'google',
'identity_token': googleModel.idToken,
'expected_client_id': googleModel.clientID,
};
} else if (isEmail) {
registerData = {
'login_type': 'email',
'email': emailInput.value.trim(),
'password': emailPassword,
};
} else if (isWechat) {
registerData = {
'login_type': 'wechat',
'wechat_code': wechatCode,
};
} else {
registerData = {
'login_type': 'verification_code',
'telephone': cleanPhone,
'verification_code': codeInput.value,
};
}
if (environmentConfig.region.value == AppRegion.global) {
try {
final timezoneInfo = await FlutterTimezone.getLocalTimezone();
registerData['tz_iana'] = timezoneInfo.identifier;
} catch (e) {
// AppLogger.w('Failed to get IANA timezone: $e');
// registerData['tz_iana'] = DateTime.now().timeZoneName;
}
}
final regRes = await _userApi.register(registerData);
if (regRes is AppSuccess<RegisterResponse>) {
accessToken = regRes.data.accessToken;
} else {
isLoggingIn.value = false;
return;
}
}
// Fetch user info and VIP info
final userInfoResFuture = _userApi.getUserInfo(accessToken: accessToken);
final vipInfoResFuture = isRegister
? Future.value(null)
: _vipApi.getVipInfo(accessToken: accessToken);
final results = await Future.wait([userInfoResFuture, vipInfoResFuture]);
final userInfoRes = results[0];
final vipInfoRes = results[1];
if (userInfoRes is AppSuccess<UserInfoResponse>) {
final me = userInfoRes.data;
UserInfoResponse? partner;
// if ((me.pairId ?? 0) > 0) {
// final partnerRes =
// await _userApi.getPartnerUserInfo(accessToken: accessToken);
// if (partnerRes is AppSuccess<BoundUserInfoResponse>) {
// partner = partnerRes.data.partnerUserInfo;
// }
// }
VipInfo? vip;
if (vipInfoRes is AppSuccess<VipInfo>) {
vip = vipInfoRes.data;
}
await _userPrefs.updateFromLogin(
accessToken: accessToken,
me: me,
partner: partner,
vip: vip,
);
try {
if (Get.isRegistered<AppEnvironmentConfig>()) {
var env = Get.find<AppEnvironmentConfig>();
await PlatformHostApi().updateLoginInfo(
jsonEncode(UserPreferences(
accessToken: accessToken,
meUserInfo: me,
partnerUserInfo: partner,
vipInfo: vip != null
? UserPreferencesVipInfo.fromVipInfo(vip)
: null,
)),
env.serverBaseUrl);
}
} on Exception catch (e) {
AppLogger.e(e);
}
await _userStateService.onLogin();
if (isRegister) {
ta.track('success_regist');
}
// 用户登录成功即代表同意了协议,持久化到本地供冷启动时 SDK 初始化判断使用
await Get.find<LocalStorage>().setTermsAgreed(true);
// 根据引导完成状态决定跳转目标
final userId = me.id ?? 0;
if (_userAccount.hasCompletedOnboarding(userId) ||
me.isPassNoviceGuide == 1) {
// 该账号已完成引导,直接进主页
Get.offAllNamed(AppRoutes.home);
} else {
// 新用户或未完成引导,进入引导页(支持断点续做)
final resumeStage = _userAccount.onboardingResumeStage(userId);
Get.offAllNamed(
AppRoutes.userOnboarding,
arguments: resumeStage != null ? {'resumeStage': resumeStage} : null,
);
}
} else {
// userInfoRes 失败,外层 finally 会重置 isLoggingIn
}
}
}