KMSignUpViewModel.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 {
  161. passwordErrorMessage = NSLocalizedString("*Please enter right Verification code", tableName: "MemberCenterLocalizable", comment: "")
  162. return
  163. }
  164. code = password
  165. }
  166. KMMemberCenterManager.manager.emailLogin(email: email, code: code, type: signUpState) { [weak self] success, wrapper in
  167. guard let self = self else { return }
  168. let resultDict = wrapper! as KMMemberCenterResult
  169. let msg = resultDict.msg
  170. if success {
  171. let result: KMMemberLoginResult = resultDict.login_Result!
  172. let refresh_token = result.refreshToken
  173. let access_token = result.accessToken
  174. let token_type = result.tokenType
  175. let expires_in = result.expiresIn
  176. let scope = result.scope
  177. if self.stayState {
  178. UserDefaults.standard.setValue(refresh_token, forKey: "MemberRefreshToken")
  179. UserDefaults.standard.setValue(access_token, forKey: "MemberAccessToken")
  180. UserDefaults.standard.synchronize()
  181. } else {
  182. UserDefaults.standard.setValue("", forKey: "MemberRefreshToken")
  183. UserDefaults.standard.setValue("", forKey: "MemberAccessToken")
  184. UserDefaults.standard.synchronize()
  185. }
  186. KMMemberInfo.shared.refresh_token = refresh_token!
  187. KMMemberInfo.shared.access_token = access_token!
  188. KMMemberInfo.shared.token_type = token_type!
  189. self.refreshUserInfo()
  190. } else {
  191. print("错误信息:%@", msg as Any)
  192. let alert = NSAlert()
  193. alert.messageText = NSLocalizedString(msg!, comment: "")
  194. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  195. alert.beginSheetModal(for: NSApp.mainWindow!)
  196. }
  197. }
  198. }
  199. /**
  200. @abstract KMForgotPasswordView 登录弹窗(忘记密码)Next 按钮响应事件
  201. @param
  202. */
  203. func forgotPasswordNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  204. if !isValidEmail() {
  205. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  206. return
  207. }
  208. if email.count <= 0 {
  209. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  210. return
  211. }
  212. if emailErrorMessage.count > 0 {
  213. return
  214. }
  215. KMMemberCenterManager.manager.emailVerification(email: email) { [weak self] error, wrapper in
  216. guard let self = self else { return }
  217. let resultDict = wrapper! as KMMemberCenterResult
  218. let msg = resultDict.msg! as String
  219. if error {
  220. print("错误信息:%@", msg as Any)
  221. let alert = NSAlert()
  222. alert.messageText = NSLocalizedString(msg, comment: "")
  223. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  224. alert.beginSheetModal(for: NSApp.mainWindow!)
  225. } else {
  226. if resultDict.code == 200 {
  227. let result: Bool = resultDict.result!
  228. if result {
  229. complete(true, msg)
  230. } else {
  231. complete(false, msg)
  232. }
  233. } else {
  234. print("错误信息:%@", msg as Any)
  235. let alert = NSAlert()
  236. alert.messageText = NSLocalizedString(msg, comment: "")
  237. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  238. alert.beginSheetModal(for: NSApp.mainWindow!)
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. @abstract KMEnterVerificationCodeView 登录弹窗(输入验证码)Next 按钮响应事件
  245. @param
  246. */
  247. func enterVerificationCodeNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  248. if verificationCode.count <= 0 || !isValidVerificationCode() {
  249. emailErrorMessage = NSLocalizedString("*Please enter right Verification code", tableName: "MemberCenterLocalizable", comment: "")
  250. complete(false, "")
  251. return
  252. }
  253. complete(true, "")
  254. }
  255. /**
  256. @abstract 获取邮箱验证码
  257. @param
  258. */
  259. func getVerificationCode(_ type: KMVerificationCodeType) -> Void {
  260. if !isValidEmail() {
  261. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  262. return
  263. }
  264. KMMemberCenterManager.manager.getVerificationCode(action: type, receiver: email) { [weak self] error, wrapper in
  265. guard let self = self else { return }
  266. let resultDict = wrapper! as KMMemberCenterResult
  267. let msg = resultDict.msg
  268. let result: Bool = resultDict.result ?? false
  269. if error {
  270. if !result {
  271. self.emailErrorMessage = NSLocalizedString("*Please enter right Address", tableName: "MemberCenterLocalizable", comment: "")
  272. print("错误信息:%@", msg as Any)
  273. let alert = NSAlert()
  274. alert.messageText = NSLocalizedString(msg!, comment: "")
  275. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  276. alert.beginSheetModal(for: NSApp.mainWindow!)
  277. }
  278. } else {
  279. if resultDict.code == 200 {
  280. if !result {
  281. self.emailErrorMessage = NSLocalizedString("*Please enter right Address", tableName: "MemberCenterLocalizable", comment: "")
  282. } else {
  283. print("验证邮箱成功")
  284. }
  285. } else {
  286. print("错误信息:%@", msg as Any)
  287. let alert = NSAlert()
  288. alert.messageText = NSLocalizedString(msg!, comment: "")
  289. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  290. alert.beginSheetModal(for: NSApp.mainWindow!)
  291. }
  292. }
  293. }
  294. }
  295. /**
  296. @abstract 获取邮箱验证码
  297. @param
  298. */
  299. func resetPassword(_ complete: @escaping ForgotPasswordComplete) -> Void {
  300. KMMemberCenterManager.manager.resetPassword(email: email, verifyCode: verificationCode, password: password) { [weak self] error, wrapper in
  301. guard let self = self else { return }
  302. let resultDict = wrapper! as KMMemberCenterResult
  303. let msg = resultDict.msg! as String
  304. let result: Bool = resultDict.result ?? false
  305. if error {
  306. if !result {
  307. print("错误信息:%@", msg as Any)
  308. complete(false, msg)
  309. }
  310. } else {
  311. if resultDict.code == 200 {
  312. if !result {
  313. print("错误信息:%@", msg as Any)
  314. complete(false, msg)
  315. } else {
  316. print("验证邮箱成功")
  317. complete(false, msg)
  318. }
  319. } else {
  320. print("错误信息:%@", msg as Any)
  321. complete(false, msg)
  322. }
  323. }
  324. }
  325. }
  326. }