LiveVideoRoomViewController.m 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. //
  2. // LiveVideoRoomViewController.m
  3. // KulexiuForTeacher
  4. //
  5. // Created by Kyle on 2022/3/30.
  6. //
  7. #import "LiveVideoRoomViewController.h"
  8. #import "KSChatInputBarControl.h"
  9. #import "LiveRoomHeadView.h"
  10. #import "LiveRoomBottomView.h"
  11. #import "KSRCMessageModel.h"
  12. #import "UserInfoManager.h"
  13. #import "KSChatroomMessageCenter.h"
  14. #import <RongIMKit/RongIMKit.h>
  15. #import "KSChatroomTextCell.h"
  16. #import "KSLiveStreamVideo.h"
  17. #import "SeatContentView.h"
  18. #import "LiveroomTimeManager.h"
  19. #import "KSLiveEmptyView.h"
  20. #import "KSChatVideoView.h"
  21. #import "LiveRoomLikeLayer.h"
  22. #import "KSDragWindowManager.h"
  23. #import "KSLiveBadNetView.h"
  24. #import <Lottie/Lottie.h>
  25. #import "KSShopCardView.h"
  26. #import "KSLiveWebViewController.h"
  27. #import "KSLiveEndView.h"
  28. #import "LiveAnimationView.h"
  29. #import "LiveRoomAlertView.h"
  30. #import "LiveApplyView.h"
  31. #import "LiveApplyingView.h"
  32. #define AUTOHIDE_TIME (10.0f)
  33. #define PACKAGE_LOST (0.30f)
  34. typedef NS_ENUM(NSInteger, MICSTATUS) {
  35. MICSTATUS_NOMAL, // 正常状态
  36. MICSTATUS_WAITING, // 申请中
  37. MICSTATUS_CONNECTING, // 连麦中
  38. };
  39. @interface LiveVideoRoomViewController ()<RCRTCEngineEventDelegate,RCRTCRoomEventDelegate,RCRTCStatusReportDelegate,UIGestureRecognizerDelegate,KSChatInputBarControlDelegate,UITableViewDataSource,UITableViewDelegate,LiveroomTimeManagerDelegate>
  40. @property (nonatomic, strong) LiveroomTimeManager *timeManager;
  41. // 音频配置
  42. @property(strong, nonatomic) RCRTCEngine *engine;
  43. @property (nonatomic, strong) RCRTCRoom *room;
  44. @property (nonatomic, strong) KSLiveStreamVideo *localVideo;
  45. @property (nonatomic) NSMutableArray <KSLiveStreamVideo *>*streamVideos;
  46. // 视频主窗口容器
  47. @property (nonatomic, strong) UIView *videoContainerView;
  48. @property (nonatomic, strong) KSChatVideoView *videoView;
  49. @property (nonatomic, strong) LiveRoomHeadView *headView;
  50. @property (nonatomic, copy) LiveRoomBottomView *bottomView;
  51. /**
  52. 上次点赞按钮点击时间
  53. */
  54. @property(nonatomic, assign) NSTimeInterval lastClickPraiseTime;
  55. // 连麦状态
  56. @property (nonatomic, assign) MICSTATUS micStatus;
  57. /// 提示窗
  58. @property (nonatomic, strong) LiveRoomAlertView *alertView;
  59. /// 连麦的视图
  60. @property (nonatomic, strong) SeatContentView *seatContainer;
  61. // 聊天UI
  62. /*!
  63. 消息列表CollectionView和输入框都在这个view里
  64. */
  65. @property(nonatomic, strong) UIView *messageContentView;
  66. /*!
  67. 会话页面的TableView
  68. */
  69. @property (nonatomic, strong) UITableView *conversationMessageTableView;
  70. /**
  71. 输入工具栏
  72. */
  73. @property(nonatomic,strong) KSChatInputBarControl *inputBar;
  74. /**
  75. * 是否需要滚动到底部
  76. */
  77. @property(nonatomic, assign) BOOL isNeedScrollToButtom;
  78. /*!
  79. 聊天内容的消息Cell数据模型的数据源
  80. @discussion 数据源中存放的元素为消息Cell的数据模型,即RCDLiveMessageModel对象。
  81. */
  82. @property(nonatomic, strong) NSMutableArray<KSRCMessageModel *> *conversationDataRepository;
  83. @property (nonatomic, assign) BOOL isImConnected;
  84. /// 主讲人是否在房间
  85. @property (nonatomic, assign) BOOL isCreaterInRoom;
  86. @property (nonatomic, assign) BOOL isCreaterVideoEnable;
  87. @property (nonatomic, assign) BOOL isCreaterAudioEnable;
  88. @property (nonatomic, strong) KSLiveEmptyView *emptyView;
  89. /// 是否在切换身份
  90. @property (nonatomic, assign) BOOL isTransferRole;
  91. @property (nonatomic, assign) BOOL hasSendWelcomeMessage;
  92. @property (nonatomic, assign) BOOL hasShowSuspendView;
  93. @property (nonatomic, assign) BOOL isPackageLostTips;
  94. @property (nonatomic, assign) NSTimeInterval lostStartTime; // 开始丢包事件
  95. @property (nonatomic, assign) NSTimeInterval bitErrorTime; // video bit zero start
  96. @property (nonatomic, strong) KSLiveBadNetView *netBadView;
  97. @property (nonatomic, assign) BOOL isLostPackage; // 严重丢包
  98. @property (nonatomic, assign) BOOL isBitError; // bit error
  99. @property (nonatomic, strong) LOTAnimationView *animationView;
  100. @property (nonatomic, assign) BOOL isCloseRoom; // 是否直播结束
  101. @property (nonatomic, strong) KSLiveEndView *endView; // 直播结束显示的画面
  102. @property (nonatomic, strong) KSShopCardView *cardView;
  103. @property (nonatomic, strong) LiveAnimationView *enterAnimationView;
  104. @property (nonatomic, assign) NSTimeInterval lastSendMsgTime;
  105. @property (nonatomic, assign) BOOL isOtherLogin; // 是否被顶掉
  106. @property (nonatomic, strong) LiveApplyView *applyView; // 未申请
  107. @property (nonatomic, strong) LiveApplyingView *applyingView; // 申请中
  108. @end
  109. // 用于记录点赞消息连续点击的次数
  110. static int clickPraiseBtnTimes = 0;
  111. @implementation LiveVideoRoomViewController
  112. - (instancetype)init {
  113. self = [super init];
  114. if (self) {
  115. [self defaultConfig];
  116. }
  117. return self;
  118. }
  119. - (void)defaultConfig {
  120. self.enableChat = YES;
  121. self.enableSeat = YES;
  122. self.enableLike = YES;
  123. self.micStatus = MICSTATUS_NOMAL;
  124. self.isCreaterInRoom = NO; // 默认主讲人不在房间
  125. self.isImConnected = [USER_MANAGER checkIMConnected];
  126. self.isCloseRoom = NO;
  127. self.isOtherLogin = NO;
  128. }
  129. - (void)viewDidLoad {
  130. [super viewDidLoad];
  131. // Do any additional setup after loading the view.
  132. self.ks_prefersNavigationBarHidden = YES;
  133. [self registerNotification];
  134. [self setupUI];
  135. if (self.isImConnected) {
  136. [self connectService];
  137. }
  138. else {
  139. MJWeakSelf;
  140. [USER_MANAGER connectionIMCallback:^(BOOL isSuccess) {
  141. dispatch_main_async_safe(^{
  142. [weakSelf connectService];
  143. });
  144. }];
  145. }
  146. [self judgeAutoClose];
  147. }
  148. - (void)muteAllAudio {
  149. if (self.room) {
  150. [self.room muteAllRemoteAudio:YES];
  151. }
  152. }
  153. - (void)IMConnetedCallback {
  154. dispatch_main_async_safe(^{
  155. // IM 连接成功回调
  156. if (self.hasSendWelcomeMessage) { // 如果已经发送了进入消息
  157. // 查询是否直播间开启
  158. [KSNetworkingManager liveRoomJoinRoomRequest:KS_GET roomUid:self.roomId success:^(NSDictionary * _Nonnull dic) {
  159. if ([dic integerValueForKey:@"code"] == 200 && [dic boolValueForKey:@"status"]) {
  160. // 回调信息
  161. MJWeakSelf;
  162. [self notiferJoinSuccessToServiceCallback:^{
  163. [weakSelf MBPShow:@"IM连接成功"];
  164. [weakSelf sendWelcomeMessage];
  165. }];
  166. }
  167. else {
  168. [self MBPShow:MESSAGEKEY];
  169. [self quitRoom];
  170. }
  171. } faliure:^(NSError * _Nonnull error) {
  172. }];
  173. }
  174. });
  175. }
  176. - (void)sendWelcomeMessage {
  177. [[RCIMClient sharedRCIMClient] joinExistChatRoom:self.roomId messageCount:-1 success:^{
  178. KSLiveChatroomWelcome *joinChatroomMessage = [[KSLiveChatroomWelcome alloc] init];
  179. [joinChatroomMessage setMsgId:[RCIM sharedRCIM].currentUserInfo.userId];
  180. MJWeakSelf;
  181. [self sendMessage:joinChatroomMessage displayMessage:NO callback:^(BOOL success) {
  182. NSString *contentString = [NSString stringWithFormat:@"%@ 进入直播间",UserDefault(NicknameKey)];
  183. [weakSelf showAnimationView:YES showMessag:contentString];
  184. [weakSelf joinRTCRoom];
  185. }];
  186. } error:^(RCErrorCode status) {
  187. NSLog(@"error code %zd" ,status);
  188. }];
  189. }
  190. - (void)joinRTCRoom {
  191. // 如果当前加入了房间 只刷新或者退出
  192. if (self.room && self.liveRoleType == RCRTCLiveRoleTypeBroadcaster) {
  193. [self connectHostWithStatus:NO];
  194. }
  195. else {
  196. [self setRoleType];
  197. }
  198. }
  199. - (void)judgeAutoClose {
  200. if (self.isTempRoom == NO) {
  201. self.timeManager.autoCloseNetworkRoomTime = [self getCloseTime];
  202. }
  203. }
  204. - (void)liveroomLogOut {
  205. if (self.isOtherLogin) {
  206. return;
  207. }
  208. self.isOtherLogin = YES;
  209. [self MBPShow:@"该账号在其他设备上登录"];
  210. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  211. [self quitRoom];
  212. [[NSNotificationCenter defaultCenter] postNotificationName:@"liveroomBackRefresh" object:nil];
  213. });
  214. }
  215. - (void)liveroomQuit {
  216. if (self.isOtherLogin) {
  217. return;
  218. }
  219. self.isOtherLogin = YES;
  220. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  221. [self quitRoom];
  222. [[NSNotificationCenter defaultCenter] postNotificationName:@"liveroomBackRefresh" object:nil];
  223. });
  224. }
  225. - (void)registerNotification {
  226. [KSChatroomMessageCenter registerMessageTypes];
  227. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessageNotification:) name:OnReceiveChatroomMessageNotification object:nil];
  228. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(liveroomLogOut) name:@"liveroomLogout" object:nil];
  229. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(liveroomQuit) name:@"liveroomQuit" object:nil];
  230. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IMConnetedCallback) name:@"RongIMConnected" object:nil];
  231. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(muteAllAudio) name:@"muteLiveAudio" object:nil];
  232. }
  233. - (void)setupUI {
  234. CGSize size = self.view.bounds.size;
  235. self.view.backgroundColor = HexRGB(0x25292e);
  236. [self.view addSubview:self.emptyView];
  237. [self.view addSubview:self.endView];
  238. // 视图主容器
  239. [self.view addSubview:self.videoContainerView];
  240. [self.videoContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
  241. make.left.top.bottom.right.mas_equalTo(self.view);
  242. }];
  243. [self.videoContainerView addSubview:self.videoView];
  244. [self.videoContainerView addSubview:self.netBadView];
  245. [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
  246. make.left.top.bottom.right.mas_equalTo(self.view);
  247. }];
  248. [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
  249. make.left.right.top.bottom.mas_equalTo(self.videoView);
  250. }];
  251. self.emptyView.hidden = YES;
  252. // 直播结束的画面
  253. [self.endView mas_makeConstraints:^(MASConstraintMaker *make) {
  254. make.left.right.top.bottom.mas_equalTo(self.videoView);
  255. }];
  256. self.endView.hidden = YES;
  257. [self.netBadView mas_makeConstraints:^(MASConstraintMaker *make) {
  258. make.left.right.top.bottom.mas_equalTo(self.videoView);
  259. }];
  260. self.netBadView.hidden = YES;
  261. [self.view addSubview:self.headView];
  262. self.headView.boardcastName.text = [NSString returnNoNullStringWithString:self.createrName];
  263. if (![NSString isEmptyString:self.createrAvatal]) {
  264. [self.headView.boardcastAvatal sd_setImageWithURL:[NSURL URLWithString:[self.createrAvatal getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:@"teacher_logo"]];
  265. }
  266. [self countLikeMessageCount];
  267. [self countMemberCount];
  268. [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
  269. make.left.right.mas_equalTo(self.view);
  270. make.height.mas_equalTo(80);
  271. if (@available(iOS 11.0, *)) {
  272. make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0);
  273. } else {
  274. // Fallback on earlier versions
  275. make.top.mas_equalTo(self.view.mas_top).offset(0);
  276. }
  277. }];
  278. [self.view addSubview:self.messageContentView];
  279. if (self.hideCartButton == NO) {
  280. [self.videoContainerView addSubview:self.animationView];
  281. [self.animationView mas_makeConstraints:^(MASConstraintMaker *make) {
  282. if (@available(iOS 11.0, *)) {
  283. make.bottom.mas_equalTo(self.videoContainerView.mas_safeAreaLayoutGuideBottom).offset(-14);
  284. } else {
  285. // Fallback on earlier versions
  286. make.bottom.mas_equalTo(self.videoContainerView.mas_bottom).offset(-14);
  287. }
  288. make.centerX.mas_equalTo(self.videoContainerView.mas_right).offset(-84);
  289. make.width.mas_equalTo(48);
  290. make.height.mas_equalTo(56);
  291. }];
  292. [self.animationView play];
  293. }
  294. [self.view addSubview:self.bottomView];
  295. self.bottomView.hideCartVButton = self.hideCartButton;
  296. [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
  297. make.left.right.mas_equalTo(self.view);
  298. if (@available(iOS 11.0, *)) {
  299. make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-10);
  300. } else {
  301. // Fallback on earlier versions
  302. make.bottom.mas_equalTo(self.view.mas_bottom).offset(-10);
  303. }
  304. make.height.mas_equalTo(44);
  305. }];
  306. [self.messageContentView mas_makeConstraints:^(MASConstraintMaker *make) {
  307. make.left.mas_equalTo(self.view.mas_left);
  308. make.right.mas_equalTo(self.view.mas_right);
  309. make.bottom.mas_equalTo(self.bottomView.mas_top).offset(-10);
  310. make.height.mas_equalTo(180);
  311. }];
  312. [self.view addSubview:self.inputBar];
  313. [_inputBar setBackgroundColor: [UIColor whiteColor]];
  314. [_inputBar setFrame:CGRectMake(0, kScreenHeight, size.width , 50)];
  315. [_inputBar setHidden:YES];
  316. [self.messageContentView addSubview:self.conversationMessageTableView];
  317. [self.conversationMessageTableView mas_makeConstraints:^(MASConstraintMaker *make) {
  318. make.left.top.mas_equalTo(self.messageContentView);
  319. make.width.mas_equalTo(KPortraitWidth);
  320. make.bottom.mas_equalTo(self.messageContentView.mas_bottom);
  321. }];
  322. UITapGestureRecognizer *resetBottomTapGesture =[[UITapGestureRecognizer alloc]
  323. initWithTarget:self
  324. action:@selector(resetBottomGesture:)];
  325. resetBottomTapGesture.delegate = self;
  326. [self.view addGestureRecognizer:resetBottomTapGesture];
  327. }
  328. - (void)connectService {
  329. [self setRoleType];
  330. [self joinChatRoom];
  331. }
  332. - (void)joinChatRoom {
  333. [[RCIMClient sharedRCIMClient] joinChatRoom:self.roomId messageCount:-1 success:^{
  334. dispatch_async(dispatch_get_main_queue(), ^{
  335. [self addConstMessage];
  336. });
  337. KSLiveChatroomWelcome *joinChatroomMessage = [[KSLiveChatroomWelcome alloc] init];
  338. [joinChatroomMessage setMsgId:[RCIM sharedRCIM].currentUserInfo.userId];
  339. MJWeakSelf;
  340. [self sendMessage:joinChatroomMessage displayMessage:NO callback:^(BOOL success) {
  341. weakSelf.hasSendWelcomeMessage = YES;
  342. NSString *contentString = [NSString stringWithFormat:@"%@ 进入直播间",UserDefault(NicknameKey)];;
  343. [weakSelf showAnimationView:YES showMessag:contentString];
  344. }];
  345. // 加入成功发送消息
  346. } error:^(RCErrorCode status) {
  347. if (status == RC_CHATROOM_NOT_EXIST || status == KICKED_FROM_CHATROOM || status == RC_PARAMETER_INVALID_CHATROOM) {
  348. dispatch_async(dispatch_get_main_queue(), ^{
  349. [self MBPShow:@"加入聊天室失败"];
  350. });
  351. }
  352. }];
  353. }
  354. - (void)viewWillAppear:(BOOL)animated {
  355. [super viewWillAppear:animated];
  356. [UIApplication sharedApplication].idleTimerDisabled = YES;
  357. [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
  358. [IQKeyboardManager sharedManager].enable = NO;
  359. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
  360. // 重新渲染view
  361. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  362. if (manager.hasShowWindow) {
  363. [manager resignDragWindow];
  364. }
  365. if (self.hasShowSuspendView) {
  366. KSLiveStreamVideo *mainVideo = nil;
  367. if (self.videoView.streamId) {
  368. NSMutableArray *steamArray = [self.streamVideos mutableCopy];
  369. for (KSLiveStreamVideo *streamVideo in steamArray) {
  370. if ([streamVideo.streamId isEqualToString:self.videoView.streamId]) {
  371. mainVideo = streamVideo;
  372. break;
  373. }
  374. }
  375. }
  376. if (mainVideo) {
  377. [self.videoView addSubview:mainVideo.canvesView];
  378. [mainVideo.canvesView mas_updateConstraints:^(MASConstraintMaker *make) {
  379. make.left.right.bottom.top.mas_equalTo(self.videoView);
  380. }];
  381. }
  382. _hasShowSuspendView = NO;
  383. }
  384. if (self.room) {
  385. [self.room muteAllRemoteAudio:NO];
  386. }
  387. }
  388. - (void)viewWillDisappear:(BOOL)animated {
  389. [super viewWillDisappear:animated];
  390. [UIApplication sharedApplication].idleTimerDisabled = NO;
  391. [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
  392. [IQKeyboardManager sharedManager].enable = YES;
  393. if (@available(iOS 13.0, *)) {
  394. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
  395. } else {
  396. // Fallback on earlier versions
  397. [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
  398. }
  399. // 退出房间才停止定时器
  400. if (_timeManager) {
  401. [_timeManager stopDurationTimer];
  402. }
  403. }
  404. // 刷新seatView
  405. - (void)renderSeatView {
  406. NSMutableArray *seatArray = [NSMutableArray array];
  407. NSArray *remoteUserArray = [self.room.remoteUsers mutableCopy];
  408. for (RCRTCRemoteUser *user in remoteUserArray) {
  409. if (![user.userId isEqualToString:self.videoView.streamUserId] && ![user.userId isEqualToString:self.createrId] && ![user.userId containsString:@"rc_mc_"]) {
  410. [seatArray addObject:user.userId];
  411. }
  412. }
  413. if (self.micStatus == MICSTATUS_CONNECTING && ![seatArray containsObject:UserDefault(UIDKey)]) {
  414. [seatArray addObject:UserDefault(UIDKey)];
  415. }
  416. if (seatArray.count) {
  417. if (![self.videoContainerView.subviews containsObject:self.seatContainer]) {
  418. [self.videoContainerView addSubview:self.seatContainer];
  419. }
  420. [self updateSeatContainerConstraint];
  421. self.seatContainer.seatMemberArray = [NSMutableArray arrayWithArray:seatArray];
  422. [self.seatContainer refreshSeatUI];
  423. }
  424. else {
  425. [self removeSeatContainer];
  426. }
  427. }
  428. - (void)updateSeatContainerConstraint {
  429. [self.seatContainer mas_remakeConstraints:^(MASConstraintMaker *make) {
  430. make.left.right.mas_equalTo(self.videoContainerView);
  431. make.top.mas_equalTo(self.headView.mas_bottom).offset(0);
  432. make.height.mas_equalTo(70);
  433. }];
  434. }
  435. // 移除连麦视图
  436. - (void)removeSeatContainer {
  437. if ([self.videoContainerView.subviews containsObject:self.seatContainer]) {
  438. [self.seatContainer removeFromSuperview];
  439. }
  440. }
  441. - (void)countLikeMessageCount {
  442. NSInteger count = self.likeCount;
  443. NSString *desc = @"";
  444. if (count > 10000) {
  445. count = count / 10000;
  446. desc = [NSString stringWithFormat:@"本场点赞%zd万+",count];
  447. }
  448. else {
  449. desc = [NSString stringWithFormat:@"本场点赞%zd",count];
  450. }
  451. self.headView.likeCount.text = desc;
  452. }
  453. - (void)setRoleType {
  454. // 1.设置切换听筒为扬声器
  455. [self.engine setDefaultAudioRouteToSpeaker:YES];
  456. // 2.加入RTC房间
  457. [self joinLiveRoom];
  458. }
  459. // 观众上下麦
  460. - (void)connectHostWithStatus:(BOOL)isConnect {
  461. // 转换中,不再处理转换身份
  462. if (self.isTransferRole) {
  463. return;
  464. }
  465. // 如果需要切换的身份和当前身份相同 拦截
  466. if (isConnect && self.liveRoleType == RCRTCLiveRoleTypeBroadcaster) {
  467. return;
  468. }
  469. else if (isConnect == NO && self.liveRoleType == RCRTCLiveRoleTypeAudience) {
  470. return;
  471. }
  472. self.isTransferRole = YES;
  473. // 清理当前视图
  474. [self removeSeatContainer];
  475. [self clearVideoViewSource];
  476. if (isConnect) {
  477. // 开启麦克风采集
  478. [self.engine.defaultAudioStream setMicrophoneDisable:NO];
  479. NSArray *streams = @[self.engine.defaultAudioStream];
  480. MJWeakSelf;
  481. [self.room.localUser switchToBroadcaster:streams onSucceed:^(RCRTCLiveInfo * _Nonnull liveInfo) {
  482. weakSelf.isTransferRole = NO;
  483. dispatch_main_async_safe(^{
  484. __strong typeof(weakSelf) strongSelf = weakSelf;
  485. //3.切换成功, 订阅远端用户流
  486. strongSelf.liveRoleType = RCRTCLiveRoleTypeBroadcaster;
  487. NSMutableArray *streamArray = [NSMutableArray array];
  488. NSArray *remoteUserArray = [strongSelf.room.remoteUsers mutableCopy];
  489. for (RCRTCRemoteUser *user in remoteUserArray) {
  490. if (user.remoteStreams.count) {
  491. [streamArray addObjectsFromArray:user.remoteStreams];
  492. }
  493. }
  494. if (streamArray.count) {
  495. [strongSelf subscribeRemoteResource:streamArray];
  496. }
  497. else {
  498. [strongSelf updateVideoViewContainer];
  499. }
  500. strongSelf.micStatus = MICSTATUS_CONNECTING;
  501. // 刷新麦位状态
  502. [strongSelf renderSeatView];
  503. });
  504. } onFailed:^(RCRTCCode code) {
  505. NSLog(@"------- up error code %ld", code);
  506. weakSelf.isTransferRole = NO;
  507. dispatch_main_async_safe(^{
  508. if (code == RCRTCCodeSwitchRoleSameRoleError) {
  509. weakSelf.liveRoleType = RCRTCLiveRoleTypeBroadcaster;
  510. // 失败
  511. weakSelf.micStatus = MICSTATUS_CONNECTING;
  512. // 刷新麦位状态
  513. [weakSelf renderSeatView];
  514. }
  515. else {
  516. // 失败
  517. [weakSelf MBPShow:@"上麦失败"];
  518. weakSelf.micStatus = MICSTATUS_NOMAL;
  519. [weakSelf renderSeatView];
  520. }
  521. });
  522. } onKicked:^{
  523. weakSelf.isTransferRole = NO;
  524. dispatch_main_async_safe(^{
  525. // 被踢出
  526. [weakSelf kickOutLiveRoom];
  527. });
  528. }];
  529. }
  530. else { // 观众下麦
  531. MJWeakSelf;
  532. [self.room.localUser switchToAudienceOnSucceed:^{
  533. weakSelf.isTransferRole = NO;
  534. dispatch_main_async_safe(^{
  535. __strong typeof(weakSelf) strongSelf = weakSelf;
  536. strongSelf.liveRoleType = RCRTCLiveRoleTypeAudience;
  537. [strongSelf.engine.defaultAudioStream setMicrophoneDisable:YES];
  538. NSMutableArray *streamArray = [NSMutableArray array];
  539. if (strongSelf.room.remoteUsers.count) {
  540. NSArray *remoteUserArray = [strongSelf.room.remoteUsers mutableCopy];
  541. for (RCRTCRemoteUser *user in remoteUserArray) {
  542. if (user.remoteStreams.count) {
  543. [streamArray addObjectsFromArray:user.remoteStreams];
  544. [strongSelf subscribeRemoteResource:streamArray];
  545. }
  546. }
  547. }
  548. if (streamArray.count == 0) {
  549. [strongSelf updateVideoViewContainer];
  550. }
  551. strongSelf.micStatus = MICSTATUS_NOMAL;
  552. // 刷新麦位状态
  553. [strongSelf renderSeatView];
  554. // 发送下麦消息
  555. [weakSelf sendDownSeatMessage];
  556. });
  557. } onFailed:^(RCRTCCode code) {
  558. weakSelf.isTransferRole = NO;
  559. NSLog(@"------- down error code %ld", code);
  560. dispatch_main_async_safe(^{
  561. if (code == RCRTCCodeSwitchRoleSameRoleError) {
  562. weakSelf.liveRoleType = RCRTCLiveRoleTypeAudience;
  563. weakSelf.micStatus = MICSTATUS_NOMAL;
  564. [weakSelf renderSeatView];
  565. }
  566. else {
  567. // 失败
  568. [weakSelf MBPShow:@"下麦失败"];
  569. weakSelf.micStatus = MICSTATUS_CONNECTING;
  570. }
  571. // 刷新麦位状态
  572. [weakSelf renderSeatView];
  573. });
  574. } onKicked:^{
  575. weakSelf.isTransferRole = NO;
  576. dispatch_main_async_safe(^{
  577. // 被踢出
  578. [weakSelf kickOutLiveRoom];
  579. });
  580. }];
  581. }
  582. }
  583. - (void)kickOutLiveRoom {
  584. [self MBPShow:@"您已被踢出直播间"];
  585. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  586. [self quitRoom];
  587. });
  588. }
  589. - (void)countMemberCount {
  590. NSInteger count = self.totalCount;
  591. NSString *desc = @"";
  592. if (count > 10000) {
  593. count = count / 10000;
  594. desc = [NSString stringWithFormat:@"%zd万+人",count];
  595. }
  596. else {
  597. desc = [NSString stringWithFormat:@"%zd人",count];
  598. }
  599. self.headView.roomMemberCount.text = desc;
  600. }
  601. - (void)clearVideoViewSource {
  602. self.videoView.streamUserId = @"";
  603. self.videoView.streamTag = @"";
  604. self.videoView.streamId = @"";
  605. }
  606. // 清空视图
  607. - (void)clearRemoteContainer {
  608. [self.streamVideos removeAllObjects];
  609. [self.videoView removeAllSubViews];
  610. [self clearVideoViewSource];
  611. [self removeSeatContainer];
  612. }
  613. // 更新视图
  614. - (void)updateVideoViewContainer {
  615. NSMutableArray *steamArray = [self.streamVideos mutableCopy];
  616. if (steamArray.count > 0) {
  617. // 渲染主播的流 优先显示主播的共享流
  618. KSLiveStreamVideo *mainVideo = nil;
  619. for (KSLiveStreamVideo *videoSource in steamArray) {
  620. if ([videoSource.userId isEqualToString:self.createrId]) { // 主屏只渲染主讲人
  621. if ([videoSource.streamTag isEqualToString:@"screenshare"]) { // 如果是共享流
  622. if (![self.videoView.streamId isEqualToString:videoSource.streamId]) { // 主屏渲染不同 则重新渲染
  623. mainVideo = videoSource;
  624. }
  625. break;
  626. }
  627. else if ([videoSource.streamTag isEqualToString:@"RongCloudRTC"]) { // 默认流
  628. if (![self.videoView.streamId isEqualToString:videoSource.streamId]) { // 主屏渲染不同 则重新渲染
  629. mainVideo = videoSource;
  630. }
  631. }
  632. else { // 其他流
  633. if (mainVideo == nil) { // 如果暂未遍历出其他视频流 先取一个作为主屏展示流
  634. if (![self.videoView.streamId isEqualToString:videoSource.streamId]) { // 主屏渲染不同 则重新渲染
  635. mainVideo = videoSource;
  636. }
  637. }
  638. }
  639. }
  640. }
  641. // 如果需要渲染主屏
  642. if (mainVideo) {
  643. [self.videoView removeAllSubViews];
  644. self.videoView.streamUserId = mainVideo.userId;
  645. self.videoView.streamId = mainVideo.streamId;
  646. self.videoView.streamTag = mainVideo.streamTag;
  647. mainVideo.canvesView.tag = 10000;
  648. [self.videoView addSubview:mainVideo.canvesView];
  649. [mainVideo.canvesView mas_makeConstraints:^(MASConstraintMaker *make) {
  650. make.left.right.bottom.top.mas_equalTo(self.videoView);
  651. }];
  652. }
  653. }
  654. [self changeEmptyStatusView];
  655. // 刷新 seatView
  656. [self renderSeatView];
  657. }
  658. - (void)removeViewSubViews:(UIView *)container {
  659. while (container.subviews.count) {
  660. [container.subviews.lastObject removeFromSuperview];
  661. }
  662. }
  663. - (void)changeEmptyStatusView {
  664. if (self.isCreaterInRoom) {
  665. if (self.isCreaterVideoEnable) {
  666. self.emptyView.hidden = YES;
  667. }
  668. else if (self.isCreaterVideoEnable == NO && self.isCreaterAudioEnable == YES) {
  669. // 主播关闭了摄像头
  670. [self showEmptyViewDisplay:YES];
  671. }
  672. else { // 休息一下
  673. [self showEmptyViewDisplay:NO];
  674. }
  675. }
  676. else {
  677. // 无主播
  678. [self.videoView removeAllSubViews];
  679. [self showEmptyViewDisplay:NO];
  680. }
  681. }
  682. #pragma mark ---- RCRTCRoomEventDelegate
  683. // 远端发布流
  684. - (void)didPublishStreams:(NSArray<RCRTCInputStream *> *)streams {
  685. [self subscribeRemoteResource:streams];
  686. NSLog(@"didPublishStreams --------");
  687. }
  688. // 订阅远端流
  689. - (void)subscribeRemoteResource:(NSArray<RCRTCInputStream *> *)streams {
  690. [self subscribeRemoteResource:streams isTiny:NO];
  691. }
  692. - (void)subscribeRemoteResource:(NSArray<RCRTCInputStream *> *)streams isTiny:(BOOL)isTiny {
  693. // 订阅房间中远端用户音视频流资源
  694. NSArray *tinyStream = isTiny ? streams : @[];
  695. NSArray *ordinaryStream = isTiny ? @[] : streams;
  696. [self.room.localUser subscribeStream:ordinaryStream
  697. tinyStreams:tinyStream
  698. completion:^(BOOL isSuccess, RCRTCCode desc) {
  699. if (desc != RCRTCCodeSuccess) {
  700. NSString *errorStr = [NSString stringWithFormat:@"订阅远端流失败:%ld", (long) desc];
  701. [self MBPShow:errorStr];
  702. return;
  703. }
  704. // 创建并设置远端视频预览视图
  705. for (RCRTCInputStream *stream in streams) {
  706. if (stream.mediaType == RTCMediaTypeVideo) {
  707. if ([stream.userId isEqualToString:self.createrId]) { // 只渲染主讲人的流
  708. self.isCreaterVideoEnable = YES;
  709. [self setupRemoteViewWithStream:stream];
  710. }
  711. }
  712. if (stream.mediaType == RTCMediaTypeAudio && [stream.userId isEqualToString:self.createrId]) {
  713. self.isCreaterAudioEnable = YES;
  714. }
  715. }
  716. [self updateVideoViewContainer];
  717. }];
  718. }
  719. // 创建并设置远端视频预览视图
  720. - (KSLiveStreamVideo *)setupRemoteViewWithStream:(RCRTCInputStream *)stream {
  721. KSLiveStreamVideo *sVideo = [self creatStreamVideoWithStreamId:stream.streamId userId:stream.userId tag:stream.tag];
  722. sVideo.userId = stream.userId;
  723. RCRTCVideoView *remoteView = (RCRTCVideoView *) sVideo.canvesView;
  724. //设置视频流的渲染视图
  725. [(RCRTCVideoInputStream *) stream setVideoView:remoteView];
  726. return sVideo;
  727. }
  728. // 远端用户取消发布资源
  729. - (void)didUnpublishStreams:(NSArray<RCRTCInputStream *> *)streams {
  730. [self unsubscribeRemoteResource:streams orStreamId:nil];
  731. }
  732. - (void)stream:(RCRTCInputStream *)stream didVideoEnable:(BOOL)enable {
  733. NSLog(@"----- video --- staus %d", enable);
  734. }
  735. - (void)stream:(RCRTCInputStream *)stream didAudioMute:(BOOL)mute {
  736. NSLog(@"----- audio --- staus %d", mute);
  737. if ([stream.userId isEqualToString:self.createrId]) {
  738. if (mute) {
  739. self.isCreaterAudioEnable = NO;
  740. }
  741. else {
  742. self.isCreaterAudioEnable = YES;
  743. }
  744. [self changeEmptyStatusView];
  745. }
  746. }
  747. - (void)didOfflineUser:(RCRTCRemoteUser *)user {
  748. [self removeRemoteVideoWithUserId:user.userId];
  749. [self renderSeatView];
  750. }
  751. // 判断是否已有预览视图
  752. - (KSLiveStreamVideo *)creatStreamVideoWithStreamId:(NSString *)streamId userId:(NSString *)userId tag:(NSString *)streamTag {
  753. KSLiveStreamVideo *sVideo = [self fetchStreamVideoWithStreamId:streamId];
  754. if (!sVideo) {
  755. sVideo = [[KSLiveStreamVideo alloc] initWithStreamId:streamId streamUserId:userId streamTag:streamTag];
  756. [self.streamVideos insertObject:sVideo atIndex:0];
  757. }
  758. return sVideo;
  759. }
  760. // 根据 streamId 确认唯一的音视频流
  761. - (KSLiveStreamVideo *)fetchStreamVideoWithStreamId:(NSString *)streamId {
  762. NSMutableArray *streamArray = [self.streamVideos mutableCopy];
  763. for (KSLiveStreamVideo *sVideo in streamArray) {
  764. if ([streamId isEqualToString:sVideo.streamId]) {
  765. return sVideo;
  766. }
  767. }
  768. return nil;
  769. }
  770. // 远端掉线/离开回掉调用,删除远端用户的所有音视频流
  771. - (void)fetchStreamVideoOffLineWithStreamId:(NSString *)streamId {
  772. NSArray *arr = [NSArray arrayWithArray:self.streamVideos];
  773. for (KSLiveStreamVideo *sVideo in arr) {
  774. if ([streamId isEqualToString:sVideo.streamId]) {
  775. if (sVideo) {
  776. [sVideo.canvesView removeFromSuperview];
  777. [self.streamVideos removeObject:sVideo];
  778. }
  779. }
  780. }
  781. [self updateVideoViewContainer];
  782. }
  783. // 远端用户切换身份(主播接收)
  784. - (void)didSwitchRoleWithUser:(RCRTCRemoteUser *)user roleType:(RCRTCLiveRoleType)roleType {
  785. [self renderSeatView];
  786. NSLog(@"didSwitchRoleWithUser --------");
  787. }
  788. - (void)judgeRefreshSeatView:(NSString *)userId {
  789. BOOL needRefresh = NO;
  790. if (_seatContainer) {
  791. if (self.seatContainer.seatMemberArray.count && [self.videoContainerView.subviews containsObject:self.seatContainer]) {
  792. NSMutableArray *memerArray = [self.seatContainer.seatMemberArray mutableCopy];
  793. for (NSString *memberId in memerArray) {
  794. if ([userId isEqualToString:memberId]) {
  795. needRefresh = YES;
  796. break;
  797. }
  798. }
  799. }
  800. }
  801. if (needRefresh) {
  802. [self renderSeatView];
  803. }
  804. }
  805. // 主播加入房间 (观众接收)
  806. - (void)didJoinUser:(RCRTCRemoteUser *)user {
  807. if ([user.userId isEqualToString:self.createrId]) { // 当主播重新进入房间需要重置连麦状态
  808. self.isCreaterInRoom = YES;
  809. // 重置连麦状态
  810. [self resetMicWaitToNomal];
  811. // 刷新顶部视图
  812. }
  813. else {
  814. [self renderSeatView];
  815. }
  816. NSLog(@"didJoinUser --------");
  817. }
  818. // 主播离开房间 (观众接收)
  819. - (void)didLeaveUser:(RCRTCRemoteUser *)user {
  820. [self removeRemoteVideoWithUserId:user.userId]; // 移除对应的视频
  821. if ([user.userId isEqualToString:self.createrId]) { // 如果是主讲人
  822. self.isCreaterInRoom = NO;
  823. [self resetMicWaitToNomal];
  824. [self tipsTeacherLeaveRoom];
  825. [self clearVideoView];
  826. [self showEmptyViewDisplay:NO];
  827. }
  828. else {
  829. [self renderSeatView];
  830. }
  831. }
  832. - (void)removeRemoteVideoWithUserId:(NSString *)userId {
  833. NSArray *arr = [NSArray arrayWithArray:self.streamVideos];
  834. for (KSLiveStreamVideo *sVideo in arr) {
  835. if ([userId isEqualToString:sVideo.userId]) {
  836. if (sVideo) {
  837. [sVideo.canvesView removeFromSuperview];
  838. [self.streamVideos removeObject:sVideo];
  839. }
  840. }
  841. }
  842. }
  843. - (void)clearVideoView {
  844. [self clearVideoViewSource];
  845. [self.videoView removeAllSubViews];
  846. }
  847. - (void)resetConnectionStatus {
  848. if (self.micStatus == MICSTATUS_CONNECTING) {
  849. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  850. [self connectHostWithStatus:NO];
  851. });
  852. }
  853. else {
  854. [self removeSeatContainer];
  855. }
  856. self.micStatus = MICSTATUS_NOMAL;
  857. }
  858. - (void)resetMicWaitToNomal {
  859. if (self.micStatus == MICSTATUS_WAITING) {
  860. self.micStatus = MICSTATUS_NOMAL;
  861. }
  862. }
  863. - (void)tipsTeacherLeaveRoom {
  864. [self MBPShow:@"主讲人已离开房间"];
  865. }
  866. #pragma mark - KSChatInputBarControlDelegate
  867. // 根据inputBar 回调来修改页面布局
  868. - (void)onInputBarControlContentSizeChanged:(CGRect)frame withAnimationDuration:(CGFloat)duration andAnimationCurve:(UIViewAnimationCurve)curve {
  869. CGRect originFrame = _inputBar.frame;
  870. __weak __typeof(&*self)weakSelf = self;
  871. // 目前只使用y值即可 -- 只修改messageContentView高度,让展示消息view和输入框随之移动
  872. [UIView animateWithDuration:duration animations:^{
  873. [UIView setAnimationCurve:curve];
  874. [weakSelf.inputBar setFrame:CGRectMake(0, frame.origin.y - originFrame.size.height, originFrame.size.width, originFrame.size.height)];
  875. [UIView commitAnimations];
  876. }];
  877. }
  878. // 发送消息
  879. - (void)onTouchSendButton:(NSString *)text {
  880. if (self.blacklistFlag == YES) {
  881. [self setDefaultBottomViewStatus];
  882. return;
  883. }
  884. NSDate *date = [NSDate date];
  885. NSTimeInterval currentInterval = [date timeIntervalSince1970];
  886. if (currentInterval - self.lastSendMsgTime < 3) {
  887. [self MBPShow:@"您说话太快啦"];
  888. return;
  889. }
  890. if (self.lastSendMsgTime == 0) {
  891. self.lastSendMsgTime = currentInterval;
  892. }
  893. if (text.length > 40) {
  894. [self MBPShow:@"聊天消息需在40个字以内哦"];
  895. return;
  896. }
  897. // if (self.enableChat) {
  898. self.lastSendMsgTime = currentInterval;
  899. [self touristSendMessage:text];
  900. // }
  901. // else {
  902. // [self setDefaultBottomViewStatus];
  903. // }
  904. }
  905. - (void)touristSendMessage:(NSString *)text {
  906. RCTextMessage *rcTextMessage = [RCTextMessage messageWithContent:text];
  907. MJWeakSelf;
  908. [self sendMessage:rcTextMessage displayMessage:YES callback:^(BOOL success) {
  909. [weakSelf setDefaultBottomViewStatus];
  910. }];
  911. }
  912. #pragma mark ---- RTC
  913. - (void)joinLiveRoom {
  914. // self.liveRoleType = RCRTCLiveRoleTypeAudience;
  915. // self.micStatus = MICSTATUS_NOMAL;
  916. // 1.配置房间
  917. RCRTCRoomConfig *config = [[RCRTCRoomConfig alloc] init];
  918. config.roomType = RCRTCRoomTypeLive;
  919. config.liveType = RCRTCLiveTypeAudioVideo;
  920. config.roleType = RCRTCLiveRoleTypeAudience;
  921. __weak typeof(self) weakSelf = self;
  922. [self.engine joinRoom:self.roomId config:config completion:^(RCRTCRoom * _Nullable room, RCRTCCode code) {
  923. dispatch_main_async_safe(^{
  924. __strong typeof(weakSelf) strongSelf = weakSelf;
  925. if (code == RCRTCCodeSignalServerNotConnect || code == RCRTCCodeParameterError || code == RCRTCCodeNotInRTCRoom || code == RCRTCCodeRTCTokenIsNull || code == RCRTCCodeHttpTimeoutError || code == RCRTCCodeHttpError || code == RCRTCCodeVoIPNotAvailable) {
  926. NSLog(@"%@",[NSString stringWithFormat:@"加入失败 code %ld",code]);
  927. // [strongSelf MBPShow:@"加入直播间失败"];
  928. // [strongSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
  929. }
  930. else { // 加入直播间成功
  931. [strongSelf notiferJoinSuccessToServiceCallback:^{
  932. }];
  933. if (room) {
  934. strongSelf.room = room;
  935. strongSelf.room.delegate = self;
  936. }
  937. [strongSelf countMemberCount];
  938. if (room.remoteUsers.count) {
  939. NSMutableArray *streamArray = [NSMutableArray array];
  940. NSMutableArray *remoteUserArray = [room.remoteUsers mutableCopy];
  941. for (RCRTCRemoteUser *user in remoteUserArray) {
  942. if ([user.userId isEqualToString:strongSelf.createrId]) {
  943. strongSelf.isCreaterInRoom = YES;
  944. }
  945. if (user.remoteStreams.count) {
  946. [streamArray addObjectsFromArray:user.remoteStreams];
  947. [strongSelf subscribeRemoteResource:streamArray];
  948. }
  949. }
  950. }
  951. [self changeEmptyStatusView];
  952. }
  953. });
  954. }];
  955. }
  956. - (void)closeAlertView {
  957. if (self.alertView && self.alertView.isShow) {
  958. [self.alertView removeFromSuperview];
  959. self.alertView = nil;
  960. }
  961. }
  962. - (void)displayCloseView {
  963. self.isCloseRoom = YES;
  964. [self hideTipsView];
  965. // 移除连麦视图
  966. [self clearRemoteContainer];
  967. if (self.micStatus != MICSTATUS_NOMAL) {
  968. self.micStatus = MICSTATUS_NOMAL;
  969. self.liveRoleType = RCRTCLiveRoleTypeAudience;
  970. [self.engine.defaultAudioStream setMicrophoneDisable:YES];
  971. }
  972. [self.engine leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
  973. if (code != RCRTCCodeSuccess) {
  974. // 退出失败
  975. }
  976. }];
  977. self.endView.hidden = NO;
  978. [self setDefaultBottomViewStatus];
  979. [[NSNotificationCenter defaultCenter] postNotificationName:@"LiveroomClose" object:nil];
  980. }
  981. - (void)insertMessage:(RCMessage *)rcMessage userInfo:(NSDictionary *)userInfo {
  982. // left
  983. NSDictionary *leftDic = userInfo;
  984. if (leftDic && [leftDic[@"left"] isEqual:@(0)]) {
  985. self.isNeedScrollToButtom = YES;
  986. }
  987. [self appendAndDisplayMessage:rcMessage];
  988. }
  989. - (void)kickSeatWithMessage:(NSString *)message {
  990. [self MBPShow:message];
  991. self.micStatus = MICSTATUS_NOMAL;
  992. [self connectHostWithStatus:NO];
  993. }
  994. - (void)showInviteAlertMessage:(NSString *)tipsMessage {
  995. if (self.alertView && self.alertView.isShow) {
  996. [self.alertView removeFromSuperview];
  997. self.alertView = nil;
  998. }
  999. MJWeakSelf;
  1000. self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:tipsMessage leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
  1001. weakSelf.micStatus = MICSTATUS_NOMAL;
  1002. [weakSelf sendSeatResponseMessage:NO];
  1003. } confirm:^{
  1004. [weakSelf sendSeatResponseMessage:YES];
  1005. }];
  1006. }
  1007. - (void)sendSeatResponseMessage:(BOOL)isApprove {
  1008. SEATRESPONSE type = isApprove ? SEATRESPONSE_AUDIENCEAPPROVE : SEATRESPONSE_AUDIENCEREJECT;
  1009. KSLiveChatroomSeatResponse *responseMessage = [[KSLiveChatroomSeatResponse alloc] init];
  1010. responseMessage.type = type;
  1011. responseMessage.audienceId = UserDefault(UIDKey);
  1012. responseMessage.audienceName = UserDefault(NicknameKey);
  1013. MJWeakSelf;
  1014. [self sendMessage:responseMessage displayMessage:YES callback:^(BOOL success) {
  1015. if (success) {
  1016. if (isApprove) {
  1017. [weakSelf connectHostWithStatus:YES];
  1018. }
  1019. }
  1020. }];
  1021. }
  1022. - (void)showEmptyViewDisplay:(BOOL)isPublish {
  1023. NSString *imageName = @"";
  1024. NSString *descMessage = @"";
  1025. if (isPublish) {
  1026. imageName = @"liveVideo_close";
  1027. descMessage = @"主讲人已关闭画面!";
  1028. }
  1029. else {
  1030. imageName = @"liveroom_empty";
  1031. descMessage = @"休息一下,马上回来!";
  1032. }
  1033. [self.emptyView configViewWithImageName:imageName desc:descMessage];
  1034. self.emptyView.hidden = NO;
  1035. }
  1036. - (void)exitRoom {
  1037. [self.engine.defaultAudioStream setMicrophoneDisable:YES];
  1038. __weak typeof(self) weakSelf = self;
  1039. [self.engine leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
  1040. dispatch_main_async_safe(^{
  1041. __strong typeof(weakSelf) strongSelf = weakSelf;
  1042. [strongSelf sendLeaveMessageCallback:^(BOOL success) {
  1043. // quit 接口
  1044. [weakSelf quitNotiferService];
  1045. [weakSelf quitChatRoom];
  1046. }];
  1047. });
  1048. }];
  1049. }
  1050. // 取消订阅流 Id 所对应的 View
  1051. - (void)unsubscribeRemoteResource:(NSArray<RCRTCInputStream *> *)streams orStreamId:(NSString *)streamId {
  1052. for (RCRTCInputStream *stream in streams) {
  1053. if (stream.mediaType == RTCMediaTypeVideo) {
  1054. streamId = stream.streamId;
  1055. if ([stream.userId isEqualToString:self.createrId]) {
  1056. [self clearVideoViewSource];
  1057. self.isCreaterVideoEnable = NO;
  1058. // 主讲老师停止发布视频流
  1059. NSLog(@"----- 停止发布视频流");
  1060. }
  1061. [self fetchStreamVideoOffLineWithStreamId:streamId];
  1062. }
  1063. else if (stream.mediaType == RTCMediaTypeAudio && [stream.userId isEqualToString:self.createrId]) {
  1064. // 主讲老师停止发布音频流
  1065. NSLog(@"----- 停止发布音频流");
  1066. self.isCreaterAudioEnable = NO;
  1067. }
  1068. }
  1069. }
  1070. #pragma mark -- 加入直播间和退出直播间回到服务
  1071. - (void)notiferJoinSuccessToServiceCallback:(void(^)(void))callback {
  1072. callback();
  1073. [KSNetworkingManager liveRoomJoinRoomRequest:KS_GET roomUid:self.roomId success:^(NSDictionary * _Nonnull dic) {
  1074. callback();
  1075. } faliure:^(NSError * _Nonnull error) {
  1076. callback();
  1077. }];
  1078. }
  1079. #pragma mark -- 退出直播间回掉服务
  1080. - (void)quitNotiferService {
  1081. [KSNetworkingManager LiveroomQuit:KS_POST success:^(NSDictionary * _Nonnull dic) {
  1082. if ([dic integerValueForKey:@"errCode"] == 0) {
  1083. NSLog(@"success");
  1084. }
  1085. else {
  1086. NSLog(@"----- error %@", [dic stringValueForKey:@"errMsg"]);
  1087. }
  1088. } faliure:^(NSError * _Nonnull error) {
  1089. }];
  1090. }
  1091. - (void)sendLeaveMessageCallback:(void(^)(BOOL success))callback {
  1092. RCUserInfo *currentUserInfo = [RCIM sharedRCIM].currentUserInfo;
  1093. KSLiveChatroomLeave *leaveMessage = [[KSLiveChatroomLeave alloc] init];
  1094. leaveMessage.userId = currentUserInfo.userId;
  1095. leaveMessage.userName = currentUserInfo.name;
  1096. [self sendMessage:leaveMessage displayMessage:NO callback:^(BOOL success) {
  1097. callback(success);
  1098. }];
  1099. }
  1100. - (void)quitChatRoom {
  1101. [[RCIMClient sharedRCIMClient] quitChatRoom:self.roomId success:^{
  1102. NSLog(@"sucess log out--");
  1103. } error:^(RCErrorCode status) {
  1104. NSLog(@"RCErrorCode------%ld ", (long)status);
  1105. }];
  1106. }
  1107. - (void)addConstMessage { // 固定欢迎词语
  1108. RCTextMessage *statement = [RCTextMessage messageWithContent:@"欢迎进入直播课堂,请遵守相关法规,禁止传播低俗、暴力等不良信息。为孩子创造健康绿色的学习环境。"];
  1109. statement.extra = @"statement";
  1110. RCMessage *constMessage = [[RCMessage alloc] initWithType:ConversationType_CHATROOM targetId:self.roomId direction:MessageDirection_SEND content:statement];
  1111. constMessage.content.senderUserInfo = [RCIM sharedRCIM].currentUserInfo;
  1112. [self appendAndDisplayMessage:constMessage];
  1113. }
  1114. #pragma mark - views init
  1115. /**
  1116. * 接收到消息的回调
  1117. */
  1118. - (void)didReceiveMessageNotification:(NSNotification *)notification {
  1119. NSDictionary *dic = notification.object;
  1120. __block RCMessage *rcMessage = dic[@"message"];
  1121. KSRCMessageModel *model = [[KSRCMessageModel alloc] initWithMessage:rcMessage];
  1122. model.userInfo = rcMessage.content.senderUserInfo;
  1123. if (model.conversationType == ConversationType_CHATROOM && [model.targetId isEqualToString:self.roomId]) {
  1124. __weak typeof(&*self) __blockSelf = self;
  1125. dispatch_main_async_safe((^{
  1126. // 对赞消息拦截 ,展示动画,不插入数据源 ,对于seat消息 和踢出消息,弹出alert
  1127. if (rcMessage) {
  1128. // 👍🏻消息
  1129. if ([rcMessage.content isMemberOfClass:[KSLiveChatroomLike class]]) {
  1130. KSLiveChatroomLike *likeMessage = (KSLiveChatroomLike *)rcMessage.content;
  1131. // 统计点赞数量
  1132. // __blockSelf.likeCount += likeMessage.counts;
  1133. // [__blockSelf countLikeMessageCount];
  1134. }
  1135. else if ([rcMessage.content isMemberOfClass:[RCChatroomLikeCount class]]) {
  1136. RCChatroomLikeCount *likeCountMessage = (RCChatroomLikeCount *)rcMessage.content;
  1137. __blockSelf.likeCount = likeCountMessage.count;
  1138. [__blockSelf countLikeMessageCount];
  1139. return;
  1140. }
  1141. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomWelcome class]]) {
  1142. // 过滤自己发送的欢迎消息
  1143. if ([rcMessage.senderUserId isEqualToString:UserDefault(UIDKey)]) {
  1144. return;
  1145. }
  1146. if ([rcMessage.senderUserId isEqual:self.createrId]) { // 如果是老师 重置连麦申请状态
  1147. [__blockSelf resetMicWaitToNomal];
  1148. }
  1149. RCUserInfo *userInfo = rcMessage.content.senderUserInfo;
  1150. NSString *userName = [userInfo.name stringByAppendingString:@""];
  1151. NSString *contentMsg = [NSString stringWithFormat:@"%@ 进入直播间",userName];
  1152. [__blockSelf showAnimationView:YES showMessag:contentMsg];
  1153. }
  1154. // 用户退出消息
  1155. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomLeave class]]) {
  1156. return;
  1157. }
  1158. // 用户退出消息
  1159. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomUserQuit class]]) {
  1160. return;
  1161. }
  1162. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomKickOut class]]) {
  1163. KSLiveChatroomKickOut *kickMessage = (KSLiveChatroomKickOut *)rcMessage.content;
  1164. NSString *currentUserId = UserDefault(UIDKey);
  1165. if ([kickMessage.targetId isEqualToString:currentUserId]) {
  1166. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1167. [__blockSelf kickOutLiveRoom];
  1168. }
  1169. return;
  1170. }
  1171. // 人数同步
  1172. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomMemberUp class]]) {
  1173. KSLiveChatroomMemberUp *member = (KSLiveChatroomMemberUp *)rcMessage.content;
  1174. __blockSelf.totalCount = member.count;
  1175. [__blockSelf countMemberCount];
  1176. return;
  1177. }
  1178. // // 禁言控制
  1179. // else if ([rcMessage.content isMemberOfClass:[RCChatroomChatBan class]]) {
  1180. // RCChatroomChatBan *banMessage = (RCChatroomChatBan *)rcMessage.content;
  1181. // if (banMessage.chatBan) { // 禁止发言
  1182. // __blockSelf.enableChat = NO;
  1183. // }
  1184. // else { // 开启发言
  1185. // __blockSelf.enableChat = YES;
  1186. // }
  1187. // [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1188. // }
  1189. // 连麦控制消息
  1190. else if ([rcMessage.content isMemberOfClass:[RCChatroomSeatsControl class]]) {
  1191. RCChatroomSeatsControl *seatControlMessage = (RCChatroomSeatsControl *)rcMessage.content;
  1192. if (seatControlMessage.seatBan) { // 禁止连麦
  1193. __blockSelf.enableSeat = NO;
  1194. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1195. [__blockSelf hideApplyView];
  1196. [__blockSelf hideApplyingView];
  1197. }
  1198. else { // 开启连麦
  1199. __blockSelf.enableSeat = YES;
  1200. }
  1201. [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1202. }
  1203. // 连麦申请消息
  1204. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomSeatApply class]]) {
  1205. KSLiveChatroomSeatApply *seatApplyMessage = (KSLiveChatroomSeatApply *)rcMessage.content;
  1206. // 只处理和自己相关的消息
  1207. if (![seatApplyMessage.audienceId isEqualToString:UserDefault(UIDKey)]) {
  1208. // 刷新麦序
  1209. return;
  1210. }
  1211. if (seatApplyMessage.type == SEATHANDLE_INVITE) { // 主讲人发起申请
  1212. NSString *titles = [NSString stringWithFormat:@"%@邀请您连麦",[NSString returnNoNullStringWithString:seatApplyMessage.teacherName]];
  1213. [__blockSelf showInviteAlertMessage:titles];
  1214. }
  1215. else if (seatApplyMessage.type == SEATHANDLE_DISINVITE) { // 主讲人撤回邀请
  1216. [__blockSelf MBPShow:@"主讲人撤回了连麦邀请"];
  1217. if (__blockSelf.alertView && __blockSelf.alertView.isShow) {
  1218. [__blockSelf.alertView dismissAlertView];
  1219. }
  1220. }
  1221. else if (seatApplyMessage.type == SEATHANDLE_KICKSEAT) { // 主讲人将麦上观众抱下麦
  1222. [__blockSelf kickSeatWithMessage:@"您已被抱下麦"];
  1223. }
  1224. [__blockSelf hideApplyingView];
  1225. [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1226. }
  1227. // 连麦回复消息(暂不处理)
  1228. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomSeatResponse class]]) {
  1229. KSLiveChatroomSeatResponse *seatResponseMessage = (KSLiveChatroomSeatResponse *)rcMessage.content;
  1230. if (![seatResponseMessage.audienceId isEqualToString:UserDefault(UIDKey)]) { // 只处理和自己相关的消息
  1231. return;
  1232. }
  1233. if (seatResponseMessage.type == SEATRESPONSE_TEACHERAPPROVE) { //
  1234. [__blockSelf connectHostWithStatus:YES];
  1235. }
  1236. else if (seatResponseMessage.type == SEATRESPONSE_TEACHERREJECT) {
  1237. [__blockSelf MBPShow:@"主讲人拒绝了您的连麦申请"];
  1238. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1239. }
  1240. [__blockSelf hideApplyingView];
  1241. [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1242. }
  1243. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomDownSeat class]]) { // 成员下麦消息
  1244. return;
  1245. }
  1246. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomDownSeat class]]) { // 成员主动下麦消息
  1247. return;
  1248. }
  1249. else if ([rcMessage.content isMemberOfClass:[KSLiveChatroomClose class]]) { // 直播间已关闭
  1250. [__blockSelf MBPShow:@"直播已结束"];
  1251. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1252. // 显示直播间关闭状态
  1253. [__blockSelf closeAlertView];
  1254. [__blockSelf displayCloseView];
  1255. [__blockSelf hideApplyingView];
  1256. });
  1257. return;
  1258. }
  1259. else if ([rcMessage.content isMemberOfClass:[RCTextMessage class]]) {
  1260. [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1261. }
  1262. else if ([rcMessage.content isMemberOfClass:[KSRCPauseLiveMessage class]]) { // 主讲人暂停直播
  1263. [__blockSelf MBPShow:@"主讲人已暂停直播"];
  1264. [__blockSelf resetConnectionStatus];
  1265. [__blockSelf resetNetTips];
  1266. [__blockSelf closeAlertView];
  1267. [__blockSelf hideApplyingView];
  1268. return;
  1269. }
  1270. else if ([rcMessage.content isMemberOfClass:[KSRCShopRushMessage class]]) { //
  1271. KSRCShopRushMessage *rushMsg = (KSRCShopRushMessage *)rcMessage.content;
  1272. NSString *contentMsg = [NSString stringWithFormat:@"%@ 正在抢购",[NSString returnNoNullStringWithString:rushMsg.userName]];
  1273. [__blockSelf showAnimationView:NO showMessag:contentMsg];
  1274. }
  1275. else if ([rcMessage.content isMemberOfClass:[KSLiveBlockUser class]]) { // 黑名单
  1276. KSLiveBlockUser *blockMessage = (KSLiveBlockUser *)rcMessage.content;
  1277. if ([blockMessage.userId isEqualToString:UserDefault(UIDKey)]) {
  1278. __blockSelf.blacklistFlag = YES;
  1279. [__blockSelf resetConnectionStatus];
  1280. }
  1281. }
  1282. else if ([rcMessage.content isMemberOfClass:[KSLiveUnBlockUser class]]) {
  1283. KSLiveUnBlockUser *unBlockMessage = (KSLiveUnBlockUser *)rcMessage.content;
  1284. if ([unBlockMessage.userId isEqualToString:UserDefault(UIDKey)]) {
  1285. __blockSelf.blacklistFlag = NO;
  1286. }
  1287. }
  1288. else if ([rcMessage.content isMemberOfClass:[KSDownSeatAllMessage class]]) { // 所有麦上用户下麦
  1289. if (__blockSelf.micStatus == MICSTATUS_CONNECTING) {
  1290. [__blockSelf kickSeatWithMessage:@"您已被抱下麦"];
  1291. [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1292. }
  1293. }
  1294. else if ([rcMessage.content isMemberOfClass:[KSRejectAllSeatMessage class]]) { // 拒绝所有连麦申请
  1295. if (__blockSelf.micStatus == MICSTATUS_WAITING) {
  1296. [__blockSelf MBPShow:@"主讲人拒绝了您的连麦申请"];
  1297. // 处理连麦状态
  1298. __blockSelf.micStatus = MICSTATUS_NOMAL;
  1299. [__blockSelf insertMessage:rcMessage userInfo:notification.userInfo];
  1300. [__blockSelf hideApplyingView];
  1301. }
  1302. }
  1303. }
  1304. }));
  1305. }
  1306. }
  1307. - (void)hideApplyView {
  1308. if (self.applyView.isShow) {
  1309. [self.applyView hideView];
  1310. }
  1311. }
  1312. - (void)hideApplyingView {
  1313. if (self.applyingView.isShow) {
  1314. [self.applyingView hideView];
  1315. }
  1316. }
  1317. // 发送人数同步消息
  1318. - (void)sendMemberCountMessage {
  1319. KSLiveChatroomMemberCount *syncMessage = [[KSLiveChatroomMemberCount alloc] init];
  1320. syncMessage.count = self.totalCount;
  1321. [self sendMessage:syncMessage displayMessage:NO callback:^(BOOL success) {
  1322. }];
  1323. }
  1324. #pragma mark ----- time manager delegate
  1325. - (void)quitClassroomNotifer {
  1326. [self MBPShow:@"直播课已结束!"];
  1327. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1328. [self quitAction];
  1329. });
  1330. }
  1331. #pragma mark - gesture and button action
  1332. - (void)resetBottomGesture:(UIGestureRecognizer *)gestureRecognizer {
  1333. if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
  1334. [self setDefaultBottomViewStatus];
  1335. }
  1336. }
  1337. - (void)setDefaultBottomViewStatus {
  1338. [self.inputBar setInputBarStatus:KSBottomBarStatusDefault];
  1339. [self.inputBar setHidden:YES];
  1340. }
  1341. #pragma mark ---- sendMessage/showMessage
  1342. - (void)sendMessage:(RCMessageContent *)messageContent displayMessage:(BOOL)displayMessage callback:(void(^)(BOOL success))callback {
  1343. if (_roomId == nil) {
  1344. return;
  1345. }
  1346. messageContent.senderUserInfo = [RCIM sharedRCIM].currentUserInfo;
  1347. if (messageContent == nil) {
  1348. return;
  1349. }
  1350. __weak typeof(&*self) __weakself = self;
  1351. [KSChatroomMessageCenter sendChatMessage:self.roomId content:messageContent success:^(long messageId) {
  1352. dispatch_async(dispatch_get_main_queue(), ^{
  1353. RCMessage *message = [[RCMessage alloc] initWithType:ConversationType_CHATROOM targetId:__weakself.roomId direction:MessageDirection_SEND content:messageContent];
  1354. message.content.senderUserInfo = [RCIM sharedRCIM].currentUserInfo;
  1355. message.senderUserId = UserDefault(UIDKey);
  1356. if (displayMessage) {
  1357. [__weakself appendAndDisplayMessage:message];
  1358. }
  1359. [__weakself.inputBar clearInputView];
  1360. callback(YES);
  1361. });
  1362. } error:^(RCErrorCode errorCode, long messageId) {
  1363. if (errorCode == RC_CHATROOM_NOT_EXIST) {
  1364. dispatch_async(dispatch_get_main_queue(), ^{
  1365. [__weakself MBPShow:@"聊天已被解散,请退出后重进。"];
  1366. });
  1367. }
  1368. dispatch_async(dispatch_get_main_queue(), ^{
  1369. [__weakself.inputBar clearInputView];
  1370. NSLog(@"发送失败,errorcode is: %ld",(long)errorCode);
  1371. callback(NO);
  1372. });
  1373. }];
  1374. }
  1375. /**
  1376. * 将消息加入本地数组
  1377. */
  1378. - (void)appendAndDisplayMessage:(RCMessage *)rcMessage {
  1379. if (!rcMessage) {
  1380. return;
  1381. }
  1382. KSRCMessageModel *model = [[KSRCMessageModel alloc] initWithMessage:rcMessage];
  1383. model.userInfo = rcMessage.content.senderUserInfo;
  1384. if (!model.userInfo) {
  1385. model.userInfo = [RCIMClient sharedRCIMClient].currentUserInfo;
  1386. }
  1387. if ([self appendMessageModel:model]) {
  1388. NSIndexPath *indexPath =
  1389. [NSIndexPath indexPathForItem:self.conversationDataRepository.count - 1
  1390. inSection:0];
  1391. if ([self.conversationMessageTableView numberOfRowsInSection:0] !=
  1392. self.conversationDataRepository.count - 1) {
  1393. return;
  1394. }
  1395. // view刷新
  1396. [self.conversationMessageTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
  1397. if ([self isAtTheBottomOfTableView] || self.isNeedScrollToButtom) {
  1398. [self scrollToBottomAnimated:YES];
  1399. self.isNeedScrollToButtom=NO;
  1400. }
  1401. }
  1402. return;
  1403. }
  1404. /**
  1405. * 如果当前会话没有这个消息id,把消息加入本地数组
  1406. */
  1407. - (BOOL)appendMessageModel:(KSRCMessageModel *)model {
  1408. if (!model.content) {
  1409. return NO;
  1410. }
  1411. //这里可以根据消息类型来决定是否显示,如果不希望显示直接return NO
  1412. //数量不可能无限制的大,这里限制收到消息过多时,就对显示消息数量进行限制。
  1413. //用户可以手动下拉更多消息,查看更多历史消息。
  1414. if (self.conversationDataRepository.count>500) {
  1415. // NSRange range = NSMakeRange(0, 1);
  1416. KSRCMessageModel *message = self.conversationDataRepository[0];
  1417. [[RCIMClient sharedRCIMClient]deleteMessages:@[@(message.messageId)]];
  1418. [self.conversationDataRepository removeObjectAtIndex:0];
  1419. [self.conversationMessageTableView reloadData];
  1420. }
  1421. [self.conversationDataRepository addObject:model];
  1422. return YES;
  1423. }
  1424. /**
  1425. * 判断消息是否在collectionView的底部
  1426. *
  1427. * @return 是否在底部
  1428. */
  1429. - (BOOL)isAtTheBottomOfTableView {
  1430. if (self.conversationMessageTableView.contentSize.height <= self.conversationMessageTableView.frame.size.height) {
  1431. return YES;
  1432. }
  1433. if(self.conversationMessageTableView.contentOffset.y +200 >= (self.conversationMessageTableView.contentSize.height - self.conversationMessageTableView.frame.size.height)) {
  1434. return YES;
  1435. }else{
  1436. return NO;
  1437. }
  1438. }
  1439. /**
  1440. * 消息滚动到底部
  1441. *
  1442. * @param animated 是否开启动画效果
  1443. */
  1444. - (void)scrollToBottomAnimated:(BOOL)animated {
  1445. if ([self.conversationMessageTableView numberOfSections] == 0) {
  1446. return;
  1447. }
  1448. NSUInteger finalRow = MAX(0, [self.conversationMessageTableView numberOfRowsInSection:0] - 1);
  1449. if (0 == finalRow) {
  1450. return;
  1451. }
  1452. NSIndexPath *finalIndexPath =
  1453. [NSIndexPath indexPathForItem:finalRow inSection:0];
  1454. [self.conversationMessageTableView scrollToRowAtIndexPath:finalIndexPath atScrollPosition:UITableViewScrollPositionTop animated:animated];
  1455. }
  1456. /*
  1457. #pragma mark - Navigation
  1458. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1459. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1460. // Get the new view controller using [segue destinationViewController].
  1461. // Pass the selected object to the new view controller.
  1462. }
  1463. */
  1464. #pragma mark ----- table data source
  1465. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  1466. return self.conversationDataRepository.count;
  1467. }
  1468. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  1469. KSRCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
  1470. RCMessageContent *messageContent = model.content;
  1471. KSChatroomTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KSChatroomTextCell"];
  1472. if(!cell){
  1473. cell = [[KSChatroomTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"KSChatroomTextCell"];
  1474. }
  1475. if ([messageContent isMemberOfClass:[RCTextMessage class]] || [messageContent isMemberOfClass:[KSLiveChatroomWelcome class]] || [messageContent isMemberOfClass:[KSLiveChatroomLike class]] || [messageContent isMemberOfClass:[KSLiveChatroomSeatApply class]] || [messageContent isMemberOfClass:[KSLiveChatroomSeatResponse class]] || [messageContent isMemberOfClass:[KSDownSeatAllMessage class]] || [messageContent isMemberOfClass:[KSRejectAllSeatMessage class]] || [messageContent isMemberOfClass:[RCChatroomSeatsControl class]]){
  1476. [cell setDataModel:model createrId:self.createrId];
  1477. }
  1478. return cell;
  1479. }
  1480. - (void)sendSeatMessageApply:(BOOL)isApply {
  1481. if (self.micStatus == MICSTATUS_CONNECTING) {
  1482. [self MBPShow:@"您已上麦"];
  1483. return;
  1484. }
  1485. SEATHANDLE type = isApply ? SEATHANDLE_APPLY : SEATHANDLE_CANCELAPPLY;
  1486. KSLiveChatroomSeatApply *applyMessage = [[KSLiveChatroomSeatApply alloc] init];
  1487. applyMessage.type = type;
  1488. applyMessage.audienceId = UserDefault(UIDKey);
  1489. applyMessage.audienceName = UserDefault(NicknameKey);
  1490. applyMessage.audienceAvatar = UserDefault(AvatarUrlKey);
  1491. applyMessage.teacherId = self.createrId;
  1492. applyMessage.teacherName = self.createrName;
  1493. MJWeakSelf;
  1494. [self sendMessage:applyMessage displayMessage:YES callback:^(BOOL success) {
  1495. if (success) {
  1496. weakSelf.micStatus = isApply ? MICSTATUS_WAITING : MICSTATUS_NOMAL;
  1497. }
  1498. }];
  1499. }
  1500. /**
  1501. 点赞
  1502. */
  1503. - (void)praiseBtnPressed {
  1504. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  1505. __weak __typeof(&*self)weakSelf = self;
  1506. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.21 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1507. if ([[NSDate date] timeIntervalSince1970] - self.lastClickPraiseTime >= 0.2) {
  1508. KSLiveChatroomLike *praiseSendMessage = [[KSLiveChatroomLike alloc] init];
  1509. praiseSendMessage.counts = clickPraiseBtnTimes;
  1510. [weakSelf sendMessage:praiseSendMessage displayMessage:NO callback:^(BOOL success) {
  1511. }];
  1512. clickPraiseBtnTimes = 0;
  1513. self.likeCount += praiseSendMessage.counts;
  1514. [self countLikeMessageCount];
  1515. }
  1516. });
  1517. KSLiveChatroomLike *praiseMessage = [[KSLiveChatroomLike alloc] init];
  1518. clickPraiseBtnTimes++;
  1519. self.lastClickPraiseTime = currentTime;
  1520. [self presentLikeMessageAnimation:praiseMessage];
  1521. }
  1522. /**
  1523. 赞动画
  1524. @param likeMessage 赞消息
  1525. */
  1526. - (void)presentLikeMessageAnimation:(KSLiveChatroomLike *)likeMessage {
  1527. LiveRoomLikeLayer *layer = [[LiveRoomLikeLayer alloc] initWithName:@"Like"];
  1528. [self.view.layer addSublayer:layer];
  1529. CGRect tempFrame = [self.view convertRect:self.bottomView.likeButton.frame fromView:self.bottomView];
  1530. CGFloat width = tempFrame.size.width;
  1531. CGFloat height = tempFrame.size.height;
  1532. CGFloat dx = CGRectGetMidX(tempFrame) - width *0.5;
  1533. CGFloat dy = CGRectGetMidY(tempFrame) - 8 - height;
  1534. layer.frame = CGRectMake(dx, dy, width, height);
  1535. [layer startAnimation];
  1536. }
  1537. #pragma mark - setter & getter
  1538. - (void)setMicStatus:(MICSTATUS)micStatus {
  1539. _micStatus = micStatus;
  1540. if (self.bottomView) {
  1541. switch (micStatus) {
  1542. case MICSTATUS_NOMAL:
  1543. {
  1544. [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_nomal"] forState:UIControlStateNormal];
  1545. }
  1546. break;
  1547. case MICSTATUS_WAITING:
  1548. {
  1549. [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seating_image"] forState:UIControlStateNormal];
  1550. }
  1551. break;
  1552. case MICSTATUS_CONNECTING:
  1553. {
  1554. [self.bottomView.seatButton setImage:[UIImage imageNamed:@"seat_image"] forState:UIControlStateNormal];
  1555. }
  1556. break;
  1557. default:
  1558. break;
  1559. }
  1560. }
  1561. }
  1562. #pragma mark ----- RCRTCEngineEventDelegate
  1563. - (void)didRTCConnectionStateChanged:(RCRTCConnectionState)state {
  1564. if (state == RCRTCConnectionStateConnecting) {
  1565. NSLog(@"--------RCRTCConnectionStateConnecting");
  1566. }
  1567. else if (state == RCRTCConnectionStateConnected) {
  1568. NSLog(@"--------RCRTCConnectionStateConnected");
  1569. }
  1570. }
  1571. #pragma mark ----- RCRTCStatusReportDelegate
  1572. - (void)didReportStatusForm:(RCRTCStatusForm *)form {
  1573. // 获取丢包率
  1574. for (RCRTCStreamStat *stat in form.recvStats) {
  1575. if ([stat.mediaType isEqualToString:@"video"]) { // 接收视频会出现视频黑的情况 bitRate = 0
  1576. if (stat.packetLoss >= PACKAGE_LOST) { // 丢包
  1577. if (self.lostStartTime == 0) { // 如果之前没有丢包
  1578. self.lostStartTime = [[NSDate date] timeIntervalSince1970];
  1579. }
  1580. else {
  1581. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  1582. if (currentTime - self.lostStartTime >= 8) {
  1583. self.isLostPackage = YES;
  1584. [self showBadNetTips];
  1585. }
  1586. }
  1587. }
  1588. else {
  1589. self.lostStartTime = 0;
  1590. self.isLostPackage = NO;
  1591. [self hideTipsView];
  1592. }
  1593. if (stat.bitRate == 0) {
  1594. if (self.bitErrorTime == 0) {
  1595. self.bitErrorTime = [[NSDate date] timeIntervalSince1970];
  1596. }
  1597. else {
  1598. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  1599. if (currentTime - self.bitErrorTime >= 5) {
  1600. self.isBitError = YES;
  1601. [self showBadNetTips];
  1602. }
  1603. }
  1604. }
  1605. else {
  1606. self.isBitError = NO;
  1607. self.bitErrorTime = 0;
  1608. [self hideTipsView];
  1609. }
  1610. }
  1611. }
  1612. // NSLog(@"%@",form.description);
  1613. }
  1614. - (void)showBadNetTips {
  1615. dispatch_main_async_safe(^{
  1616. if (self.isCloseRoom == NO) {
  1617. if (self.netBadView.hidden == YES) {
  1618. self.netBadView.hidden = NO;
  1619. self.videoView.hidden = YES;
  1620. }
  1621. }
  1622. });
  1623. }
  1624. - (void)hideTipsView {
  1625. dispatch_main_async_safe(^{
  1626. if (self.netBadView.hidden == NO) {
  1627. if (self.isBitError == NO && self.isLostPackage == NO) {
  1628. self.netBadView.hidden = YES;
  1629. self.videoView.hidden = NO;
  1630. }
  1631. }
  1632. })
  1633. }
  1634. #pragma mark --- lazying
  1635. - (KSChatVideoView *)videoView {
  1636. if (!_videoView) {
  1637. _videoView = [[KSChatVideoView alloc] initWithFrame:self.view.bounds];
  1638. _videoView.backgroundColor = [UIColor clearColor];
  1639. }
  1640. return _videoView;
  1641. }
  1642. - (UIView *)videoContainerView {
  1643. if (!_videoContainerView) {
  1644. _videoContainerView = [[UIView alloc] initWithFrame:CGRectZero];
  1645. _videoContainerView.backgroundColor = [UIColor clearColor];
  1646. }
  1647. return _videoContainerView;
  1648. }
  1649. - (LiveRoomHeadView *)headView {
  1650. if (!_headView) {
  1651. _headView = [LiveRoomHeadView shareInstance];
  1652. MJWeakSelf;
  1653. [_headView quitAction:^{
  1654. [weakSelf showQuitAlert];
  1655. }];
  1656. }
  1657. return _headView;
  1658. }
  1659. - (void)showQuitAlert {
  1660. if (self.isCloseRoom) { // 如果直播结束 直接点击退出房间
  1661. [self quitRoom];
  1662. }
  1663. else if (self.micStatus == MICSTATUS_CONNECTING) {
  1664. [self quitAction];
  1665. }
  1666. else {
  1667. MJWeakSelf;
  1668. self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"是否退出直播间" leftButtonTitle:@"取消" rightTitle:@"退出" inView:self.view cancel:^{
  1669. } confirm:^{
  1670. [weakSelf quitAction];
  1671. }];
  1672. }
  1673. }
  1674. - (LiveRoomBottomView *)bottomView {
  1675. if (!_bottomView) {
  1676. _bottomView = [LiveRoomBottomView shareInstance];
  1677. MJWeakSelf;
  1678. [_bottomView bottomClickAction:^(LIVEROOMACTION action) {
  1679. [weakSelf bottomViewAction:action];
  1680. }];
  1681. }
  1682. return _bottomView;
  1683. }
  1684. - (void)bottomViewAction:(LIVEROOMACTION)action {
  1685. if (self.isCloseRoom) {
  1686. [self MBPShow:@"直播已结束"];
  1687. return;
  1688. }
  1689. switch (action) {
  1690. case LIVEROOMACTION_CHAT: // 聊天
  1691. {
  1692. if (self.blacklistFlag == YES) {
  1693. [self MBPShow:@"您已被管理员禁言"];
  1694. return;
  1695. }
  1696. // if (self.enableChat) { // 判断是否全员禁言
  1697. [_inputBar setHidden:NO];
  1698. [_inputBar setInputBarStatus:KSBottomBarStatusKeyboard];
  1699. // }
  1700. // else {
  1701. // [self MBPShow:@"管理员关闭聊天"];
  1702. // }
  1703. }
  1704. break;
  1705. case LIVEROOMACTION_SEAT: // // 连麦按钮
  1706. { // 连麦按钮
  1707. // 判断是否是连麦状态
  1708. if (self.micStatus == MICSTATUS_CONNECTING) { // 连麦中
  1709. // 是否取消连麦
  1710. MJWeakSelf;
  1711. self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"连麦中,确认取消连麦吗?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
  1712. } confirm:^{
  1713. [weakSelf connectHostWithStatus:NO];
  1714. }];
  1715. }
  1716. else if (self.micStatus == MICSTATUS_WAITING) { // 连麦申请中
  1717. // 弹窗取消申请
  1718. [self displayApplyingView];
  1719. }
  1720. else {
  1721. if (self.blacklistFlag == YES) {
  1722. [self MBPShow:@"您已被管理员禁言"];
  1723. return;
  1724. }
  1725. if (self.isCreaterInRoom == NO) {
  1726. [self MBPShow:@"主讲人不在直播间"];
  1727. return;
  1728. }
  1729. if (self.enableSeat) {
  1730. // 显示弹窗
  1731. [self displaySeatApplyView];
  1732. }
  1733. else {
  1734. [self MBPShow:@"管理员关闭连麦申请"];
  1735. }
  1736. }
  1737. }
  1738. break;
  1739. case LIVEROOMACTION_SHOP:
  1740. {
  1741. [self showCartAlert];
  1742. }
  1743. break;
  1744. case LIVEROOMACTION_LIKE:
  1745. {
  1746. if (self.isCreaterInRoom) {
  1747. [self praiseBtnPressed];
  1748. }
  1749. else {
  1750. [self MBPShow:@"主讲人不在直播间"];
  1751. }
  1752. }
  1753. break;
  1754. default:
  1755. break;
  1756. }
  1757. }
  1758. - (void)displaySeatApplyView {
  1759. [self.applyView showInView:self.view];
  1760. }
  1761. - (void)displayApplyingView {
  1762. [self.applyingView showInView:self.view];
  1763. }
  1764. - (void)showCartAlert {
  1765. [self.cardView showViewInView:self.view];
  1766. }
  1767. - (void)quitAction {
  1768. if (self.micStatus == MICSTATUS_CONNECTING) {
  1769. MJWeakSelf;
  1770. self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"连麦中,是否退出房间?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
  1771. } confirm:^{
  1772. [weakSelf quitRoom];
  1773. }];
  1774. }
  1775. else {
  1776. [self quitRoom];
  1777. }
  1778. }
  1779. - (void)quitRoom {
  1780. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  1781. if (manager.hasShowWindow) {
  1782. [manager resignDragWindow];
  1783. }
  1784. // 清理视图
  1785. [self clearRemoteContainer];
  1786. // 退出房间
  1787. [self exitRoom];
  1788. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  1789. }
  1790. - (RCRTCEngine *)engine {
  1791. if (!_engine) {
  1792. _engine = [RCRTCEngine sharedInstance];
  1793. [_engine setStatusReportDelegate:self];
  1794. [_engine setDelegate:self];
  1795. }
  1796. return _engine;
  1797. }
  1798. - (NSMutableArray<KSLiveStreamVideo *> *)streamVideos {
  1799. if (!_streamVideos) {
  1800. _streamVideos = [NSMutableArray array];
  1801. }
  1802. return _streamVideos;
  1803. }
  1804. - (KSLiveStreamVideo *)localVideo {
  1805. if (!_localVideo) {
  1806. _localVideo = [KSLiveStreamVideo LocalStreamVideo];
  1807. }
  1808. return _localVideo;
  1809. }
  1810. - (UIView *)messageContentView {
  1811. if (!_messageContentView) {
  1812. _messageContentView = [[UIView alloc] init];
  1813. [_messageContentView setBackgroundColor: [UIColor clearColor]];
  1814. }
  1815. return _messageContentView;
  1816. }
  1817. - (NSMutableArray<KSRCMessageModel *> *)conversationDataRepository {
  1818. if (!_conversationDataRepository) {
  1819. _conversationDataRepository = [NSMutableArray array];
  1820. }
  1821. return _conversationDataRepository;
  1822. }
  1823. - (KSChatInputBarControl *)inputBar {
  1824. if (!_inputBar) {
  1825. _inputBar = [[KSChatInputBarControl alloc] initWithStatus:KSBottomBarStatusDefault];
  1826. [_inputBar setDelegate:self];
  1827. }
  1828. return _inputBar;
  1829. }
  1830. - (UITableView *)conversationMessageTableView {
  1831. if (!_conversationMessageTableView) {
  1832. _conversationMessageTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
  1833. _conversationMessageTableView.backgroundColor = [UIColor clearColor];
  1834. _conversationMessageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  1835. _conversationMessageTableView.dataSource = self;
  1836. _conversationMessageTableView.delegate = self;
  1837. _conversationMessageTableView.rowHeight = UITableViewAutomaticDimension;
  1838. _conversationMessageTableView.estimatedRowHeight = 40.0f;
  1839. _conversationMessageTableView.showsVerticalScrollIndicator = NO;
  1840. [_conversationMessageTableView registerClass:[KSChatroomTextCell class] forCellReuseIdentifier:@"KSChatroomTextCell"];
  1841. }
  1842. return _conversationMessageTableView;
  1843. }
  1844. - (SeatContentView *)seatContainer {
  1845. if (!_seatContainer) {
  1846. _seatContainer = [[SeatContentView alloc] init];
  1847. }
  1848. return _seatContainer;
  1849. }
  1850. - (KSLiveEmptyView *)emptyView {
  1851. if (!_emptyView) {
  1852. _emptyView = [[KSLiveEmptyView alloc] init];
  1853. _emptyView.backgroundColor = [UIColor clearColor];
  1854. BOOL isPhoneLive = YES;
  1855. [_emptyView dispPlayViewIsPhoneLive:isPhoneLive];
  1856. }
  1857. return _emptyView;
  1858. }
  1859. - (KSLiveEndView *)endView {
  1860. if (!_endView) {
  1861. _endView = [[KSLiveEndView alloc] init];
  1862. _endView.backgroundColor = HexRGB(0x25292e);
  1863. BOOL isPhoneLive = YES;
  1864. [_endView dispPlayViewIsPhoneLive:isPhoneLive];
  1865. }
  1866. return _endView;
  1867. }
  1868. - (KSLiveBadNetView *)netBadView {
  1869. if (!_netBadView) {
  1870. _netBadView = [[KSLiveBadNetView alloc] init];
  1871. BOOL isPhoneLive = YES;
  1872. [_netBadView dispPlayViewIsPhoneLive:isPhoneLive];
  1873. MJWeakSelf;
  1874. [_netBadView configViewWithImageName:@"liveVideo_close" desc:@"当前网络状态不佳" callback:^{
  1875. [weakSelf resetAllConnection];
  1876. }];
  1877. }
  1878. return _netBadView;
  1879. }
  1880. - (LOTAnimationView *)animationView {
  1881. if (!_animationView) {
  1882. _animationView = [LOTAnimationView animationWithFilePath:[[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"LiveCard" ofType:@"bundle"]] pathForResource:@"cardAnimation" ofType:@"json"]];
  1883. _animationView.loopAnimation = YES;
  1884. }
  1885. return _animationView;
  1886. }
  1887. - (void)resetNetTips {
  1888. self.lostStartTime = 0;
  1889. self.isBitError = NO;
  1890. self.bitErrorTime = 0;
  1891. self.isLostPackage = NO;
  1892. [self hideTipsView];
  1893. }
  1894. // 黑名单
  1895. - (void)setBlacklistFlag:(BOOL)blacklistFlag {
  1896. _blacklistFlag = blacklistFlag;
  1897. [self refreshBottomChatStatus];
  1898. }
  1899. - (void)refreshBottomChatStatus {
  1900. if (self.bottomView) {
  1901. NSString *tipsTitle = self.blacklistFlag ? @"您已被管理员禁言" : @"快来互动吧!";
  1902. self.bottomView.tipsLabel.text = tipsTitle;
  1903. }
  1904. }
  1905. - (void)resetAllConnection {
  1906. [self resetNetTips];
  1907. // 清理视图
  1908. [self.streamVideos removeAllObjects];
  1909. [self clearVideoViewSource];
  1910. [self removeSeatContainer];
  1911. // 立刻房间后重新加入房间
  1912. // 退出房间
  1913. [self.engine.defaultAudioStream setMicrophoneDisable:YES];
  1914. __weak typeof(self) weakSelf = self;
  1915. [self.engine leaveRoom:^(BOOL isSuccess, RCRTCCode code) {
  1916. __strong typeof(weakSelf) strongSelf = weakSelf;
  1917. if (code != RCRTCCodeSuccess) {
  1918. // 退出失败
  1919. }
  1920. // 3.加入RTC房间
  1921. [strongSelf joinLiveRoom];
  1922. }];
  1923. }
  1924. - (void)sendDownSeatMessage {
  1925. KSLiveChatroomDownSeat *downSeatMessage = [[KSLiveChatroomDownSeat alloc] init];
  1926. downSeatMessage.audienceId = UserDefault(UIDKey);
  1927. downSeatMessage.audienceName = UserDefault(NicknameKey);
  1928. MJWeakSelf;
  1929. [self sendMessage:downSeatMessage displayMessage:NO callback:^(BOOL success) {
  1930. weakSelf.micStatus = MICSTATUS_NOMAL;
  1931. }];
  1932. }
  1933. - (LiveroomTimeManager *)timeManager {
  1934. if (!_timeManager) {
  1935. _timeManager = [[LiveroomTimeManager alloc] initWithDelegate:self];
  1936. }
  1937. return _timeManager;
  1938. }
  1939. - (NSInteger)getCloseTime {
  1940. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1941. [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1942. formatter.timeZone = [NSTimeZone systemTimeZone];
  1943. NSDate *currentDate = [NSDate date];
  1944. NSDate *expireDate = [formatter dateFromString:self.liveEndTime];
  1945. NSTimeInterval timeInterval = [expireDate timeIntervalSinceDate:currentDate];
  1946. return self.expiredMinute * 60 + timeInterval;
  1947. }
  1948. - (KSShopCardView *)cardView {
  1949. if (!_cardView) {
  1950. _cardView = [KSShopCardView shareInstance];
  1951. MJWeakSelf;
  1952. [_cardView clickAction:^(CART_TYPE type) {
  1953. [weakSelf displayTeacherInfo:type];
  1954. }];
  1955. }
  1956. return _cardView;
  1957. }
  1958. // tabs= practice | 陪练课 live | 直播课 video | 视频课 music | 乐谱 跳转到对应tab页
  1959. - (void)displayTeacherInfo:(CART_TYPE)type {
  1960. [self sendRushMessage];
  1961. RCRTCVideoView *videoView = nil;
  1962. for (UIView *view in self.videoView.subviews) {
  1963. if ([view isKindOfClass:[RCRTCVideoView class]]) {
  1964. videoView = (RCRTCVideoView *)view;
  1965. }
  1966. }
  1967. if (videoView) {
  1968. _hasShowSuspendView = YES;
  1969. KSDragWindowManager *manager = [KSDragWindowManager sharedManager];
  1970. [manager initDragWindow];
  1971. manager.rootVC = (CustomNavViewController *)self.navigationController;
  1972. [videoView removeFromSuperview];
  1973. [manager.dragWindow.containerView addSubview:videoView];
  1974. [videoView mas_updateConstraints:^(MASConstraintMaker *make) {
  1975. make.left.right.top.bottom.mas_equalTo(manager.dragWindow.containerView);
  1976. }];
  1977. [manager.dragWindow bringSubviewToFront:manager.dragWindow.cancelButton];
  1978. }
  1979. NSString *tabs = @"";
  1980. switch (type) {
  1981. case CART_TYPE_ACCOMPANY:
  1982. {
  1983. tabs = @"practice";
  1984. }
  1985. break;
  1986. case CART_TYPE_LIVE:
  1987. {
  1988. tabs = @"live";
  1989. }
  1990. break;
  1991. case CART_TYPE_VIDEO:
  1992. {
  1993. tabs = @"video";
  1994. }
  1995. break;
  1996. case CART_TYPE_MUSIC:
  1997. {
  1998. tabs = @"music";
  1999. }
  2000. break;
  2001. default:
  2002. break;
  2003. }
  2004. NSString *url = [NSString stringWithFormat:@"%@%@%@&tabs=%@", WEBHOST,@"/#/teacherHome?teacherId=",self.createrId,tabs];
  2005. KSLiveWebViewController *ctrl = [[KSLiveWebViewController alloc] init];
  2006. ctrl.url = url;
  2007. [self.navigationController pushViewController:ctrl animated:YES];
  2008. }
  2009. - (void)sendRushMessage {
  2010. // KSRCShopRushMessage *rushMessage = [[KSRCShopRushMessage alloc] init];
  2011. // rushMessage.userId = UserDefault(UIDKey);
  2012. // rushMessage.userName = UserDefault(NicknameKey);
  2013. // [self sendMessage:rushMessage displayMessage:NO callback:^(BOOL success) {
  2014. //
  2015. // }];
  2016. }
  2017. - (void)showAnimationView:(BOOL)isJoinRoom showMessag:(NSString *)message {
  2018. if (self.enterAnimationView && self.enterAnimationView.isShow) {
  2019. return;
  2020. }
  2021. else {
  2022. ANIMATIONTYPE type = isJoinRoom ? ANIMATIONTYPE_JOIN : ANIMATIONTYPE_RUSH;
  2023. self.enterAnimationView = [[LiveAnimationView alloc] initWithTitle:message animationType:type];
  2024. [self.view addSubview:self.enterAnimationView];
  2025. [self.enterAnimationView mas_makeConstraints:^(MASConstraintMaker *make) {
  2026. make.left.right.mas_equalTo(self.view);
  2027. make.width.mas_equalTo(KPortraitWidth);
  2028. make.height.mas_equalTo(24.0f);
  2029. make.bottom.mas_equalTo(self.messageContentView.mas_top).offset(-6);
  2030. }];
  2031. [self.view bringSubviewToFront:self.enterAnimationView];
  2032. MJWeakSelf;
  2033. [self.enterAnimationView startAnimationEndCallback:^{
  2034. weakSelf.enterAnimationView.isShow = NO;
  2035. weakSelf.enterAnimationView = nil;
  2036. }];
  2037. }
  2038. }
  2039. - (void)dealloc {
  2040. [[NSNotificationCenter defaultCenter] removeObserver:self];
  2041. }
  2042. - (LiveApplyView *)applyView {
  2043. if (!_applyView) {
  2044. _applyView = [LiveApplyView shareInstance];
  2045. MJWeakSelf;
  2046. [_applyView applySeatCallback:^{
  2047. [weakSelf applySeatAction];
  2048. }];
  2049. }
  2050. return _applyView;
  2051. }
  2052. - (void)applySeatAction {
  2053. [self MBPShow:@"已发起连麦申请"];
  2054. [self sendSeatMessageApply:YES];
  2055. }
  2056. - (LiveApplyingView *)applyingView {
  2057. if (!_applyingView) {
  2058. _applyingView = [LiveApplyingView shareInstance];
  2059. NSString *avatar = UserDefaultObjectForKey(AvatarUrlKey);
  2060. [_applyingView.myAvatal sd_setImageWithURL:[NSURL URLWithString:[avatar getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:USERDEFAULT_LOGO]];
  2061. [_applyingView.teacherAvatal sd_setImageWithURL:[NSURL URLWithString:[self.createrAvatal getUrlEndcodeString]] placeholderImage:[UIImage imageNamed:USERDEFAULT_LOGO]];
  2062. MJWeakSelf;
  2063. [_applyingView cancleApplyCallback:^{
  2064. [weakSelf cancleApplyAction];
  2065. }];
  2066. }
  2067. return _applyingView;
  2068. }
  2069. - (void)cancleApplyAction {
  2070. MJWeakSelf;
  2071. self.alertView = [LiveRoomAlertView liveroomAlertWithTitle:@"连麦申请中,确认取消连麦申请吗?" leftButtonTitle:@"取消" rightTitle:@"确定" inView:self.view cancel:^{
  2072. } confirm:^{
  2073. [weakSelf.applyingView hideView];
  2074. [weakSelf sendSeatMessageApply:NO];
  2075. }];
  2076. }
  2077. @end