KMSignUpViewModel.swift 19 KB

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