OOLoginViewModel.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //
  2. // OOLoginViewModel.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 2018/4/5.
  6. // Copyright © 2018年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import Moya
  10. import Promises
  11. import ReactiveSwift
  12. import ReactiveCocoa
  13. import CocoaLumberjack
  14. import O2OA_Auth_SDK
  15. public enum OOLoginError:Error {
  16. case imLoginFail(OOAppError)
  17. case imRegisterFail(OOAppError)
  18. }
  19. class OOLoginViewModel: NSObject {
  20. private let faceRecognizeAPI = OOMoyaProvider<FaceRecognizeAPI>()
  21. //密码输入及验证码按钮可用
  22. let passwordIsValid = MutableProperty(false)
  23. // 内网密码
  24. let pwdIsValid = MutableProperty(false)
  25. let submitButtionIsValid = MutableProperty(false)
  26. let submitButtonCurrentColor = MutableProperty(UIColor.lightGray)
  27. let faceRecognizeLoginButtonisValid = MutableProperty(false)
  28. override init() {
  29. super.init()
  30. }
  31. }
  32. extension OOLoginViewModel {
  33. func _saveAppConfigToDb() {
  34. //判断本地hash和服务器的hash是否一致
  35. let local = AppConfigSettings.shared.customStyleHash
  36. if let remote = O2AuthSDK.shared.customStyleHash(), remote != local {
  37. if let current = O2AuthSDK.shared.customStyle() {
  38. var currentIndex = 0
  39. var existApps:[String] = [] // 删除配置中不存在的 或者 不需要显示的应用
  40. if let nativeList = current.nativeAppList {
  41. nativeList.forEachEnumerated { (index, app) in
  42. if app.enable == true {
  43. let nApp = O2App(title: app.name, appId: app.key, storyBoard: app.iOS?.storyboard, vcName: app.iOS?.vcname, segueIdentifier: nil, normalIcon: "icon_\(app.key!)", selectedIcon: "icon_\(app.key!)", customParameter: nil, order: currentIndex, mainOrder: currentIndex)
  44. OOAppsInfoDB.shareInstance.insertData(nApp)
  45. currentIndex += 1
  46. existApps.append(app.key!)
  47. }
  48. }
  49. }
  50. if let portalList = current.portalList {
  51. portalList.forEachEnumerated { (index, o2app2) in
  52. let status = "{'portalId':'"+o2app2.id!+"'}"
  53. let weburl = AppDelegate.o2Collect.genrateURLWithWebContextKey(DesktopContext.DesktopContextKey, query: DesktopContext.appDetailQuery, parameter: ["##status##":status as AnyObject],covertd:false)
  54. let app = O2App(title: o2app2.name!, appId:o2app2.id!, storyBoard: "webview", vcName: weburl!, segueIdentifier: "showMailSegue", normalIcon: "icon_youjian", selectedIcon: "icon_youjian", order: currentIndex, mainOrder: currentIndex)
  55. OOAppsInfoDB.shareInstance.insertData(app)
  56. currentIndex += 1
  57. existApps.append(o2app2.id!)
  58. }
  59. }
  60. // 删除配置中不存在的 或者 不需要显示的应用
  61. OOAppsInfoDB.shareInstance.deleteNotExistApp(existApps)
  62. }
  63. }else {
  64. DDLogError("不需要更新数据???????")
  65. }
  66. }
  67. // MARK:- Login IM
  68. func loginIM() -> Promise<Bool> {
  69. return Promise { fulfill,reject in
  70. if let account = O2AuthSDK.shared.myInfo() {
  71. JMSGUser.login(withUsername: account.id!, password: "QazWsxEdc!@#", completionHandler: { (resultObject, errMsg) in
  72. if errMsg == nil {
  73. O2Logger.info("IM登录成功,user = \(String(describing: resultObject))")
  74. fulfill(true)
  75. }else{
  76. O2Logger.error("IM登录失改,error = \(String(describing: errMsg))")
  77. let loginErr = OOAppError.common(type: "im", message: "im login Fail,\(String(describing: errMsg))", statusCode: 40001)
  78. reject(loginErr)
  79. }
  80. })
  81. }else {
  82. O2Logger.error("IM登录失改,error = 当前登录用户为空!!!")
  83. let loginErr = OOAppError.common(type: "im", message: "im login Fail,前登录用户为空!!", statusCode: 40001)
  84. reject(loginErr)
  85. }
  86. }
  87. }
  88. // MARK:- register IM
  89. func registerIM() -> Promise<Bool> {
  90. return Promise { fulfill,reject in
  91. if let account = O2AuthSDK.shared.myInfo() {
  92. let username = account.id
  93. let nickname = account.name
  94. let gener = account.genderType
  95. let info = JMSGUserInfo()
  96. info.nickname = nickname!
  97. if gener == "f" {
  98. info.gender = .female
  99. }else if gener == "m" {
  100. info.gender = .male
  101. }else{
  102. info.gender = .unknown
  103. }
  104. JMSGUser.register(withUsername: username!, password: "QazWsxEdc!@#", userInfo: info, completionHandler: { (resultObject, regError) in
  105. if let error = regError {
  106. let registerErr = OOAppError.common(type: "im", message: "im register Fail,\(String(describing: error))", statusCode: 40001)
  107. reject(OOLoginError.imRegisterFail(registerErr))
  108. }else{
  109. fulfill(true)
  110. }
  111. })
  112. }else {
  113. let registerErr = OOAppError.common(type: "im", message: "im register Fail,当前登录用户为空", statusCode: 40001)
  114. reject(OOLoginError.imRegisterFail(registerErr))
  115. }
  116. }
  117. }
  118. /// 人脸识别
  119. ///
  120. /// - Parameter image: 需要识别的图片
  121. /// - Returns: 如果成功识别 返回userId
  122. func faceRecognize(image: UIImage) -> Promise<String> {
  123. return Promise { fulfill, reject in
  124. //TODO 这里的faceset 到时候要用collect上的unit id代替
  125. self.faceRecognizeAPI.request(.search(image, "dev_o2oa_io"), completion: { (result) in
  126. switch result {
  127. case .success(let data):
  128. let response = data.mapObject(FaceSearchResponse.self)
  129. var userId = ""
  130. if let ar = response?.data?.results {
  131. if ar.count > 0 {
  132. userId = ar[0].user_id ?? ""
  133. DDLogDebug("userId:\(userId)")
  134. }
  135. }
  136. if userId != "" {
  137. fulfill(userId)
  138. }else {
  139. reject(OOAppError.common(type:"faceError",message:"没有识别到用户",statusCode:1024))
  140. }
  141. break
  142. case .failure(let error):
  143. reject(error)
  144. break
  145. }
  146. })
  147. }
  148. }
  149. // MARK:- helper
  150. private static func cleanCookieCache(_ remoteURL:String) {
  151. let cstorage = HTTPCookieStorage.shared
  152. if let comps = URLComponents(string:remoteURL) {
  153. let url = "\(comps.scheme!)://\(comps.host!):\(comps.port!)"
  154. if let cookies = cstorage.cookies(for: URL(string: url)!){
  155. for cookie in cookies {
  156. cstorage.deleteCookie(cookie)
  157. }
  158. }
  159. }
  160. }
  161. }
  162. extension OOLoginViewModel {
  163. func loginControlIsValid(_ userNameField:UITextField,_ passwordTextField:UITextField, _ isInner: Bool = false) -> Void {
  164. let phoneValidSingal = userNameField.reactive.continuousTextValues.map { (text) -> Bool in
  165. guard let t = text,t.count > 0 else {
  166. return false
  167. }
  168. return true
  169. }
  170. phoneValidSingal.observeValues { (res) in
  171. if isInner {
  172. self.pwdIsValid.value = res
  173. }else {
  174. self.passwordIsValid.value = res
  175. }
  176. }
  177. let passwordValidSingal = passwordTextField.reactive.continuousTextValues.map { (text) -> Bool in
  178. if isInner {
  179. guard let t = text, t.count > 0 else {
  180. return false
  181. }
  182. }else {
  183. guard let t = text, t.count >= 4 else {
  184. return false
  185. }
  186. }
  187. return true
  188. }
  189. let signUpActiveSignal = Signal.combineLatest(phoneValidSingal, passwordValidSingal).scan(into: false) { (myResult, arg) in
  190. myResult = arg.0 && arg.1
  191. }
  192. signUpActiveSignal.observeValues { (res) in
  193. self.submitButtionIsValid.value = res
  194. }
  195. let signUpColorSignal = signUpActiveSignal.map { (param) -> UIColor in
  196. if param {
  197. return base_color
  198. }else{
  199. return UIColor.lightGray
  200. }
  201. }
  202. signUpColorSignal.observeValues { (currentColor) in
  203. self.submitButtonCurrentColor.value = currentColor
  204. }
  205. }
  206. /// 人脸识别功能是否可用
  207. func faceRecognizeValidate() {
  208. // face++ 授权验证
  209. MGFaceLicenseHandle.license { (result, date) in
  210. DDLogInfo("face++ 验证权限完成, result:\(result)")
  211. self.faceRecognizeLoginButtonisValid.value = result
  212. }
  213. }
  214. }