CNLiveLoginRequest.m 7.68 KB
//
//  CNLiveLoginRequest.m
//  CNLiveLoginModule
//
//  Created by 153993236@qq.com on 11/12/2019.
//  Copyright (c) 2019 153993236@qq.com. All rights reserved.
//

#import "CNLiveLoginRequest.h"
#import <UIKit/UIKit.h>
#import "QMUIKit.h"

#import "CNLiveEnvironment.h"
#import <CNLiveRequestBastKit/CNLiveNetworking.h>
#import "TIMAdapter.h"
#import "CommonLibrary.h"

#import "NBSAppAgent.h"
#import "CNLiveBusinessTools.h"

@interface CNLiveLoginRequest()
@property (nonatomic, strong) IMALoginParam *loginParam;

@end

@implementation CNLiveLoginRequest
static const NSInteger timeValue = 1.5;
#define XWKeyWindow [UIApplication sharedApplication].keyWindow
#pragma mark - 单例
+ (instancetype)manager {
    static CNLiveLoginRequest *_singleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _singleton = [[super allocWithZone:NULL] init];
        BOOL isAutoLogin = [IMAPlatform isAutoLogin];

        if (isAutoLogin) {
            _singleton.loginParam = [IMALoginParam loadFromLocal];
           
        } else {
            _singleton.loginParam = [[IMALoginParam alloc] init];
       
        }
        [IMAPlatform configWith:_singleton.loginParam.config];

    });
    return _singleton;
    
}

// 防止外部调用alloc 或者 new
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [CNLiveLoginRequest manager];
}

// 防止外部调用copy
- (id)copyWithZone:(nullable NSZone *)zone {
    return [CNLiveLoginRequest manager];
}

// 防止外部调用mutableCopy
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
    return [CNLiveLoginRequest manager];
}

//获取token
- (void)getTIMLoginToken:(NSString *)identifier success:(void (^)(NSString * token))success failed:(void (^)(int code, NSString * msg))failed{
    NSDictionary *params = @{@"appId":AppId,
                             @"plat":@"i",
                             @"sdkAppId":SdkAppId,
                             @"identifier":identifier};
    
    [CNLiveNetworking setupShowDataResult:NO];
    [CNLiveNetworking setAllowRequestDefaultArgument:YES];
    [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:TIM_GetTokenUrl Param:params CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
        if (!error) {
            if (responseObject && [responseObject isKindOfClass:[NSDictionary class]] && [[responseObject allKeys] containsObject:@"data"] && [[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                NSNumber *code = responseObject[@"errorCode"];
                if (code && code.intValue == 0) {
                    if (success) {
                        success(responseObject[@"data"][@"token"]);
                    }
                } else {
                    if (failed) {
                        failed(31012, @"获取token失败");
                    }
                }
                
            }
           
        }else{
            if (failed) failed(31012, @"获取token失败");
        }
    }];
    
}

- (void)loginTIM:(NSString *)uid success:(void (^)(void))success failed:(void (^)(int code, NSString * msg))failed{
    [QMUITips showLoading:@"正在连接服务器..." inView:XWKeyWindow];

    // 1.获取token
    [self getTIMLoginToken:uid success:^(NSString * _Nonnull token) {
        
        self.loginParam.identifier = uid;
        self.loginParam.userSig = token;
        self.loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
        
        // 2.登录im
        [[IMAPlatform sharedInstance] login:self.loginParam succ:^{
            [QMUITips hideAllToastInView:XWKeyWindow animated:YES];

            [self.loginParam saveToLocal];
                        
            [[IMAPlatform sharedInstance].contactMgr asyncUpdateContact];
            [[IMAPlatform sharedInstance].contactMgr saveGroupIdList:YES];
            [[IMAPlatform sharedInstance] configHost:self.loginParam];
            [IMAPlatform sharedInstance].didConnectSuccess = YES;
            
            // 听云
            [NBSAppAgent setUserIdentifier:[CNLiveBusinessTools getSidIdfv]];

            // 设置电商sdk
//            [[DSCnliveShopSDKManager sharedManager] loginUser:uid];
            
            //设置APP已活跃
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"is_Active_Application"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [QMUITips showSucceed:@"登录成功" inView:XWKeyWindow hideAfterDelay:timeValue];
            success?success():@"";

            // 3.im配置信息
            [[IMAPlatform sharedInstance].host asyncSetAllowType:TIM_FRIEND_NEED_CONFIRM succ:^{
                NSLog(@"asyncSetAllowType Suc");
                [self.loginParam saveToLocal];
                
            } fail:^(int code, NSString *msg) {
                NSLog(@"asyncSetAllowType failed : %@", msg);
                
            }];
            
        } fail:^(int code, NSString *msg) {
            NSLog(@"login failed : %@", msg);
            [QMUITips hideAllToastInView:XWKeyWindow animated:YES];
            if (code == 6208) {
                //离线被踢下线重新登录
                [self resumeLogin];
            }
            else{
                [QMUITips showError:msg inView:XWKeyWindow hideAfterDelay:timeValue];
                failed?failed(code, msg):@"";
            }
        }];
        
    } failed:^(int code, NSString * _Nonnull msg) {
        NSLog(@"token code:%d     msg:%@", code, msg);
        [QMUITips hideAllToastInView:XWKeyWindow animated:YES];
        [QMUITips showError:msg inView:XWKeyWindow hideAfterDelay:timeValue];
        failed?failed(code, msg):@"";
        
    }];
    
}

// 如果遇到离线被踢下线重新登录
- (void)resumeLogin {
    __weak typeof(self)weakSelf = self;
    [[IMAPlatform sharedInstance] login:self.loginParam succ:^{
        [QMUITips hideAllToastInView:XWKeyWindow animated:YES];
        [QMUITips showSucceed:@"登录成功" inView:XWKeyWindow hideAfterDelay:timeValue];
        [self.loginParam saveToLocal];

        [[IMAPlatform sharedInstance] configHost:self.loginParam];
        [IMAPlatform sharedInstance].didConnectSuccess = YES;
        
        [[IMAPlatform sharedInstance].host asyncSetAllowType:TIM_FRIEND_NEED_CONFIRM succ:^{
            NSLog(@"asyncSetAllowType Suc");
            [self.loginParam saveToLocal];
            
        } fail:^(int code, NSString *msg) {
            NSLog(@"asyncSetAllowType failed : %@", msg);
        }];
        
    } fail:^(int code, NSString *msg) {
        NSLog(@"tokenCode login failed : %@", msg);
        if (code == 6028) {
            dispatch_async(dispatch_get_main_queue(), ^{
                QMUIAlertAction *action = [QMUIAlertAction actionWithTitle:@"重试" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
                    [weakSelf resumeLogin];
                }];
                QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"连接服务器失败,请点击重试" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
                [alertController addAction:action];
                
                NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.alertTitleAttributes];
                       
                titleAttributs[NSForegroundColorAttributeName] = [UIColor colorWithRed:35/255.0 green:212/255.0 blue:30/255.0 alpha:1.0];

                action.buttonAttributes = titleAttributs;
                [alertController showWithAnimated:YES];
                
            });
        }
    }];
}

@end