KMSignUpViewModel.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //
  2. // KMSignUpViewModel.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2024/10/24.
  6. //
  7. import Foundation
  8. import Combine
  9. @objc enum KMSignUpState : Int {
  10. case verificationCode = 0 // 验证码
  11. case password // 密码
  12. }
  13. @objc enum KMSuccessLoginJump : Int {
  14. case null = 0 //
  15. case compare // 比较表
  16. }
  17. typealias ForgotPasswordComplete = (_ success: Bool,_ msg: String) -> Void
  18. @objcMembers
  19. class KMSignUpViewModel: ObservableObject {
  20. /**
  21. 是否可视,默认不可视
  22. */
  23. @Published var isVisible: Bool = false
  24. /**
  25. 是否保持登录,默认保持登录
  26. */
  27. @Published var stayState: Bool = true
  28. /**
  29. 是否同意隐私权限
  30. */
  31. @Published var privacyState: Bool = false
  32. /**
  33. 登录界面是验证码验证还是邮箱验证
  34. */
  35. @Published var signUpState: KMSignUpState = .verificationCode
  36. /**
  37. 用户邮箱,字符串格式,默认为空
  38. */
  39. @Published var email: String = ""
  40. /**
  41. 用户邮箱登录的验证码,字符串格式,默认为空
  42. */
  43. @Published var verificationCode: String = ""
  44. /**
  45. 用户邮箱登录的密码,字符串格式,默认为空
  46. */
  47. @Published var password: String = ""
  48. /**
  49. 邮件 错误提示文案
  50. */
  51. @Published var emailErrorMessage: String = ""
  52. /**
  53. 验证码 / 密码 错误提示文案
  54. */
  55. @Published var passwordErrorMessage: String = ""
  56. /**
  57. 序列码按钮 文案
  58. */
  59. @Published var sendContent: String = NSLocalizedString("Send", tableName: "MemberCenterLocalizable", comment: "")
  60. @Published private var timer: AnyCancellable?
  61. private var remainingSeconds: Int = 60
  62. var sendBoxSelect: Bool = false
  63. // MARK: Public Method
  64. func signUpStateChange(state: KMSignUpState) -> Void {
  65. if state == signUpState {
  66. return
  67. }
  68. emailErrorMessage = ""
  69. passwordErrorMessage = ""
  70. if signUpState == .verificationCode {
  71. signUpState = .password
  72. } else {
  73. signUpState = .verificationCode
  74. }
  75. }
  76. func countDown(type: KMVerificationCodeType, count: Int = 60) -> Void {
  77. if emailErrorMessage.count > 0 || !isValidEmail() {
  78. return
  79. }
  80. getVerificationCode(type)
  81. sendBoxSelect = true
  82. remainingSeconds = count
  83. timer = Timer.publish(every: 1, on: .main, in: .common)
  84. .autoconnect()
  85. .sink { [weak self] _ in
  86. guard let self = self else { return }
  87. if self.remainingSeconds > 0 {
  88. self.remainingSeconds -= 1
  89. self.sendContent = String(format: "%d", self.remainingSeconds)
  90. } else {
  91. // 倒计时结束,停止定时器
  92. self.timer?.cancel()
  93. self.sendContent = NSLocalizedString("Resend", tableName: "MemberCenterLocalizable", comment: "")
  94. sendBoxSelect = false
  95. }
  96. }
  97. }
  98. /**
  99. 邮件 错误提示文案
  100. */
  101. func emailError() -> Bool {
  102. if emailErrorMessage.count > 0 {
  103. return true
  104. }
  105. return false
  106. }
  107. /**
  108. 验证码 / 密码 格式错误
  109. */
  110. func passwordError() -> Bool {
  111. if passwordErrorMessage.count > 0 {
  112. return true
  113. }
  114. return false
  115. }
  116. /**
  117. @abstract 验证邮箱是否合规
  118. */
  119. func isValidEmail() -> Bool {
  120. let emailRegex = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
  121. let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
  122. return emailTest.evaluate(with: email)
  123. }
  124. /**
  125. @abstract 验证验证码是否合规
  126. */
  127. func isValidVerificationCode() -> Bool {
  128. let pattern = "^\\d{6}$"
  129. let regex = try! NSRegularExpression(pattern: pattern)
  130. return regex.firstMatch(in: verificationCode, options: [], range: NSRange(location: 0, length: verificationCode.utf16.count)) != nil
  131. }
  132. func stayStateAction() -> Void {
  133. if !stayState {
  134. UserDefaults.standard.setValue("", forKey: "MemberAccessToken")
  135. UserDefaults.standard.synchronize()
  136. }
  137. }
  138. // MARK: Private Method
  139. /**
  140. @abstract 刷新用户个人信息
  141. */
  142. private func refreshUserInfo() -> Void {
  143. KMUserInfoVCModel().refreshUserInfo { success, msg in
  144. if success {
  145. KMMemberInfo.shared.isLogin = true
  146. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MemberCenterLoginSuccess"), object: nil)
  147. } else {
  148. KMMemberInfo.shared.isLogin = false
  149. }
  150. }
  151. }
  152. // MARK: Action Method
  153. /**
  154. @abstract KMSignUpView Sign Up 登录按钮响应事件
  155. @param
  156. */
  157. func signUpAction() -> Void {
  158. if email.count <= 0 || email.count > 100 || !isValidEmail() {
  159. emailErrorMessage = NSLocalizedString("Email format error. Please enter the correct email.", tableName: "MemberCenterLocalizable", comment: "")
  160. return
  161. }
  162. var code: String = ""
  163. if signUpState == .verificationCode {
  164. if verificationCode.count <= 0 || verificationCode.count > 6 || !isValidVerificationCode() {
  165. passwordErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  166. return
  167. }
  168. code = verificationCode
  169. } else if signUpState == .password {
  170. if password.count <= 0 || verificationCode.count > 30 {
  171. passwordErrorMessage = NSLocalizedString("Password error.", tableName: "MemberCenterLocalizable", comment: "")
  172. return
  173. }
  174. code = password
  175. }
  176. if !privacyState {
  177. let alert = NSAlert()
  178. alert.messageText = NSLocalizedString("Please agree and check the above agreement first.", tableName: "MemberCenterLocalizable", comment: "")
  179. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  180. // alert.beginSheetModal(for: NSApp.mainWindow!)
  181. let result = alert.runModal()
  182. if (result == .alertFirstButtonReturn) {
  183. privacyState = true
  184. }
  185. return
  186. }
  187. KMMemberCenterManager.manager.emailLogin(email: email, code: code, type: signUpState) { [weak self] success, wrapper in
  188. guard let self = self else { return }
  189. let resultDict = wrapper! as KMMemberCenterResult
  190. let msg = resultDict.msg
  191. if success {
  192. let result: KMMemberLoginResult = resultDict.login_Result!
  193. let refresh_token = result.refreshToken
  194. let access_token = result.accessToken
  195. let token_type = result.tokenType
  196. let expires_in = result.expiresIn
  197. let scope = result.scope
  198. if self.stayState {
  199. UserDefaults.standard.setValue(refresh_token, forKey: "MemberRefreshToken")
  200. UserDefaults.standard.setValue(access_token, forKey: "MemberAccessToken")
  201. UserDefaults.standard.synchronize()
  202. } else {
  203. UserDefaults.standard.setValue("", forKey: "MemberRefreshToken")
  204. UserDefaults.standard.setValue("", forKey: "MemberAccessToken")
  205. UserDefaults.standard.synchronize()
  206. }
  207. KMMemberInfo.shared.refresh_token = refresh_token!
  208. KMMemberInfo.shared.access_token = access_token!
  209. KMMemberInfo.shared.token_type = token_type!
  210. self.refreshUserInfo()
  211. self.timer?.cancel()
  212. self.sendContent = NSLocalizedString("Resend", tableName: "MemberCenterLocalizable", comment: "")
  213. } else {
  214. print("错误信息:%@", msg as Any)
  215. let alert = NSAlert()
  216. alert.messageText = NSLocalizedString(msg!, comment: "")
  217. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  218. alert.beginSheetModal(for: NSApp.mainWindow!)
  219. }
  220. }
  221. }
  222. /**
  223. @abstract KMForgotPasswordView 登录弹窗(忘记密码)Next 按钮响应事件
  224. @param
  225. */
  226. func forgotPasswordNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  227. if email.count <= 0 || email.count > 100 || !isValidEmail() {
  228. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  229. return
  230. }
  231. if emailErrorMessage.count > 0 {
  232. return
  233. }
  234. KMMemberCenterManager.manager.emailVerification(email: email) { [weak self] success, wrapper in
  235. guard let self = self else { return }
  236. let resultDict = wrapper! as KMMemberCenterResult
  237. let msg = resultDict.msg! as String
  238. if success {
  239. complete(true, msg)
  240. } else {
  241. complete(false, msg)
  242. }
  243. }
  244. }
  245. /**
  246. @abstract KMEnterVerificationCodeView 登录弹窗(输入验证码)Next 按钮响应事件
  247. @param
  248. */
  249. func enterVerificationCodeNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  250. if verificationCode.count <= 0 || verificationCode.count > 6 || !isValidVerificationCode() {
  251. emailErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  252. complete(false, "")
  253. return
  254. }
  255. KMMemberCenterManager.manager.checkVerificationCode(type: .reset, account: email, code: verificationCode) { [weak self] success, wrapper in
  256. guard let self = self else { return }
  257. let resultDict = wrapper! as KMMemberCenterResult
  258. let msg = resultDict.msg
  259. let result: Bool = resultDict.result ?? false
  260. if success {
  261. complete(true, "")
  262. } else {
  263. self.passwordErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  264. complete(false, "")
  265. }
  266. }
  267. }
  268. /**
  269. @abstract 获取邮箱验证码
  270. @param
  271. */
  272. func getVerificationCode(_ type: KMVerificationCodeType) -> Void {
  273. if !isValidEmail() {
  274. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  275. return
  276. }
  277. KMMemberCenterManager.manager.getVerificationCode(action: type, receiver: email) { [weak self] success, wrapper in
  278. guard let self = self else { return }
  279. let resultDict = wrapper! as KMMemberCenterResult
  280. let msg = resultDict.msg
  281. let result: Bool = resultDict.result ?? false
  282. if success {
  283. print("验证邮箱成功")
  284. } else {
  285. self.emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  286. }
  287. }
  288. }
  289. /**
  290. @abstract 重置密码
  291. @param
  292. */
  293. func resetPassword(_ complete: @escaping ForgotPasswordComplete) -> Void {
  294. if password.count <= 0 || verificationCode.count > 30 {
  295. passwordErrorMessage = NSLocalizedString("Password error.", tableName: "MemberCenterLocalizable", comment: "")
  296. return
  297. }
  298. KMMemberCenterManager.manager.resetPassword(email: email, verifyCode: verificationCode, password: password) { [weak self] success, wrapper in
  299. guard let self = self else { return }
  300. let resultDict = wrapper! as KMMemberCenterResult
  301. let msg = resultDict.msg! as String
  302. let result: Bool = resultDict.result ?? false
  303. complete(success, msg)
  304. }
  305. }
  306. }