KMSignUpViewModel.swift 12 KB

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