AppDelegate.m 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. //
  2. // AppDelegate.m
  3. // aiim
  4. //
  5. // Created by gan on 2025/2/27.
  6. //
  7. #import "AppDelegate.h"
  8. #import "UDManager.h"
  9. #import <UserNotifications/UserNotifications.h>
  10. #import <PushKit/PushKit.h>
  11. #import "CallKit/CallKit.h"
  12. #import "UserNetApi.h"
  13. #import "CryptoAES.h"
  14. #import "GWebSocket.h"
  15. #import "GDBManager.h"
  16. #import "APPLocker.h"
  17. #import "JSGController.h"
  18. #import "LoginStateManager.h"
  19. #import "FloatingWindow.h"
  20. #import "ChatIndexController.h"
  21. #import "ChatController.h"
  22. #import "ChatListStore.h"
  23. #import "ChatsStore.h"
  24. #import "OSSManager.h"
  25. #import <Bugly/Bugly.h>
  26. #ifdef DEBUG
  27. #import <DoraemonKit/DoraemonManager.h>
  28. #endif
  29. @import JitsiMeetSDK;
  30. @interface AppDelegate ()<UNUserNotificationCenterDelegate,PKPushRegistryDelegate,CXProviderDelegate>
  31. @property (nonatomic, strong) CXProvider *callProvider;
  32. @property (nonatomic) NSUUID *uuid;
  33. @property (nonatomic) NSDictionary *msg;
  34. @property (strong, nonatomic) NSString *bgMark;
  35. @property (strong, nonatomic) FloatingWindow *floatWindow;
  36. @property (nonatomic, strong) JSGController * _Nullable jsyuyinctr;
  37. @property (nonatomic) BOOL isNotification;
  38. @property (nonatomic, assign) NSInteger badgeCount;
  39. @property (nonatomic, assign) NSInteger addFriendBadgeCount;
  40. @end
  41. @implementation AppDelegate
  42. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  43. // Override point for customization after application launch.
  44. app = self;
  45. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  46. self.window.backgroundColor = UIColor.blackColor;
  47. BOOL isLoggedIn = [LoginStateManager sharedManager].isLoggedIn;
  48. if (isLoggedIn) {
  49. [self initDataAfterLogin:YES];
  50. } else {
  51. [self openLoginController];
  52. }
  53. [self.window makeKeyAndVisible];
  54. BuglyConfig *config = [[BuglyConfig alloc] init];
  55. config.reportLogLevel = BuglyLogLevelVerbose;
  56. [Bugly startWithAppId:@"1d9e6b546a" config:config];
  57. self.isJitsiMeet=false;
  58. _isNotification=false;
  59. self.shouldShowLock = YES;
  60. self.bgMark=@"";
  61. [self initJSMSDK];
  62. [self setupListener];
  63. [self registerPushright];
  64. [self setupCallProvider];
  65. _floatWindow = [[FloatingWindow alloc] initWithFrame:self.window.bounds];
  66. [_floatWindow hide];
  67. self.bgMark = @"";
  68. NSLog(@"didFinishLaunchingWithOptions------");
  69. AVAudioSession *session = [AVAudioSession sharedInstance];
  70. [session setCategory:AVAudioSessionCategoryPlayAndRecord mode:AVAudioSessionModeVoiceChat options:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP | AVAudioSessionCategoryOptionAllowAirPlay error:nil];
  71. [session setActive:YES error:nil];
  72. #ifdef DEBUG
  73. //默认
  74. [[DoraemonManager shareInstance] install];
  75. // 或者使用传入位置,解决遮挡关键区域,减少频繁移动
  76. //[[DoraemonManager shareInstance] installWithStartingPosition:CGPointMake(66, 66)];
  77. #endif
  78. return YES;
  79. }
  80. -(void)applicationDidBecomeActive:(UIApplication *)application{
  81. NSLog(@"applicationDidBecomeActive");
  82. if(self.isLogin){
  83. if(self.isJitsiMeet){
  84. [_floatWindow viewInFload:0];
  85. }
  86. [self showLockScreen];
  87. if(!_isNotification){
  88. if ([[self.window jk_currentViewController] isKindOfClass:UITabBarController.class]){
  89. UITabBarController * tabbarVc= (UITabBarController *)[self.window jk_currentViewController];
  90. if (tabbarVc.selectedIndex==0) {
  91. ChatIndexController * chatListVc = tabbarVc.viewControllers[0];
  92. if (chatListVc) {
  93. [chatListVc reloadList];
  94. }
  95. }
  96. }
  97. else{
  98. [Bugly reportException:[NSException exceptionWithName:@"applicationDidBecomeActive1" reason:@"1" userInfo:nil]];
  99. if ([[self.window jk_currentViewController] isKindOfClass:ChatController.class]) {
  100. ChatController * currentChatVc = (ChatController *)[self.window jk_currentViewController];
  101. [currentChatVc reloadAllData];
  102. [Bugly reportException:[NSException exceptionWithName:@"applicationDidBecomeActive2" reason:@"2" userInfo:nil]];
  103. }
  104. }
  105. }
  106. }
  107. }
  108. -(void)applicationDidEnterBackground:(UIApplication *)application{
  109. NSLog(@"applicationDidEnterBackground");
  110. _isNotification=false;
  111. // [self endWebsocket];
  112. __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  113. [application endBackgroundTask:bgTask];
  114. bgTask = UIBackgroundTaskInvalid;
  115. }];
  116. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  117. // 在这里保持任务运行或等待事件,例如等待来电等。
  118. [application endBackgroundTask:bgTask];
  119. bgTask = UIBackgroundTaskInvalid;
  120. });
  121. // 应用进入后台时标记需要显示锁屏
  122. if(self.isJitsiMeet == YES){
  123. [self.window endEditing:YES];
  124. }
  125. else{
  126. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  127. self.shouldShowLock = YES;
  128. }
  129. }
  130. }
  131. + (instancetype)sharedInstance {
  132. return app;
  133. }
  134. -(void)initJSMSDK{
  135. JitsiMeetConferenceOptions *defaultOptions
  136. = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder *builder) {
  137. builder.serverURL = [NSURL URLWithString:JitsiMeetSV];
  138. [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
  139. [builder setFeatureFlag:@"prejoinPage.enabled" withBoolean:NO];
  140. //媒体流优化
  141. builder.audioMuted = NO; // 提前初始化音频模块
  142. builder.videoMuted = NO; // 提前初始化视频模块
  143. //禁用非必要功能(减少初始化负载)
  144. [builder setFeatureFlag:@"add-people.enabled" withBoolean:NO];
  145. [builder setFeatureFlag:@"invite.enabled" withBoolean:NO];
  146. [builder setFeatureFlag:@"live-streaming.enabled" withBoolean:NO];
  147. [builder setFeatureFlag:@"video-share.enabled" withBoolean:NO];
  148. [builder setFeatureFlag:@"call-integration.enabled" withBoolean:NO];
  149. [builder setFeatureFlag:@"startWithAudioMuted" withBoolean:NO];
  150. [builder setFeatureFlag:@"recording.enabled" withBoolean:NO];
  151. [builder setFeatureFlag:@"kick-out.enabled" withBoolean:NO];
  152. [builder setFeatureFlag:@"security-options.enabled" withBoolean:NO];
  153. //
  154. // //网络传输层加速
  155. // [builder setConfigOverride:@"disableSimulcast" withBoolean:YES];
  156. // [builder setFeatureFlag:@"reconnect.enabled" withBoolean:YES];
  157. // [builder setFeatureFlag:@"websocket-keep-alive.enabled" withBoolean:YES];
  158. // [builder setFeatureFlag:@"network-monitor.enabled" withBoolean:YES];
  159. // [builder setConfigOverride:@"iceTransportPolicy" withValue:@"relay"];
  160. // // 界面渲染加速
  161. // [builder setFeatureFlag:@"filmstrip.enabled" withBoolean:NO];
  162. // [builder setFeatureFlag:@"tile-view.enabled" withBoolean:NO];
  163. //
  164. // [builder setFeatureFlag:@"pip.enabled" withBoolean:NO];
  165. // [builder setFeatureFlag:@"chat.enabled" withBoolean:NO];
  166. [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
  167. }];
  168. [JitsiMeet sharedInstance].defaultConferenceOptions = defaultOptions;
  169. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  170. _jsyuyinctr = [board instantiateViewControllerWithIdentifier:@"JSGController"];
  171. _jsyuyinctr.modalPresentationStyle = UIModalPresentationFullScreen;
  172. }
  173. -(void)setupListener{
  174. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLoginSucc) name:nkonLoginSucc object:nil];
  175. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogout) name:nkonLogoutSucc object:nil];
  176. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addFriend) name:nkonAddFriendNote object:nil];;
  177. }
  178. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  179. NSLog(@"Failed to get token, error: %@", error);
  180. }
  181. #pragma mark push token voip token
  182. -(void)registerPushright{
  183. // 请求推送权限
  184. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  185. center.delegate = self; // 设置代理以处理通知相关事件
  186. [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionProvidesAppNotificationSettings) completionHandler:^(BOOL granted, NSError * _Nullable error) {
  187. if (granted) {
  188. // 用户授权成功
  189. dispatch_async(dispatch_get_main_queue(), ^{
  190. [[UIApplication sharedApplication] registerForRemoteNotifications];
  191. });
  192. } else {
  193. // 用户授权失败
  194. }
  195. }];
  196. PKPushRegistry *registry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
  197. registry.delegate = self;
  198. registry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
  199. }
  200. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  201. // 将NSData转换为NSString以便于传输或存储
  202. NSRange range = NSMakeRange(0, 16); // 例如,从索引0开始,获取前10个字节
  203. NSData *subData1 = [deviceToken subdataWithRange:range];
  204. range = NSMakeRange(16, 16);
  205. NSData *subData2 = [deviceToken subdataWithRange:range];
  206. range = NSMakeRange(24, 32);
  207. NSString *token1=[[subData1 description] substringWithRange:range];
  208. NSString *token2=[[subData2 description] substringWithRange:range];
  209. NSString *token = [NSString stringWithFormat:@"%@%@",token1,token2];
  210. NSLog(@"%@",token);
  211. // 将token发送到你的服务器或其他需要的地方
  212. [UDManager.shareInstance setSDManager:token key:dkpushtoken];
  213. NSString *bgMark = [NSString stringWithFormat:@"推送token:%ld",token.length];
  214. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  215. if(self.isLogin){
  216. [self updivicetoken];
  217. }
  218. }
  219. -(void)updivicetoken{
  220. NSString *token =[UDManager.shareInstance getSDManager:dkpushtoken];
  221. NSDictionary *usinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  222. NSLog(@"dkpushtoken:%@",token);
  223. NSDictionary *ud=@{
  224. @"registrationId": token?:@"",
  225. @"userId":usinfo[@"id"]?:@"",
  226. @"platformType":@"i"
  227. };
  228. NSString *bgMark = [NSString stringWithFormat:@"上传推送token:%ld",token.length];
  229. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  230. [UserNetApi setUserinfo:ud succ:^(int code, NSDictionary * res) {
  231. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:res options:0 error:nil];
  232. if (!jsonData) {
  233. NSLog(@"Got an error:");
  234. } else {
  235. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  236. NSLog(@"%@", jsonString); // 输出:{"name":"John","age":25}
  237. }
  238. } fail:^(NSError * _Nonnull error) {
  239. NSLog(@"--%@",error);
  240. }];
  241. }
  242. -(void)updiviceVoIPtoken{
  243. NSString *token =[UDManager.shareInstance getSDManager:dkvoiptoken];
  244. NSDictionary *usinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  245. NSLog(@"dkvoiptoken:%@",token);
  246. NSString *bgMark = [NSString stringWithFormat:@"上传 voip 推送token:%ld",token.length];
  247. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  248. if([token isKindOfClass:[NSNull class]]){
  249. return;
  250. }
  251. NSDictionary *ud=@{
  252. @"voipTk": token?:@"",
  253. @"userId":usinfo[@"id"]?:@"",
  254. @"platformType":@"i"
  255. };
  256. [UserNetApi setUserinfo:ud succ:^(int code, NSDictionary * res) {
  257. NSLog(@"updiviceVoIPtoken:%@",[res description]);
  258. } fail:^(NSError * _Nonnull error) {
  259. NSLog(@"--%@",error);
  260. }];
  261. }
  262. - (void)addFriend{
  263. self.addFriendBadgeCount++;
  264. NSLog(@"addFriend------------:%ld", self.addFriendBadgeCount);
  265. [self updateTabBarBadgeValueAtIndex:1 badgeCount:self.addFriendBadgeCount];
  266. [self sendAddFreindNotice];
  267. [self updateApplicationIconBadgeNumber];
  268. }
  269. - (void)sendAddFreindNotice {
  270. // 发送本地通知
  271. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  272. content.title = @"好友申请";
  273. content.body = @"您收到了新的好友申请";
  274. content.sound = [UNNotificationSound defaultSound];
  275. content.badge = @(self.addFriendBadgeCount);
  276. content.userInfo = @{
  277. @"addFriend":@(1)
  278. };
  279. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  280. NSString *identifier = [NSString stringWithFormat:@"FriendRequest_%@", [[NSUUID UUID] UUIDString]];
  281. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  282. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  283. if (error) {
  284. NSLog(@"发送本地通知失败: %@", error);
  285. } else {
  286. NSLog(@"发送本地通知成功");
  287. }
  288. }];
  289. }
  290. - (void)updateApplicationIconBadgeNumber {
  291. NSInteger total = self.badgeCount + self.addFriendBadgeCount;
  292. if (@available(iOS 16.0, *)) {
  293. [[UNUserNotificationCenter currentNotificationCenter] setBadgeCount:total withCompletionHandler:^(NSError * _Nullable error) {
  294. if (error) {
  295. NSLog(@"设置消息未读数 error: %@", error);
  296. }
  297. }];
  298. } else {
  299. // Fallback on earlier versions
  300. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:total];
  301. }
  302. }
  303. - (void)resetAddFriendBadgeCount {
  304. self.addFriendBadgeCount = 0;
  305. [self updateTabBarBadgeValueAtIndex:1 badgeCount:0];
  306. [self updateApplicationIconBadgeNumber];
  307. }
  308. - (void)resetBadgeCount {
  309. self.badgeCount = 0;
  310. [self updateApplicationIconBadgeNumber];
  311. }
  312. - (void)updateTabBarBadgeValueAtIndex:(NSInteger)index badgeCount:(NSInteger)badgeCount {
  313. UITabBarController * tabbarVc = (UITabBarController *)self.window.rootViewController;
  314. if (![tabbarVc isKindOfClass:[UITabBarController class]]) {
  315. return;
  316. }
  317. if(index < 0 || index >= tabbarVc.tabBar.items.count){
  318. return;
  319. }
  320. UITabBarItem *tabBarItem = tabbarVc.tabBar.items[index];
  321. NSString *badgeValue = badgeCount > 0 ? [NSString stringWithFormat:@"%ld", badgeCount] : nil;
  322. badgeValue = badgeValue.length > 2 ? @"99+" : badgeValue;
  323. tabBarItem.badgeValue = badgeValue;
  324. }
  325. - (void)updateBadgeCount:(NSInteger)badgeCount {
  326. self.badgeCount = badgeCount;
  327. [self updateApplicationIconBadgeNumber];
  328. }
  329. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  330. NSLog(@"Received notification: %@", userInfo);
  331. NSDictionary *temp =userInfo[@"imMsg"];
  332. if(temp){
  333. if ([temp jk_hasKey:@"addFriend"]) {
  334. [self addFriend];
  335. }
  336. NSDictionary *msg =temp[@"message"];
  337. NSString *msgtype=msg[@"msgtype"];
  338. if([msgtype isEqualToString:@"close"]){
  339. if(self.uuid!=nil){
  340. NSString *fromId = self.msg[@"fromId"];
  341. if ( [fromId isEqualToString:msg[@"fromId"]]) {
  342. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  343. self.uuid = nil;
  344. self.msg =nil;
  345. }
  346. }
  347. }
  348. }
  349. // 处理推送消息,例如更新UI或处理数据等
  350. completionHandler(UIBackgroundFetchResultNewData);
  351. }
  352. #pragma mark - PKPushRegistryDelegate
  353. - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type {
  354. // 处理推送凭证更新,例如保存 token 到服务器
  355. NSLog(@"Credentials updated: %@", credentials.token);
  356. NSData *deviceToken = (NSData *)credentials.token;
  357. NSRange range = NSMakeRange(0, 16); // 例如,从索引0开始,获取前10个字节
  358. NSData *subData1 = [deviceToken subdataWithRange:range];
  359. range = NSMakeRange(16, 16);
  360. NSData *subData2 = [deviceToken subdataWithRange:range];
  361. range = NSMakeRange(24, 32);
  362. //NSLog(@"subData1: %@",subData1);
  363. //NSLog(@"subData2: %@",subData2);
  364. NSString *token1=[[subData1 description] substringWithRange:range];
  365. NSString *token2=[[subData2 description] substringWithRange:range];
  366. NSString *token = [NSString stringWithFormat:@"%@%@",token1,token2];
  367. NSLog(@"%@",token);
  368. //将token发送到你的服务器或其他需要的地方
  369. NSString *bgMark = [NSString stringWithFormat:@"voip token:%ld",token.length];
  370. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  371. [UDManager.shareInstance setSDManager:token key:dkvoiptoken];
  372. if(self.isLogin){
  373. [self updiviceVoIPtoken];
  374. }
  375. }
  376. - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion{
  377. NSDictionary * temp =payload.dictionaryPayload;
  378. temp =temp[@"business"];
  379. temp=temp[@"incomingCallParams"];
  380. NSString *name =temp[@"localizedCallerName"];
  381. NSLog(@"name:%@",name);
  382. temp =payload.dictionaryPayload;
  383. temp =temp[@"imMsg"];
  384. if(self.uuid!=nil||self.isJitsiMeet){//通知对方正忙,功能需要补上
  385. [self isBUSYNow:temp[@"message"]];
  386. return;
  387. }
  388. self.msg = temp[@"message"];
  389. NSLog(@"self.msg-----:%@",self.msg);
  390. CXCallUpdate * callUpdate = [[CXCallUpdate alloc]init];
  391. callUpdate.supportsGrouping = YES;
  392. callUpdate.supportsDTMF = YES;
  393. callUpdate.hasVideo = YES;
  394. callUpdate.supportsHolding = YES;
  395. [callUpdate setLocalizedCallerName:name];
  396. CXHandle * handle = [[CXHandle alloc]initWithType:CXHandleTypePhoneNumber value:@""];
  397. callUpdate.remoteHandle = handle;
  398. self.uuid = [NSUUID UUID];
  399. [self.callProvider reportNewIncomingCallWithUUID:self.uuid update:callUpdate completion:^(NSError * _Nullable error) {
  400. NSLog(@"%@",error);
  401. }];
  402. completion();
  403. }
  404. -(void)isBUSYNow:(NSDictionary *)msg{
  405. NSDate *now = [NSDate date];
  406. NSTimeInterval trt = [now timeIntervalSince1970];
  407. NSInteger time = trt*1000;
  408. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  409. NSDictionary *callMsg = @{
  410. @"code":SendCode_WEBRTC_DFBUSY,
  411. @"message": @{
  412. @"chatId":msg[@"fromId"],
  413. @"fromId":msg[@"chatId"],
  414. @"type":@"0",
  415. @"messageType":MessageType_DFBUSY,
  416. @"timestamp":strtime,
  417. @"payload":@""
  418. }
  419. };
  420. NSError *error;
  421. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
  422. if (!jsonData) {
  423. NSLog(@"Got an error: %@", error);
  424. } else {
  425. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  426. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  427. [GWebSocket.shareInstance sendMsg:jsonString];
  428. }
  429. }
  430. #pragma mark - CXProviderDelegate Methods
  431. - (void)setupCallProvider {
  432. // 创建配置对象
  433. CXProviderConfiguration *config = [[CXProviderConfiguration alloc] init];
  434. config.supportsVideo = YES; // 是否支持视频通话
  435. config.maximumCallGroups = 1; // 最大通话组数
  436. config.maximumCallsPerCallGroup = 1; // 每个通话组的最大通话数
  437. config.supportedHandleTypes = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:CXHandleTypeGeneric],[NSNumber numberWithInt:CXHandleTypePhoneNumber], nil];//[NSSet setWithArray:@[CXHandleTypePhoneNumber]]; // 支持的号码类型
  438. config.iconTemplateImageData = UIImagePNGRepresentation([UIImage imageNamed:@"AppIcon"]); // 应用图标
  439. config.ringtoneSound = @"ringtone.aiff"; // 铃声文件(可选)
  440. // 创建CXProvider实例
  441. self.callProvider = [[CXProvider alloc] initWithConfiguration:config];
  442. [self.callProvider setDelegate:self queue:nil];
  443. //self.callRoomMap = [NSMutableDictionary dictionary];
  444. }
  445. - (void)providerDidReset:(CXProvider *)provider {
  446. NSLog(@"Provider reset");
  447. }
  448. - (void)provider:(CXProvider *)provider performStartCallAction:(CXStartCallAction *)action {
  449. // 开始通话的逻辑,如连接服务器等
  450. NSLog(@"performStartCallAction:%@",action);
  451. [action fulfill]; // 当通话开始时调用此方法完成action
  452. }
  453. -(void)provider:(CXProvider *)provider performAnswerCallAction:(CXAnswerCallAction *)action{
  454. [self reciveVoip];
  455. //使用GCD创建一个在3秒后执行的定时器
  456. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  457. NSLog(@"performAnswerCallAction:%@",action);
  458. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  459. // 应用已经解锁并且在前台
  460. if(self.uuid){
  461. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  462. self.msg = nil;
  463. self.uuid = nil;
  464. }
  465. }
  466. });
  467. }
  468. -(void)provider:(CXProvider *)provider timedOutPerformingAction:(CXAction *)action{
  469. if (!self.uuid) {
  470. return;
  471. }
  472. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  473. self.msg = nil;
  474. self.uuid = nil;
  475. NSLog(@"timedOutPerformingAction:%@",action);
  476. }
  477. - (void)provider:(CXProvider *)provider performEndCallAction:(CXEndCallAction *)action {
  478. // 挂断电话的逻辑,如断开服务器连接等
  479. NSLog(@"performEndCallAction:%@",action);
  480. NSDate *now = [NSDate date];
  481. NSTimeInterval trt = [now timeIntervalSince1970];
  482. NSInteger time = trt*1000;
  483. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  484. NSDictionary *callMsg = @{
  485. @"code":@"9",
  486. @"message": @{
  487. @"chatId":self.msg[@"fromId"],
  488. @"fromId":self.msg[@"chatId"],
  489. @"type":@"0",
  490. @"msgtype":@"close",
  491. @"timestamp":strtime,
  492. @"payload":self.msg[@"payload"]
  493. }
  494. };
  495. NSError *error;
  496. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
  497. if (!jsonData) {
  498. NSLog(@"Got an error: %@", error);
  499. } else {
  500. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  501. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  502. [GWebSocket.shareInstance sendMsg:jsonString];
  503. }
  504. self.uuid = nil;
  505. self.msg =nil;
  506. [action fulfill]; // 当通话结束时调用此方法完成action
  507. }
  508. -(void)reciveVoip{
  509. NSLog(@"reciveVoip-------------1");
  510. if(self.msg){
  511. NSNumber *conetType = self.msg[@"conetType"];
  512. NSLog(@"vidio:%@",self.msg[@"payload"]);
  513. BOOL audioOnly = YES;
  514. if(conetType.boolValue){
  515. audioOnly = NO;
  516. }
  517. else{
  518. audioOnly = YES;
  519. }
  520. [self startJSCall:self.msg[@"fromId"] room:self.msg[@"payload"] isCaller:NO audioOnly:audioOnly];
  521. }
  522. }
  523. //开启悬浮窗拨打方式
  524. -(void)startJSCall:(NSString *_Nonnull)chatId room:(NSString *_Nonnull)roomId isCaller:(BOOL)isCaller audioOnly:(BOOL)audioOnly{
  525. self.isJitsiMeet = YES;
  526. if(_jsyuyinctr){
  527. _jsyuyinctr.chatId = chatId.copy;
  528. _jsyuyinctr.room = roomId.copy;
  529. _jsyuyinctr.audioOnly = audioOnly;
  530. _jsyuyinctr.isCaller = isCaller;
  531. }
  532. else{
  533. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  534. _jsyuyinctr = [board instantiateViewControllerWithIdentifier:@"JSGController"];
  535. _jsyuyinctr.modalPresentationStyle = UIModalPresentationFullScreen;
  536. _jsyuyinctr.chatId = chatId.copy;
  537. _jsyuyinctr.room = roomId.copy;
  538. _jsyuyinctr.audioOnly = audioOnly;
  539. _jsyuyinctr.isCaller = isCaller;
  540. }
  541. NSLog(@"startJSCall roomId:%@",roomId);
  542. [_floatWindow showView:_jsyuyinctr.view];
  543. [_jsyuyinctr startJitsiMeetCall];
  544. [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
  545. }
  546. -(void)floadinSmWindow:(NSInteger )type{
  547. if(type!=0){
  548. [_floatWindow viewInFload:type];
  549. }
  550. }
  551. +(void)closeVoip{
  552. if(app.uuid!=nil){
  553. [app.callProvider reportCallWithUUID:app.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  554. app.uuid = nil;
  555. app.msg =nil;
  556. }
  557. }
  558. +(void)JitsiMeetState:(BOOL)state{
  559. app.isJitsiMeet=state;
  560. if(!state){
  561. if(app.shouldShowLock){
  562. [app showLockScreen];
  563. }
  564. else{
  565. [app.floatWindow hide];
  566. }
  567. }
  568. }
  569. +(void)unlockAPP{
  570. app.shouldShowLock=NO;
  571. }
  572. +(void)changeFloadViewState:(BOOL)state{
  573. if (state) {
  574. [app.floatWindow hide];
  575. }
  576. else{
  577. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  578. [app.floatWindow show:1];
  579. }
  580. }
  581. }
  582. #pragma mark 用户点击消息推送或滑动
  583. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  584. NSDictionary *userInfo = notification.request.content.userInfo;
  585. NSInteger addFriend = [[userInfo objectForKey:@"addFriend"] integerValue];
  586. if (addFriend) {
  587. // 添加好友通知在app内也要展示
  588. completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner |
  589. UNNotificationPresentationOptionSound |
  590. UNNotificationPresentationOptionBadge);
  591. }
  592. }
  593. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
  594. // 处理用户对通知的响应(点击、滑动等)
  595. if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
  596. // 用户点击了通知
  597. NSDictionary *userInfo = response.notification.request.content.userInfo;
  598. [self handleNotification:userInfo];
  599. NSLog(@"userInfo: %@", userInfo);
  600. } else if ([response.actionIdentifier isEqualToString:@"customActionIdentifier"]) {
  601. // 处理自定义动作(如果有的话)
  602. }
  603. completionHandler(); // 调用完成处理程序以结束操作
  604. }
  605. - (void)handleNotification:(NSDictionary *)userInfo {
  606. NSDictionary * tempDict = userInfo[@"imMsg"];
  607. NSDictionary * imMsg = tempDict[@"message"];
  608. _isNotification=true;
  609. NSMutableDictionary * mutablemsg = imMsg.mutableCopy;
  610. NSLog(@"------mutablemsg:%@",mutablemsg);
  611. NSDictionary * user = [UDManager.shareInstance getDDManager:dkuserinfo];
  612. if([user[@"id"] isEqual:imMsg[@"fromId"]]){
  613. [mutablemsg setObject:@"true" forKey:@"mine"];
  614. }else{
  615. if([Friendchat isEqual:imMsg[@"type"]]){
  616. [mutablemsg setObject:imMsg[@"fromId"] forKey:@"chatId"];
  617. }
  618. }
  619. if (imMsg) {
  620. if (![LoginStateManager sharedManager].isLoggedIn) {
  621. return;
  622. }
  623. if ([imMsg jk_hasKey:@"addFriend"]) {
  624. return;
  625. }
  626. NSString *strtype = mutablemsg[@"type"];
  627. NSInteger type = [strtype integerValue];
  628. NSString *chatId = mutablemsg[@"chatId"];
  629. NSString *titlename = mutablemsg[@"fromName"]?:@"";
  630. NSString *avatar = mutablemsg[@"fromAvatar"]?:@"";
  631. // NSLog(@"top className:%@",[[self.window jk_topMostController] class]);
  632. // NSLog(@"current className:%@",[[self.window jk_currentViewController] class]);
  633. if ([[self.window jk_currentViewController] isKindOfClass:ChatController.class]) {
  634. ChatController * currentChatVc = (ChatController *)[self.window jk_currentViewController];
  635. if (![currentChatVc.chatId isEqualToString:mutablemsg[@"chatId"]]) {
  636. currentChatVc.chatId = chatId;
  637. currentChatVc.type = type;
  638. currentChatVc.titlename = titlename;
  639. currentChatVc.avatar = avatar;
  640. [currentChatVc reloadAllData];
  641. return;
  642. }
  643. else{
  644. currentChatVc.chatId = chatId;
  645. currentChatVc.type = type;
  646. currentChatVc.titlename = titlename;
  647. currentChatVc.avatar = avatar;
  648. [currentChatVc reloadAllData];
  649. return;
  650. }
  651. }
  652. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  653. ChatController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatController"];
  654. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
  655. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  656. chatctr.chatId = chatId;
  657. chatctr.type = type;
  658. chatctr.titlename = titlename;
  659. chatctr.avatar = avatar;
  660. UITabBarController * tabbarVc = (UITabBarController *)self.window.rootViewController;
  661. ChatIndexController * chatListVc = tabbarVc.viewControllers[0];
  662. if (chatListVc) {
  663. [chatListVc presentViewController:uiNavC animated:YES completion:nil];
  664. }
  665. }
  666. }
  667. #pragma mark -user state and note
  668. -(void)onLoginSucc{
  669. [self initDataAfterLogin:NO];
  670. }
  671. -(void)onLogout{
  672. self.isLogin =false;
  673. [[LoginStateManager sharedManager] cleanLoginState];
  674. [self openLoginController];
  675. [self resetBadgeCount];
  676. [self resetAddFriendBadgeCount];
  677. }
  678. - (void)initDataAfterLogin:(BOOL)needRequest {
  679. self.isLogin =TRUE;
  680. [self openFMDB];
  681. [self openMainController];
  682. [self updivicetoken];
  683. [self updiviceVoIPtoken];
  684. [self sartWebsocket];
  685. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  686. [self showLockScreen];
  687. } else{
  688. self.shouldShowLock = NO;
  689. }
  690. if (needRequest) {
  691. [[LoginStateManager sharedManager] requestUserInfoWith:^(BOOL isSuccess) {
  692. }];
  693. }
  694. }
  695. #pragma mark mainControllor Manager
  696. -(void)openMainController{
  697. NSLog(@"openMainController");
  698. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  699. UITabBarController *tbc = [board instantiateViewControllerWithIdentifier:@"GTabBarController"];
  700. //UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tbc];
  701. NSArray *ctrs = tbc.viewControllers;
  702. //------------1
  703. UIViewController *time = ctrs[0];
  704. // 创建一个新的 UITabBarItem
  705. UIImage *index = [[UIImage imageNamed:@"index"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  706. UIImage *index_cur = [[UIImage imageNamed:@"index_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  707. UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem1", @"")
  708. image:index
  709. selectedImage:index_cur];
  710. // 设置标签文本
  711. tabBarItem.title = NSLocalizedString(@"TabBarItem1", @"");
  712. // 设置标签的文本颜色
  713. [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  714. [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  715. [time setTabBarItem:tabBarItem];
  716. //----------------2
  717. time = ctrs[1];
  718. // 创建一个新的 UITabBarItem
  719. UIImage *index1 = [[UIImage imageNamed:@"txl"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  720. UIImage *index_cur1 = [[UIImage imageNamed:@"txl_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  721. UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem2", @"")
  722. image:index1
  723. selectedImage:index_cur1];
  724. // 设置标签文本
  725. tabBarItem1.title = NSLocalizedString(@"TabBarItem2", @"");
  726. // 设置标签的文本颜色
  727. [tabBarItem1 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  728. [tabBarItem1 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  729. [time setTabBarItem:tabBarItem1];
  730. //------------------3
  731. time = ctrs[2];
  732. // 创建一个新的 UITabBarItem
  733. UIImage *index2 = [[UIImage imageNamed:@"qunzu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  734. UIImage *index_cur2 = [[UIImage imageNamed:@"qunzu_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  735. UITabBarItem *tabBarItem2 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem3", @"")
  736. image:index2
  737. selectedImage:index_cur2];
  738. // 设置标签文本
  739. tabBarItem2.title = NSLocalizedString(@"TabBarItem3", @"");
  740. // 设置标签的文本颜色
  741. [tabBarItem2 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  742. [tabBarItem2 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  743. [time setTabBarItem:tabBarItem2];
  744. //------------------4
  745. time = ctrs[3];
  746. // 创建一个新的 UITabBarItem
  747. UIImage *index3 = [[UIImage imageNamed:@"wode"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  748. UIImage *index_cur3 = [[UIImage imageNamed:@"wode_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  749. UITabBarItem *tabBarItem3 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem4", @"")
  750. image:index3
  751. selectedImage:index_cur3];
  752. // 设置标签文本
  753. tabBarItem3.title = NSLocalizedString(@"TabBarItem4", @"");
  754. // 设置标签的文本颜色
  755. [tabBarItem3 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  756. [tabBarItem3 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  757. [time setTabBarItem:tabBarItem3];
  758. self.window.rootViewController = tbc;
  759. }
  760. -(void)openLoginController{
  761. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  762. GLoginController *login = [board instantiateViewControllerWithIdentifier:@"LoginController"];
  763. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
  764. self.window.rootViewController = nav;
  765. }
  766. #pragma mark openSocket
  767. -(void)sartWebsocket{
  768. [[GWebSocket shareInstance] connectWebSocket];
  769. }
  770. #pragma mark init DB
  771. -(void)openFMDB {
  772. [[GDBManager shareInstance] initDataBase];
  773. }
  774. #pragma mark - UISceneSession lifecycle
  775. //- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
  776. // // Called when a new scene session is being created.
  777. // // Use this method to select a configuration to create the new scene with.
  778. // return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
  779. //}
  780. //
  781. //
  782. //- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
  783. // // Called when the user discards a scene session.
  784. // // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  785. // // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  786. //}
  787. #pragma mark - Core Data stack
  788. @synthesize persistentContainer = _persistentContainer;
  789. - (NSPersistentContainer *)persistentContainer {
  790. // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
  791. @synchronized (self) {
  792. if (_persistentContainer == nil) {
  793. _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"555IM"];
  794. [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
  795. if (error != nil) {
  796. // Replace this implementation with code to handle the error appropriately.
  797. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  798. /*
  799. Typical reasons for an error here include:
  800. * The parent directory does not exist, cannot be created, or disallows writing.
  801. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  802. * The device is out of space.
  803. * The store could not be migrated to the current model version.
  804. Check the error message to determine what the actual problem was.
  805. */
  806. NSLog(@"Unresolved error %@, %@", error, error.userInfo);
  807. abort();
  808. }
  809. }];
  810. }
  811. }
  812. return _persistentContainer;
  813. }
  814. #pragma mark - Core Data Saving support
  815. - (void)saveContext {
  816. NSManagedObjectContext *context = self.persistentContainer.viewContext;
  817. NSError *error = nil;
  818. if ([context hasChanges] && ![context save:&error]) {
  819. // Replace this implementation with code to handle the error appropriately.
  820. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  821. NSLog(@"Unresolved error %@, %@", error, error.userInfo);
  822. abort();
  823. }
  824. }
  825. #pragma mark applock
  826. - (void)showLockScreen {
  827. // 确保在主线程执行
  828. if (self.shouldShowLock && [[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  829. NSLog(@"showLockScreen--------------1");
  830. if (self.isJitsiMeet) {
  831. [_floatWindow viewInFload:0];
  832. return;
  833. }
  834. else{
  835. [_floatWindow show:1];
  836. }
  837. return;
  838. }
  839. if (!self.isJitsiMeet) {
  840. [_floatWindow hide];
  841. }
  842. }
  843. - (void)applicationWillTerminate:(UIApplication *)application {
  844. [[OSSManager sharedManager] applicationWillTerminate];
  845. }
  846. @end