KMSignUpViewModel.swift 17 KB

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