KMSignUpViewModel.swift 19 KB

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