KMSignUpViewModel.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. @objc enum KMLoginScreenType : Int {
  18. case signUp = 0 //
  19. case forgotPassword //
  20. case enterVerificationCode //
  21. case enterNewPassword //
  22. }
  23. typealias ForgotPasswordComplete = (_ success: Bool,_ msg: String) -> Void
  24. @objcMembers
  25. class KMSignUpViewModel: ObservableObject {
  26. /**
  27. 是否可视,默认不可视
  28. */
  29. @Published var isVisible: Bool = false
  30. /**
  31. 是否保持登录,默认保持登录
  32. */
  33. @Published var stayState: Bool = true
  34. /**
  35. 是否同意隐私权限
  36. */
  37. @Published var privacyState: Bool = false
  38. /**
  39. 登录界面是验证码验证还是邮箱验证
  40. */
  41. @Published var signUpState: KMSignUpState = .verificationCode
  42. /**
  43. 用户邮箱,字符串格式,默认为空
  44. */
  45. @Published var email: String = ""
  46. /**
  47. 用户邮箱登录的验证码,字符串格式,默认为空
  48. */
  49. @Published var verificationCode: String = ""
  50. /**
  51. 用户邮箱登录的密码,字符串格式,默认为空
  52. */
  53. @Published var password: String = ""
  54. /**
  55. 邮件 错误提示文案
  56. */
  57. @Published var emailErrorMessage: String = ""
  58. /**
  59. 验证码 / 密码 错误提示文案
  60. */
  61. @Published var passwordErrorMessage: String = ""
  62. /**
  63. 序列码按钮 文案
  64. */
  65. @Published var sendContent: String = NSLocalizedString("Send", tableName: "MemberCenterLocalizable", comment: "")
  66. /**
  67. 当前视图类型
  68. */
  69. @Published var screenType: KMLoginScreenType = .signUp
  70. @Published private var timer: AnyCancellable?
  71. private var remainingSeconds: Int = 60
  72. var sendBoxSelect: Bool = false
  73. // MARK: Public Method
  74. func signUpStateChange(state: KMSignUpState) -> Void {
  75. if state == signUpState {
  76. return
  77. }
  78. emailErrorMessage = ""
  79. passwordErrorMessage = ""
  80. if signUpState == .verificationCode {
  81. signUpState = .password
  82. } else {
  83. signUpState = .verificationCode
  84. }
  85. }
  86. func countDown(type: KMVerificationCodeType, count: Int = 60, callback: ((Bool?, Any ...)->Void)?) -> Void {
  87. if emailErrorMessage.count > 0 || !isValidEmail() {
  88. return
  89. }
  90. getVerificationCode(type, callback: callback)
  91. sendBoxSelect = true
  92. remainingSeconds = count
  93. timer = Timer.publish(every: 1, on: .main, in: .common)
  94. .autoconnect()
  95. .sink { [weak self] _ in
  96. guard let self = self else { return }
  97. if self.remainingSeconds > 0 {
  98. self.remainingSeconds -= 1
  99. self.sendContent = String(format: "%d", self.remainingSeconds)
  100. } else {
  101. // 倒计时结束,停止定时器
  102. self.timer?.cancel()
  103. self.sendContent = NSLocalizedString("Resend", tableName: "MemberCenterLocalizable", comment: "")
  104. self.sendBoxSelect = false
  105. }
  106. }
  107. }
  108. /**
  109. 邮件 错误提示文案
  110. */
  111. func emailError() -> Bool {
  112. if emailErrorMessage.count > 0 {
  113. return true
  114. }
  115. return false
  116. }
  117. /**
  118. 验证码 / 密码 格式错误
  119. */
  120. func passwordError() -> Bool {
  121. if passwordErrorMessage.count > 0 {
  122. return true
  123. }
  124. return false
  125. }
  126. /**
  127. @abstract 验证邮箱是否合规
  128. */
  129. func isValidEmail() -> Bool {
  130. let emailRegex = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
  131. let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
  132. return emailTest.evaluate(with: email)
  133. }
  134. /**
  135. @abstract 验证验证码是否合规
  136. */
  137. func isValidVerificationCode() -> Bool {
  138. let pattern = "^\\d{6}$"
  139. let regex = try! NSRegularExpression(pattern: pattern)
  140. return regex.firstMatch(in: verificationCode, options: [], range: NSRange(location: 0, length: verificationCode.utf16.count)) != nil
  141. }
  142. func stayStateAction() -> Void {
  143. if !stayState {
  144. UserDefaults.standard.setValue("", forKey: "MemberAccessToken")
  145. UserDefaults.standard.synchronize()
  146. }
  147. }
  148. // MARK: Private Method
  149. /**
  150. @abstract 刷新用户个人信息
  151. */
  152. private func refreshUserInfo() -> Void {
  153. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  154. let alert = NSAlert()
  155. alert.alertStyle = .critical
  156. alert.messageText = NSLocalizedString("Error Information", comment: "")
  157. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  158. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  159. alert.runModal()
  160. return
  161. }
  162. KMUserInfoVCModel().refreshUserInfo { success, msg in
  163. if success {
  164. KMMemberInfo.shared.isLogin = true
  165. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MemberCenterLoginSuccess"), object: nil)
  166. } else {
  167. KMMemberInfo.shared.isLogin = false
  168. }
  169. }
  170. }
  171. // MARK: Action Method
  172. /**
  173. @abstract KMSignUpView Sign Up 登录按钮响应事件
  174. @param
  175. */
  176. func signUpAction(callback: ((Bool?, Any ...)->Void)?) -> Void {
  177. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  178. let alert = NSAlert()
  179. alert.alertStyle = .critical
  180. alert.messageText = NSLocalizedString("Error Information", comment: "")
  181. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  182. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  183. alert.runModal()
  184. callback?(nil)
  185. return
  186. }
  187. if email.count <= 0 || email.count > 100 || !isValidEmail() {
  188. emailErrorMessage = NSLocalizedString("Email format error. Please enter the correct email.", tableName: "MemberCenterLocalizable", comment: "")
  189. callback?(nil)
  190. return
  191. }
  192. var code: String = ""
  193. if signUpState == .verificationCode {
  194. if verificationCode.count <= 0 || verificationCode.count > 6 || !isValidVerificationCode() {
  195. passwordErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  196. callback?(nil)
  197. return
  198. }
  199. code = verificationCode
  200. } else if signUpState == .password {
  201. if password.count <= 0 || verificationCode.count > 30 {
  202. passwordErrorMessage = NSLocalizedString("Password error.", tableName: "MemberCenterLocalizable", comment: "")
  203. callback?(nil)
  204. return
  205. }
  206. code = password
  207. }
  208. if !privacyState {
  209. let alert = NSAlert()
  210. alert.messageText = NSLocalizedString("Please agree and check the above agreement first.", tableName: "MemberCenterLocalizable", comment: "")
  211. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  212. // alert.beginSheetModal(for: NSApp.mainWindow!)
  213. let result = alert.runModal()
  214. if (result == .alertFirstButtonReturn) {
  215. privacyState = true
  216. }
  217. callback?(nil)
  218. return
  219. }
  220. KMMemberCenterManager.manager.emailLogin(email: email, code: code, type: signUpState) { [weak self] success, wrapper in
  221. callback?(success)
  222. guard let self = self else { return }
  223. let resultDict = wrapper! as KMMemberCenterResult
  224. let msg = resultDict.msg
  225. if success {
  226. let result: KMMemberLoginResult = resultDict.login_Result!
  227. let refresh_token = result.refreshToken
  228. let access_token = result.accessToken
  229. let token_type = result.tokenType
  230. let expires_in = result.expiresIn
  231. let scope = result.scope
  232. if self.stayState {
  233. UserDefaults.standard.setValue(refresh_token, forKey: "MemberRefreshToken")
  234. UserDefaults.standard.setValue(access_token, forKey: "MemberAccessToken")
  235. UserDefaults.standard.synchronize()
  236. } else {
  237. UserDefaults.standard.setValue("", forKey: "MemberRefreshToken")
  238. UserDefaults.standard.setValue("", forKey: "MemberAccessToken")
  239. UserDefaults.standard.synchronize()
  240. }
  241. KMMemberInfo.shared.refresh_token = refresh_token!
  242. KMMemberInfo.shared.access_token = access_token!
  243. KMMemberInfo.shared.token_type = token_type!
  244. self.refreshUserInfo()
  245. self.timer?.cancel()
  246. self.sendContent = NSLocalizedString("Resend", tableName: "MemberCenterLocalizable", comment: "")
  247. } else {
  248. if(resultDict.code == 305) {
  249. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  250. let alert = NSAlert()
  251. alert.alertStyle = .critical
  252. alert.messageText = NSLocalizedString("Error Information", comment: "")
  253. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  254. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  255. alert.runModal()
  256. return
  257. }
  258. KMMemberCenterManager.manager.getUserDeviceList(email: self.email) { [weak self] success, result in
  259. guard self != nil else { return }
  260. if success {
  261. KMMemberCenterWindowController.shared.showWindow(nil)
  262. KMMemberCenterWindowController.shared.memberCenterdeviceResult = result ?? KMMemberCenterResult(loginResult: KMMemberLoginResult(refreshToken: "", accessToken: "", tokenType: "", expiresIn: ""))
  263. }
  264. }
  265. } else {
  266. print("错误信息:%@", msg as Any)
  267. let alert = NSAlert()
  268. alert.messageText = NSLocalizedString(msg!, comment: "")
  269. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  270. let response = alert.runModal()
  271. if response == .alertFirstButtonReturn {
  272. if(resultDict.code == 317) {
  273. self.signUpState = .verificationCode
  274. self.countDown(type: .login, callback: nil)
  275. } else {
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. /**
  283. @abstract KMForgotPasswordView 登录弹窗(忘记密码)Next 按钮响应事件
  284. @param
  285. */
  286. func forgotPasswordNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  287. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  288. let alert = NSAlert()
  289. alert.alertStyle = .critical
  290. alert.messageText = NSLocalizedString("Error Information", comment: "")
  291. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  292. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  293. alert.runModal()
  294. return
  295. }
  296. if email.count <= 0 || email.count > 100 || !isValidEmail() {
  297. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  298. return
  299. }
  300. if emailErrorMessage.count > 0 {
  301. return
  302. }
  303. KMMemberCenterManager.manager.emailVerification(email: email) { [weak self] success, wrapper in
  304. guard let self = self else { return }
  305. let resultDict = wrapper! as KMMemberCenterResult
  306. let msg = resultDict.msg! as String
  307. if success {
  308. complete(true, msg)
  309. } else {
  310. complete(false, msg)
  311. }
  312. }
  313. }
  314. /**
  315. @abstract KMEnterVerificationCodeView 登录弹窗(输入验证码)Next 按钮响应事件
  316. @param
  317. */
  318. func enterVerificationCodeNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  319. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  320. let alert = NSAlert()
  321. alert.alertStyle = .critical
  322. alert.messageText = NSLocalizedString("Error Information", comment: "")
  323. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  324. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  325. alert.runModal()
  326. return
  327. }
  328. if verificationCode.count <= 0 || verificationCode.count > 6 || !isValidVerificationCode() {
  329. emailErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  330. complete(false, "")
  331. return
  332. }
  333. KMMemberCenterManager.manager.checkVerificationCode(type: .reset, account: email, code: verificationCode) { [weak self] success, wrapper in
  334. guard let self = self else { return }
  335. let resultDict = wrapper! as KMMemberCenterResult
  336. let msg = resultDict.msg
  337. let result: Bool = resultDict.result ?? false
  338. if success {
  339. complete(true, "")
  340. } else {
  341. self.passwordErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  342. complete(false, "")
  343. }
  344. }
  345. }
  346. /**
  347. @abstract 获取邮箱验证码
  348. @param
  349. */
  350. func getVerificationCode(_ type: KMVerificationCodeType, callback: ((Bool?, Any ...)->Void)?) -> Void {
  351. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  352. let alert = NSAlert()
  353. alert.alertStyle = .critical
  354. alert.messageText = NSLocalizedString("Error Information", comment: "")
  355. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  356. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  357. alert.runModal()
  358. callback?(nil)
  359. return
  360. }
  361. if !isValidEmail() {
  362. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  363. callback?(nil)
  364. return
  365. }
  366. KMMemberCenterManager.manager.getVerificationCode(action: type, receiver: email) { [weak self] success, wrapper in
  367. callback?(success)
  368. guard let self = self else { return }
  369. let resultDict = wrapper! as KMMemberCenterResult
  370. let msg = resultDict.msg
  371. let result: Bool = resultDict.result ?? false
  372. if success {
  373. print("验证邮箱成功")
  374. } else {
  375. self.emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  376. }
  377. }
  378. }
  379. /**
  380. @abstract 重置密码
  381. @param
  382. */
  383. func resetPassword(_ complete: @escaping ForgotPasswordComplete) -> Void {
  384. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  385. let alert = NSAlert()
  386. alert.alertStyle = .critical
  387. alert.messageText = NSLocalizedString("Error Information", comment: "")
  388. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  389. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  390. alert.runModal()
  391. return
  392. }
  393. if password.count <= 0 || verificationCode.count > 30 {
  394. passwordErrorMessage = NSLocalizedString("Password error.", tableName: "MemberCenterLocalizable", comment: "")
  395. return
  396. }
  397. KMMemberCenterManager.manager.resetPassword(email: email, verifyCode: verificationCode, password: password) { [weak self] success, wrapper in
  398. guard let self = self else { return }
  399. let resultDict = wrapper! as KMMemberCenterResult
  400. let msg = resultDict.msg! as String
  401. let result: Bool = resultDict.result ?? false
  402. complete(success, msg)
  403. }
  404. }
  405. }