KMSignUpViewModel.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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(callback: ((Bool?, Any ...)->Void)?) -> 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. callback?(nil)
  161. return
  162. }
  163. KMUserInfoVCModel().refreshUserInfo(networkAlert: false) { success, msg in
  164. callback?(success)
  165. if success {
  166. KMMemberInfo.shared.isLogin = true
  167. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MemberCenterLoginSuccess"), object: nil)
  168. } else {
  169. KMMemberInfo.shared.isLogin = false
  170. }
  171. }
  172. }
  173. // MARK: Action Method
  174. /**
  175. @abstract KMSignUpView Sign Up 登录按钮响应事件
  176. @param
  177. */
  178. func signUpAction(callback: ((Bool?, Any ...)->Void)?) -> Void {
  179. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  180. let alert = NSAlert()
  181. alert.alertStyle = .critical
  182. alert.messageText = NSLocalizedString("Error Information", comment: "")
  183. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  184. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  185. alert.runModal()
  186. callback?(nil)
  187. return
  188. }
  189. if email.count <= 0 || email.count > 100 || !isValidEmail() {
  190. emailErrorMessage = NSLocalizedString("Email format error. Please enter the correct email.", tableName: "MemberCenterLocalizable", comment: "")
  191. callback?(nil)
  192. return
  193. }
  194. var code: String = ""
  195. if signUpState == .verificationCode {
  196. if verificationCode.count <= 0 || verificationCode.count > 6 || !isValidVerificationCode() {
  197. passwordErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  198. callback?(nil)
  199. return
  200. }
  201. code = verificationCode
  202. } else if signUpState == .password {
  203. if password.count <= 0 || password.count > 30 {
  204. passwordErrorMessage = NSLocalizedString("Password cannot exceed 30 characters.", tableName: "MemberCenterLocalizable", comment: "")
  205. callback?(nil)
  206. return
  207. }
  208. code = password
  209. }
  210. if !privacyState {
  211. DispatchQueue.main.async {
  212. let alert = NSAlert()
  213. alert.messageText = NSLocalizedString("Please agree and check the above agreement first.", tableName: "MemberCenterLocalizable", comment: "")
  214. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  215. // alert.beginSheetModal(for: NSApp.mainWindow!)
  216. let result = alert.runModal()
  217. if (result == .alertFirstButtonReturn) {
  218. self.privacyState = true
  219. }
  220. callback?(nil)
  221. }
  222. return
  223. }
  224. KMMemberCenterManager.manager.emailLogin(email: email, code: code, type: signUpState) { [weak self] success, wrapper in
  225. guard let self = self else { return }
  226. let resultDict = wrapper! as KMMemberCenterResult
  227. let msg = resultDict.msg
  228. if success {
  229. let result: KMMemberLoginResult = resultDict.login_Result!
  230. let refresh_token = result.refreshToken
  231. let access_token = result.accessToken
  232. let token_type = result.tokenType
  233. let expires_in = result.expiresIn
  234. let scope = result.scope
  235. if self.stayState {
  236. UserDefaults.standard.setValue(refresh_token, forKey: "MemberRefreshToken")
  237. UserDefaults.standard.setValue(access_token, forKey: "MemberAccessToken")
  238. UserDefaults.standard.synchronize()
  239. } else {
  240. UserDefaults.standard.setValue("", forKey: "MemberRefreshToken")
  241. UserDefaults.standard.setValue("", forKey: "MemberAccessToken")
  242. UserDefaults.standard.synchronize()
  243. }
  244. KMMemberInfo.shared.refresh_token = refresh_token!
  245. KMMemberInfo.shared.access_token = access_token!
  246. KMMemberInfo.shared.token_type = token_type!
  247. self.refreshUserInfo(callback: callback)
  248. self.timer?.cancel()
  249. self.sendContent = NSLocalizedString("Resend", tableName: "MemberCenterLocalizable", comment: "")
  250. } else {
  251. if(resultDict.code == 305) {
  252. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  253. DispatchQueue.main.async {
  254. let alert = NSAlert()
  255. alert.alertStyle = .critical
  256. alert.messageText = NSLocalizedString("Error Information", comment: "")
  257. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  258. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  259. alert.runModal()
  260. callback?(false)
  261. }
  262. return
  263. }
  264. KMMemberCenterManager.manager.getUserDeviceList(email: self.email) { [weak self] success, result in
  265. callback?(false)
  266. guard self != nil else { return }
  267. if success {
  268. KMMemberCenterWindowController.shared.showWindow(nil)
  269. KMMemberCenterWindowController.shared.signUpViewModel = self
  270. KMMemberCenterWindowController.shared.memberCenterdeviceResult = result ?? KMMemberCenterResult(loginResult: KMMemberLoginResult(refreshToken: "", accessToken: "", tokenType: "", expiresIn: ""))
  271. }
  272. }
  273. } else {
  274. callback?(false)
  275. print("错误信息:%@", msg as Any)
  276. DispatchQueue.main.async {
  277. let alert = NSAlert()
  278. alert.messageText = NSLocalizedString(msg!, comment: "")
  279. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  280. let response = alert.runModal()
  281. if response == .alertFirstButtonReturn {
  282. if(resultDict.code == 317) {
  283. self.signUpState = .verificationCode
  284. self.countDown(type: .login, callback: nil)
  285. } else {
  286. }
  287. }
  288. }
  289. }
  290. }
  291. }
  292. }
  293. /**
  294. @abstract KMForgotPasswordView 登录弹窗(忘记密码)Next 按钮响应事件
  295. @param
  296. */
  297. func forgotPasswordNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  298. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  299. let alert = NSAlert()
  300. alert.alertStyle = .critical
  301. alert.messageText = NSLocalizedString("Error Information", comment: "")
  302. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  303. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  304. alert.runModal()
  305. return
  306. }
  307. if email.count <= 0 || email.count > 100 || !isValidEmail() {
  308. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  309. return
  310. }
  311. if emailErrorMessage.count > 0 {
  312. return
  313. }
  314. KMMemberCenterManager.manager.emailVerification(email: email) { [weak self] success, wrapper in
  315. guard let self = self else { return }
  316. let resultDict = wrapper! as KMMemberCenterResult
  317. let msg = resultDict.msg! as String
  318. if success {
  319. complete(true, msg)
  320. } else {
  321. complete(false, msg)
  322. }
  323. }
  324. }
  325. /**
  326. @abstract KMEnterVerificationCodeView 登录弹窗(输入验证码)Next 按钮响应事件
  327. @param
  328. */
  329. func enterVerificationCodeNextAction(_ complete: @escaping ForgotPasswordComplete) -> Void {
  330. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  331. let alert = NSAlert()
  332. alert.alertStyle = .critical
  333. alert.messageText = NSLocalizedString("Error Information", comment: "")
  334. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  335. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  336. alert.runModal()
  337. return
  338. }
  339. if verificationCode.count <= 0 || verificationCode.count > 6 || !isValidVerificationCode() {
  340. emailErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  341. complete(false, "")
  342. return
  343. }
  344. KMMemberCenterManager.manager.checkVerificationCode(type: .reset, account: email, code: verificationCode) { [weak self] success, wrapper in
  345. guard let self = self else { return }
  346. let resultDict = wrapper! as KMMemberCenterResult
  347. let msg = resultDict.msg
  348. let result: Bool = resultDict.result ?? false
  349. if success {
  350. complete(true, "")
  351. } else {
  352. self.passwordErrorMessage = NSLocalizedString("Verification code error.", tableName: "MemberCenterLocalizable", comment: "")
  353. complete(false, "")
  354. }
  355. }
  356. }
  357. /**
  358. @abstract 获取邮箱验证码
  359. @param
  360. */
  361. func getVerificationCode(_ type: KMVerificationCodeType, callback: ((Bool?, Any ...)->Void)?) -> Void {
  362. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  363. let alert = NSAlert()
  364. alert.alertStyle = .critical
  365. alert.messageText = NSLocalizedString("Error Information", comment: "")
  366. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  367. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  368. alert.runModal()
  369. callback?(nil)
  370. return
  371. }
  372. if !isValidEmail() {
  373. emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  374. callback?(nil)
  375. return
  376. }
  377. KMMemberCenterManager.manager.getVerificationCode(action: type, receiver: email) { [weak self] success, wrapper in
  378. callback?(success)
  379. guard let self = self else { return }
  380. let resultDict = wrapper! as KMMemberCenterResult
  381. let msg = resultDict.msg
  382. let result: Bool = resultDict.result ?? false
  383. if success {
  384. print("验证邮箱成功")
  385. } else {
  386. self.emailErrorMessage = NSLocalizedString("Please enter the correct email format", tableName: "MemberCenterLocalizable", comment: "")
  387. }
  388. }
  389. }
  390. /**
  391. @abstract 重置密码
  392. @param
  393. */
  394. func resetPassword(_ complete: @escaping ForgotPasswordComplete) -> Void {
  395. if KMMemberCenterManager.manager.isConnectionAvailable() == false {
  396. let alert = NSAlert()
  397. alert.alertStyle = .critical
  398. alert.messageText = NSLocalizedString("Error Information", comment: "")
  399. alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
  400. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  401. alert.runModal()
  402. return
  403. }
  404. if password.count <= 0 || verificationCode.count > 30 {
  405. passwordErrorMessage = NSLocalizedString("Password error.", tableName: "MemberCenterLocalizable", comment: "")
  406. return
  407. }
  408. KMMemberCenterManager.manager.resetPassword(email: email, verifyCode: verificationCode, password: password) { [weak self] success, wrapper in
  409. guard let self = self else { return }
  410. let resultDict = wrapper! as KMMemberCenterResult
  411. let msg = resultDict.msg! as String
  412. let result: Bool = resultDict.result ?? false
  413. complete(success, msg)
  414. }
  415. }
  416. }