CNLiveLoginViewModel.swift 20.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
//
//  CNLiveLoginViewModel.swift
//  metaCode
//
//  Created by open on 2023/6/5.
//

import Foundation
import CNLiveRequestBastKit
import HandyJSON
import RangersAPM
import CNLiveShareToolKit
import CNLiveBusinessTools

//验证码发送成功回调
typealias resultCodeBlock = () -> Void
//登陆成功回调
typealias resultLoginBlock = () -> Void
//结束登录按钮刷新回调
typealias endRefreshBlock = () -> Void


class CNLiveLoginViewModel : NSObject,URLSessionTaskDelegate {
    
    /// 获取验证码
    /// - Parameters:
    ///   - phone: 手机号
    ///   - code: 验证码
    ///   - resultBlock: 登陆结果
    static func requestVerCodeAction(phone: String, code: String, resultBlock: @escaping resultCodeBlock) {
        
        if !phone.isNotBlank() {
            showMessage(message: "请输入手机号")
            return
        }
        if phone.lengthOfBytes(using: .utf8) >= 20 {
            showMessage(message: "手机号格式不正确")
            return
        }
        if !phone.isPurnInt() {
            showMessage(message: "手机号格式不正确")
            return
        }
        showLoading(message: "")
        let param = ["mobile":phone,"countryCode":code]
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.setupShowResult(true)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: CNLiveMCEnvironmentManager.shared.loginHost+"/open/api2/user/sendVerifyCode", param: param, cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    showMessage(message: "验证码已发送")
                    resultBlock()
                } else {
                    //showMessage(message: resp["errorMessage"] as! String)
                }
            } else{
                showMessage(message: "获取验证码失败")
            }
        }
    }
    
    /// 修改手机号获取验证码
    /// - Parameters:
    ///   - phone: 手机号
    ///   - code: 验证码
    static func requestChangePhoneVerCodeAction(phone: String, code: String, resultBlock: @escaping resultCodeBlock) {
        
        if !phone.isNotBlank() {
            showMessage(message: "请输入手机号")
            return
        }
        if phone.lengthOfBytes(using: .utf8) >= 20 {
            showMessage(message: "手机号格式不正确")
            return
        }
        if !phone.isPurnInt() {
            showMessage(message: "手机号格式不正确")
            return
        }
        showLoading(message: "")
        let param = ["mobile":phone,"countryCode":code,"clientPlat":"i"]
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.setupShowResult(true)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: CNLiveMCEnvironmentManager.shared.loginHost+"/open/api2/user/sendVerifyCodeForUnRegistered", param: param, cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    showMessage(message: "验证码已发送")
                    resultBlock()
                } else {
                    //showMessage(message: resp["errorMessage"] as! String)
                }
            } else{
                showMessage(message: "获取验证码失败")
            }
        }
    }
    
    /// 登陆
    /// - Parameters:
    ///   - userName: 手机号
    ///   - countryCode: 国家区号
    ///   - verCode: 验证码
    ///   - resultBlock: 结果回调
    static func requestLoginAction(userName: String, countryCode: String, verCode: String, resultBlock: @escaping resultLoginBlock ,endrefreshBlock: @escaping endRefreshBlock) {
        
        if !userName.isNotBlank() {
            showMessage(message: "请输入手机号")
            endrefreshBlock()
            return
        }
        if userName.lengthOfBytes(using: .utf8) >= 20 {
            showMessage(message: "手机号格式不正确")
            endrefreshBlock()
            return
        }
        if !userName.isPurnInt() {
            showMessage(message: "手机号格式不正确")
            endrefreshBlock()
            return
        }
        if !verCode.isNotBlank() {
            showMessage(message: "请输入验证码")
            endrefreshBlock()
            return
        }
        if verCode.lengthOfBytes(using: .utf8) >= 20 {
            showMessage(message: "验证码格式不正确")
            endrefreshBlock()
            return
        }
        if !verCode.isPurnInt() {
            showMessage(message: "验证码格式不正确")
            endrefreshBlock()
            return
        }
        
        showLoading(message: "")
        let param = ["userName":userName,"countryCode":countryCode,"verificationCode":verCode,"inviterId":""]
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPLoginHost+"/open/api2/user/loginInMetaCode", param: param, cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    if resp.allKeys.contains(where: { item in
                        return item as! String == "data"
                    }) {
                        let userInfoModel = dictionaryToModel(resp as! [String : Any], UserInfoModel.self,"data")
                        UserInfoManager.cacheUserInfo(userInfo: userInfoModel as! UserInfoModel)
                        UserDefaults.standard.set(true,forKey: "is_login")
                        RangersAPM.setUserID(UserInfoManager.shared.userInfo.uid)
                        resultBlock()
                    }
                } else {
                    //showMessage(message: resp["errorMessage"] as! String)
                    endrefreshBlock()
                }
            } else {
                showMessage(message: "登陆失败")
                endrefreshBlock()
            }
        }
    }
    
    /**
     *  @abstract 三方登录
     *
     *  @param type  三方类型
     *  @param model 模型
     *  @param block 回调
     */
    static func thirdPartyLoginWithType(type: CNLiveSendAuthResp, model: CNThreeLoginModel, resultBlock: @escaping downSlideResultBlock) {
        showLoading(message: "")
        
        let param = ["thirdPartyPlat":model.thirdPartyPlat,"thirdPartyId":model.thirdPartyId,"frmId":model.frmId,"clientPlat":"i"]
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPLoginHost+"/open/api2/user/loginIn3rdForMetaCode", param: param, cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    if resp.allKeys.contains(where: { item in
                        return item as! String == "data"
                    }) {
                        let userInfoModel = dictionaryToModel(resp as! [String : Any], UserInfoModel.self,"data")
                        UserInfoManager.cacheUserInfo(userInfo: userInfoModel as! UserInfoModel)
                        UserDefaults.standard.set(true,forKey: "is_login")
                        RangersAPM.setUserID(UserInfoManager.shared.userInfo.uid)
                        resultBlock(userInfoModel, .success)
                    }
                } else {
                    //showMessage(message: resp["errorMessage"] as! String)
                    if errorCode as? String == "42013"{
                        resultBlock(errorCode ?? "", .failed)
                    }else{
                        resultBlock(NSNull(), .failed)
                    }
                }
            } else {
                showMessage(message: "登录失败")
                resultBlock(NSNull(), .failed)
            }
        }
    }
    
    /**
     *  @abstract  绑定手机号请求登录
     *
     *  @param block 回调
     */
    static func thirdPartyLoginBindingTel(mobile: String,verificationCode:String, model: CNThreeLoginModel, resultBlock: @escaping downSlideResultBlock) {
        showLoading(message: "")
        
        let param = ["mobile":mobile,"countryCode":model.countryCode,"verificationCode":verificationCode,"thirdPartyPlat":model.thirdPartyPlat,"thirdPartyId":model.thirdPartyId,"frmId":model.frmId,"clientPlat":"i","nickName":model.nickName,"gender":model.gender,"location":model.location,"faceUrl":model.faceUrl]
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPLoginHost+"/open/api2/user/loginIn3rdAndMobileForMetaCode", param: param, cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    if resp.allKeys.contains(where: { item in
                        return item as! String == "data"
                    }) {
                        let userInfoModel = dictionaryToModel(resp as! [String : Any], UserInfoModel.self,"data")
                        UserInfoManager.cacheUserInfo(userInfo: userInfoModel as! UserInfoModel)
                        UserDefaults.standard.set(true,forKey: "is_login")
                        RangersAPM.setUserID(UserInfoManager.shared.userInfo.uid)
                        resultBlock(userInfoModel, .success)
                    }
                } else {
                    //showMessage(message: resp["errorMessage"] as! String)
                    resultBlock(NSNull(), .failed)
                }
            } else {
                showMessage(message: "登录失败")
                resultBlock(NSNull(), .failed)
            }
        }
    }
    
    /**
     *  @abstract  苹果登录
     *
     *  @param block 回调
     */
    static func appleLogin(model: CNThreeLoginModel, resultBlock: @escaping downSlideResultBlock) {
        showLoading(message: "")
        
        let param = ["thirdPartyPlat":model.thirdPartyPlat,"thirdPartyId":model.thirdPartyId,"frmId":model.frmId,"clientPlat":"i","nickName":model.nickName,"gender":model.gender,"location":model.location,"faceUrl":model.faceUrl,"uuid": CNLiveBusinessTools.getUidForStat(Date()),"accessToken":model.access_token,"appId":CNLiveMCEnvironmentManager.shared.appId]
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPLoginHost+"/open/api2/user/loginIn3rdForMetaCodeApple", param: param, cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    if resp.allKeys.contains(where: { item in
                        return item as! String == "data"
                    }) {
                        let userInfoModel = dictionaryToModel(resp as! [String : Any], UserInfoModel.self,"data")
                        UserInfoManager.cacheUserInfo(userInfo: userInfoModel as! UserInfoModel)
                        UserDefaults.standard.set(true,forKey: "is_login")
                        RangersAPM.setUserID(UserInfoManager.shared.userInfo.uid)
                        resultBlock(userInfoModel, .success)
                    }
                } else {
                    showMessage(message: resp["errorMessage"] as! String)
                    resultBlock(NSNull(), .failed)
                }
            } else {
                let resp = result as? NSDictionary
                let err = resp?["errorMessage"] as? String
                showMessage(message: err ?? "登录失败")
                resultBlock(NSNull(), .failed)
            }
        }
    }
    
    
    /// UUID LoginInDevice
    static func requestUUIDLoginInDevice(uuid: String ,frmld:String, resultBlock: @escaping downSlideResultBlock) {
        let param = NSMutableDictionary.init()
        param.setValue(uuid, forKey: "uuid")
        param.setValue(frmld, forKey: "frmld")
        param.setValue("i", forKey: "clientPlat")
        showLoading(message: "")
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.setupShowResult(true)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPLoginHost+"/open/api2/user/loginInDevice", param: param as! [String : Any], cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    if resp.allKeys.contains(where: { item in
                        return item as! String == "data"
                    }) {
                        let userInfoModel = dictionaryToModel(resp as! [String : Any], UserInfoModel.self,"data")
                        UserInfoManager.cacheUserInfo(userInfo: userInfoModel as! UserInfoModel)
                        UserDefaults.standard.set(false,forKey: "is_login")
                        RangersAPM.setUserID(UserInfoManager.shared.userInfo.uid)
                        resultBlock(userInfoModel, .success)
                    }
                } else {
//                    showMessage(message: resp["errorMessage"] as! String)
                    resultBlock(NSNull(), .failed)
                }
            } else {
                resultBlock(NSNull(), .failed)
            }
        }
    }
    
    /**
     *  @abstract App 一键登录
     *
     *  @param accessToken 阿里云号码认证token
     *  @param block 回调
     */
    class func oneClickLogin(accessToken: String, frmld:String, resultBlock: @escaping downSlideResultBlock) {
        showLoading(message: "")
        
        // 获取当前时间戳(自1970年以来的秒数)
        let timeInterval = Date().timeIntervalSince1970
        // 将时间戳转换为字符串
        let timeString = "\(Int64(timeInterval))"
        let bundleIdentifier = Bundle.main.bundleIdentifier
        let shortVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String

        let param = NSMutableDictionary()
        param.setValue(accessToken, forKey: "accessToken")
        param.setValue(CNLiveBusinessTools.getUidForStat(Date()), forKey: "uuid")
        param.setValue(frmld, forKey: "frmId")
        param.setValue("i", forKey: "clientPlat")
        let appIdStr = CNLiveMCEnvironmentManager.shared.appId_wjj
        param.setValue(appIdStr, forKey: "appId")
        param.setValue("i", forKey: "plat")
        param.setValue(shortVersion, forKey: "ver")
        param.setValue(bundleIdentifier, forKey: "platform_id")
        param.setValue(timeString, forKey: "timestamp")

        let signStr = CNLiveBusinessTools.signvalue(param as! [AnyHashable : Any])
        let appkeyStr = CNLiveMCEnvironmentManager.shared.appKey_wjj
        let string1 = "\(signStr)&key=\(appkeyStr)"
        let signString1 = CNLiveBusinessTools.sha1(string1).uppercased()
        param.setValue(signString1, forKey: "sign")
        let custom_param = NSMutableDictionary()
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appId_wjj, forKey: "appId")
        custom_param.setValue(CNLiveMCEnvironmentManager.shared.appKey_wjj, forKey: "appKey")
        CNLiveNetworking.setupCustomParam(custom_param as? [String : String])

        CNLiveNetworking.setAllowRequestDefaultArgument(false)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPLoginHost+"/open/api2/user/getMobileAndLoginApp", param: param as! [String : String], cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    if resp.allKeys.contains(where: { item in
                        return item as! String == "data"
                    }) {
                        let userInfoModel = dictionaryToModel(resp as! [String : Any], UserInfoModel.self,"data")
                        UserInfoManager.cacheUserInfo(userInfo: userInfoModel as! UserInfoModel)
                        UserDefaults.standard.set(true,forKey: "is_login")
                        RangersAPM.setUserID(UserInfoManager.shared.userInfo.uid)
                        resultBlock(userInfoModel, .success)
                    }
                } else {
                    if errorCode as? String == "42013"{
                        resultBlock(errorCode ?? "", .failed)
                    }else{
                        showMessage(message: "登录失败,请重试")
                        resultBlock(NSNull(), .failed)
                    }
                }
            } else {
                showMessage(message: "登录失败,请重试")
                resultBlock(NSNull(), .failed)
            }
            
        }
    }
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        print("\(response.statusCode)") // 302
        print("\(response.allHeaderFields["Location"] as? String ?? "无重定向地址")") // 重定向地址URL
        
        // 根据业务需求决定是否使用新的请求继续任务
        // completionHandler(request) // 使用新的请求继续任务
        // completionHandler(nil) // 不使用新的请求,取消重定向
        
        // 在这个例子中,我们简单地取消重定向(即不使用新的请求)
        completionHandler(nil)
    }


}