KMSignUpViewModel.swift 16 KB

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