KMSignUpViewModel.swift 18 KB

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