diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample.xcodeproj/project.pbxproj b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample.xcodeproj/project.pbxproj index 28c16230..0a9d44c6 100644 --- a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample.xcodeproj/project.pbxproj +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample.xcodeproj/project.pbxproj @@ -22,6 +22,8 @@ 39ED7B1E290FA9C700CAE608 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 39ED7B20290FA9C700CAE608 /* Localizable.strings */; }; DD774A7729485F6600347A9E /* CustomRouterViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = DD774A7629485F6600347A9E /* CustomRouterViewController.m */; }; DDC1AC8929651B6C008C085A /* ConversationController+Test.m in Sources */ = {isa = PBXBuildFile; fileRef = DDC1AC8829651B6C008C085A /* ConversationController+Test.m */; }; + DDE8123A29E950440040E401 /* InhertViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDE8123929E950440040E401 /* InhertViewController.swift */; }; + DDE8123C29E9510F0040E401 /* TestViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDE8123B29E9510F0040E401 /* TestViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -72,6 +74,8 @@ DD774A7629485F6600347A9E /* CustomRouterViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CustomRouterViewController.m; sourceTree = ""; }; DDC1AC8729651B6C008C085A /* ConversationController+Test.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ConversationController+Test.h"; sourceTree = ""; }; DDC1AC8829651B6C008C085A /* ConversationController+Test.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ConversationController+Test.m"; sourceTree = ""; }; + DDE8123929E950440040E401 /* InhertViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InhertViewController.swift; sourceTree = ""; }; + DDE8123B29E9510F0040E401 /* TestViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestViewController.swift; sourceTree = ""; }; DDF443AC294851D90077184F /* IMUIKitOCExample-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "IMUIKitOCExample-Bridging-Header.h"; sourceTree = ""; }; F984299B79B347145EA4AF84 /* Pods-IMUIKitOCExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IMUIKitOCExample.debug.xcconfig"; path = "Target Support Files/Pods-IMUIKitOCExample/Pods-IMUIKitOCExample.debug.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ @@ -179,6 +183,8 @@ DD774A7629485F6600347A9E /* CustomRouterViewController.m */, DDC1AC8729651B6C008C085A /* ConversationController+Test.h */, DDC1AC8829651B6C008C085A /* ConversationController+Test.m */, + DDE8123B29E9510F0040E401 /* TestViewController.swift */, + DDE8123929E950440040E401 /* InhertViewController.swift */, 39ED7B20290FA9C700CAE608 /* Localizable.strings */, DDF443AC294851D90077184F /* IMUIKitOCExample-Bridging-Header.h */, ); @@ -205,7 +211,7 @@ 39A2F20628D9B2C400DDCAF2 /* Frameworks */, 39A2F20728D9B2C400DDCAF2 /* Resources */, DB787379DE2DF44860C11CF1 /* [CP] Embed Pods Frameworks */, - 8F14E37FD20AEF03EA4142FE /* [CP] Copy Pods Resources */, + 2A3377106BCBB5C08F3A27B1 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -325,7 +331,7 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 8F14E37FD20AEF03EA4142FE /* [CP] Copy Pods Resources */ = { + 2A3377106BCBB5C08F3A27B1 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -394,6 +400,8 @@ 39A2F24B28DABC6700DDCAF2 /* NENavigationController.m in Sources */, 39A2F24728DABC1700DDCAF2 /* NETabbarController.m in Sources */, 39A2F21F28D9B2C500DDCAF2 /* main.m in Sources */, + DDE8123A29E950440040E401 /* InhertViewController.swift in Sources */, + DDE8123C29E9510F0040E401 /* TestViewController.swift in Sources */, DD774A7729485F6600347A9E /* CustomRouterViewController.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -593,7 +601,7 @@ INFOPLIST_KEY_UIMainStoryboardFile = Main; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -629,7 +637,7 @@ INFOPLIST_KEY_UIMainStoryboardFile = Main; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -647,6 +655,7 @@ 39A2F23C28D9B2C600DDCAF2 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; @@ -664,6 +673,7 @@ 39A2F23D28D9B2C600DDCAF2 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; @@ -681,6 +691,7 @@ 39A2F23F28D9B2C600DDCAF2 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; @@ -696,6 +707,7 @@ 39A2F24028D9B2C600DDCAF2 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/AppKey.h b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/AppKey.h index 5e105323..f5538b15 100644 --- a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/AppKey.h +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/AppKey.h @@ -7,6 +7,6 @@ #define AppKey_h /// IM key -static NSString *const AppKey = @""; +static NSString *const AppKey = @"<#appKey#>"; #endif /* AppKey_h */ diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Info.plist b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Info.plist index 0c67376e..97ff79dd 100644 --- a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Info.plist +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Info.plist @@ -1,5 +1,11 @@ - + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.h b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.h index 17470e70..fa0a737e 100644 --- a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.h +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.h @@ -8,5 +8,4 @@ @interface AppDelegate : UIResponder @property(nonatomic, strong) UIWindow *window; - @end diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.m b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.m index 28d53e7e..83c37813 100644 --- a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.m +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/AppDelegate.m @@ -13,8 +13,9 @@ #import #import #import -//#import +// #import #import "CustomRouterViewController.h" +#import "IMUIKitOCExample-Swift.h" @import NIMSDK; @@ -27,45 +28,116 @@ @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] init]; - self.window.backgroundColor = [UIColor whiteColor]; - self.window.frame = UIScreen.mainScreen.bounds; + self.window.frame = [[UIScreen mainScreen] bounds]; [self.window makeKeyAndVisible]; - UIViewController *controller = [[UIViewController alloc] init]; - self.window.rootViewController = controller; + [self.window makeKeyWindow]; + UIViewController *root = [[UIViewController alloc] init]; + root.view.backgroundColor = [UIColor whiteColor]; + self.window.backgroundColor = [UIColor clearColor]; + self.window.rootViewController = root; [self setupInit]; return YES; } - (void)setupInit { - // 初始化NIMSDK - NIMSDKOption *option = [NIMSDKOption optionWithAppKey:AppKey]; - option.apnsCername = @""; - option.pkCername = @""; - [[IMKitClient instance] setupCoreKitIM:option]; - - // 登录IM之前先初始化 @ 消息监听mananger - NEAtMessageManager * _ = [NEAtMessageManager instance]; - - [[IMKitClient instance] loginIM:@"imaccid" :@"imToken" :^(NSError * _Nullable error) { - if (error != nil) { - NSLog(@"NEKitCore login error : %@", [error description]); + // 初始化NIMSDK + NIMSDKOption *option = [NIMSDKOption optionWithAppKey:AppKey]; + [[IMKitClient instance] setupCoreKitIM:option]; + + // 统一登录组件 + YXConfig *config = [[YXConfig alloc] init]; + config.appKey = AppKey; + config.parentScope = @2; + config.scope = @7; + config.supportInternationalize = false; + config.type = YXLoginPhone; + +#ifdef DEBUG + config.isOnline = NO; +#else + config.isOnline = YES; +#endif + [[AuthorManager shareInstance] initAuthorWithConfig:config]; + if ([AuthorManager shareInstance].canAutologin) { + [[AuthorManager shareInstance] + autoLoginWithCompletion:^(YXUserInfo *_Nullable userinfo, NSError *_Nullable error) { + if (error) { + NSLog(@"auto login failed,error = %@", error); + } else { + [self setupXKit:userinfo]; + } + }]; + } else { + [self loginWithUI]; + } +} + +- (void)loginWithUI { + [[AuthorManager shareInstance] + startLoginWithCompletion:^(YXUserInfo *_Nullable userinfo, NSError *_Nullable error) { + if (!error) { + [self setupXKit:userinfo]; } else { - [self setupTabbar]; + NSLog(@"login failed,error = %@", error); } - }]; + }]; +} + +- (void)setupXKit:(YXUserInfo *)user { + // 登录云信IM + if (user.imToken && user.imAccid) { + [[IMKitClient instance] loginIM:user.imAccid :user.imToken :^(NSError * _Nullable error) { + if (!error) { + [ChatRouter setupInit]; + [self setupTabbar]; + //登录圈组模块,如不需要圈组功能则不用登录 +// QChatLoginParam *parama = [[QChatLoginParam alloc]init:user.imAccid :user.imToken]; +// [[IMKitClient instance] loginQchat:parama completion:^(NSError * _Nullable error, QChatLoginResult * _Nullable result) { +// if (!error) { +// [self setupTabbar]; +// }else { +// NSLog(@"qchat login failed,error = %@",error); +// } +// }]; + + }else { + NSLog(@"loginIM failed,error = %@",error); + } + }]; + } else { + NSLog(@"parameter is nil"); + } } - (void)setupTabbar { + self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[NETabbarController alloc] init]; [self registerRouter]; } +- (void)customClick { + NSLog(@"custom more action click"); +} + // 注册路由 - (void)registerRouter { [ChatRouter register]; [ConversationRouter register]; [ContactRouter register]; + // 聊天页面自定义面板示例 + /* + NEMoreItemModel *item = [[NEMoreItemModel alloc] init]; + item.title = @"自定义"; + item.customDelegate = self; + item.action = @selector(customClick); + item.image = [UIImage imageNamed:@"chatSelect"]; + NSMutableArray *muta = [[NSMutableArray alloc] initWithArray: + NEChatUIKitClient.instance.moreAction]; + [muta addObject:item]; + NEChatUIKitClient.instance.moreAction = muta; + */ + [[Router shared] register:@"imkit://chat/p2pChat.page" closure:^(NSDictionary *_Nonnull param) { NSObject *param1 = [param objectForKey:@"nav"]; diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/InhertViewController.swift b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/InhertViewController.swift new file mode 100644 index 00000000..d28217c4 --- /dev/null +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/InhertViewController.swift @@ -0,0 +1,24 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEConversationUIKit +import UIKit + +public class InhertViewController: ConversationController { + override public func viewDidLoad() { + super.viewDidLoad() + let test = TestViewController(sessionId: "") + // Do any additional setup after loading the view. + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ +} diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/NETabbarController.m b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/NETabbarController.m index 7c0fef9e..b87216eb 100644 --- a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/NETabbarController.m +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/NETabbarController.m @@ -6,12 +6,14 @@ #import "NETabbarController.h" #import "NENavigationController.h" +#import #import +#import #import #import #import #import -//#import +// #import @interface NETabbarController () @@ -26,8 +28,14 @@ - (void)viewDidLoad { } - (void)setUpControllers { + // ChatViewController *chat = [[ChatViewController alloc] init]; + // NENavigationView *nenav = [[NENavigationView alloc] init]; + + [ChatRouter registerFun]; + // 会话列表页 ConversationController *sessionCtrl = [[ConversationController alloc] init]; + sessionCtrl.view.backgroundColor = [UIColor whiteColor]; sessionCtrl.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"message", @"") image:[UIImage imageNamed:@"chat"] @@ -46,13 +54,13 @@ - (void)setUpControllers { // 圈组 -// QChatHomeViewController *qchatCtrl = [[QChatHomeViewController alloc] init]; -// qchatCtrl.tabBarItem = -// [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"qchat", @"") -// image:[UIImage imageNamed:@"qchat_tabbar_icon"] -// selectedImage:[UIImage imageNamed:@"qchat_tabbar_icon"]]; -// NENavigationController *qchatNav = -// [[NENavigationController alloc] initWithRootViewController:qchatCtrl]; + // QChatHomeViewController *qchatCtrl = [[QChatHomeViewController alloc] init]; + // qchatCtrl.tabBarItem = + // [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"qchat", @"") + // image:[UIImage imageNamed:@"qchat_tabbar_icon"] + // selectedImage:[UIImage imageNamed:@"qchat_tabbar_icon"]]; + // NENavigationController *qchatNav = + // [[NENavigationController alloc] initWithRootViewController:qchatCtrl]; self.tabBar.backgroundColor = [UIColor whiteColor]; self.viewControllers = @[ sessionNav, contactNav ]; diff --git a/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/TestViewController.swift b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/TestViewController.swift new file mode 100644 index 00000000..9d0b33f3 --- /dev/null +++ b/IMUIKitOC/IMUIKitOCExample/IMUIKitOCExample/Main/TestViewController.swift @@ -0,0 +1,23 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatUIKit +import UIKit +public class TestViewController: P2PChatViewController { + override public func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ +} diff --git a/IMUIKitOC/IMUIKitOCExample/Podfile b/IMUIKitOC/IMUIKitOCExample/Podfile index 30342eee..ae9e436f 100644 --- a/IMUIKitOC/IMUIKitOCExample/Podfile +++ b/IMUIKitOC/IMUIKitOCExample/Podfile @@ -1,56 +1,35 @@ # Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' -platform :ios, '9.0' +platform :ios, '11.0' source 'https://github.com/CocoaPods/Specs.git' target 'IMUIKitOCExample' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! #登录组件 - pod 'YXLogin', '1.0.0' + pod 'YXLogin', '1.1.0' #可选UI库 - pod 'NEContactUIKit', '9.5.0' -# pod 'NEQChatUIKit', '9.5.0' - pod 'NEConversationUIKit', '9.5.0' - pod 'NEChatUIKit', '9.5.0' - pod 'NETeamUIKit', '9.5.0' - - - #可选Kit库(和UIKit对应) - pod 'NEContactKit', '9.5.0' -# pod 'NEQChatKit', '9.5.0' - pod 'NEConversationKit', '9.5.0' - pod 'NEChatKit', '9.5.0' - pod 'NETeamKit', '9.5.0' - - #基础kit库 - pod 'NECommonUIKit', '9.5.0' - pod 'NECommonKit', '9.5.0' - pod 'NECoreIMKit', '9.5.0' - pod 'NECoreKit', '9.5.0' - pod 'NEMapKit', '9.5.0' - - - - - #fix bug in Xcode 14 - post_install do |installer| - installer.pods_project.targets.each do |target| - if target.name == 'RSKPlaceholderTextView' - target.build_configurations.each do |config| - config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES' - end - end - end - end + pod 'NEContactUIKit', '9.7.0' + pod 'NEConversationUIKit', '9.7.0' + pod 'NEChatUIKit', '9.7.0' + pod 'NETeamUIKit', '9.7.0' + pod 'NEMapKit', '9.7.0' + + #基础kit库 + pod 'NECoreKit', '9.6.6' + pod 'NECoreIMKit', '9.6.7' + pod 'NECommonKit', '9.6.6' + pod 'NECommonUIKit', '9.6.6' + pod 'NEChatKit', '9.7.0' # 如果需要查看UI部分源码请注释掉以上在线依赖,打开下面的本地依赖 -# pod 'NEQChatUIKit', :path => '../NEQChatUIKit/NEQChatUIKit.podspec' -# pod 'NEContactUIKit', :path => '../NEContactUIKit/NEContactUIKit.podspec' -# pod 'NEConversationUIKit', :path => '../NEConversationUIKit/NEConversationUIKit.podspec' -# pod 'NETeamUIKit', :path => '../NETeamUIKit/NETeamUIKit.podspec' -# pod 'NEChatUIKit', :path => '../NEChatUIKit/NEChatUIKit.podspec' +# pod 'NEQChatUIKit', :path => '../NEQChatUIKit/NEQChatUIKit.podspec' +# pod 'NEContactUIKit', :path => '../NEContactUIKit/NEContactUIKit.podspec' +# pod 'NEConversationUIKit', :path => '../NEConversationUIKit/NEConversationUIKit.podspec' +# pod 'NETeamUIKit', :path => '../NETeamUIKit/NETeamUIKit.podspec' +# pod 'NEChatUIKit', :path => '../NEChatUIKit/NEChatUIKit.podspec' end + + diff --git a/NEChatUIKit/NEChatUIKit.podspec b/NEChatUIKit/NEChatUIKit.podspec index e83b1a6d..34d6e4d9 100644 --- a/NEChatUIKit/NEChatUIKit.podspec +++ b/NEChatUIKit/NEChatUIKit.podspec @@ -16,7 +16,7 @@ Pod::Spec.new do |s| # s.name = 'NEChatUIKit' - s.version = '9.6.5' + s.version = '9.7.0' s.summary = 'Chat Module of IM.' # This description is used to generate tags and improve search results. diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/Contents.json new file mode 100644 index 00000000..56de524b --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_selece_delete@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_selece_delete@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/fun_selece_delete@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/fun_selece_delete@2x.png new file mode 100644 index 00000000..be3612db Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/fun_selece_delete@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/fun_selece_delete@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/fun_selece_delete@3x.png new file mode 100644 index 00000000..2f7cad8a Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_delete.imageset/fun_selece_delete@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/Contents.json new file mode 100644 index 00000000..5780241e --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_select_merge@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_select_merge@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/fun_select_merge@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/fun_select_merge@2x.png new file mode 100644 index 00000000..48e3b003 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/fun_select_merge@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/fun_select_merge@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/fun_select_merge@3x.png new file mode 100644 index 00000000..9ce89971 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_multiForward.imageset/fun_select_merge@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/Contents.json new file mode 100644 index 00000000..8bbf2f0d --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_select_perItem@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_select_perItem@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/fun_select_perItem@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/fun_select_perItem@2x.png new file mode 100644 index 00000000..6737ec8e Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/fun_select_perItem@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/fun_select_perItem@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/fun_select_perItem@3x.png new file mode 100644 index 00000000..50315680 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_select_singleForward.imageset/fun_select_perItem@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/Contents.json new file mode 100644 index 00000000..a6577c58 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_unselect_delete@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_unselect_delete@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/fun_unselect_delete@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/fun_unselect_delete@2x.png new file mode 100644 index 00000000..803d4eec Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/fun_unselect_delete@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/fun_unselect_delete@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/fun_unselect_delete@3x.png new file mode 100644 index 00000000..63c95be8 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_delete.imageset/fun_unselect_delete@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/Contents.json new file mode 100644 index 00000000..1acc5ca8 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_unselect_merge@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_unselect_merge@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/fun_unselect_merge@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/fun_unselect_merge@2x.png new file mode 100644 index 00000000..85ea81fc Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/fun_unselect_merge@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/fun_unselect_merge@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/fun_unselect_merge@3x.png new file mode 100644 index 00000000..9d70a7ef Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_multiForward.imageset/fun_unselect_merge@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/Contents.json new file mode 100644 index 00000000..aa0750d5 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_unselect_perItem@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_unselect_perItem@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/fun_unselect_perItem@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/fun_unselect_perItem@2x.png new file mode 100644 index 00000000..d0434735 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/fun_unselect_perItem@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/fun_unselect_perItem@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/fun_unselect_perItem@3x.png new file mode 100644 index 00000000..cfd4ad5b Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/fun_unselect_singleForward.imageset/fun_unselect_perItem@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/Contents.json new file mode 100644 index 00000000..487d440c --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "merge_message_receive_fun@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "merge_message_receive_fun@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/merge_message_receive_fun@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/merge_message_receive_fun@2x.png new file mode 100644 index 00000000..4bf7d9c7 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/merge_message_receive_fun@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/merge_message_receive_fun@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/merge_message_receive_fun@3x.png new file mode 100644 index 00000000..49ff055c Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_receive_fun.imageset/merge_message_receive_fun@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/Contents.json new file mode 100644 index 00000000..d3b7d64c --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "merge_message_send_fun@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "merge_message_send_fun@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/merge_message_send_fun@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/merge_message_send_fun@2x.png new file mode 100644 index 00000000..5e86f750 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/merge_message_send_fun@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/merge_message_send_fun@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/merge_message_send_fun@3x.png new file mode 100644 index 00000000..fcbab1fa Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/Chat/multiForward_message_send_fun.imageset/merge_message_send_fun@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Contents.json new file mode 100644 index 00000000..5c4d3b18 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Frame@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Frame@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Frame@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Frame@2x.png new file mode 100644 index 00000000..20463344 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Frame@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Frame@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Frame@3x.png new file mode 100644 index 00000000..2413d297 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_fold.imageset/Frame@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Contents.json new file mode 100644 index 00000000..6a4d508b --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Vector@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Vector@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Vector@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Vector@2x.png new file mode 100644 index 00000000..b9af7788 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Vector@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Vector@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Vector@3x.png new file mode 100644 index 00000000..e8892f6c Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_input_unfold.imageset/Vector@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/Contents.json new file mode 100644 index 00000000..ea2e4827 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "clicked_we@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "clicked_we@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/clicked_we@2x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/clicked_we@2x.png new file mode 100644 index 00000000..f69ac913 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/clicked_we@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/clicked_we@3x.png b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/clicked_we@3x.png new file mode 100644 index 00000000..75777604 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/FunChatUIKit.xcassets/fun_select.imageset/clicked_we@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Contents.json new file mode 100644 index 00000000..5c4d3b18 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Frame@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Frame@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Frame@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Frame@2x.png new file mode 100644 index 00000000..2a398288 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Frame@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Frame@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Frame@3x.png new file mode 100644 index 00000000..c78c8954 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NEBaseChatUIKit.xcassets/Commom/multiple_send_image.imageset/Frame@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/Contents.json new file mode 100644 index 00000000..1a82d813 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "merge_message_receive@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "merge_message_receive@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/merge_message_receive@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/merge_message_receive@2x.png new file mode 100644 index 00000000..29e0c47f Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/merge_message_receive@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/merge_message_receive@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/merge_message_receive@3x.png new file mode 100644 index 00000000..a2bd621b Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_receive.imageset/merge_message_receive@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/Contents.json new file mode 100644 index 00000000..bb808c80 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "merge_message_send@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "merge_message_send@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/merge_message_send@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/merge_message_send@2x.png new file mode 100644 index 00000000..a1be3fd4 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/merge_message_send@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/merge_message_send@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/merge_message_send@3x.png new file mode 100644 index 00000000..7b4b6a0c Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/multiForward_message_send.imageset/merge_message_send@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Contents.json new file mode 100644 index 00000000..5c4d3b18 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Frame@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Frame@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Frame@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Frame@2x.png new file mode 100644 index 00000000..a1e475c7 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Frame@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Frame@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Frame@3x.png new file mode 100644 index 00000000..a497f04e Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_fold.imageset/Frame@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Contents.json new file mode 100644 index 00000000..6a4d508b --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Vector@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Vector@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Vector@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Vector@2x.png new file mode 100644 index 00000000..238406e2 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Vector@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Vector@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Vector@3x.png new file mode 100644 index 00000000..5bcfcba8 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/normal_input_unfold.imageset/Vector@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/Contents.json new file mode 100644 index 00000000..f30c214d --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "selece_delete@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "selece_delete@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/selece_delete@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/selece_delete@2x.png new file mode 100644 index 00000000..dfca74b6 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/selece_delete@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/selece_delete@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/selece_delete@3x.png new file mode 100644 index 00000000..bedf9ea5 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_delete.imageset/selece_delete@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/Contents.json new file mode 100644 index 00000000..dc57be77 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "select_merge@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "select_merge@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/select_merge@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/select_merge@2x.png new file mode 100644 index 00000000..9e47f6ce Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/select_merge@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/select_merge@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/select_merge@3x.png new file mode 100644 index 00000000..b978990e Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_multiForward.imageset/select_merge@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/Contents.json new file mode 100644 index 00000000..ec424469 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "select_perItem@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "select_perItem@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/select_perItem@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/select_perItem@2x.png new file mode 100644 index 00000000..3edad741 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/select_perItem@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/select_perItem@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/select_perItem@3x.png new file mode 100644 index 00000000..849f39db Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/select_singleForward.imageset/select_perItem@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/Contents.json new file mode 100644 index 00000000..efd809a7 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "unselect_delete@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "unselect_delete@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/unselect_delete@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/unselect_delete@2x.png new file mode 100644 index 00000000..b3b4939c Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/unselect_delete@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/unselect_delete@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/unselect_delete@3x.png new file mode 100644 index 00000000..7e053041 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_delete.imageset/unselect_delete@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/Contents.json new file mode 100644 index 00000000..be0eaf13 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "unselect_merge@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "unselect_merge@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/unselect_merge@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/unselect_merge@2x.png new file mode 100644 index 00000000..b70e1283 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/unselect_merge@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/unselect_merge@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/unselect_merge@3x.png new file mode 100644 index 00000000..10b6b81f Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_multiForward.imageset/unselect_merge@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/Contents.json b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/Contents.json new file mode 100644 index 00000000..5962db64 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "unselect_perItem@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "unselect_perItem@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/unselect_perItem@2x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/unselect_perItem@2x.png new file mode 100644 index 00000000..42fa6ce0 Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/unselect_perItem@2x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/unselect_perItem@3x.png b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/unselect_perItem@3x.png new file mode 100644 index 00000000..04ec3f8f Binary files /dev/null and b/NEChatUIKit/NEChatUIKit/Assets/NormalChatUIKit.xcassets/Chat/unselect_singleForward.imageset/unselect_perItem@3x.png differ diff --git a/NEChatUIKit/NEChatUIKit/Assets/en.lproj/Localizable.strings b/NEChatUIKit/NEChatUIKit/Assets/en.lproj/Localizable.strings index a73fea56..fcfad433 100644 --- a/NEChatUIKit/NEChatUIKit/Assets/en.lproj/Localizable.strings +++ b/NEChatUIKit/NEChatUIKit/Assets/en.lproj/Localizable.strings @@ -24,7 +24,6 @@ "downloading"="downloading..."; "read"="read"; "unread"="unread"; -"network_unavailable"="No internet, Please check your setting"; //MARK: tips @@ -42,7 +41,7 @@ "out"="remove"; "has_updated" = "update"; "to" = "to "; -"only_team_owner" = "Only the group owner"; +"only_team_owner" = "Group owners and administrators"; "everyone" = "Everyone"; "team_name" = "Group Name"; @@ -60,6 +59,7 @@ "not_mute" = "unmute"; "mute" = "mute"; "team_has_been_removed" = "This group is disbanded"; +"team_has_been_quit" = "You have been removed"; "team_has_quit" = "Group chat has exited"; "join"="joined"; "pass"="Passed"; @@ -92,7 +92,6 @@ "operation_delete"="delete"; "operation_recall"="recall"; "withdrew_message" = "withdrew this message"; -"message_has_be_withdrawn" = "message recalled"; "message_reedit" = "reedit"; "message_revoke_confirm" = "Wether to recall this message"; "message_delete_confirm"="Wether to delete this message"; @@ -108,6 +107,9 @@ "msg_video"="video message"; "msg_file"="file message"; "msg_location"="location message"; +"msg_rtc_audio"="audio call message"; +"msg_rtc_video"="video call message"; +"msg_rtc_call"="RTC call message"; "msg_custom"="custom message"; "msg_unknown"="Unknown message type"; "message_read"="Reading Status"; @@ -181,4 +183,21 @@ "no_location"="Please select the location you want to send"; -"delete_failed"="Delete failed"; +// 多选 +"select_multi"="select_multi"; +"select_per_item"="select_per_item"; +"chat_history"="chat history"; +"chat_history_by"="`s messages"; +"leave_message"="leave message"; +"exist_invalid"="There are messages cannot be forwarded. Can it be removed and sent?"; +"forward_failed"="Eror, forwarding failed"; +"multiForward_open_failed"="Failed to obtain information"; +"file_check_failed"="File verification failed"; +"per_item_forward_limit"="Forward one by one to limit %d messages"; +"multiForward_forward_limit"="Combined forwarding limits %d messages"; +"exception_description"="Exception description"; + +"multiple_line_placleholder"="Please enter title"; +"null_message_not_support"="Empty messages are not allowed to be sent"; + +"black_list_tip"="Opposite has blocked you and the message cannot be sent."; diff --git a/NEChatUIKit/NEChatUIKit/Assets/zh-Hans.lproj/Localizable.strings b/NEChatUIKit/NEChatUIKit/Assets/zh-Hans.lproj/Localizable.strings index 45a7848a..0d699799 100644 --- a/NEChatUIKit/NEChatUIKit/Assets/zh-Hans.lproj/Localizable.strings +++ b/NEChatUIKit/NEChatUIKit/Assets/zh-Hans.lproj/Localizable.strings @@ -24,7 +24,6 @@ "downloading"="正在下载中..."; "read"="已读(0)"; "unread"="未读(0)"; -"network_unavailable"="当前网络不可用,请检查你的网络设置"; //MARK: tips //MARK: team @@ -41,7 +40,7 @@ "out"="移除了 "; "has_updated" = "更新了"; "to" = "为 "; -"only_team_owner" = "仅群主"; +"only_team_owner" = "群主和管理员"; "everyone" = "所有人"; "team_name" = "名称"; @@ -60,13 +59,14 @@ "not_mute" = "解除禁言"; "mute" = "禁言"; "team_has_been_removed" = "当前群聊已解散"; +"team_has_been_quit" = "您已被移除群聊"; "team_has_quit" = "已退出群聊"; "join"="进入了"; "pass"="通过了"; "leave"="退出了"; "transfer"="转移了群主身份给"; -"added_manager"="被添加为群管理员"; -"removed_manager"="被撤销了群管理员身份"; +"added_manager"="被任命为群管理员"; +"removed_manager"="被移除管理员"; "accept"="接受入群邀请来自"; "team_mute"="当前群主设置为禁言"; "team_all_mute"="群禁言已开启"; @@ -89,7 +89,6 @@ "operation_delete"="删除"; "operation_recall"="撤回"; "withdrew_message" = "撤回了一条消息"; -"message_has_be_withdrawn" = "此消息已撤回"; "message_reedit" = "重新编辑"; "message_revoke_confirm" = "确认要撤回该消息吗?"; "message_delete_confirm"="确认要删除该消息吗?"; @@ -100,13 +99,16 @@ "collection_success"="已收藏"; "no_permession"="暂无权限"; "msg_reply"="回复"; -"msg_image"="图片消息"; -"msg_audio"="语音消息"; -"msg_video"="视频消息"; -"msg_file"="文件消息"; -"msg_location"="地理位置"; -"msg_custom"="自定义消息"; -"msg_unknown"="未知消息体"; +"msg_image"="[图片消息]"; +"msg_audio"="[语音消息]"; +"msg_video"="[视频消息]"; +"msg_file"="[文件消息]"; +"msg_location"="[地理位置]"; +"msg_rtc_audio"="[语音通话]"; +"msg_rtc_video"="[视频通话]"; +"msg_rtc_call"="[音视频通话]"; +"msg_custom"="[自定义消息]"; +"msg_unknown"="[未知消息体]"; "message_read"="消息阅读状态"; "message_all_unread"="全部成员未读"; "user_select"="选择提醒"; @@ -141,7 +143,7 @@ "message_recalled"="此消息已撤回"; "video_call"="视频通话"; -"audio_call"="音频通话"; +"audio_call"="语音通话"; "call_complete"="通话时长"; "call_canceled"="已取消"; @@ -179,4 +181,21 @@ "no_location"="请选择你要发送的位置信息"; -"delete_failed"="删除失败"; +// 多选 +"select_multi"="合并转发"; +"select_per_item"="逐条转发"; +"chat_history"="聊天记录"; +"chat_history_by"="的消息"; +"leave_message"="留言"; +"exist_invalid"="存在不可转发的消息体,是否去除后发送?"; +"forward_failed"="系统异常,转发失败"; +"multiForward_open_failed"="信息获取失败"; +"file_check_failed"="文件校验失败"; +"per_item_forward_limit"="逐条转发限制%d条消息"; +"multiForward_forward_limit"="合并转发限制%d条消息"; +"exception_description"="异常说明"; + +"multiple_line_placleholder"="请输入标题"; +"null_message_not_support"="不支持发送空消息"; + +"black_list_tip"="对方已将您拉黑,消息无法发送"; diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCenterTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCenterTextCell.swift index ee402b6b..f6b587af 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCenterTextCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCenterTextCell.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ChatCenterTextCell: ChatCornerCell { +open class ChatCenterTextCell: ChatCornerCell { public var titleLabel: UILabel = .init() public var line = UIView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { @@ -35,7 +35,7 @@ public class ChatCenterTextCell: ChatCornerCell { ]) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCornerCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCornerCell.swift index 19ad994f..f238c1c0 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCornerCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatCornerCell.swift @@ -8,4 +8,4 @@ import NECommonUIKit import UIKit @objcMembers -public class ChatCornerCell: CornerCell {} +open class ChatCornerCell: CornerCell {} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatHeaderView.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatHeaderView.swift index d73c2897..4f52d551 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatHeaderView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatHeaderView.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ChatHeaderView: UIView { +open class ChatHeaderView: UIView { public lazy var titleLabel: UILabel = { let label = UILabel() label.font = DefaultTextFont(12) @@ -28,7 +28,7 @@ public class ChatHeaderView: UIView { setupUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { super.init(coder: coder) } @@ -42,7 +42,7 @@ public class ChatHeaderView: UIView { backgroundColor = .clear } - public func setTitle(_ name: String) { + open func setTitle(_ name: String) { titleLabel.text = name .count > 2 ? String(name[name.index(name.endIndex, offsetBy: -2)...]) : name } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatImageTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatImageTextCell.swift index 271d01b7..2ce65364 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatImageTextCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatImageTextCell.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ChatImageTextCell: ChatStateCell { +open class ChatImageTextCell: ChatStateCell { var circleView = UIImageView() override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) @@ -50,7 +50,7 @@ public class ChatImageTextCell: ChatStateCell { ]) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -80,7 +80,7 @@ public class ChatImageTextCell: ChatStateCell { return label }() - public func setup(accid: String?, nickName: String?) { + open func setup(accid: String?, nickName: String?) { let name = nickName?.count ?? 0 > 0 ? nickName : accid nameLabel.text = name guard let n = name else { return } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatSectionView.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatSectionView.swift index 1a495bce..e0998732 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatSectionView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatSectionView.swift @@ -6,14 +6,14 @@ import UIKit @objcMembers -public class ChatSectionView: UITableViewHeaderFooterView { +open class ChatSectionView: UITableViewHeaderFooterView { public var titleLabel = UILabel() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) commonUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatStateCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatStateCell.swift index 5cfd2959..84f90b78 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatStateCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatStateCell.swift @@ -13,7 +13,7 @@ public enum RightStyle: Int { } @objcMembers -public class ChatStateCell: ChatCornerCell { +open class ChatStateCell: ChatCornerCell { private var style: RightStyle = .none public var rightImage = UIImageView() var rightImageMargin: NSLayoutConstraint? @@ -51,18 +51,7 @@ public class ChatStateCell: ChatCornerCell { ]) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextArrowCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextArrowCell.swift index 338df7af..1acc67a0 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextArrowCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextArrowCell.swift @@ -6,13 +6,13 @@ import UIKit @objcMembers -public class ChatTextArrowCell: ChatTextCell { +open class ChatTextArrowCell: ChatTextCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) rightStyle = .indicate } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextCell.swift index 2e26829f..d8fa170d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatTextCell.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ChatTextCell: ChatStateCell { +open class ChatTextCell: ChatStateCell { public var titleLabel: UILabel = .init() public var detailLabel: UILabel = .init() public var line = UIView() @@ -63,7 +63,7 @@ public class ChatTextCell: ChatStateCell { ]) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUnfoldCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUnfoldCell.swift index 049697b3..e9b21bc2 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUnfoldCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUnfoldCell.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ChatUnfoldCell: ChatCornerCell { +open class ChatUnfoldCell: ChatCornerCell { lazy var arrowImage: UIImageView = { let arrow = UIImageView() arrow.translatesAutoresizingMaskIntoConstraints = false @@ -22,23 +22,12 @@ public class ChatUnfoldCell: ChatCornerCell { return label }() - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { super.init(coder: coder) } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUserHeaderView.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUserHeaderView.swift index bc25c960..34ba3b5b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUserHeaderView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/ChatUserHeaderView.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ChatUserHeaderView: UIImageView { +open class ChatUserHeaderView: UIImageView { public lazy var titleLabel: UILabel = { let label = UILabel() label.font = DefaultTextFont(12) @@ -20,7 +20,7 @@ public class ChatUserHeaderView: UIImageView { setupUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { super.init(coder: coder) } @@ -36,7 +36,7 @@ public class ChatUserHeaderView: UIImageView { backgroundColor = .clear } - public func setTitle(_ name: String) { + open func setTitle(_ name: String) { titleLabel.text = name .count > 2 ? String(name[name.index(name.endIndex, offsetBy: -2)...]) : name } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/NEChatBaseCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/NEChatBaseCell.swift index 517da2ce..42f8e49d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/NEChatBaseCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseView/NEChatBaseCell.swift @@ -17,9 +17,10 @@ open class NEChatBaseCell: UITableViewCell { fatalError("init(coder:) has not been implemented") } - public func uploadProgress(byRight: Bool, _ progress: Float) { + open func uploadProgress(byRight: Bool, _ progress: Float) { fatalError("override in sub class") } open func setModel(_ model: MessageContentModel) {} + open func setModel(_ model: MessageContentModel, _ isSend: Bool = false) {} } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseViewController/ChatTableViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseViewController/ChatTableViewController.swift index c7af6d83..4bfcb77a 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Base/BaseViewController/ChatTableViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Base/BaseViewController/ChatTableViewController.swift @@ -13,7 +13,7 @@ open class ChatTableViewController: NEBaseViewController, UITableViewDelegate, public var topConstraint: NSLayoutConstraint? public var bottomConstraint: NSLayoutConstraint? - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() tableView.separatorStyle = .none tableView.delegate = self @@ -47,12 +47,12 @@ open class ChatTableViewController: NEBaseViewController, UITableViewDelegate, tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1)) } - public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) } - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 0 } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/ChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/ChatViewController.swift index b70f658b..bc51c77a 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/ChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/ChatViewController.swift @@ -19,7 +19,7 @@ import WebKit open class ChatViewController: ChatBaseViewController, UINavigationControllerDelegate, ChatInputViewDelegate, ChatViewModelDelegate, NIMMediaManagerDelegate, MessageOperationViewDelegate, UITableViewDataSource, - UITableViewDelegate, UIDocumentPickerDelegate, UIDocumentInteractionControllerDelegate, CLLocationManagerDelegate, UITextViewDelegate { + UITableViewDelegate, UIDocumentPickerDelegate, UIDocumentInteractionControllerDelegate, CLLocationManagerDelegate, UITextViewDelegate, ChatInputMultilineDelegate { private let tag = "ChatViewController" private let kCallKitDismissNoti = "kCallKitDismissNoti" private let kCallKitShowNoti = "kCallKitShowNoti" @@ -32,16 +32,16 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel private var playingModel: MessageAudioModel? private var timer: Timer? private var isFile: Bool? // 是否以文件形式发送 - private var isCurrentPage = true + public var isCurrentPage = true + public var isMute = false // 是否禁言 + private var isMutilSelect = false // 是否多选模式 public var operationCellFilter: [OperationType]? // 消息长按菜单全局过滤列表 public var cellRegisterDic = [String: UITableViewCell.Type]() private var needMarkReadMsgs = [NIMMessage]() private var atUsers = [NSRange]() - let group = DispatchGroup() var replyView = ReplyView() -// public var menuView: NEBaseChatInputView! public var operationView: MessageOperationView? public var normalOffset: CGFloat = 0 @@ -62,12 +62,14 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } } - public lazy var bottomViewHeight: CGFloat = 304 { + public lazy var bottomViewHeight: CGFloat = 404 { didSet { bottomViewHeightAnchor?.constant = bottomViewHeight } } + public var currentKeyboardHeight: CGFloat = 0 + public var bodyTopViewHeightAnchor: NSLayoutConstraint? public var bodyBottomViewHeightAnchor: NSLayoutConstraint? public var contentViewTopAnchor: NSLayoutConstraint? @@ -77,12 +79,10 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel public init(session: NIMSession) { viewmodel = ChatViewModel(session: session, anchor: nil) super.init(nibName: nil, bundle: nil) -// menuView = getMenuView() NEKeyboardManager.shared.enable = false NEKeyboardManager.shared.enableAutoToolbar = false NIMSDK.shared().mediaManager.add(self) - NIMSDK.shared().mediaManager.switch(viewmodel.getHandSetEnable() ? .receiver : .speaker) } public required init?(coder: NSCoder) { @@ -129,7 +129,10 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel if NIMSDK.shared().mediaManager.isPlaying() { NIMSDK.shared().mediaManager.stopPlay() } + clearAtRemind() + chatInputView.textView.resignFirstResponder() + chatInputView.titleField.resignFirstResponder() } override open func viewDidDisappear(_ animated: Bool) { @@ -137,9 +140,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel stopPlay() } - open func commonUI() { - title = viewmodel.session.sessionId - navigationView.titleBarBottomLine.isHidden = false + open func setMoreButton() { if NEKitChatConfig.shared.ui.messageProperties.showTitleBarRightIcon { let image = NEKitChatConfig.shared.ui.messageProperties.titleBarRightRes ?? UIImage.ne_imageNamed(name: "three_point") addRightAction(image, #selector(toSetting), self) @@ -147,6 +148,13 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } else { navigationView.moreButton.isHidden = true } + } + + open func commonUI() { + title = viewmodel.session.sessionId + navigationView.titleBarBottomLine.isHidden = false + setMoreButton() + setMutilSelectBottomView() view.addSubview(bodyTopView) view.addSubview(bodyView) @@ -168,28 +176,28 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel bodyTopView.rightAnchor.constraint(equalTo: view.rightAnchor), ]) + bottomViewTopAnchor = bottomView.topAnchor.constraint(equalTo: view.bottomAnchor, constant: -normalInputHeight) + bottomViewTopAnchor?.isActive = true + bottomViewHeightAnchor = bottomView.heightAnchor.constraint(equalToConstant: bottomViewHeight) + bottomViewHeightAnchor?.isActive = true NSLayoutConstraint.activate([ - bodyView.topAnchor.constraint(equalTo: bodyTopView.bottomAnchor), - bodyView.leftAnchor.constraint(equalTo: view.leftAnchor), - bodyView.rightAnchor.constraint(equalTo: view.rightAnchor), - bodyView.bottomAnchor.constraint(equalTo: bodyBottomView.topAnchor), + bottomView.leftAnchor.constraint(equalTo: view.leftAnchor), + bottomView.rightAnchor.constraint(equalTo: view.rightAnchor), ]) bodyBottomViewHeightAnchor = bodyBottomView.heightAnchor.constraint(equalToConstant: bodyBottomViewHeight) bodyBottomViewHeightAnchor?.isActive = true NSLayoutConstraint.activate([ - bodyBottomView.bottomAnchor.constraint(equalTo: chatInputView.topAnchor), + bodyBottomView.bottomAnchor.constraint(equalTo: bottomView.topAnchor), bodyBottomView.leftAnchor.constraint(equalTo: view.leftAnchor), bodyBottomView.rightAnchor.constraint(equalTo: view.rightAnchor), ]) - bottomViewTopAnchor = bottomView.topAnchor.constraint(equalTo: view.bottomAnchor, constant: -normalInputHeight) - bottomViewTopAnchor?.isActive = true - bottomViewHeightAnchor = bottomView.heightAnchor.constraint(equalToConstant: bottomViewHeight) - bottomViewHeightAnchor?.isActive = true NSLayoutConstraint.activate([ - bottomView.leftAnchor.constraint(equalTo: view.leftAnchor), - bottomView.rightAnchor.constraint(equalTo: view.rightAnchor), + bodyView.topAnchor.constraint(equalTo: bodyTopView.bottomAnchor), + bodyView.leftAnchor.constraint(equalTo: view.leftAnchor), + bodyView.rightAnchor.constraint(equalTo: view.rightAnchor), + bodyView.bottomAnchor.constraint(equalTo: bodyBottomView.topAnchor), ]) tableView.register( @@ -214,6 +222,8 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel // MARK: 子类可重写方法 + public func onTeamMemberChange(team: NIMTeam) {} + override open func backEvent() { super.backEvent() cleanDelegate() @@ -253,9 +263,17 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel return } + // 多选模式下屏蔽消息长按事件 + if isMutilSelect { + return + } + // 底部收起 - chatInputView.textView.resignFirstResponder() - layoutInputView(offset: 0) + if chatInputView.textView.isFirstResponder || chatInputView.titleField.isFirstResponder { + chatInputView.textView.resignFirstResponder() + chatInputView.titleField.resignFirstResponder() + layoutInputView(offset: 0) + } operationView?.removeFromSuperview() @@ -283,42 +301,39 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel setOperationItems(items: &filterItems, model: model) viewmodel.operationModel = model - group.notify(queue: .main) { - DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: DispatchWorkItem(block: { [self] in - // size - let w = filterItems.count <= 5 ? 60.0 * Double(filterItems.count) + 16.0 : 60.0 * 5 + 16.0 - let h = filterItems.count <= 5 ? 56.0 + 16.0 : 56.0 * 2 + 16.0 - - if let index = tableView.indexPath(for: cell) { - let rectInTableView = tableView.rectForRow(at: index) - let rectInView = tableView.convert(rectInTableView, to: view) - let topOffset = NEConstant.navigationAndStatusHeight - var operationY = 0.0 - if topOffset + h + bodyTopViewHeight > rectInView.origin.y { - // under the cell - operationY = rectInView.origin.y + rectInView.size.height - } else { - operationY = rectInView.origin.y - h - } - var frameX = 0.0 - if let msg = model?.message, - msg.isOutgoingMsg { - frameX = kScreenWidth - w - } - var frame = CGRect(x: frameX, y: operationY, width: w, height: h) - if frame.origin.y + h < tableView.frame.origin.y { - frame.origin.y = tableView.frame.origin.y - } else if frame.origin.y + h > view.frame.size.height { - frame.origin.y = tableView.frame.origin.y + tableView.frame.size.height - h - } + guard let index = tableView.indexPath(for: cell) else { return } + DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: DispatchWorkItem(block: { [self] in + // size + let w = filterItems.count <= 5 ? 60.0 * Double(filterItems.count) + 16.0 : 60.0 * 5 + 16.0 + let h = filterItems.count <= 5 ? 56.0 + 16.0 : 56.0 * 2 + 16.0 + + let rectInTableView = tableView.rectForRow(at: index) + let rectInView = tableView.convert(rectInTableView, to: view) + let topOffset = NEConstant.navigationAndStatusHeight + var operationY = 0.0 + if topOffset + h + bodyTopViewHeight > rectInView.origin.y { + // under the cell + operationY = rectInView.origin.y + rectInView.size.height + } else { + operationY = rectInView.origin.y - h + } + var frameX = 0.0 + if let msg = model?.message, + msg.isOutgoingMsg { + frameX = kScreenWidth - w + } + var frame = CGRect(x: frameX, y: operationY, width: w, height: h) + if frame.origin.y + h < tableView.frame.origin.y { + frame.origin.y = tableView.frame.origin.y + } else if frame.origin.y + h > view.frame.size.height { + frame.origin.y = tableView.frame.origin.y + tableView.frame.size.height - h + } - operationView = MessageOperationView(frame: frame) - operationView!.delegate = self - operationView!.items = filterItems - view.addSubview(operationView!) - } - })) - } + operationView = MessageOperationView(frame: frame) + operationView!.delegate = self + operationView!.items = filterItems + view.addSubview(operationView!) + })) } // MARK: lazy Method @@ -405,24 +420,40 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.clear - view.addSubview(chatInputView) + view.addSubview(chatInputView) NSLayoutConstraint.activate([ chatInputView.leftAnchor.constraint(equalTo: view.leftAnchor), chatInputView.rightAnchor.constraint(equalTo: view.rightAnchor), - chatInputView.heightAnchor.constraint(equalToConstant: 304), - chatInputView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + chatInputView.heightAnchor.constraint(equalToConstant: 404), + chatInputView.topAnchor.constraint(equalTo: view.topAnchor), + ]) + + view.addSubview(mutilSelectBottomView) + NSLayoutConstraint.activate([ + mutilSelectBottomView.leftAnchor.constraint(equalTo: view.leftAnchor), + mutilSelectBottomView.rightAnchor.constraint(equalTo: view.rightAnchor), + mutilSelectBottomView.heightAnchor.constraint(equalToConstant: 304), + mutilSelectBottomView.topAnchor.constraint(equalTo: view.topAnchor), ]) return view }() public lazy var chatInputView: NEBaseChatInputView = { - let menu = getMenuView() - menu.translatesAutoresizingMaskIntoConstraints = false - menu.backgroundColor = UIColor(hexString: "#EFF1F3") - menu.delegate = self - return menu + let inputView = getMenuView() + inputView.translatesAutoresizingMaskIntoConstraints = false + inputView.backgroundColor = .ne_backgroundColor + inputView.delegate = self + return inputView + }() + + public lazy var mutilSelectBottomView: NEMutilSelectBottomView = { + let view = NEMutilSelectBottomView() + view.translatesAutoresizingMaskIntoConstraints = false + view.delegate = self + view.isHidden = true + return view }() // MARK: UIGestureRecognizerDelegate @@ -433,18 +464,25 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel return true } - // 消息操作按钮 - if view.bounds.size.width == 60 { - return false - } // 点击重发按钮 // 点击撤回重新编辑按钮 if view.isKind(of: UIButton.self) { return false } - if view.isKind(of: UIImageView.self) { + + // 回复消息view + // 已读未读按钮 + // 消息操作按钮(撤回、删除) + // 地图view + // 文件消息图标 + if view.accessibilityIdentifier == "id.replyTextView" || + view.accessibilityIdentifier == "id.readView" || + view.accessibilityIdentifier == "id.menuCell" || + view.accessibilityIdentifier == "id.mapView" || + view.accessibilityIdentifier == "id.fileStatus" { return false } + return true } @@ -476,7 +514,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } deinit { - print("will deinit") + NELog.infoLog(className(), desc: "deinit") cleanDelegate() } @@ -487,7 +525,54 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel // MARK: objc 方法 - override open func toSetting() {} + func getUserSettingViewController() -> NEBaseUserSettingViewController { + UserSettingViewController(userId: viewmodel.session.sessionId) + } + + /// 设置按钮点击事件 + override open func toSetting() { + // 自定义设置按钮点击事件 + if let block = NEKitChatConfig.shared.ui.messageProperties.titleBarRightClick { + block() + return + } + + // 多选模式下屏蔽设置按钮点击事件 + if isMutilSelect { + return + } + + if viewmodel.session.sessionType == .team { + Router.shared.use( + TeamSettingViewRouter, + parameters: ["nav": navigationController as Any, + "teamid": viewmodel.session.sessionId], + closure: nil + ) + } else if viewmodel.session.sessionType == .P2P { + let userSetting = getUserSettingViewController() + navigationController?.pushViewController(userSetting, animated: true) + } + } + + open func viewTap(tap: UITapGestureRecognizer) { + if isMutilSelect { + return + } + + if let opeView = operationView, + view.subviews.contains(opeView) { + opeView.removeFromSuperview() + + } else { + if chatInputView.textView.isFirstResponder || chatInputView.titleField.isFirstResponder { + chatInputView.textView.resignFirstResponder() + chatInputView.titleField.resignFirstResponder() + } else { + layoutInputView(offset: 0) + } + } + } // MARK: private 方法 @@ -501,10 +586,9 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel ) if let ms = weakSelf?.viewmodel.messages, ms.count > 0 { - weakSelf?.tableView.reloadData() + weakSelf?.didRefreshTable() if weakSelf?.viewmodel.isHistoryChat == true { let indexPath = IndexPath(row: index, section: 0) - print("queryRoamMsgHasMoreTime_v2 index : ", index) weakSelf?.tableView.scrollToRow(at: indexPath, at: .middle, animated: false) if newEnd > 0 { weakSelf?.addBottomLoadMore() @@ -520,7 +604,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } } else if let err = error { - weakSelf?.showToast(err.localizedDescription) + weakSelf?.showErrorToast(err) } weakSelf?.loadDataFinish() } @@ -533,7 +617,6 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel ModuleName + " " + self.tag, desc: #function + "CALLBACK dropDownRemoteRefresh " + (error?.localizedDescription ?? "no error") ) - print("dropDownRemoteRefresh messages count ", messages?.count as Any) weakSelf?.tableView.reloadData() if count > 0 { @@ -566,10 +649,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } func addObseve() { - NotificationCenter.default.addObserver(self, - selector: #selector(markNeedReadMsg), - name: UIApplication.willEnterForegroundNotification, - object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(didRefreshTable), name: NENotificationName.updateFriendInfo, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, @@ -627,11 +707,15 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel func appEnterForegournd() { isCurrentPage = true + markNeedReadMsg() } // MARK: 键盘通知相关操作 open func keyBoardWillShow(_ notification: Notification) { + if !isCurrentPage { + return + } operationView?.removeFromSuperview() if chatInputView.currentType != .text { return @@ -644,9 +728,14 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel let keyboardRect = (notification .userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue + var animationDuration: TimeInterval = 0.1 + + if let userInfo = notification.userInfo, + let keyboardAnimationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval { + animationDuration = keyboardAnimationDuration + } - print("chat view key board size : ", keyboardRect) - layoutInputView(offset: keyboardRect.size.height) + layoutInputViewWithAnimation(offset: keyboardRect.size.height, animationDuration) weak var weakSelf = self UIView.animate(withDuration: 0.25, animations: { weakSelf?.view.layoutIfNeeded() @@ -665,16 +754,18 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel return } chatInputView.currentButton?.isSelected = false - // 解决点击operation点击无效问题 -// if operationView?.superview != nil { -// operationView?.removeFromSuperview() -// } - layoutInputView(offset: 0) + var animationDuration: TimeInterval = 0.1 + + if let userInfo = notification.userInfo, + let keyboardAnimationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval { + animationDuration = keyboardAnimationDuration + } + layoutInputViewWithAnimation(offset: 0, animationDuration) } private func scrollTableViewToBottom() { - print("self.viewmodel.messages.count\(viewmodel.messages.count)") - print("self.tableView.numberOfRows(inSection: 0)\(tableView.numberOfRows(inSection: 0))") + NELog.infoLog(className(), desc: "self.viewmodel.messages.count\(viewmodel.messages.count)") + NELog.infoLog(className(), desc: "self.tableView.numberOfRows(inSection: 0)\(tableView.numberOfRows(inSection: 0))") if viewmodel.messages.count > 0 { weak var weakSelf = self DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: DispatchWorkItem(block: { @@ -687,16 +778,21 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } open func layoutInputView(offset: CGFloat) { - print("layoutInputView offset : ", offset) - print("normalOffset : ", normalOffset) - print("normalInputHeight : ", normalInputHeight) + layoutInputViewWithAnimation(offset: offset) + } + + open func layoutInputViewWithAnimation(offset: CGFloat, _ animation: CGFloat = 0.1) { + NELog.infoLog(className(), desc: "normal height : \(normalInputHeight) normal offset: \(normalOffset) offset : \(offset)") weak var weakSelf = self - let topValue = normalInputHeight - normalOffset + var topValue = normalInputHeight + if chatInputView.chatInpuMode != .multipleReturn { + topValue -= normalOffset + } if offset == 0 { chatInputView.contentSubView?.isHidden = true chatInputView.currentButton?.isSelected = false } - UIView.animate(withDuration: 0.1, animations: { + UIView.animate(withDuration: animation, animations: { weakSelf?.bottomViewTopAnchor?.constant = -topValue - offset }) } @@ -704,6 +800,64 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel // MARK: ChatInputViewDelegate open func sendText(text: String?, attribute: NSAttributedString?) { + if let title = chatInputView.titleField.text, title.trimmingCharacters(in: .whitespaces).isEmpty == false { + // 换行消息 + NELog.infoLog(className(), desc: "换行消息: \(title)") + var dataDic = [String: Any]() + dataDic["title"] = title + if let t = text?.trimmingCharacters(in: .whitespacesAndNewlines), !t.isEmpty { + dataDic["body"] = text + } + + var attachDic = [String: Any]() + attachDic["type"] = customRichTextType + attachDic["data"] = dataDic + + let attachment = NECustomAttachment(customType: customRichTextType, data: attachDic) + let remoteExt = chatInputView.getRemoteExtension(attribute) + + weak var weakSelf = self + if viewmodel.isReplying, let msg = viewmodel.operationModel?.message { + viewmodel.replyMessageWithoutThread(message: + MessageUtils.customMessage(attachment: attachment, + remoteExt: remoteExt, + apnsContent: title), + target: msg) { [weak self] error in + NELog.infoLog( + ModuleName + " " + (self?.tag ?? "ChatViewController"), + desc: #function + "CALLBACK replyMessage " + (error?.localizedDescription ?? "no error") + ) + if error != nil { + weakSelf?.showErrorToast(error) + } else { + weakSelf?.closeReply(button: nil) + } + self?.chatInputView.titleField.text = nil + self?.chatInputView.textView.text = nil + self?.didSendFinishAndCheckoutInput() + } + } else { + viewmodel.sendCustomMessage(attachment: attachment, + remoteExt: remoteExt, + apnsConstent: title) { [weak self] error in + self?.showErrorToast(error) + self?.chatInputView.titleField.text = nil + self?.chatInputView.textView.text = nil + self?.didSendFinishAndCheckoutInput() + } + } + } else { + // 文本消息 + sendContentText(text: text, attribute: attribute) + } + } + + func sendContentText(text: String?, attribute: NSAttributedString?) { + guard let removeSpace = text?.trimmingCharacters(in: .whitespaces), removeSpace.count > 0 else { + chatInputView.titleField.text = nil + showToast(chatLocalizable("null_message_not_support")) + return + } guard let content = text, content.count > 0 else { return } @@ -717,10 +871,11 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel desc: #function + "CALLBACK replyMessage " + (error?.localizedDescription ?? "no error") ) if error != nil { - weakSelf?.view.makeToast(error?.localizedDescription) + weakSelf?.showErrorToast(error) } else { weakSelf?.closeReply(button: nil) } + weakSelf?.didSendFinishAndCheckoutInput() } } else { @@ -729,9 +884,10 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel ModuleName + " " + (self?.tag ?? "ChatViewController"), desc: #function + "CALLBACK sendTextMessage " + (error?.localizedDescription ?? "no error") ) - if error != nil { - weakSelf?.view.makeToast(error?.localizedDescription) - } + weakSelf?.showErrorToast(error) + self?.chatInputView.titleField.text = nil + self?.chatInputView.textView.text = nil + self?.didSendFinishAndCheckoutInput() } } } @@ -817,9 +973,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel ctrl.completion = { model in NELog.infoLog(self.className(), desc: "position : \(model.yx_modelToJSONString() ?? "")") weakSelf?.viewmodel.sendLocationMessage(model) { error in - if let err = error { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.showErrorToast(error) } } } @@ -893,23 +1047,41 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel return true } - open func textFieldDidChange(_ textField: UITextView) { - if let text = textField.text { - if text.count > 0 { + open func textFieldDidEndEditing(_ text: String?) { + viewmodel.sendInputTypingEndState() + } + + open func textFieldDidBeginEditing(_ text: String?) { + checkAndSendTypingState() + } + + open func textFieldDidChange(_ text: String?) { + checkAndSendTypingState() + } + + func checkAndSendTypingState() { + if chatInputView.chatInpuMode == .normal { + if let content = chatInputView.textView.text, content.count > 0 { viewmodel.sendInputTypingState() } else { viewmodel.sendInputTypingEndState() } - } - } + } else { + var title = "" + var content = "" - open func textFieldDidEndEditing(_ textField: UITextView) { - viewmodel.sendInputTypingEndState() - } + if let titleText = chatInputView.titleField.text { + title = titleText + } - open func textFieldDidBeginEditing(_ textField: UITextView) { - if let count = textField.text?.count, count > 0 { - viewmodel.sendInputTypingState() + if let contentText = chatInputView.textView.text { + content = contentText + } + if title.count <= 0, content.count <= 0 { + viewmodel.sendInputTypingEndState() + } else { + viewmodel.sendInputTypingState() + } } } @@ -920,7 +1092,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel open func willSelectItem(button: UIButton?, index: Int) { operationView?.removeFromSuperview() - if button?.isSelected == true { + if index == 2 || button?.isSelected == true { if index == 0 { // 语音 layoutInputView(offset: bottomExanpndHeight) @@ -1023,9 +1195,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel ModuleName + " " + (weakSelf?.tag ?? "ChatViewController"), desc: #function + "CALLBACK sendVideoMessage " + (error?.localizedDescription ?? "no error") ) - if let err = error { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.showErrorToast(error) } } return @@ -1054,6 +1224,49 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } } } else { + if let url = info[.referenceURL] as? URL { + if url.absoluteString.hasSuffix("ext=GIF") == true { + // GIF 需要特殊处理 + let imageAsset: PHAsset? + if #available(iOS 11.0, *) { + imageAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset + } else { + imageAsset = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil).firstObject + } + let options = PHImageRequestOptions() + options.version = .current + guard let asset = imageAsset else { + return + } + weak var weakSelf = self + PHImageManager.default().requestImageData(for: asset, options: options) { imageData, dataUTI, orientation, info in + if let data = imageData { + let tempDirectoryURL = FileManager.default.temporaryDirectory + let uniqueString = UUID().uuidString + let temUrl = tempDirectoryURL.appendingPathComponent(uniqueString + ".gif") + print("tem url path : ", temUrl.path) + do { + try data.write(to: temUrl) + DispatchQueue.main.async { + weakSelf?.viewmodel.sendImageMessage(path: temUrl.path) { error in + NELog.infoLog( + ModuleName + " " + (weakSelf?.tag ?? "ChatViewController"), + desc: #function + "CALLBACK sendImageMessage " + (error?.localizedDescription ?? "no error") + ) + if error != nil { + weakSelf?.view.makeToast(error?.localizedDescription) + } + } + } + } catch { + NELog.infoLog(ModuleName, desc: #function + "write tem gif data error : \(error.localizedDescription)") + } + } + } + return + } + } + viewmodel.sendImageMessage(image: image) { [weak self] error in NELog.infoLog( ModuleName + " " + (self?.tag ?? "ChatViewController"), @@ -1071,8 +1284,6 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController .InfoKey: Any]) { -// picker.dismiss(animated: true, completion: nil) -// sendMediaMessage(didFinishPickingMediaWithInfo: info) weak var weakSelf = self picker.dismiss(animated: true, completion: { weakSelf?.sendMediaMessage(didFinishPickingMediaWithInfo: info) @@ -1211,6 +1422,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel if atIndexs.isEmpty { return } + viewmodel.selectedMessages.removeAll(where: { $0.messageId == message.messageId }) operationView?.removeFromSuperview() tableViewDeleteIndexs(atIndexs) DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: DispatchWorkItem(block: { [weak self] in @@ -1226,6 +1438,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel if atIndexs.isEmpty { return } + viewmodel.selectedMessages.removeAll(where: { $0.messageId == message.messageId }) operationView?.removeFromSuperview() NELog.infoLog(className(), desc: "on revoke message at indexs \(atIndexs)") tableViewReloadIndexs(atIndexs) @@ -1256,6 +1469,12 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel tableView.reloadRows(at: indexs, with: .none) tableView.endUpdates() } + + indexs.forEach { index in + if index.row == tableView.numberOfRows(inSection: 0) - 1 { + tableView.scrollToRow(at: index, at: .bottom, animated: true) + } + } } open func didReadedMessageIndexs() { @@ -1275,11 +1494,12 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } open func didRefreshTable() { - group.enter() - DispatchQueue.main.async { [weak self] in - self?.tableView.reloadData() - self?.group.leave() - } + getSessionInfo(session: viewmodel.session) + tableView.reloadData() + } + + open func selectedMessagesChanged(_ count: Int) { + mutilSelectBottomView.setEnable(count > 0) } // record audio @@ -1314,31 +1534,26 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } } - open func viewTap(tap: UITapGestureRecognizer) { - if let opeView = operationView, - view.subviews.contains(opeView) { - opeView.removeFromSuperview() - - } else { - if chatInputView.textView.isFirstResponder { - chatInputView.textView.resignFirstResponder() - } else { - layoutInputView(offset: 0) - } - } - } - // MARK: audio play - func startPlaying(audio: NIMAudioObject, isSend: Bool) { + func startPlaying(audioMessage: NIMMessage?, isSend: Bool) { + guard let message = audioMessage, let audio = message.messageObject as? NIMAudioObject else { + return + } playingCell?.startAnimation(byRight: isSend) - if let url = audio.path { + if let path = audio.path, FileManager.default.fileExists(atPath: path) { + NELog.infoLog(className(), desc: #function + " play path : " + path) + if viewmodel.getHandSetEnable() == true { NIMSDK.shared().mediaManager.switch(.receiver) } else { NIMSDK.shared().mediaManager.switch(.speaker) } - NIMSDK.shared().mediaManager.play(url) + NIMSDK.shared().mediaManager.play(path) + } else { + NELog.infoLog(className(), desc: #function + " audio path is empty, play url : " + (audio.url ?? "")) + playingCell?.stopAnimation(byRight: isSend) + ChatMessageHelper.downloadAudioFile(message: message) } } @@ -1351,17 +1566,17 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel if NIMSDK.shared().mediaManager.isPlaying() { stopPlay() } else { - startPlaying(audio: audio, isSend: isSend) + startPlaying(audioMessage: model?.message, isSend: isSend) } } else { stopPlay() playingCell = cell playingModel = model - startPlaying(audio: audio, isSend: isSend) + startPlaying(audioMessage: model?.message, isSend: isSend) } } - public func stopPlay() { + open func stopPlay() { if NIMSDK.shared().mediaManager.isPlaying() { playingCell?.startAnimation(byRight: playingModel?.message?.isOutgoingMsg ?? true) NIMSDK.shared().mediaManager.stopPlay() @@ -1379,9 +1594,10 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel // play open func playAudio(_ filePath: String, didBeganWithError error: Error?) { - print(#function + "\(error)") + print(#function + "\(error?.localizedDescription ?? "")") + NIMSDK.shared().mediaManager.switch(viewmodel.getHandSetEnable() ? .receiver : .speaker) if let e = error { - showToast(e.localizedDescription) + showErrorToast(error) // stop playingCell?.stopAnimation(byRight: playingModel?.message?.isOutgoingMsg ?? true) playingModel?.isPlaying = false @@ -1389,20 +1605,16 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } open func playAudio(_ filePath: String, didCompletedWithError error: Error?) { - print(#function + "\(error)") - if let e = error { - showToast(e.localizedDescription) - } + print(#function + "\(error?.localizedDescription ?? "")") + showErrorToast(error) // stop playingCell?.stopAnimation(byRight: playingModel?.message?.isOutgoingMsg ?? true) playingModel?.isPlaying = false } open func stopPlayAudio(_ filePath: String, didCompletedWithError error: Error?) { - print(#function + "\(error)") - if let e = error { - showToast(e.localizedDescription) - } + print(#function + "\(error?.localizedDescription ?? "")") + showErrorToast(error) playingCell?.stopAnimation(byRight: playingModel?.message?.isOutgoingMsg ?? true) playingModel?.isPlaying = false } @@ -1422,16 +1634,16 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel playingModel?.isPlaying = false } - // record + // record open func recordAudio(_ filePath: String?, didBeganWithError error: Error?) { - print("[record] sdk Began error:\(error)") + print("[record] sdk Began error:\(error?.localizedDescription ?? "")") } open func recordAudio(_ filePath: String?, didCompletedWithError error: Error?) { - print("[record] sdk Completed error:\(error)") + print("[record] sdk Completed error:\(error?.localizedDescription ?? "")") chatInputView.stopRecordAnimation() guard let fp = filePath else { - showToast(error?.localizedDescription ?? "") + showErrorToast(error) return } let dur = recordDuration(filePath: fp) @@ -1443,9 +1655,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel ModuleName + " " + self.tag, desc: #function + "CALLBACK sendAudioMessage " + (error?.localizedDescription ?? "no error") ) - if let e = error { - self.showToast(e.localizedDescription) - } else {} + self.showErrorToast(error) } } else { showToast(chatLocalizable("record_too_short")) @@ -1563,7 +1773,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel var addText = "" var accid = "" - if index == 0 { + if model == nil { addText += chatLocalizable("user_select_all") } else { if let m = model { @@ -1579,6 +1789,17 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel present(selectVC, animated: true, completion: nil) } + private func showErrorToast(_ error: Error?) { + if let err = error as? NSError { + switch err.code { + case noNetworkCode: + showToast(commonLocalizable("network_error")) + default: + showToast(err.localizedDescription) + } + } + } + // MARK: MessageOperationViewDelegate open func didSelectedItem(item: OperationItem) { @@ -1593,7 +1814,9 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel case .delete: deleteMessage() case .reply: - showReplyMessageView() + if !isMute { + showReplyMessageView() + } case .recall: recallMessage() case .collection: @@ -1604,6 +1827,8 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel pinMessage() case .removePin: removePinMessage() + case .multiSelect: + selectMessage() default: customOperation() } @@ -1612,37 +1837,44 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel open func customOperation() {} open func copyMessage() { - if let model = viewmodel.operationModel as? MessageTextModel, - let text = model.message?.text { - let pasteboard = UIPasteboard.general - pasteboard.string = text - view.makeToast(chatLocalizable("copy_success"), duration: 2, position: .center) + if let model = viewmodel.operationModel as? MessageTextModel { + if let text = model.message?.text, !text.isEmpty { + UIPasteboard.general.string = text + showToast(chatLocalizable("copy_success")) + } else if let body = model.attributeStr?.string, !body.isEmpty { + UIPasteboard.general.string = body + showToast(chatLocalizable("copy_success")) + } else if let model = viewmodel.operationModel as? MessageRichTextModel { + if let title = model.titleAttributeStr?.string, !title.isEmpty { + UIPasteboard.general.string = title + showToast(chatLocalizable("copy_success")) + } + } } } open func deleteMessage() { showAlert(message: chatLocalizable("message_delete_confirm")) { - if let message = self.viewmodel.operationModel?.message { - self.viewmodel.deleteMessage(message: message) { error in - if error != nil { - self.showToast(chatLocalizable("delete_failed")) - } - } + self.viewmodel.deleteMessage { error in + self.showErrorToast(error) } } } open func showReplyMessageView(isReEdit: Bool = false) { viewmodel.isReplying = true - view.addSubview(replyView) - replyView.closeButton.addTarget(self, action: #selector(closeReply), for: .touchUpInside) - replyView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - replyView.leadingAnchor.constraint(equalTo: chatInputView.leadingAnchor), - replyView.trailingAnchor.constraint(equalTo: chatInputView.trailingAnchor), - replyView.bottomAnchor.constraint(equalTo: chatInputView.topAnchor), - replyView.heightAnchor.constraint(equalToConstant: 36), - ]) + if chatInputView.chatInpuMode != .multipleReturn { + view.addSubview(replyView) + replyView.closeButton.addTarget(self, action: #selector(closeReply), for: .touchUpInside) + replyView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + replyView.leadingAnchor.constraint(equalTo: chatInputView.leadingAnchor), + replyView.trailingAnchor.constraint(equalTo: chatInputView.trailingAnchor), + replyView.bottomAnchor.constraint(equalTo: chatInputView.topAnchor), + replyView.heightAnchor.constraint(equalToConstant: 36), + ]) + } + if let message = viewmodel.operationModel?.message { if isReEdit { replyView.textLabel.attributedText = NEEmotionTool.getAttWithStr(str: viewmodel.operationModel?.replyText ?? "", @@ -1654,38 +1886,18 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } else { var text = chatLocalizable("msg_reply") if let uid = message.from { - var showName = viewmodel.getShowName(userId: uid, teamId: viewmodel.session.sessionId, false) + var showName = ChatUserCache.getShowName(userId: uid, teamId: viewmodel.session.sessionId, false) if viewmodel.session.sessionType != .P2P, !IMKitClient.instance.isMySelf(uid) { addToAtUsers(addText: "@" + showName + "", isReply: true, accid: uid) } let user = viewmodel.getUserInfo(userId: uid) - if let alias = user?.alias { + if let alias = user?.alias, !alias.isEmpty { showName = alias } text += " " + showName } - text += ": " - switch message.messageType { - case .text: - if let t = message.text { - text += t - } - case .image: - text += "[\(chatLocalizable("msg_image"))]" - case .audio: - text += "[\(chatLocalizable("msg_audio"))]" - case .video: - text += "[\(chatLocalizable("msg_video"))]" - case .file: - text += "[\(chatLocalizable("msg_file"))]" - case .location: - text += "[\(chatLocalizable("msg_location"))]" - case .custom: - text += "[\(chatLocalizable("msg_custom"))]" - default: - text += "[\(chatLocalizable("msg_unknown"))]" - } + text += ": \(ChatMessageHelper.contentOfMessage(message))" replyView.textLabel.attributedText = NEEmotionTool.getAttWithStr(str: text, font: replyView.textLabel.font, color: replyView.textLabel.textColor) @@ -1703,12 +1915,15 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel weak var weakSelf = self showAlert(message: chatLocalizable("message_revoke_confirm")) { if let message = weakSelf?.viewmodel.operationModel?.message { - if let messageType = weakSelf?.viewmodel.operationModel?.message?.messageType, messageType == .text { + if message.messageType == .text { weakSelf?.viewmodel.operationModel?.isRevokedText = true } -// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(120)) { -// weakSelf?.tableView.reloadData() -// } + + if message.messageType == .custom, + let attach = NECustomAttachment.attachmentOfCustomMessage(message: message), attach.customType == customRichTextType { + weakSelf?.viewmodel.operationModel?.isRevokedText = true + } + let isPin = weakSelf?.viewmodel.operationModel?.isPined ?? false weakSelf?.viewmodel.revokeMessage(message: message) { error in NELog.infoLog( @@ -1716,12 +1931,10 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel desc: #function + "CALLBACK revokeMessage " + (error?.localizedDescription ?? "no error") ) if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(chatLocalizable("ravoked_failed")) - } else if err.code == 508 { + if err.code == 508 { weakSelf?.showToast(chatLocalizable("ravokable_time_expired")) } else { - weakSelf?.showToast(err.localizedDescription) + weakSelf?.showToast(chatLocalizable("ravoked_failed")) } } else { // 自己撤回成功 & 收到对方撤回 都会走回调方法 onRevokeMessage @@ -1750,7 +1963,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel desc: #function + "CALLBACK addColletion " + (error?.localizedDescription ?? "no error") ) if error != nil { - self.showToast(error!.localizedDescription) + self.showErrorToast(error) } else { self.showToast(chatLocalizable("collection_success")) } @@ -1762,10 +1975,28 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel NEBaseForwardAlertViewController() } - func forwardMessageToUser(message: NIMMessage) { + func addForwardAlertController(items: [ForwardItem], + type: String, + _ sureBlock: ((String?) -> Void)? = nil) { + let forwardAlert = getForwardAlertController() + forwardAlert.setItems(items) + forwardAlert.type = type + forwardAlert.context = ChatMessageHelper.getSessionName(session: viewmodel.session) + forwardAlert.sureBlock = sureBlock + + addChild(forwardAlert) + view.addSubview(forwardAlert.view) + + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: DispatchWorkItem(block: { + UIApplication.shared.keyWindow?.endEditing(true) + })) + } + + func forwardMessageToUser(isMultiForward: Bool = false, + depth: Int = 0, + _ sureBlock: (() -> Void)? = nil) { weak var weakSelf = self Router.shared.register(ContactSelectedUsersRouter) { param in - print("user setting accids : ", param) var items = [ForwardItem]() if let users = param["im_user"] as? [NIMUser] { @@ -1773,40 +2004,40 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel let item = ForwardItem() item.uid = user.userId item.avatar = user.userInfo?.avatarUrl - item.name = user.userInfo?.nickName + item.name = user.getShowName() items.append(item) } - let forwardAlert = weakSelf?.getForwardAlertController() ?? NEBaseForwardAlertViewController() - forwardAlert.setItems(items) - if let senderName = message.senderName { - forwardAlert.context = senderName - } - weakSelf?.addChild(forwardAlert) - weakSelf?.view.addSubview(forwardAlert.view) - - DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: DispatchWorkItem(block: { - UIApplication.shared.keyWindow?.endEditing(true) - })) + let type = isMultiForward ? chatLocalizable("select_multi") : + (weakSelf?.isMutilSelect == true ? chatLocalizable("select_per_item") : chatLocalizable("operation_forward")) + weakSelf?.addForwardAlertController(items: items, type: type) { comment in + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + weakSelf?.showToast(commonLocalizable("network_error")) + return + } - forwardAlert.sureBlock = { - print("sure click ") - weakSelf?.viewmodel.forwardUserMessage(message, users) + weakSelf?.viewmodel.forwardUserMessage(users, isMultiForward, depth, comment) { error in + if let err = error as? NSError { + if err.code != 0 { + weakSelf?.showErrorToast(err) + } + } else { + sureBlock?() + } + } } } } + var param = [String: Any]() param["nav"] = weakSelf?.navigationController as Any param["limit"] = 6 - if let session = weakSelf?.viewmodel.session, session.sessionType == .P2P { - var filters = Set() - filters.insert(session.sessionId) - param["filters"] = filters - } Router.shared.use(ContactUserSelectRouter, parameters: param, closure: nil) } - func forwardMessageToTeam(message: NIMMessage) { + func forwardMessageToTeam(isMultiForward: Bool = false, + depth: Int = 0, + _ sureBlock: (() -> Void)? = nil) { weak var weakSelf = self Router.shared.register(ContactTeamDataRouter) { param in if let team = param["team"] as? NIMTeam { @@ -1815,19 +2046,24 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel item.name = team.getShowName() item.uid = team.teamId - let forwardAlert = weakSelf!.getForwardAlertController() - forwardAlert.setItems([item]) - if let senderName = message.senderName { - forwardAlert.context = senderName - } - forwardAlert.sureBlock = { - weakSelf?.viewmodel.forwardTeamMessage(message, team) + let type = isMultiForward ? chatLocalizable("select_multi") : + (weakSelf?.isMutilSelect == true ? chatLocalizable("select_per_item") : chatLocalizable("operation_forward")) + weakSelf?.addForwardAlertController(items: [item], type: type) { comment in + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + weakSelf?.showToast(commonLocalizable("network_error")) + return + } + + weakSelf?.viewmodel.forwardTeamMessage(team, isMultiForward, depth, comment) { error in + if let err = error as? NSError { + if err.code != 0 { + weakSelf?.showErrorToast(err) + } + } else { + sureBlock?() + } + } } - weakSelf?.addChild(forwardAlert) - weakSelf?.view.addSubview(forwardAlert.view) - DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: DispatchWorkItem(block: { - UIApplication.shared.keyWindow?.endEditing(true) - })) } } @@ -1841,25 +2077,8 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel open func forwardMessage() { if let message = viewmodel.operationModel?.message { - if IMKitClient.instance.getConfigCenter().teamEnable { - weak var weakSelf = self - let userAction = UIAlertAction(title: chatLocalizable("contact_user"), - style: .default) { action in - weakSelf?.forwardMessageToUser(message: message) - } - - let teamAction = UIAlertAction(title: chatLocalizable("team"), style: .default) { action in - weakSelf?.forwardMessageToTeam(message: message) - } - - let cancelAction = UIAlertAction(title: chatLocalizable("cancel"), - style: .cancel) { action in - } - - showActionSheet([teamAction, userAction, cancelAction]) - } else { - forwardMessageToUser(message: message) - } + viewmodel.selectedMessages = [message] + didClickSingleForwardButton() } } @@ -1877,7 +2096,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel desc: #function + "CALLBACK pinMessage " + (error?.localizedDescription ?? "no error") ) if let err = error as? NSError { - if err.code == 408 { + if err.code == noNetworkCode { self?.view.makeToast(commonLocalizable("network_error"), position: .center) } else { self?.view.makeToast(error?.localizedDescription, position: .center) @@ -1906,7 +2125,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel if let err = error as? NSError { if err.code == 404 { return - } else if err.code == 408 { + } else if err.code == noNetworkCode { self?.view.makeToast(commonLocalizable("network_error"), position: .center) } else { self?.view.makeToast(error?.localizedDescription, position: .center) @@ -1921,6 +2140,38 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } } + open func selectMessage() { + isMutilSelect = true + if let model = viewmodel.operationModel, let msg = model.message { + model.isSelected = true + viewmodel.selectedMessages = [msg] + } + + navigationView.setMoreButtonTitle(chatLocalizable("cancel")) + navigationView.moreButton.setTitleColor(.ne_darkText, for: .normal) + navigationView.addMoreButtonTarget(target: self, selector: #selector(cancelMutilSelect)) + setInputView(edit: false) + tableView.reloadData() + } + + func cancelMutilSelect() { + isMutilSelect = false + viewmodel.selectedMessages.removeAll() + viewmodel.messages.forEach { model in + model.isSelected = false + } + setMoreButton() + setInputView(edit: true) + tableView.reloadData() + } + + // edit: 是否显示输入框 + func setInputView(edit: Bool) { + bottomViewTopAnchor?.constant = edit ? -normalInputHeight : -100 + chatInputView.isHidden = !edit + mutilSelectBottomView.isHidden = edit + } + // MARK: UITableViewDataSource, UITableViewDelegate open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -1931,16 +2182,34 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + guard indexPath.row < viewmodel.messages.count else { return NEBaseChatMessageCell() } let model = viewmodel.messages[indexPath.row] var reuseId = "" if model.replyedModel?.isReplay == true, model.isRevoked == false { - reuseId = "\(MessageType.reply.rawValue)" + if model.replyedModel?.message?.serverID == nil || + model.replyedModel?.message?.serverID.isEmpty == true { + if let message = model.message { + model.replyedModel = viewmodel.getReplyMessageWithoutThread(message: message) + } + } + + if let attch = NECustomAttachment.attachmentOfCustomMessage(message: model.message), + attch.customType == customRichTextType { + reuseId = "\(MessageType.richText.rawValue)" + } else { + reuseId = "\(MessageType.reply.rawValue)" + } } else { let key = "\(model.type.rawValue)" - if model.type == .custom, let object = model.message?.messageObject as? NIMCustomObject, let custom = object.attachment as? NECustomAttachmentProtocol { - if cellRegisterDic["\(custom.customType)"] != nil { - reuseId = "\(custom.customType)" + if model.type == .custom, + let attch = NECustomAttachment.attachmentOfCustomMessage(message: model.message) { + if attch.customType == customMultiForwardType { + reuseId = "\(MessageType.multiForward.rawValue)" + } else if attch.customType == customRichTextType { + reuseId = "\(MessageType.richText.rawValue)" + } else if NEChatUIKitClient.instance.getRegisterCustomCell()["\(attch.customType)"] != nil { + reuseId = "\(attch.customType)" } else { reuseId = "\(NEBaseChatMessageCell.self)" } @@ -1956,7 +2225,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel let cell = tableView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) if let c = cell as? NEBaseChatMessageTipCell { if let m = model as? MessageTipsModel { - m.resetNotiText() + m.setText() c.setModel(m) } return c @@ -1965,16 +2234,17 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel if let m = model as? MessageContentModel { // 更新好友昵称、头像 if let from = model.message?.from, - let user = viewmodel.newUserInfoDic[from] { + let user = ChatUserCache.getUserInfo(from) { if let uid = user.userId, viewmodel.session.sessionType == .team || viewmodel.session.sessionType == .superTeam { - m.fullName = viewmodel.getShowName(userId: uid, teamId: viewmodel.session.sessionId) - m.shortName = viewmodel.getShortName(name: user.showName(false) ?? "", length: 2) + m.fullName = ChatUserCache.getShowName(userId: uid, teamId: viewmodel.session.sessionId) + m.shortName = ChatUserCache.getShortName(name: user.showName(false) ?? "", length: 2) } m.avatar = user.userInfo?.avatarUrl } - c.setModel(m) + c.setModel(m, m.message?.isOutgoingMsg ?? false) + c.setSelect(m, isMutilSelect) } if let audioCell = cell as? ChatAudioCellProtocol, @@ -1988,7 +2258,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel return c } else if let c = cell as? NEChatBaseCell, let m = model as? MessageContentModel { - c.setModel(m) + c.setModel(m, m.message?.isOutgoingMsg ?? false) return cell } else { return NEBaseChatMessageCell() @@ -1996,6 +2266,23 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + guard indexPath.row < viewmodel.messages.count else { return } + if isMutilSelect { + if indexPath.row < viewmodel.messages.count { + let model = viewmodel.messages[indexPath.row] + if !model.isRevoked, + let cell = tableView.cellForRow(at: indexPath) as? NEBaseChatMessageCell { + model.isSelected = !model.isSelected + cell.seletedBtn.isSelected = model.isSelected + viewmodel.selectedMessages.removeAll(where: { $0.messageId == model.message?.messageId }) + if model.isSelected, let msg = model.message { + viewmodel.selectedMessages.append(msg) + } + } + } + return + } + operationView?.removeFromSuperview() if chatInputView.textView.isFirstResponder { chatInputView.textView.resignFirstResponder() @@ -2006,13 +2293,13 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { - let m = viewmodel.messages[indexPath.row] - if m.type == .custom { - if let object = m.message?.messageObject as? NIMCustomObject, let custom = object.attachment as? NECustomAttachmentProtocol { - return custom.cellHeight - } + guard indexPath.row < viewmodel.messages.count else { return 0 } + let model = viewmodel.messages[indexPath.row] + if let m = model as? MessageTipsModel { + m.commonInit() } - return m.cellHeight() + + return model.cellHeight() + chat_content_margin } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { @@ -2025,7 +2312,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel // MARK: UIScrollViewDelegate - public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { operationView?.removeFromSuperview() } @@ -2066,12 +2353,42 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel // print(error) // } - func getTextViewController(text: String) -> TextViewController { - let textViewController = TextViewController(content: text) + func getTextViewController(title: String?, body: String?) -> TextViewController { + let textViewController = TextViewController(title: title, body: body) textViewController.view.backgroundColor = .white return textViewController } + // MARK: OVERRIDE + + open func getMenuView() -> NEBaseChatInputView { + NEBaseChatInputView() + } + + open func setMutilSelectBottomView() { + mutilSelectBottomView.backgroundColor = .ne_backgroundColor + } + + open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + MultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } + + open func expandMoreAction() { + chatInputView.chatAddMoreView.configData(data: NEChatUIKitClient.instance.getMoreActionData(sessionType: viewmodel.session.sessionType)) + } + + open func showTextViewController(_ model: MessageContentModel?) { + let title = NECustomAttachment.titleOfRichText(message: model?.message) + let body = NECustomAttachment.bodyOfRichText(message: model?.message) ?? model?.message?.text + let textView = getTextViewController(title: title, body: body) + textView.modalPresentationStyle = .fullScreen + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: DispatchWorkItem(block: { [weak self] in + self?.navigationController?.present(textView, animated: false) + })) + } + open func didTapMessage(_ cell: UITableViewCell?, _ model: MessageContentModel?, _ replyIndex: Int? = nil) { if model?.type == .audio { startPlay(cell: cell as? ChatAudioCellProtocol, model: model as? MessageAudioModel) @@ -2088,14 +2405,13 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } if imageUrl.count > 0 { let showController = PhotoBrowserController( - urls: viewmodel.getUrls(), + urls: ChatMessageHelper.getUrls(messages: viewmodel.messages), url: imageUrl ) showController.modalPresentationStyle = .overFullScreen present(showController, animated: false, completion: nil) } } - } else if model?.type == .video, let object = model?.message?.messageObject as? NIMVideoObject { stopPlay() @@ -2118,7 +2434,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } videoModel.state = .Downalod if let videoCell = cell as? NEBaseChatMessageCell { - videoCell.setModel(videoModel) + videoCell.setModel(videoModel, videoModel.message?.isOutgoingMsg ?? false) } viewmodel.downLoad(urlString, path) { progress in @@ -2130,20 +2446,11 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } videoModel.cell?.uploadProgress(byRight: videoModel.message?.isOutgoingMsg ?? true, progress) } _: { error in - if let err = error as NSError? { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.showErrorToast(error) } } } else if replyIndex != nil, model?.type == .text || model?.type == .reply { - print("message did tap: text") - if let text = model?.message?.text { - let textView = getTextViewController(text: text) - textView.modalPresentationStyle = .fullScreen - DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: DispatchWorkItem(block: { [weak self] in - self?.navigationController?.present(textView, animated: false) - })) - } + showTextViewController(model) } else if model?.type == .location { if let locationModel = model as? MessageLocationModel, let lat = locationModel.lat, let lng = locationModel.lng { let mapDetail = NEDetailMapController(type: .detail) @@ -2165,7 +2472,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel } fileModel.state = .Downalod if let fileCell = cell as? NEBaseChatMessageCell { - fileCell.setModel(fileModel) + fileCell.setModel(fileModel, fileModel.message?.isOutgoingMsg ?? false) } viewmodel.downLoad(urlString, path) { [weak self] progress in @@ -2181,9 +2488,7 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel fileModel.cell?.uploadProgress(byRight: fileModel.message?.isOutgoingMsg ?? true, newProgress) } _: { [weak self] error in - if let err = error as NSError? { - self?.showToast(err.localizedDescription) - } + self?.showErrorToast(error) } } } else { @@ -2209,19 +2514,204 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel param["type"] = NSNumber(integerLiteral: 2) as AnyObject } Router.shared.use(CallViewRouter, parameters: param) + } else if model?.type == .custom, let attach = NECustomAttachment.attachmentOfCustomMessage(message: model?.message) { + if attach.customType == customRichTextType { + if replyIndex != nil { + showTextViewController(model) + } + } else if attach.customType == customMultiForwardType, + let data = NECustomAttachment.dataOfCustomMessage(message: model?.message) { + let url = data["url"] as? String + let md5 = data["md5"] as? String + guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } + let fileName = multiForwardFileName + (model?.message?.messageId ?? "") + let filePath = documentsDirectory.appendingPathComponent("NEIMUIKit/\(fileName)").relativePath + let multiForwardVC = getMultiForwardViewController(url, filePath, md5) + navigationController?.pushViewController(multiForwardVC, animated: true) + } } else { - print(#function + "message did tap, type:\(model?.type.rawValue)") + print(#function + "message did tap, type:\(String(describing: model?.type.rawValue))") } } +} - // MARK: OVERRIDE +// MARK: NEMutilSelectBottomViewDelegate + +extension ChatViewController: NEMutilSelectBottomViewDelegate { + /// 移除不可转发的消息 + /// - Parameters cancelSelect: 是否取消勾选 + func filterSelectedMessage(invalidMessages: [NIMMessage]) { + // 取消勾选 + for msg in viewmodel.selectedMessages { + if invalidMessages.contains(msg) { + for (row, model) in viewmodel.messages.enumerated() { + if msg.messageId == model.message?.messageId { + let indexPath = IndexPath(row: row, section: 0) + let model = viewmodel.messages[indexPath.row] + if !model.isRevoked, + let cell = tableView.cellForRow(at: indexPath) as? NEBaseChatMessageCell { + model.isSelected = !model.isSelected + cell.seletedBtn.isSelected = model.isSelected + } + } + } + } + } - open func getMenuView() -> NEBaseChatInputView { - NEBaseChatInputView() + // 无论UI上是否取消勾选,都需要移除该消息 + viewmodel.selectedMessages.removeAll(where: { invalidMessages.contains($0) }) } - open func expandMoreAction() { - chatInputView.chatAddMoreView.configData(data: NEChatUIKitClient.instance.getMoreActionData(sessionType: viewmodel.session.sessionType)) + // 合并转发 + open func didClickMultiForwardButton() { + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + showToast(commonLocalizable("network_error")) + return + } + + if viewmodel.selectedMessages.count > customMultiForwardLimitCount { + showToast(String(format: chatLocalizable("multiForward_forward_limit"), customMultiForwardLimitCount)) + return + } + + var depth = 0 + var invalidMessages = [NIMMessage]() + for msg in viewmodel.selectedMessages { + if msg.deliveryState == .failed || msg.isBlackListed { + invalidMessages.append(msg) + continue + } + + // 解析消息中的depth + if let data = NECustomAttachment.dataOfCustomMessage(message: msg) { + if let dep = data["depth"] as? Int { + if dep >= customMultiForwardMaxDepth { + invalidMessages.append(msg) + } else if dep >= depth { + depth = dep + } + } + } + } + + depth += 1 + + // 存在不可转发的消息:提示+取消勾选 + if invalidMessages.count > 0 { + showAlert(title: chatLocalizable("exception_description"), + message: chatLocalizable("exist_invalid")) { [self] in + filterSelectedMessage(invalidMessages: invalidMessages) + if !viewmodel.selectedMessages.isEmpty { + multiForwardForward(depth) + } + } + } else { + if !viewmodel.selectedMessages.isEmpty { + multiForwardForward(depth) + } + } + } + + open func multiForwardForward(_ depth: Int) { + weak var weakSelf = self + if IMKitClient.instance.getConfigCenter().teamEnable { + let userAction = UIAlertAction(title: chatLocalizable("contact_user"), style: .default) { action in + weakSelf?.forwardMessageToUser(isMultiForward: true, depth: depth) { + weakSelf?.cancelMutilSelect() + } + } + + let teamAction = UIAlertAction(title: chatLocalizable("team"), style: .default) { action in + weakSelf?.forwardMessageToTeam(isMultiForward: true, depth: depth) { + weakSelf?.cancelMutilSelect() + } + } + + let cancelAction = UIAlertAction(title: chatLocalizable("cancel"), style: .cancel) + showActionSheet([teamAction, userAction, cancelAction]) + } else { + forwardMessageToUser(isMultiForward: true, depth: depth) { + weakSelf?.cancelMutilSelect() + } + } + } + + // 逐条转发 + open func didClickSingleForwardButton() { + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + showToast(commonLocalizable("network_error")) + return + } + + if viewmodel.selectedMessages.count > customSingleForwardLimitCount { + showToast(String(format: chatLocalizable("per_item_forward_limit"), customSingleForwardLimitCount)) + return + } + + var invalidMessages = [NIMMessage]() + for msg in viewmodel.selectedMessages { + if msg.messageType == .audio || + msg.messageType == .rtcCallRecord || + msg.deliveryState == .failed + || msg.isBlackListed { + invalidMessages.append(msg) + } + } + + if invalidMessages.count > 0 { + showAlert(title: chatLocalizable("exception_description"), + message: chatLocalizable("exist_invalid")) { [self] in + filterSelectedMessage(invalidMessages: invalidMessages) + if !viewmodel.selectedMessages.isEmpty { + singleForward() + } + } + } else { + if !viewmodel.selectedMessages.isEmpty { + singleForward() + } + } + } + + open func singleForward() { + weak var weakSelf = self + if IMKitClient.instance.getConfigCenter().teamEnable { + let userAction = UIAlertAction(title: chatLocalizable("contact_user"), style: .default) { action in + weakSelf?.forwardMessageToUser { + weakSelf?.cancelMutilSelect() + } + } + + let teamAction = UIAlertAction(title: chatLocalizable("team"), style: .default) { action in + weakSelf?.forwardMessageToTeam { + weakSelf?.cancelMutilSelect() + } + } + + let cancelAction = UIAlertAction(title: chatLocalizable("cancel"), style: .cancel) + showActionSheet([teamAction, userAction, cancelAction]) + } else { + forwardMessageToUser { + weakSelf?.cancelMutilSelect() + } + } + } + + // 多选删除 + open func didClickDeleteButton() { + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + showToast(commonLocalizable("network_error")) + return + } + + showAlert(message: chatLocalizable("message_delete_confirm")) { [weak self] in + if let messages = self?.viewmodel.selectedMessages { + self?.viewmodel.deleteMessages(messages: messages) { error in + self?.showErrorToast(error) + } + } + self?.cancelMutilSelect() + } } } @@ -2229,16 +2719,21 @@ open class ChatViewController: ChatBaseViewController, UINavigationControllerDel extension ChatViewController: ChatBaseCellDelegate { open func didLongPressAvatar(_ cell: UITableViewCell, _ model: MessageContentModel?) { - print("didLongPressAvatar") - if viewmodel.session.sessionType == .P2P { + // 非群聊 + // 禁言 + // 多选 + guard viewmodel.session.sessionType == .team, + !isMute, + !isMutilSelect else { return } + var addText = "" var accid = "" if let m = model, let from = m.message?.from { accid = from - addText += viewmodel.getShowName(userId: from, teamId: viewmodel.session.sessionId, false) + addText += ChatUserCache.getShowName(userId: from, teamId: viewmodel.session.sessionId, false) } addText = "@" + addText + "" @@ -2247,6 +2742,10 @@ extension ChatViewController: ChatBaseCellDelegate { } open func didTapAvatarView(_ cell: UITableViewCell, _ model: MessageContentModel?) { + // 多选模式下屏蔽头像点击事件 + if isMutilSelect { + return + } didTapHeadPortrait(model: model) } @@ -2256,7 +2755,10 @@ extension ChatViewController: ChatBaseCellDelegate { return } - if model?.isRevoked == true { + // 已撤回消息不可点击 + // 多选模式下屏蔽消息点击事件 + guard model?.isRevoked == false, + !isMutilSelect else { return } @@ -2290,6 +2792,10 @@ extension ChatViewController: ChatBaseCellDelegate { } open func didTapResendView(_ cell: UITableViewCell, _ model: MessageContentModel?) { + if isMutilSelect { + return + } + if playingCell?.messageId == model?.message?.messageId { if playingCell?.isPlaying == true { stopPlay() @@ -2315,7 +2821,23 @@ extension ChatViewController: ChatBaseCellDelegate { } open func didTapReeditButton(_ cell: UITableViewCell, _ model: MessageContentModel?) { - if model?.type == .revoke, model?.message?.messageType == .text, let message = model?.message { + // 禁言下不可重新编辑 + // 多选下不可重新编辑 + guard !isMute, + !isMutilSelect else { + return + } + + if model?.type == .revoke, let message = model?.message, + message.messageType == .text || message.messageType == .custom { + if message.messageType == .custom { + guard let attach = NECustomAttachment.attachmentOfCustomMessage(message: message), + attach.customType == customRichTextType else { + return + } + } + let data = NECustomAttachment.dataOfCustomMessage(message: model?.message) + let time = message.timestamp let date = Date() let currentTime = date.timeIntervalSince1970 @@ -2324,17 +2846,24 @@ extension ChatViewController: ChatBaseCellDelegate { didRefreshTable() return } - if model?.message?.remoteExt?[keyReplyMsgKey] != nil { + if message.remoteExt?[keyReplyMsgKey] != nil { viewmodel.operationModel = model showReplyMessageView(isReEdit: true) } else { closeReply(button: nil) } - guard let text = message.text else { - return + + var attributeStr: NSMutableAttributedString? + var text = "" + if message.messageType == .text, let txt = message.text { + text = txt + } else if message.messageType == .custom, let body = data?["body"] as? String { + text = body } - let attributeStr = NSMutableAttributedString(string: text) - attributeStr.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.ne_darkText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], range: NSMakeRange(0, text.utf16.count)) + + attributeStr = NSMutableAttributedString(string: text) + attributeStr?.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.ne_darkText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], range: NSMakeRange(0, text.utf16.count)) + if let remoteExt = message.remoteExt, let dic = remoteExt[yxAtMsg] as? [String: AnyObject] { dic.forEach { (key: String, value: AnyObject) in if let contentDic = value as? [String: AnyObject] { @@ -2348,8 +2877,8 @@ extension ChatViewController: ChatBaseCellDelegate { chatInputView.nickAccidDic[text] = key } - if attributeStr.length > model.end { - attributeStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.ne_blueText, range: NSMakeRange(model.start, model.end - model.start)) + if (attributeStr?.length ?? 0) > model.end { + attributeStr?.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.ne_blueText, range: NSMakeRange(model.start, model.end - model.start)) } } } @@ -2357,12 +2886,40 @@ extension ChatViewController: ChatBaseCellDelegate { } } } + + if let title = data?["title"] as? String { + // 切换换行输入框 + // 标题填入 + chatInputView.titleField.text = title + expandButtonDidClick() + } + chatInputView.textView.attributedText = attributeStr chatInputView.textView.becomeFirstResponder() } } - open func didTapReadView(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + open func didTapReadView(_ cell: UITableViewCell, _ model: MessageContentModel?) { + if isMutilSelect { + return + } + + if let msg = model?.message, msg.session?.sessionType == .team { + let readVC = getReadView(msg) + navigationController?.pushViewController(readVC, animated: true) + } + } + + open func didTapSelectButton(_ cell: UITableViewCell, _ model: MessageContentModel?) { + viewmodel.selectedMessages.removeAll(where: { $0.messageId == model?.message?.messageId }) + if model?.isSelected == true, let msg = model?.message { + viewmodel.selectedMessages.append(msg) + } + } + + open func getReadView(_ message: NIMMessage) -> NEBaseReadViewController { + ReadViewController(message: message) + } open func loadDataFinish() {} @@ -2373,4 +2930,33 @@ extension ChatViewController: ChatBaseCellDelegate { } open func didDismissCallView() {} + + // MARK: mutile line delegate + + open func expandButtonDidClick() { + chatInputView.textView.resignFirstResponder() + scrollTableViewToBottom() + operationView?.removeFromSuperview() + } + + open func didHideMultipleButtonClick() { + chatInputView.restoreNormalInputStyle() + chatInputView.textView.resignFirstResponder() + chatInputView.titleField.resignFirstResponder() + } + + open func titleTextDidClearEmpty() {} + + open func didSendFinishAndCheckoutInput() { + if chatInputView.chatInpuMode != .normal { + chatInputView.chatInpuMode = .normal + chatInputView.restoreNormalInputStyle() + if chatInputView.textView.isFirstResponder || chatInputView.titleField.isFirstResponder { + chatInputView.textView.becomeFirstResponder() + } + didHideMultiple() + } + } + + open func didHideMultiple() {} } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/MultiForwardViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/MultiForwardViewController.swift new file mode 100644 index 00000000..bf5be3c6 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/MultiForwardViewController.swift @@ -0,0 +1,387 @@ + +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK +import UIKit + +@objcMembers +open class MultiForwardViewController: ChatBaseViewController, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, ChatBaseCellDelegate, UIDocumentInteractionControllerDelegate, MultiForwardViewModelDelegate { + public var viewmodel = MultiForwardViewModel() + private var messageAttachmentUrl: String? + private var messageAttachmentFilePath: String = "" + private var messageAttachmentMD5: String? + public var cellRegisterDic = [String: UITableViewCell.Type]() + public var brokenNetworkViewHeight: CGFloat = 36 + let interactionController = UIDocumentInteractionController() + + public init(_ attachmentUrl: String?, + _ attachmentFilePath: String, + _ attachmentMD5: String?) { + super.init(nibName: nil, bundle: nil) + messageAttachmentFilePath = attachmentFilePath + messageAttachmentUrl = attachmentUrl + messageAttachmentMD5 = attachmentMD5 + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + NEChatDetectNetworkTool.shareInstance.netWorkReachability { [weak self] status in + if status == .notReachable { + self?.brokenNetworkView.isHidden = false + } else { + self?.brokenNetworkView.isHidden = true + } + } + } + + override func backEvent() { + super.backEvent() + } + + override open func viewDidLoad() { + super.viewDidLoad() + viewmodel.delegate = self + commonUI() + loadData() + } + + open func commonUI() { + title = chatLocalizable("chat_history") + navigationView.backgroundColor = .white + navigationView.titleBarBottomLine.isHidden = false + navigationView.moreButton.isHidden = true + navigationView.addBackButtonTarget(target: self, selector: #selector(backEvent)) + + tableView.register( + NEBaseChatMessageCell.self, + forCellReuseIdentifier: "\(NEBaseChatMessageCell.self)" + ) + + NEChatUIKitClient.instance.getRegisterCustomCell().forEach { (key: String, value: UITableViewCell.Type) in + cellRegisterDic[key] = value + } + + cellRegisterDic.forEach { (key: String, value: UITableViewCell.Type) in + tableView.register(value, forCellReuseIdentifier: key) + } + + view.addSubview(tableView) + if #available(iOS 11.0, *) { + NSLayoutConstraint.activate([ + tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), + tableView.leftAnchor.constraint(equalTo: view.leftAnchor), + tableView.rightAnchor.constraint(equalTo: view.rightAnchor), + tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), + ]) + } else { + NSLayoutConstraint.activate([ + tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), + tableView.leftAnchor.constraint(equalTo: view.leftAnchor), + tableView.rightAnchor.constraint(equalTo: view.rightAnchor), + tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -34), + ]) + } + + view.addSubview(brokenNetworkView) + NSLayoutConstraint.activate([ + brokenNetworkView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), + brokenNetworkView.leftAnchor.constraint(equalTo: view.leftAnchor), + brokenNetworkView.rightAnchor.constraint(equalTo: view.rightAnchor), + brokenNetworkView.heightAnchor.constraint(equalToConstant: brokenNetworkViewHeight), + ]) + } + + func loadData() { + view.makeToastActivity(.center) + viewmodel.loadData(messageAttachmentUrl, + messageAttachmentFilePath, + messageAttachmentMD5) { [weak self] error in + self?.view.hideToastActivity() + if let err = error as? NSError { + if err.code == 0 { + self?.showToast(err.domain) + } else { + self?.showToast(chatLocalizable("multiForward_open_failed")) + } + self?.navigationController?.popViewController(animated: true) + } else { + self?.tableView.reloadData() + } + } + } + + private func showErrorToast(_ error: Error?) { + if let err = error as? NSError { + switch err.code { + case noNetworkCode, -1009: + showToast(commonLocalizable("network_error")) + default: + showToast(err.localizedDescription) + } + } + } + + // MARK: lazy Method + + public lazy var brokenNetworkView: NEBrokenNetworkView = { + let view = NEBrokenNetworkView() + view.translatesAutoresizingMaskIntoConstraints = false + view.isHidden = true + return view + }() + + public lazy var tableView: UITableView = { + let tableView = UITableView(frame: .zero, style: .plain) + tableView.translatesAutoresizingMaskIntoConstraints = false + tableView.separatorStyle = .none + tableView.showsVerticalScrollIndicator = false + tableView.delegate = self + tableView.dataSource = self + tableView.backgroundColor = .clear + tableView.keyboardDismissMode = .onDrag + return tableView + }() + + // MARK: UIDocumentInteractionControllerDelegate + + open func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { + self + } + + // MARK: UITableViewDataSource, UITableViewDelegate + + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + let count = viewmodel.messages.count + print("numberOfRowsInSection count : ", count) + return count + } + + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let model = viewmodel.messages[indexPath.row] + model.inMultiForward = true + model.isPined = false + var reuseId = "" + if model.replyedModel?.isReplay == true, + model.isRevoked == false { + reuseId = "\(MessageType.reply.rawValue)" + } else { + let key = "\(model.type.rawValue)" + if model.type == .custom { + if let attch = NECustomAttachment.attachmentOfCustomMessage(message: model.message) { + if attch.customType == customMultiForwardType { + reuseId = "\(MessageType.multiForward.rawValue)" + } else if attch.customType == customRichTextType { + reuseId = "\(MessageType.richText.rawValue)" + } else if NEChatUIKitClient.instance.getRegisterCustomCell()["\(attch.customType)"] != nil { + reuseId = "\(attch.customType)" + } else { + reuseId = "\(NEBaseChatMessageCell.self)" + } + } else { + reuseId = "\(NEBaseChatMessageCell.self)" + } + } else if model.type == .time || model.type == .notification || model.type == .tip { + reuseId = "\(MessageType.time.rawValue)" + } else if cellRegisterDic[key] != nil { + reuseId = key + } else { + reuseId = "\(NEBaseChatMessageCell.self)" + } + } + + let cell = tableView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) + if let c = cell as? NEBaseChatMessageTipCell { + if let m = model as? MessageTipsModel { + c.setModel(m) + } + return c + } else if let c = cell as? NEBaseChatMessageCell { + if let m = model as? MessageContentModel { + c.setModel(m, false) + c.setSelect(m, false) + c.delegate = self + } + + return c + } else if let c = cell as? NEChatBaseCell, let m = model as? MessageContentModel { + c.setModel(m, false) + return cell + } else { + return NEBaseChatMessageCell() + } + } + + open func tableView(_ tableView: UITableView, + heightForRowAt indexPath: IndexPath) -> CGFloat { + viewmodel.messages[indexPath.row].cellHeight() + chat_content_margin + } + + open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + MultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } + + // MARK: ChatBaseCellDelegate + + open func didTapMessageView(_ cell: UITableViewCell, _ model: MessageContentModel?) { + if let tapClick = NEKitChatConfig.shared.ui.messageItemClick { + tapClick(cell, model) + return + } + + // 已撤回消息不可点击 + if model?.isRevoked == true { + return + } + + didTapMessage(cell, model) + } + + open func didTapMessage(_ cell: UITableViewCell?, _ model: MessageContentModel?, _ replyIndex: Int? = nil) { + if model?.type == .image { + if let imageObject = model?.message?.messageObject as? NIMImageObject { + var imageUrl = "" + + if let url = imageObject.url { + imageUrl = url + } else { + if let path = imageObject.path, FileManager.default.fileExists(atPath: path) { + imageUrl = path + } + } + if imageUrl.count > 0 { + let showController = PhotoBrowserController( + urls: ChatMessageHelper.getUrls(messages: viewmodel.messages), + url: imageUrl + ) + showController.modalPresentationStyle = .overFullScreen + present(showController, animated: false, completion: nil) + } + } + + } else if model?.type == .video, + let object = model?.message?.messageObject as? NIMVideoObject { + weak var weakSelf = self + let videoPlayer = VideoPlayerViewController() + videoPlayer.modalPresentationStyle = .overFullScreen + if let path = object.path, FileManager.default.fileExists(atPath: path) == true { + let url = URL(fileURLWithPath: path) + videoPlayer.videoUrl = url + videoPlayer.totalTime = object.duration + print("video url : ", videoPlayer.videoUrl as Any) + present(videoPlayer, animated: true, completion: nil) + } else if let urlString = object.url, let path = object.path, + let videoModel = model as? MessageVideoModel { + print("fetch message attachment") + if let index = replyIndex, index >= 0 { + tableView.scrollToRow(at: IndexPath(row: index, section: 0), + at: .middle, + animated: true) + } + videoModel.state = .Downalod + if let videoCell = cell as? NEBaseChatMessageCell { + videoCell.setModel(videoModel, false) + } + + viewmodel.downLoad(urlString, path) { progress in + NELog.infoLog(ModuleName + " " + (weakSelf?.className() ?? ""), desc: #function + "CALLBACK downLoad: \(progress)") + + videoModel.progress = progress + if progress >= 1.0 { + videoModel.state = .Success + } + videoModel.cell?.uploadProgress(byRight: false, progress) + } _: { error in + weakSelf?.showErrorToast(error) + } + } + } else if model?.type == .location { + if let locationModel = model as? MessageLocationModel, let lat = locationModel.lat, let lng = locationModel.lng { + let mapDetail = NEDetailMapController(type: .detail) + mapDetail.currentPoint = CGPoint(x: lat, y: lng) + mapDetail.locationTitle = locationModel.title + mapDetail.subTitle = locationModel.subTitle + navigationController?.pushViewController(mapDetail, animated: true) + } + } else if model?.type == .file, + let object = model?.message?.messageObject as? NIMFileObject, + let path = object.path { + if !FileManager.default.fileExists(atPath: path) { + if let urlString = object.url, let path = object.path, + let fileModel = model as? MessageFileModel { + if let index = replyIndex, index >= 0 { + tableView.scrollToRow(at: IndexPath(row: index, section: 0), + at: .middle, + animated: true) + } + fileModel.state = .Downalod + if let fileCell = cell as? NEBaseChatMessageCell { + fileCell.setModel(fileModel, false) + } + + viewmodel.downLoad(urlString, path) { [weak self] progress in + NELog.infoLog(ModuleName + " " + (self?.className() ?? ""), desc: #function + "downLoad file progress: \(progress)") + var newProgress = progress + if newProgress < 0 { + newProgress = abs(progress) / fileModel.size + } + fileModel.progress = newProgress + if newProgress >= 1.0 { + fileModel.state = .Success + } + fileModel.cell?.uploadProgress(byRight: false, newProgress) + + } _: { [weak self] error in + self?.showErrorToast(error) + } + } + } else { + let url = URL(fileURLWithPath: path) + interactionController.url = url + interactionController.delegate = self // UIDocumentInteractionControllerDelegate + if interactionController.presentPreview(animated: true) {} else { + interactionController.presentOptionsMenu(from: view.bounds, in: view, animated: true) + } + } + } else if model?.type == .custom, let attach = NECustomAttachment.attachmentOfCustomMessage(message: model?.message) { + if attach.customType == customMultiForwardType, + let data = NECustomAttachment.dataOfCustomMessage(message: model?.message) { + let url = data["url"] as? String + let md5 = data["md5"] as? String + guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } + let fileName = multiForwardFileName + (model?.message?.messageId ?? "") + let filePath = documentsDirectory.appendingPathComponent("NEIMUIKit/\(fileName)").relativePath + let multiForwardVC = getMultiForwardViewController(url, filePath, md5) + navigationController?.pushViewController(multiForwardVC, animated: true) + } + } else { + print(#function + "message did tap, type:\(String(describing: model?.type.rawValue))") + } + } + + // MARK: ChatBaseCellDelegate ignore protocol + + public func didTapAvatarView(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + + public func didLongPressAvatar(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + + public func didLongPressMessageView(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + + public func didTapResendView(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + + public func didTapReeditButton(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + + public func didTapReadView(_ cell: UITableViewCell, _ model: MessageContentModel?) {} + + public func didTapSelectButton(_ cell: UITableViewCell, _ model: MessageContentModel?) {} +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseForwardAlertViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseForwardAlertViewController.swift index 8d5d2f73..f19da8fd 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseForwardAlertViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseForwardAlertViewController.swift @@ -7,8 +7,8 @@ import NECommonKit import NECommonUIKit import UIKit -@objc -public class ForwardItem: NSObject { +@objcMembers +open class ForwardItem: NSObject { var name: String? var uid: String? var avatar: String? @@ -16,7 +16,7 @@ public class ForwardItem: NSObject { } @objcMembers -public class NEBaseForwardUserCell: UICollectionViewCell { +open class NEBaseForwardUserCell: UICollectionViewCell { lazy var userHeader: NEUserHeaderView = { let header = NEUserHeaderView(frame: .zero) header.translatesAutoresizingMaskIntoConstraints = false @@ -31,7 +31,7 @@ public class NEBaseForwardUserCell: UICollectionViewCell { setupUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { super.init(coder: coder) } @@ -47,17 +47,19 @@ public class NEBaseForwardUserCell: UICollectionViewCell { } @objcMembers -public class NEBaseForwardAlertViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, +open class NEBaseForwardAlertViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var datas = [ForwardItem]() - typealias ForwardCallBack = () -> Void + typealias ForwardCallBack = (String?) -> Void var cancelBlock: ForwardCallBack? var sureBlock: ForwardCallBack? + var type = chatLocalizable("operation_forward") // 合并转发/逐条转发/转发 var context = "" public let sureBtn = UIButton() public let tip = UILabel() + public var contentViewCenterYAnchor: NSLayoutConstraint? lazy var userCollection: UICollectionView = { let flow = UICollectionViewFlowLayout() @@ -103,25 +105,61 @@ public class NEBaseForwardAlertViewController: UIViewController, UICollectionVie label.translatesAutoresizingMaskIntoConstraints = false label.font = NEConstant.defaultTextFont(14.0) label.textColor = .ne_darkText - label.numberOfLines = 0 + label.numberOfLines = 1 + label.lineBreakMode = .byTruncatingMiddle label.accessibilityIdentifier = "id.forwardContentText" return label }() - override public func viewDidLoad() { - super.viewDidLoad() + // 留言 + lazy var commentTextFeild: UITextField = { + let textFeild = UITextField() + textFeild.translatesAutoresizingMaskIntoConstraints = false + textFeild.placeholder = chatLocalizable("leave_message") + textFeild.layer.cornerRadius = 4 + textFeild.layer.borderWidth = 1 + textFeild.layer.borderColor = forwardLineColor.cgColor + textFeild.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 0)) + textFeild.leftViewMode = .always + textFeild.font = .systemFont(ofSize: 14) + return textFeild + }() + + override open func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + if let parent = parent as? ChatViewController { + parent.isCurrentPage = false + } + } - // Do any additional setup after loading the view. + override open func viewDidLoad() { + super.viewDidLoad() setupUI() + NotificationCenter.default.addObserver(self, + selector: #selector(keyBoardWillShow(_:)), + name: UIResponder.keyboardWillShowNotification, + object: nil) + + NotificationCenter.default.addObserver(self, + selector: #selector(keyBoardWillHide(_:)), + name: UIResponder.keyboardWillHideNotification, + object: nil) + } + + override open func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + navigationController?.viewControllers.last?.view.endEditing(false) } - public func setupUI() { + open func setupUI() { view.backgroundColor = NEConstant.hexRGB(0x000000).withAlphaComponent(0.4) view.addSubview(contentView) + contentViewCenterYAnchor = contentView.centerYAnchor.constraint(equalTo: view.centerYAnchor) NSLayoutConstraint.activate([ contentView.centerXAnchor.constraint(equalTo: view.centerXAnchor), - contentView.centerYAnchor.constraint(equalTo: view.centerYAnchor), + contentViewCenterYAnchor!, contentView.widthAnchor.constraint(equalToConstant: 276), + contentView.heightAnchor.constraint(equalToConstant: 250), ]) tip.translatesAutoresizingMaskIntoConstraints = false @@ -181,24 +219,32 @@ public class NEBaseForwardAlertViewController: UIViewController, UICollectionVie contentText.topAnchor.constraint(equalTo: textBack.topAnchor, constant: 7), contentText.bottomAnchor.constraint(equalTo: textBack.bottomAnchor, constant: -7), ]) - contentText.text = "[转发]\(context)的会话记录" + contentText.text = "[\(type)]\(context)的会话记录" + + // 留言 + contentView.addSubview(commentTextFeild) + NSLayoutConstraint.activate([ + commentTextFeild.leftAnchor.constraint(equalTo: textBack.leftAnchor), + commentTextFeild.rightAnchor.constraint(equalTo: textBack.rightAnchor), + commentTextFeild.topAnchor.constraint(equalTo: textBack.bottomAnchor, constant: 16), + commentTextFeild.heightAnchor.constraint(equalToConstant: 32), + ]) let verticalLine = UIView() verticalLine.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(verticalLine) - verticalLine.backgroundColor = NEConstant.hexRGB(0xE1E6E8) + verticalLine.backgroundColor = forwardLineColor NSLayoutConstraint.activate([ verticalLine.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), - verticalLine.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), verticalLine.widthAnchor.constraint(equalToConstant: 1.0), verticalLine.heightAnchor.constraint(equalToConstant: 51), - verticalLine.topAnchor.constraint(equalTo: textBack.bottomAnchor, constant: 16.0), + verticalLine.topAnchor.constraint(equalTo: commentTextFeild.bottomAnchor, constant: 24.0), ]) let horizontalLine = UIView() horizontalLine.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(horizontalLine) - horizontalLine.backgroundColor = NEConstant.hexRGB(0xE1E6E8) + horizontalLine.backgroundColor = forwardLineColor NSLayoutConstraint.activate([ horizontalLine.leftAnchor.constraint(equalTo: contentView.leftAnchor), horizontalLine.rightAnchor.constraint(equalTo: contentView.rightAnchor), @@ -236,7 +282,25 @@ public class NEBaseForwardAlertViewController: UIViewController, UICollectionVie ]) } - public func setItems(_ items: [ForwardItem]) { + // MARK: 键盘通知相关操作 + + open func keyBoardWillShow(_ notification: Notification) { + contentViewCenterYAnchor?.constant = -60 + + UIView.animate(withDuration: 0.5) { + self.view.layoutIfNeeded() + } + } + + open func keyBoardWillHide(_ notification: Notification) { + contentViewCenterYAnchor?.constant = 0 + + UIView.animate(withDuration: 0.5) { + self.view.layoutIfNeeded() + } + } + + open func setItems(_ items: [ForwardItem]) { datas.append(contentsOf: items) if datas.count == 1 { let item = datas[0] @@ -247,7 +311,7 @@ public class NEBaseForwardAlertViewController: UIViewController, UICollectionVie oneUserHead.setTitle(uid) oneUserName.text = uid } - if let url = item.avatar { + if let url = item.avatar, !url.isEmpty { oneUserHead.sd_setImage(with: URL(string: url), completed: nil) oneUserHead.titleLabel.text = "" oneUserHead.backgroundColor = .clear @@ -264,35 +328,38 @@ public class NEBaseForwardAlertViewController: UIViewController, UICollectionVie func sureClick() { if let block = sureBlock { - block() + block(commentTextFeild.text) } removeSelf() } func cancelClick() { if let block = cancelBlock { - block() + block(commentTextFeild.text) } removeSelf() } - override public func touchesBegan(_ touches: Set, with event: UIEvent?) { - removeSelf() + override open func touchesBegan(_ touches: Set, with event: UIEvent?) { + view.endEditing(true) } func removeSelf() { + if let parent = parent as? ChatViewController { + parent.isCurrentPage = true + } view.removeFromSuperview() removeFromParent() } - public func collectionView(_ collectionView: UICollectionView, - numberOfItemsInSection section: Int) -> Int { + open func collectionView(_ collectionView: UICollectionView, + numberOfItemsInSection section: Int) -> Int { datas.count } open func setCellModel(cell: NEBaseForwardUserCell, indexPath: IndexPath) -> UICollectionViewCell { let item = datas[indexPath.row] - if let url = item.avatar { + if let url = item.avatar, !url.isEmpty { cell.userHeader.sd_setImage(with: URL(string: url), completed: nil) cell.userHeader.titleLabel.text = "" cell.userHeader.backgroundColor = .clear @@ -308,14 +375,14 @@ public class NEBaseForwardAlertViewController: UIViewController, UICollectionVie return cell } - public func collectionView(_ collectionView: UICollectionView, - cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + open func collectionView(_ collectionView: UICollectionView, + cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { UICollectionViewCell() } - public func collectionView(_ collectionView: UICollectionView, - layout collectionViewLayout: UICollectionViewLayout, - sizeForItemAt indexPath: IndexPath) -> CGSize { + open func collectionView(_ collectionView: UICollectionView, + layout collectionViewLayout: UICollectionViewLayout, + sizeForItemAt indexPath: IndexPath) -> CGSize { CGSize(width: 32.0, height: 32) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBasePinMessageViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBasePinMessageViewController.swift index a0e29241..c14e7c20 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBasePinMessageViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBasePinMessageViewController.swift @@ -2,26 +2,40 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit +import NECommonUIKit +import NECoreIMKit import NIMSDK import UIKit let PinMessageDefaultType = 1000 @objcMembers -open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDataSource, UITableViewDelegate, PinMessageViewModelDelegate, PinMessageCellDelegate { +open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDataSource, UITableViewDelegate, PinMessageViewModelDelegate, PinMessageCellDelegate, UIDocumentInteractionControllerDelegate, NIMMediaManagerDelegate { let viewmodel = PinMessageViewModel() var session: NIMSession + var cellClassDic: [String: NEBasePinMessageCell.Type] = [:] + // pin 列表内容最大宽度 + public var pin_content_maxW = (kScreenWidth - 72) + + var playingCell: NEBasePinMessageAudioCell? + var playingModel: MessageAudioModel? public init(session: NIMSession) { self.session = session super.init(nibName: nil, bundle: nil) + NIMSDK.shared().mediaManager.add(self) } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + deinit { + NIMSDK.shared().mediaManager.remove(self) + } + private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.translatesAutoresizingMaskIntoConstraints = false @@ -45,7 +59,9 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa return view }() - override public func viewDidLoad() { + let interactionController = UIDocumentInteractionController() + + override open func viewDidLoad() { super.viewDidLoad() viewmodel.delegate = self @@ -53,6 +69,11 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa loadData() } + override open func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + stopPlay() + } + func loadData() { weak var weakSelf = self viewmodel.getPinitems(session: session) { error in @@ -63,6 +84,9 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa weakSelf?.showToast(err.localizedDescription) } } else { + weakSelf?.viewmodel.items.forEach { model in + ChatMessageHelper.downloadAudioFile(message: model.message) + } weakSelf?.emptyView.isHidden = (weakSelf?.viewmodel.items.count ?? 0) > 0 weakSelf?.tableView.reloadData() } @@ -88,8 +112,9 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa emptyView.rightAnchor.constraint(equalTo: tableView.rightAnchor), emptyView.bottomAnchor.constraint(equalTo: tableView.bottomAnchor), ]) - let cellClassDic = getRegisterCellDic() - cellClassDic.forEach { (key: Int, value: NEBasePinMessageCell.Type) in + cellClassDic = getRegisterCellDic() + tableView.register(NEBasePinMessageTextCell.self, forCellReuseIdentifier: "\(NEBasePinMessageTextCell.self)") + cellClassDic.forEach { (key: String, value: NEBasePinMessageCell.Type) in tableView.register(value, forCellReuseIdentifier: "\(key)") } } @@ -104,7 +129,7 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa } */ - public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = viewmodel.items[indexPath.row] if item.message.session?.sessionType == .P2P { let session = item.message.session @@ -125,21 +150,39 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa } } - public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let model = viewmodel.items[indexPath.row] - let cell = tableView.dequeueReusableCell(withIdentifier: "\(model.getMessageType())", for: indexPath) as! NEBasePinMessageCell + var reuseId = "\(model.chatmodel.type.rawValue)" + if model.chatmodel.type == .custom, + let attach = NECustomAttachment.attachmentOfCustomMessage(message: model.chatmodel.message) { + if attach.customType == customMultiForwardType { + reuseId = "\(MessageType.multiForward.rawValue)" + } else if attach.customType == customRichTextType { + reuseId = "\(MessageType.richText.rawValue)" + } else { + reuseId = "\(NEBasePinMessageTextCell.self)" + } + } else if cellClassDic[reuseId] == nil { + reuseId = "\(NEBasePinMessageTextCell.self)" + } + let cell = tableView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) as! NEBasePinMessageCell cell.delegate = self cell.configure(model) return cell } - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewmodel.items.count } - public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let model = viewmodel.items[indexPath.row] - return model.cellHeight() + if let attach = NECustomAttachment.attachmentOfCustomMessage(message: model.message) { + if attach.customType == customMultiForwardType { + return model.cellHeight(pinContentMaxW: pin_content_maxW) - 30 + } + } + return model.cellHeight(pinContentMaxW: pin_content_maxW) } func cancelPinActionClicked(item: PinMessageModel) { @@ -183,28 +226,6 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa open func showAction(item: PinMessageModel) { var actions = [UIAlertAction]() weak var weakSelf = self - /* - let jumpAction = UIAlertAction(title: chatLocalizable("pin_jump_detail"), style: .default) { _ in - if item.message.session?.sessionType == .P2P { - let session = item.message.session - Router.shared.use( - PushP2pChatVCRouter, - parameters: ["nav": weakSelf?.navigationController as Any, "session": session as Any, - "anchor": item.message], - closure: nil - ) - } else if item.message.session?.sessionType == .team { - let session = item.message.session - Router.shared.use( - PushTeamChatVCRouter, - parameters: ["nav": weakSelf?.navigationController as Any, "session": session as Any, - "anchor": item.message], - closure: nil - ) - } - } - actions.append(jumpAction) - */ let cancelPinAction = UIAlertAction(title: chatLocalizable("operation_cancel_pin"), style: .default) { _ in weakSelf?.cancelPinActionClicked(item: item) } @@ -245,32 +266,38 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa let item = ForwardItem() item.uid = user.userId item.avatar = user.userInfo?.avatarUrl - item.name = user.userInfo?.nickName + item.name = user.getShowName() items.append(item) } let forwardAlert = weakSelf!.getForwardAlertController() forwardAlert.setItems(items) - if let senderName = message.senderName { - forwardAlert.context = senderName + if let session = self.viewmodel.session { + forwardAlert.context = ChatMessageHelper.getSessionName(session: session) } weakSelf?.addChild(forwardAlert) weakSelf?.view.addSubview(forwardAlert.view) - forwardAlert.sureBlock = { - print("sure click ") - weakSelf?.viewmodel.forwardUserMessage(message, users) + forwardAlert.sureBlock = { comment in + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + weakSelf?.showToast(commonLocalizable("network_error")) + return + } + weakSelf?.viewmodel.forwardUserMessage(message, users, comment) { error in + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else { + weakSelf?.showToast(err.localizedDescription) + } + } + } } } } var param = [String: Any]() param["nav"] = weakSelf?.navigationController as Any param["limit"] = 6 - if let session = weakSelf?.session, session.sessionType == .P2P { - var filters = Set() - filters.insert(session.sessionId) - param["filters"] = filters - } Router.shared.use(ContactUserSelectRouter, parameters: param, closure: nil) } @@ -285,11 +312,23 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa let forwardAlert = weakSelf!.getForwardAlertController() forwardAlert.setItems([item]) - if let senderName = message.senderName { - forwardAlert.context = senderName + if let session = self.viewmodel.session { + forwardAlert.context = ChatMessageHelper.getSessionName(session: session) } - forwardAlert.sureBlock = { - weakSelf?.viewmodel.forwardTeamMessage(message, team) + forwardAlert.sureBlock = { comment in + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + weakSelf?.showToast(commonLocalizable("network_error")) + return + } + weakSelf?.viewmodel.forwardTeamMessage(message, team, comment) { error in + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else { + weakSelf?.showToast(err.localizedDescription) + } + } + } } weakSelf?.addChild(forwardAlert) weakSelf?.view.addSubview(forwardAlert.view) @@ -328,29 +367,258 @@ open class NEBasePinMessageViewController: ChatBaseViewController, UITableViewDa // MARK: PinMessageViewModelDelegate - public func didNeedRefreshUI() { + open func didNeedRefreshUI() { loadData() } // MARK: PinMessageCellDelegate - public func didClickMore(_ model: PinMessageModel?) { - print("did click more") + open func didClickMore(_ model: PinMessageModel?) { if let item = model { showAction(item: item) } } - open func getRegisterCellDic() -> [Int: NEBasePinMessageCell.Type] { - let cellClassDic = [ - NIMMessageType.text.rawValue: NEBasePinMessageTextCell.self, - NIMMessageType.image.rawValue: NEBasePinMessageImageCell.self, - NIMMessageType.audio.rawValue: NEBasePinMessageAudioCell.self, - NIMMessageType.video.rawValue: NEBasePinMessageVideoCell.self, - NIMMessageType.location.rawValue: NEBasePinMessageLocationCell.self, - NIMMessageType.file.rawValue: NEBasePinMessageFileCell.self, - PinMessageDefaultType: NEBasePinMessageDefaultCell.self, - ] - return cellClassDic + open func didClickContent(_ model: PinMessageModel?, _ cell: NEBasePinMessageCell) { + NELog.infoLog(className(), desc: #function + "didClickContent") + + if model?.message.messageType == .audio { + startPlay(cell: cell, model: model) + } else if model?.message.messageType == .image { + if let imageObject = model?.message.messageObject as? NIMImageObject { + var imageUrl = "" + + if let url = imageObject.url { + imageUrl = url + } else { + if let path = imageObject.path, FileManager.default.fileExists(atPath: path) { + imageUrl = path + } + } + if imageUrl.count > 0 { + let showController = PhotoBrowserController( + urls: [imageUrl], + url: imageUrl + ) + showController.modalPresentationStyle = .overFullScreen + present(showController, animated: false, completion: nil) + } + } + } else if model?.message.messageType == .video, + let object = model?.message.messageObject as? NIMVideoObject { + stopPlay() + let videoPlayer = VideoPlayerViewController() + videoPlayer.modalPresentationStyle = .overFullScreen + videoPlayer.totalTime = object.duration + + if let path = object.path, FileManager.default.fileExists(atPath: path) == true { + let url = URL(fileURLWithPath: path) + videoPlayer.videoUrl = url + present(videoPlayer, animated: true, completion: nil) + + } else if let url = object.url, let remoteUrl = URL(string: url) { + videoPlayer.videoUrl = remoteUrl + present(videoPlayer, animated: true, completion: nil) + } + + } else if model?.message.messageType == .text { + showTextViewController(model) + } else if model?.message.messageType == .location, let title = model?.message.text, + let locationObject = model?.message.messageObject as? NIMLocationObject { + let lat = locationObject.latitude + let lng = locationObject.longitude + let subTitle = locationObject.title + + let mapDetail = NEDetailMapController(type: .detail) + mapDetail.currentPoint = CGPoint(x: lat, y: lng) + mapDetail.locationTitle = title + mapDetail.subTitle = subTitle + navigationController?.pushViewController(mapDetail, animated: true) + } else if model?.message.messageType == .file, + let object = model?.message.messageObject as? NIMFileObject, + let path = object.path { + guard let fileModel = model?.pinFileModel as? PinMessageFileModel else { + NELog.infoLog(ModuleName + " " + className(), desc: #function + "PinMessageFileModel not exit") + return + } + + if fileModel.state == .Downalod { + NELog.infoLog(ModuleName + " " + className(), desc: #function + "downLoad state, click ingore") + return + } + if !FileManager.default.fileExists(atPath: path) { + if let urlString = object.url, let path = object.path { + fileModel.state = .Downalod + + viewmodel.downLoad(urlString, path) { [weak self] progress in + NELog.infoLog(ModuleName + " " + (self?.className() ?? ""), desc: #function + "downLoad file progress: \(progress)") + var newProgress = progress + if newProgress < 0 { + newProgress = abs(progress) / fileModel.size + } + fileModel.progress = newProgress + if newProgress >= 1.0 { + fileModel.state = .Success + } + fileModel.cell?.uploadProgress(progress: newProgress) + + } _: { error in + } + } + } else { + let url = URL(fileURLWithPath: path) + interactionController.url = url + interactionController.delegate = self + if interactionController.presentPreview(animated: true) {} + else { + interactionController.presentOptionsMenu(from: view.bounds, in: view, animated: true) + } + } + } else if model?.message.messageType == .custom, let attach = NECustomAttachment.attachmentOfCustomMessage(message: model?.message) { + if attach.customType == customRichTextType { + showTextViewController(model) + } else if attach.customType == customMultiForwardType, + let data = NECustomAttachment.dataOfCustomMessage(message: model?.message) { + let url = data["url"] as? String + let md5 = data["md5"] as? String + guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } + let fileName = multiForwardFileName + (model?.message.messageId ?? "") + let filePath = documentsDirectory.appendingPathComponent("NEIMUIKit/\(fileName)").relativePath + let multiForwardVC = getMultiForwardViewController(url, filePath, md5) + navigationController?.pushViewController(multiForwardVC, animated: true) + } + } + } + + private func startPlay(cell: NEBasePinMessageCell?, model: PinMessageModel?) { + guard let audioModel = model?.chatmodel as? MessageAudioModel else { + return + } + + if playingModel == audioModel { + if NIMSDK.shared().mediaManager.isPlaying() { + stopPlay() + } else { + startPlaying(audioMessage: model?.message) + } + } else { + stopPlay() + if let pCell = cell as? NEBasePinMessageAudioCell { + playingCell = pCell + } + if let audioModel = model?.chatmodel as? MessageAudioModel { + playingModel = audioModel + } + startPlaying(audioMessage: model?.message) + } + } + + func startPlaying(audioMessage: NIMMessage?) { + guard let message = audioMessage, let audio = message.messageObject as? NIMAudioObject else { + return + } + playingCell?.startAnimation() + if let path = audio.path, FileManager.default.fileExists(atPath: path) == true { + NELog.infoLog(className(), desc: #function + " play path : " + path) + if viewmodel.getHandSetEnable() == true { + NIMSDK.shared().mediaManager.switch(.receiver) + } else { + NIMSDK.shared().mediaManager.switch(.speaker) + } + NIMSDK.shared().mediaManager.play(path) + } else { + NELog.infoLog(className(), desc: #function + " audio path is empty, play url : " + (audio.url ?? "")) + ChatMessageHelper.downloadAudioFile(message: message) + playingCell?.stopAnimation() + } + } + + func stopPlay() { + if NIMSDK.shared().mediaManager.isPlaying() { + playingCell?.stopAnimation() + playingModel?.isPlaying = false + NIMSDK.shared().mediaManager.stopPlay() + } + } + + // play + open func playAudio(_ filePath: String, didBeganWithError error: Error?) { + print(#function + "\(error?.localizedDescription ?? "")") + NIMSDK.shared().mediaManager.switch(viewmodel.getHandSetEnable() ? .receiver : .speaker) + if let e = error { + if e.localizedDescription.count > 0 { + view.makeToast(e.localizedDescription) + } + playingCell?.stopAnimation() + playingModel?.isPlaying = false + } + } + + open func playAudio(_ filePath: String, didCompletedWithError error: Error?) { + print(#function + "\(error?.localizedDescription ?? "")") + if error?.localizedDescription.count ?? 0 > 0 { + view.makeToast(error?.localizedDescription ?? "") + } + // stop + playingCell?.stopAnimation() + playingModel?.isPlaying = false + } + + open func stopPlayAudio(_ filePath: String, didCompletedWithError error: Error?) { + print(#function + "\(error?.localizedDescription ?? "")") + + playingCell?.stopAnimation() + playingModel?.isPlaying = false + } + + open func playAudio(_ filePath: String, progress value: Float) {} + + open func playAudioInterruptionEnd() { + print(#function) + playingCell?.stopAnimation() + playingModel?.isPlaying = false + } + + open func playAudioInterruptionBegin() { + print(#function) + // stop play + playingCell?.stopAnimation() + playingModel?.isPlaying = false + } + + open func getRegisterCellDic() -> [String: NEBasePinMessageCell.Type] { + cellClassDic + } + + open func showTextViewController(_ model: PinMessageModel?) { + let title = NECustomAttachment.titleOfRichText(message: model?.message) + let body = NECustomAttachment.bodyOfRichText(message: model?.message) ?? model?.message.text + let textView = getTextViewController(title: title, body: body) + textView.modalPresentationStyle = .fullScreen + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: DispatchWorkItem(block: { [weak self] in + self?.navigationController?.present(textView, animated: false) + })) + } + + func getTextViewController(title: String?, body: String?) -> TextViewController { + let textViewController = TextViewController(title: title, body: body) + textViewController.view.backgroundColor = .white + return textViewController + } + + open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + MultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } + + // MARK: UIDocumentInteractionControllerDelegate + + open func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { + self + } + + open func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { + controller.dismiss(animated: true) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseReadViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseReadViewController.swift index ad90af47..ff999a40 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseReadViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseReadViewController.swift @@ -15,8 +15,8 @@ open class NEBaseReadViewController: ChatBaseViewController, UIScrollViewDelegat public var line: UIView = .init() public var lineLeftCons: NSLayoutConstraint? public var readTableView = UITableView(frame: .zero, style: .plain) - public var readUsers = [User]() - public var unReadUsers = [User]() + public var readUsers = [NEKitUser]() + public var unReadUsers = [NEKitUser]() public let readButton = UIButton(type: .custom) public let unreadButton = UIButton(type: .custom) private var message: NIMMessage @@ -44,22 +44,24 @@ open class NEBaseReadViewController: ChatBaseViewController, UIScrollViewDelegat readButton.setTitleColor(UIColor.ne_darkText, for: .normal) readButton.translatesAutoresizingMaskIntoConstraints = false readButton.addTarget(self, action: #selector(readButtonEvent), for: .touchUpInside) - view.addSubview(readButton) + readButton.accessibilityIdentifier = "id.tabHasRead" unreadButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) unreadButton.setTitle(chatLocalizable("unread"), for: .normal) unreadButton.setTitleColor(UIColor.ne_darkText, for: .normal) unreadButton.translatesAutoresizingMaskIntoConstraints = false unreadButton.addTarget(self, action: #selector(unreadButtonEvent), for: .touchUpInside) + readButton.accessibilityIdentifier = "id.tabUnRead" - view.addSubview(unreadButton) + view.addSubview(readButton) NSLayoutConstraint.activate([ readButton.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), readButton.leadingAnchor.constraint(equalTo: view.leadingAnchor), readButton.heightAnchor.constraint(equalToConstant: 48), - readButton.widthAnchor.constraint(equalTo: unreadButton.widthAnchor), + readButton.widthAnchor.constraint(equalToConstant: kScreenWidth / 2.0), ]) + view.addSubview(unreadButton) NSLayoutConstraint.activate([ unreadButton.topAnchor.constraint(equalTo: readButton.topAnchor), unreadButton.leadingAnchor.constraint(equalTo: readButton.trailingAnchor), @@ -166,7 +168,7 @@ open class NEBaseReadViewController: ChatBaseViewController, UIScrollViewDelegat NIMSDK.shared().chatManager.queryMessageReceiptDetail(message) { anError, receiptInfo in print("anError:\(anError) receiptInfo:\(receiptInfo)") if let error = anError as? NSError { - if error.code == 408 { + if error.code == noNetworkCode { self.showToast(commonLocalizable("network_error")) } else { self.showToast(error.localizedDescription) diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseSelectUserViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseSelectUserViewController.swift index e382e6f3..afbec002 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseSelectUserViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseSelectUserViewController.swift @@ -6,6 +6,7 @@ import NEChatKit import NECoreIMKit import UIKit + public typealias DidSelectedAtRow = (_ index: Int, _ model: ChatTeamMemberInfoModel?) -> Void @objcMembers @@ -18,6 +19,7 @@ open class NEBaseSelectUserViewController: ChatBaseViewController, UITableViewDe var teamInfo: ChatTeamInfoModel? private var showSelf = true // 是否展示自己 var className = "SelectUserViewController" + var isShowAtAll = true init(sessionId: String, showSelf: Bool = true) { self.sessionId = sessionId @@ -29,7 +31,7 @@ open class NEBaseSelectUserViewController: ChatBaseViewController, UITableViewDe fatalError("init(coder:) has not been implemented") } - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() navigationController?.isNavigationBarHidden = true navigationView.isHidden = true @@ -40,6 +42,7 @@ open class NEBaseSelectUserViewController: ChatBaseViewController, UITableViewDe func commonUI() { let btn = UIButton(type: .custom) btn.translatesAutoresizingMaskIntoConstraints = false + btn.accessibilityIdentifier = "id.arrowDown" btn.setImage(UIImage.ne_imageNamed(name: "arrowDown"), for: .normal) btn.addTarget(self, action: #selector(btnEvent), for: .touchUpInside) view.addSubview(btn) @@ -115,33 +118,80 @@ open class NEBaseSelectUserViewController: ChatBaseViewController, UITableViewDe } // 人员选择页面移除自己 + var selfIndex = -1 if !(self?.showSelf ?? true), let users = team?.users { for (index, user) in users.enumerated() { + if let u = team?.users[index].nimUser { + ChatUserCache.updateUserInfo(u) + } if user.nimUser?.userId == IMKitLoginManager.instance.currentAccount() { - team?.users.remove(at: index) + if user.teamMember?.type != .manager, let custom = team?.team?.clientCustomInfo, custom.count > 0, let json = getDictionaryFromJSONString(custom), let atValue = json[keyAllowAtAll] as? String, atValue == allowAtManagerValue { + self?.isShowAtAll = false + } + selfIndex = index } } + team?.users.remove(at: selfIndex) + } + + // 根据身份+进群时间正序排序 + if let users = team?.users { + var owner: ChatTeamMemberInfoModel? // 群主 + var managers = [ChatTeamMemberInfoModel]() // 管理员 + var normals = [ChatTeamMemberInfoModel]() // 普通成员 + + for user in users { + if user.teamMember?.type == .owner { + owner = user + } else if user.teamMember?.type == .manager { + managers.append(user) + } else { + normals.append(user) + } + } + + managers.sort(by: { m1, m2 in + (m1.teamMember?.createTime ?? 0) < (m2.teamMember?.createTime ?? 0) + }) + + normals.sort(by: { m1, m2 in + (m1.teamMember?.createTime ?? 0) < (m2.teamMember?.createTime ?? 0) + }) + + if let owner = owner { + team?.users = [owner] + managers + normals + } else { + team?.users = managers + normals + } } + self?.teamInfo = team self?.tableView.reloadData() } } - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func numberOfSections(in tableView: UITableView) -> Int { + 2 + } + + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + if section == 0 { + return isShowAtAll ? 1 : 0 + } if let count = teamInfo?.users.count { - return count + 1 + return count } return 0 } - public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { UITableViewCell() } - public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - if indexPath.row == 0 { + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if indexPath.section == 0 { if let block = selectedBlock { block(indexPath.row, nil) } @@ -149,7 +199,7 @@ open class NEBaseSelectUserViewController: ChatBaseViewController, UITableViewDe return } if let block = selectedBlock { - block(indexPath.row, teamInfo?.users[indexPath.row - 1]) + block(indexPath.row, teamInfo?.users[indexPath.row]) } dismiss(animated: true, completion: nil) } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseUserSettingViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseUserSettingViewController.swift index e702da51..b9fc7f57 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseUserSettingViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEBaseUserSettingViewController.swift @@ -70,7 +70,7 @@ open class NEBaseUserSettingViewController: ChatBaseViewController, UserSettingV fatalError("init(coder:) has not been implemented") } - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() viewmodel.delegate = self if let uid = userId { @@ -124,7 +124,7 @@ open class NEBaseUserSettingViewController: ChatBaseViewController, UserSettingV tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 - if let url = viewmodel.userInfo?.userInfo?.avatarUrl { + if let url = viewmodel.userInfo?.userInfo?.avatarUrl, !url.isEmpty { userHeader.sd_setImage(with: URL(string: url), completed: nil) userHeader.setTitle("") userHeader.backgroundColor = .clear @@ -265,7 +265,7 @@ open class NEBaseUserSettingViewController: ChatBaseViewController, UserSettingV // MARK: UITableViewDataSource, UITableViewDelegate - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewmodel.cellDatas.count } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEDetailMapController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEDetailMapController.swift index 4e05cb17..2c51c0c9 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEDetailMapController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/NEDetailMapController.swift @@ -7,7 +7,7 @@ import NECoreKit import UIKit @objcMembers -public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomViewDelegate { +open class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomViewDelegate { // 地图展示类型 public var mapType: NEMapType? public var currentPoint = CGPoint(x: 0, y: 0) @@ -20,9 +20,6 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView // 记录键盘弹起状态 private var foldKeyBoard = true -// private let defaultFieldFrame = CGRect(x: 12, y: 12, width: kScreenWidth - 24, height: 32) -// private let focusFieldFrame = CGRect(x: 12, y: 12, width: kScreenWidth - 64, height: 32) - private let defaultTableHeight: CGFloat = 230 var completion: NEPositionSelectCompletion? @@ -40,11 +37,11 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView super.init(nibName: nil, bundle: nil) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - override public func viewWillAppear(_ animated: Bool) { + override open func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.isHidden = true weak var weakSelf = self NEChatDetectNetworkTool.shareInstance.netWorkReachability { status in @@ -58,11 +55,11 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView } } - override public func viewWillDisappear(_ animated: Bool) { + override open func viewWillDisappear(_ animated: Bool) { navigationController?.navigationBar.isHidden = false } - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() setupSubviews() } @@ -257,14 +254,10 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView func keyBoardWillHide(_ notification: Notification) { foldKeyBoard = true -// layoutInputView(offset: 0) } private func layoutInputView(offset: CGFloat) { tableViewBottomConstraint?.constant = defaultTableHeight + offset -// UIView.animate(withDuration: 0.25, animations: { -// self.view.layoutIfNeeded() -// }) } lazy var backBtn: UIButton = { @@ -364,7 +357,6 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView ) tableView.rowHeight = 72 tableView.backgroundColor = .white -// tableView.tableHeaderView = searchBgView tableView.keyboardDismissMode = .onDrag return tableView }() @@ -388,7 +380,6 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView }() lazy var searchBgView: UIView = { - // let bgView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 60)) let bgView = UIView() bgView.translatesAutoresizingMaskIntoConstraints = false return bgView @@ -520,7 +511,7 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView // MARK: NEMapGuideBottomViewDelegate - public func didClickGuide() { + open func didClickGuide() { showBottomSelectAlert(firstContent: chatLocalizable("gaode_map"), secondContent: chatLocalizable("tencent_map")) { value in if value == 0 { @@ -571,7 +562,7 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView } } - public func loadModels(models: [ChatLocaitonModel]) { + open func loadModels(models: [ChatLocaitonModel]) { currentIndex = 0 locations.removeAll() if let keyword = searchTextField.text, keyword.count > 0 { @@ -596,7 +587,7 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView refreshCurrentCache() } - public func refreshCurrentCache() { + open func refreshCurrentCache() { if locations.count > currentIndex { currentModel = locations[currentIndex] } @@ -604,12 +595,12 @@ public class NEDetailMapController: ChatBaseViewController, NEMapGuideBottomView } extension NEDetailMapController: UITableViewDelegate, UITableViewDataSource { - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { locations.count } - public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: reuseId, for: indexPath @@ -619,7 +610,7 @@ extension NEDetailMapController: UITableViewDelegate, UITableViewDataSource { return cell } - public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let preiousCell = tableView.cellForRow(at: IndexPath(row: currentIndex, section: 0)) as? NEMapAddressCell { preiousCell.selectImg.isHidden = true } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/TextViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/TextViewController.swift index ec9fe42f..6b365f5d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/TextViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Controller/TextViewController.swift @@ -7,9 +7,10 @@ import NECommonKit @objcMembers open class TextViewController: ChatBaseViewController { - let leftRightMargin: CGFloat = 24 + let leftRightMargin: CGFloat = 20 var contentMaxWidth: CGFloat = 0 - let textFont = UIFont.systemFont(ofSize: 24, weight: .regular) + let titleFont = UIFont.systemFont(ofSize: 24, weight: .semibold) + let bodyFont = UIFont.systemFont(ofSize: 24) lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() @@ -18,27 +19,66 @@ open class TextViewController: ChatBaseViewController { return scrollView }() + lazy var textView: UIView = { + let view = UIView() + view.translatesAutoresizingMaskIntoConstraints = false + view.backgroundColor = .clear + + view.addSubview(titleLabel) + NSLayoutConstraint.activate([ + titleLabel.topAnchor.constraint(equalTo: view.topAnchor), + titleLabel.leftAnchor.constraint(equalTo: view.leftAnchor), + titleLabel.rightAnchor.constraint(equalTo: view.rightAnchor), + ]) + + view.addSubview(bodyLabel) + NSLayoutConstraint.activate([ + bodyLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor), + bodyLabel.leftAnchor.constraint(equalTo: view.leftAnchor), + bodyLabel.rightAnchor.constraint(equalTo: view.rightAnchor), + bodyLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + + return view + }() + + lazy var titleLabel: CopyableLabel = { + let label = CopyableLabel() + label.numberOfLines = 0 + label.translatesAutoresizingMaskIntoConstraints = false + label.font = titleFont + label.backgroundColor = .clear + label.textColor = .ne_darkText + return label + }() + + lazy var bodyLabel: CopyableLabel = { + let label = CopyableLabel() + label.numberOfLines = 0 + label.translatesAutoresizingMaskIntoConstraints = false + label.font = bodyFont + label.backgroundColor = .clear + label.textColor = .ne_darkText + return label + }() + var contentLabelTopAnchor: NSLayoutConstraint? var contentLabelLeftAnchor: NSLayoutConstraint? - lazy var contentLabel: CopyableLabel = { - let contentLabel = CopyableLabel() - contentLabel.numberOfLines = 0 - contentLabel.translatesAutoresizingMaskIntoConstraints = false - contentLabel.font = textFont - contentLabel.backgroundColor = .clear - return contentLabel - }() - init(content: String) { + init(title: String?, body: String?) { super.init(nibName: nil, bundle: nil) contentMaxWidth = kScreenWidth - leftRightMargin * 2 - let att = NEEmotionTool.getAttWithStr(str: content, font: textFont, CGPoint(x: 0, y: -3)) - contentLabel.copyString = att.string - contentLabel.attributedText = att - let line = String.calculateMaxLines(width: kScreenWidth - 2 * leftRightMargin, - string: att.string, - font: textFont) - contentLabel.textAlignment = .justified + if let title = title { + let titleAtt = NEEmotionTool.getAttWithStr(str: title, font: titleFont, CGPoint(x: 0, y: -3)) + titleLabel.copyString = titleAtt.string + titleLabel.attributedText = titleAtt + } + + if let body = body { + let bodyAtt = NEEmotionTool.getAttWithStr(str: body, font: bodyFont, CGPoint(x: 0, y: -3)) + bodyLabel.copyString = bodyAtt.string + bodyLabel.attributedText = bodyAtt + } } public required init?(coder: NSCoder) { @@ -64,35 +104,45 @@ open class TextViewController: ChatBaseViewController { view.addSubview(scrollView) if #available(iOS 11.0, *) { NSLayoutConstraint.activate([ - scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), + scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20), + scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20), scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0), scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -0), ]) } else { NSLayoutConstraint.activate([ - scrollView.topAnchor.constraint(equalTo: view.topAnchor), - scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), + scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20), scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0), scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -0), ]) } - scrollView.addSubview(contentLabel) - contentLabel.preferredMaxLayoutWidth = contentMaxWidth - contentLabelTopAnchor = contentLabel.topAnchor.constraint(equalTo: scrollView.topAnchor) - contentLabelLeftAnchor = contentLabel.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: leftRightMargin) + titleLabel.preferredMaxLayoutWidth = contentMaxWidth + bodyLabel.preferredMaxLayoutWidth = contentMaxWidth + scrollView.addSubview(textView) + contentLabelTopAnchor = textView.topAnchor.constraint(equalTo: scrollView.topAnchor) + contentLabelLeftAnchor = textView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: leftRightMargin) NSLayoutConstraint.activate([ contentLabelTopAnchor!, - contentLabel.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), + textView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), contentLabelLeftAnchor!, - contentLabel.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -leftRightMargin), + textView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -leftRightMargin), ]) } // textView 垂直居中 func contentSizeToFit() { - let textSize = contentLabel.attributedText?.finalSize(textFont, CGSize(width: contentMaxWidth, height: CGFloat.greatestFiniteMagnitude)) ?? .zero + var label = bodyLabel + if let titleLength = titleLabel.attributedText?.length { + if let bodyLength = bodyLabel.attributedText?.length { + label = titleLength > bodyLength ? titleLabel : bodyLabel + } else { + label = titleLabel + } + } + + let textSize = label.attributedText?.finalSize(bodyFont, CGSize(width: contentMaxWidth, height: CGFloat.greatestFiniteMagnitude)) ?? .zero let textViewHeight = kScreenHeight - kNavigationHeight - KStatusBarHeight if textSize.height <= textViewHeight { let offsetY = (textViewHeight - textSize.height) / 2 diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/EmojiPageView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/EmojiPageView.swift index e32d44e7..cc6471f8 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/EmojiPageView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/EmojiPageView.swift @@ -19,9 +19,9 @@ import UIKit @objc optional func needScrollAnimation() -> Bool } -public class EmojiPageView: UIView { - public weak var dataSource: EmojiPageViewDataSource? - public weak var pageViewDelegate: EmojiPageViewDelegate? +open class EmojiPageView: UIView { + open weak var dataSource: EmojiPageViewDataSource? + open weak var pageViewDelegate: EmojiPageViewDelegate? private var currentPage: NSInteger = 0 private var pages = [AnyObject]() private let className = "EmojiPageView" @@ -31,7 +31,7 @@ public class EmojiPageView: UIView { setupControls() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -52,14 +52,14 @@ public class EmojiPageView: UIView { addSubview(scrollView) } - public func scrollToPage(page: NSInteger) { + open func scrollToPage(page: NSInteger) { if currentPage != page || page == 0 { currentPage = page reloadData() } } - public func reloadData() { + open func reloadData() { calculatePageNumbers() setupInit() // reloadPage() @@ -187,7 +187,7 @@ public class EmojiPageView: UIView { } } - override public func layoutSubviews() { + override open func layoutSubviews() { super.layoutSubviews() let size = bounds.size scrollView.contentSize = CGSize( diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonContainerView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonContainerView.swift index 40ab4145..1d6ec145 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonContainerView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonContainerView.swift @@ -10,7 +10,7 @@ import UIKit func didPressSend(sender: UIButton) } -public class InputEmoticonContainerView: UIView { +open class InputEmoticonContainerView: UIView { private let classTag = "InputEmoticonContainerView" public weak var delegate: InputEmoticonContainerViewDelegate? @@ -45,7 +45,7 @@ public class InputEmoticonContainerView: UIView { loadEmojiData() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -287,11 +287,11 @@ extension InputEmoticonContainerView { // MARK: ====== EmojiPageViewDelegate,EmojiPageViewDataSource ============== extension InputEmoticonContainerView: EmojiPageViewDelegate, EmojiPageViewDataSource { - public func numberOfPages(pageView: EmojiPageView?) -> NSInteger { + open func numberOfPages(pageView: EmojiPageView?) -> NSInteger { sumPages() } - public func pageView(pageView: EmojiPageView?, index: NSInteger) -> UIView { + open func pageView(pageView: EmojiPageView?, index: NSInteger) -> UIView { var page = 0 var resultEmotion = NIMInputEmoticonCatalog() @@ -311,13 +311,13 @@ extension InputEmoticonContainerView: EmojiPageViewDelegate, EmojiPageViewDataSo return emojiPageView(pageView: targetView, emoticon: resultEmotion, page: index - page) } - public func needScrollAnimation() -> Bool { + open func needScrollAnimation() -> Bool { true } - public func pageViewDidScroll(_ pageView: EmojiPageView?) {} + open func pageViewDidScroll(_ pageView: EmojiPageView?) {} - public func pageViewScrollEnd(_ pageView: EmojiPageView?, currentIndex: Int, totolPages: Int) { + open func pageViewScrollEnd(_ pageView: EmojiPageView?, currentIndex: Int, totolPages: Int) { // let emticon = emoticonWithIndex(index: currentIndex) // 补充pageController逻辑 } @@ -326,13 +326,13 @@ extension InputEmoticonContainerView: EmojiPageViewDelegate, EmojiPageViewDataSo // MARK: =============== InputEmoticonTabViewDelegate =============== extension InputEmoticonContainerView: InputEmoticonTabViewDelegate { - public func tabView(_ tabView: InputEmoticonTabView?, didSelectTabIndex index: Int) {} + open func tabView(_ tabView: InputEmoticonTabView?, didSelectTabIndex index: Int) {} } // MARK: =============== InputEmoticonTabViewDelegate =============== extension InputEmoticonContainerView: NIMInputEmoticonButtonDelegate { - public func selectedEmoticon(emotion: NIMInputEmoticon, catalogID: String) { + open func selectedEmoticon(emotion: NIMInputEmoticon, catalogID: String) { guard let emotionId = emotion.emoticonID else { NELog.errorLog(classTag, desc: "❌emoticonID is nil") return diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonTabView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonTabView.swift index 042dad9e..acc9fb49 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonTabView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/InputEmoticonTabView.swift @@ -9,8 +9,8 @@ import UIKit @objc optional func tabView(_ tabView: InputEmoticonTabView?, didSelectTabIndex index: Int) } -public class InputEmoticonTabView: UIControl { - public weak var delegate: InputEmoticonTabViewDelegate? +open class InputEmoticonTabView: UIControl { + open weak var delegate: InputEmoticonTabViewDelegate? private var tabs = [UIButton]() private var seps = [UIView]() private var className = "InputEmoticonTabView" @@ -20,7 +20,7 @@ public class InputEmoticonTabView: UIControl { setUpSubViews() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -35,14 +35,14 @@ public class InputEmoticonTabView: UIControl { ]) } - public func selectTabIndex(_ index: Int) { + open func selectTabIndex(_ index: Int) { for i in 0 ..< tabs.count { let btn = tabs[i] btn.isSelected = i == index } } - public func loadCatalogs(_ emoticonCatalogs: [NIMInputEmoticonCatalog]?) { + open func loadCatalogs(_ emoticonCatalogs: [NIMInputEmoticonCatalog]?) { tabs.forEach { btn in btn.removeFromSuperview() } @@ -86,6 +86,7 @@ public class InputEmoticonTabView: UIControl { button.titleLabel?.textColor = .white button.backgroundColor = UIColor.ne_blueText button.titleLabel?.font = DefaultTextFont(14) + button.accessibilityIdentifier = "id.emojiSend" return button }() } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionAttachment.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionAttachment.swift index b765ec19..76afc50c 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionAttachment.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionAttachment.swift @@ -5,7 +5,7 @@ import UIKit -public class NEEmotionAttachment: NSTextAttachment { +open class NEEmotionAttachment: NSTextAttachment { private var _emotion: NIMInputEmoticon? public var emotion: NIMInputEmoticon? { diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionTool.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionTool.swift index dfb54c64..f5879a7e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionTool.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NEEmotionTool.swift @@ -5,7 +5,7 @@ import UIKit -public class NEEmotionTool: NSObject { +open class NEEmotionTool: NSObject { class func getAttWithStr(str: String, font: UIFont, _ offset: CGPoint = CGPoint(x: 0, y: -3)) -> NSMutableAttributedString { let regular = "\\[[^\\[|^\\]]+\\]" diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonButton.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonButton.swift index be4553e0..35f25ac0 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonButton.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonButton.swift @@ -9,14 +9,14 @@ public protocol NIMInputEmoticonButtonDelegate: NSObjectProtocol { func selectedEmoticon(emotion: NIMInputEmoticon, catalogID: String) } -public class NIMInputEmoticonButton: UIButton { +open class NIMInputEmoticonButton: UIButton { public var emotionData: NIMInputEmoticon? public var catalogID: String? public weak var delegate: NIMInputEmoticonButtonDelegate? private let classsTag = "NIMInputEmoticonButton" - public class func iconButtonWithData(data: NIMInputEmoticon, catalogID: String, - delegate: NIMInputEmoticonButtonDelegate) + open class func iconButtonWithData(data: NIMInputEmoticon, catalogID: String, + delegate: NIMInputEmoticonButtonDelegate) -> NIMInputEmoticonButton { let icon = NIMInputEmoticonButton() icon.addTarget(icon, action: #selector(onIconSelected), for: .touchUpInside) @@ -26,6 +26,8 @@ public class NIMInputEmoticonButton: UIButton { icon.isExclusiveTouch = true icon.contentMode = .scaleToFill icon.delegate = delegate + icon.accessibilityIdentifier = "id.emoji" + icon.accessibilityValue = data.tag switch data.type { case .unicode: icon.setTitle(data.unicode, for: .normal) diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonManager.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonManager.swift index 1305c12b..60c43eee 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonManager.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Emoji/NIMInputEmoticonManager.swift @@ -10,7 +10,7 @@ public enum NIMEmoticonType: NSInteger { case unicode } -public class NIMInputEmoticon: NSObject { +open class NIMInputEmoticon: NSObject { public var type: NIMEmoticonType { if let ucode = unicode, ucode.count > 0 { return .unicode @@ -25,7 +25,7 @@ public class NIMInputEmoticon: NSObject { public var unicode: String? } -public class NIMInputEmoticonLayout: NSObject { +open class NIMInputEmoticonLayout: NSObject { public var rows: NSInteger = 0 // 行数 public var columes: NSInteger = 0 // 列数 public var itemCountInPage: NSInteger = 0 // 每页显示几项 @@ -50,7 +50,7 @@ public class NIMInputEmoticonLayout: NSObject { } } -public class NIMInputEmoticonCatalog: NSObject { +open class NIMInputEmoticonCatalog: NSObject { public var layout: NIMInputEmoticonLayout? public var catalogID: String? public var title: String? @@ -65,7 +65,7 @@ public class NIMInputEmoticonCatalog: NSObject { public var pagesCount: NSInteger = 0 } -public class NIMInputEmoticonManager: NSObject { +open class NIMInputEmoticonManager: NSObject { public static let shared = NIMInputEmoticonManager() private var catalogs: [NIMInputEmoticonCatalog]? private var classTag = "NIMInputEmoticonManager" @@ -136,7 +136,7 @@ public class NIMInputEmoticonManager: NSObject { func preloadEmoticonResource() {} - public func emoticonCatalog(catalogID: String) -> NIMInputEmoticonCatalog? { + open func emoticonCatalog(catalogID: String) -> NIMInputEmoticonCatalog? { guard let infos = catalogs else { return nil } for catalog in infos { @@ -147,7 +147,7 @@ public class NIMInputEmoticonManager: NSObject { return nil } - public func emoticonByTag(tag: String) -> NIMInputEmoticon? { + open func emoticonByTag(tag: String) -> NIMInputEmoticon? { var emotion: NIMInputEmoticon? guard let clogs = catalogs else { @@ -168,7 +168,7 @@ public class NIMInputEmoticonManager: NSObject { return emotion } - public func emoticonByID(emoticonID: String) -> NIMInputEmoticon? { + open func emoticonByID(emoticonID: String) -> NIMInputEmoticon? { var emotion: NIMInputEmoticon? guard let clogs = catalogs else { NELog.errorLog(classTag, desc: "❌catalogs is nil") @@ -188,7 +188,7 @@ public class NIMInputEmoticonManager: NSObject { return emotion } - public func emoticonByCatalogID(catalogID: String, emoticonID: String) -> NIMInputEmoticon? { + open func emoticonByCatalogID(catalogID: String, emoticonID: String) -> NIMInputEmoticon? { var emotion: NIMInputEmoticon? guard let clogs = catalogs else { NELog.errorLog(classTag, desc: "❌catalogs is nil") diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatDeduplicationHelper.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatDeduplicationHelper.swift new file mode 100644 index 00000000..ae841bf6 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatDeduplicationHelper.swift @@ -0,0 +1,79 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import Foundation +import NIMSDK +@objcMembers +public class ChatDeduplicationHelper: NSObject, NIMLoginManagerDelegate { + // 单例变量 + static let instance = ChatDeduplicationHelper() + // 最多缓存数量,可外部修改 + public var limit = 100 + // 黑名单消息id记录 + public var blackListMessageIds = Set() + // 音频消息记录 + public var recordAudioMessagePaths = Set() + // 撤回消息记录 + public var revokeMessageIds = Set() + + override private init() { + super.init() + NIMSDK.shared().loginManager.add(self) + } + + deinit { + NIMSDK.shared().loginManager.remove(self) + } + + public func onLogin(_ step: NIMLoginStep) { + if step == .logout { + clearCache() + } + } + + public func onKickout(_ result: NIMLoginKickoutResult) { + clearCache() + } + + public func clearCache() { + blackListMessageIds.removeAll() + recordAudioMessagePaths.removeAll() + revokeMessageIds.removeAll() + } + + // 是否已经发送过对应消息的提示 + public func isBlackTipSended(messageId: String) -> Bool { + if blackListMessageIds.contains(messageId) { + return true + } + if blackListMessageIds.count > limit { + blackListMessageIds.removeAll() + } + blackListMessageIds.insert(messageId) + return false + } + + // 是否已经发过对应路径的音频消息,防止重复发送 + public func isRecordAudioSended(path: String) -> Bool { + if recordAudioMessagePaths.contains(path) { + return true + } + if recordAudioMessagePaths.count > limit { + recordAudioMessagePaths.removeAll() + } + return false + } + + // 是否已经保存过此撤回消息,防止重复保存本地撤回记录 + public func isRevokeMessageSaved(messageId: String) -> Bool { + if revokeMessageIds.contains(messageId) { + return true + } + if revokeMessageIds.count > limit { + revokeMessageIds.removeAll() + } + revokeMessageIds.insert(messageId) + return false + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatMessageHelper.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatMessageHelper.swift index 697e8847..258da275 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatMessageHelper.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ChatMessageHelper.swift @@ -3,10 +3,17 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import CommonCrypto import Foundation +import NEChatKit +import NECommonKit +import NECoreIMKit +import NIMSDK @objcMembers public class ChatMessageHelper: NSObject { + public static let repo = ChatRepo.shared + // 获取图片合适尺寸 public class func getSizeWithMaxSize(_ maxSize: CGSize, size: CGSize, miniWH: CGFloat) -> CGSize { @@ -34,4 +41,291 @@ public class ChatMessageHelper: NSObject { return realSize } + + public static func getSessionName(session: NIMSession, showAlias: Bool = true) -> String { + session.sessionType == .P2P ? ChatUserCache.getShowName(userId: session.sessionId, teamId: nil, showAlias) : repo.getTeamInfo(teamId: session.sessionId)?.teamName ?? "" + } + + // MARK: message + + public static func getChatCellRegisterDic(isFun: Bool) -> [String: UITableViewCell.Type] { + [ + "\(MessageType.text.rawValue)": + isFun ? FunChatMessageTextCell.self : ChatMessageTextCell.self, + "\(MessageType.rtcCallRecord.rawValue)": + isFun ? FunChatMessageCallCell.self : ChatMessageCallCell.self, + "\(MessageType.audio.rawValue)": + isFun ? FunChatMessageAudioCell.self : ChatMessageAudioCell.self, + "\(MessageType.image.rawValue)": + isFun ? FunChatMessageImageCell.self : ChatMessageImageCell.self, + "\(MessageType.revoke.rawValue)": + isFun ? FunChatMessageRevokeCell.self : ChatMessageRevokeCell.self, + "\(MessageType.video.rawValue)": + isFun ? FunChatMessageVideoCell.self : ChatMessageVideoCell.self, + "\(MessageType.file.rawValue)": + isFun ? FunChatMessageFileCell.self : ChatMessageFileCell.self, + "\(MessageType.reply.rawValue)": + isFun ? FunChatMessageReplyCell.self : ChatMessageReplyCell.self, + "\(MessageType.location.rawValue)": + isFun ? FunChatMessageLocationCell.self : ChatMessageLocationCell.self, + "\(MessageType.time.rawValue)": + isFun ? FunChatMessageTipCell.self : ChatMessageTipCell.self, + "\(MessageType.multiForward.rawValue)": + isFun ? FunChatMessageMultiForwardCell.self : ChatMessageMultiForwardCell.self, + "\(MessageType.richText.rawValue)": + isFun ? FunChatMessageRichTextCell.self : ChatMessageRichTextCell.self, + ] + } + + public static func getPinCellRegisterDic(isFun: Bool) -> [String: NEBasePinMessageCell.Type] { + [ + "\(MessageType.text.rawValue)": + isFun ? FunPinMessageTextCell.self : PinMessageTextCell.self, + "\(MessageType.image.rawValue)": + isFun ? FunPinMessageImageCell.self : PinMessageImageCell.self, + "\(MessageType.audio.rawValue)": + isFun ? FunPinMessageAudioCell.self : PinMessageAudioCell.self, + "\(MessageType.video.rawValue)": + isFun ? FunPinMessageVideoCell.self : PinMessageVideoCell.self, + "\(MessageType.location.rawValue)": + isFun ? FunPinMessageLocationCell.self : PinMessageLocationCell.self, + "\(MessageType.file.rawValue)": + isFun ? FunPinMessageFileCell.self : PinMessageFileCell.self, + "\(MessageType.multiForward.rawValue)": + isFun ? FunPinMessageMultiForwardCell.self : PinMessageMultiForwardCell.self, + "\(MessageType.richText.rawValue)": + isFun ? FunPinMessageRichTextCell.self : PinMessageRichTextCell.self, + "\(NEBasePinMessageTextCell.self)": + isFun ? FunPinMessageDefaultCell.self : PinMessageDefaultCell.self, + ] + } + + public static func modelFromMessage(message: NIMMessage) -> MessageModel { + var model: MessageModel + switch message.messageType { + case .video: + model = MessageVideoModel(message: message) + case .text: + model = MessageTextModel(message: message) + case .image: + model = MessageImageModel(message: message) + case .audio: + model = MessageAudioModel(message: message) + case .notification, .tip: + model = MessageTipsModel(message: message) + case .file: + model = MessageFileModel(message: message) + case .location: + model = MessageLocationModel(message: message) + case .rtcCallRecord: + model = MessageCallRecordModel(message: message) + case .custom: + if let attach = NECustomAttachment.attachmentOfCustomMessage(message: message) { + if attach.customType == customRichTextType { + return MessageRichTextModel(message: message) + } + return MessageCustomModel(message: message) + } + fallthrough + default: + // 未识别的消息类型,默认为文本消息类型,text为未知消息体 + message.text = chatLocalizable("msg_unknown") + model = MessageTextModel(message: message) + } + return model + } + + /// 获取消息列表的中所以图片消息的 url + public static func getUrls(messages: [MessageModel]) -> [String] { + NELog.infoLog(ModuleName + " " + className(), desc: #function) + var urls = [String]() + messages.forEach { model in + if model.type == .image, let message = model.message?.messageObject as? NIMImageObject { + if let url = message.url { + urls.append(url) + } else { + if let path = message.path, FileManager.default.fileExists(atPath: path) { + urls.append(path) + } + } + } + } + return urls + } + + // history message insert message at first of messages, send message add last of messages + static func addTimeMessage(_ model: MessageModel, _ lastModel: MessageModel?) { + guard let message = model.message else { + NELog.errorLog(ModuleName + " " + className(), desc: #function + ", model.message is nil") + return + } + + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) + if NotificationMessageUtils.isDiscussSeniorTeamNoti(message: message) { + return + } + + let lastTs = lastModel?.message?.timestamp ?? 0.0 + let curTs = message.timestamp + let dur = curTs - lastTs + if (dur / 60) > 5 { + let timeText = String.stringFromDate(date: Date(timeIntervalSince1970: curTs)) + model.timeContent = timeText + } + } + + public static func contentOfMessage(_ message: NIMMessage?) -> String { + switch message?.messageType { + case .text: + if let t = message?.text { + return t + } else { + return chatLocalizable("message_not_found") + } + case .image: + return chatLocalizable("msg_image") + case .audio: + return chatLocalizable("msg_audio") + case .video: + return chatLocalizable("msg_video") + case .file: + return chatLocalizable("msg_file") + case .location: + return chatLocalizable("msg_location") + case .rtcCallRecord: + if let record = message?.messageObject as? NIMRtcCallRecordObject { + return record.callType == .audio ? chatLocalizable("msg_rtc_audio") : + chatLocalizable("msg_rtc_video") + } + return chatLocalizable("msg_rtc_call") + case .custom: + if let content = NECustomAttachment.contentOfRichText(message: message) { + return content + } + + if let attach = NECustomAttachment.attachmentOfCustomMessage(message: message), + attach.customType == customMultiForwardType { + return "[\(chatLocalizable("chat_history"))]" + } + + return chatLocalizable("msg_custom") + default: + return chatLocalizable("msg_unknown") + } + } + + /// 移除消息扩展字段中的 回复、@ + public static func clearForwardAtMark(_ forwardMessage: NIMMessage) { + forwardMessage.remoteExt?.removeValue(forKey: yxAtMsg) + forwardMessage.remoteExt?.removeValue(forKey: keyReplyMsgKey) + if forwardMessage.remoteExt?.count ?? 0 <= 0 { + forwardMessage.remoteExt = nil + } + } + + public static func buildHeader(messageCount: Int) -> String { + var dic = [String: Any]() + dic["version"] = 0 // 功能版本 + dic["terminal"] = 2 // iOS + // dic["sdk_version"] = IMKitClient.instance.sdkVersion() + // dic["app_version"] = imkitVersion + dic["message_count"] = messageCount // 转发消息数量 + + return getJSONStringFromDictionary(dic) + } + + public static func buildBody(messages: [NIMMessage], + _ completion: @escaping (String, [[String: Any]]) -> Void) { + let enter = "\n" // 分隔符 + var body = "" // 序列化结果 + var abstracts = [[String: Any]]() // 摘要信息 + let group = DispatchGroup() + + for (i, msg) in messages.enumerated() { + // 移除扩展字段中的 回复、@ 信息 + let remoteExt = msg.remoteExt + clearForwardAtMark(msg) + + // 保存消息昵称和头像 + if let from = msg.from { + group.enter() + ChatUserCache.getUserInfo(from) { user, error in + if let user = user { + let senderNick = user.showName(false) + if msg.remoteExt != nil { + msg.remoteExt![mergedMessageNickKey] = senderNick + msg.remoteExt![mergedMessageAvatarKey] = user.userInfo?.avatarUrl ?? user.shortName(count: 2) + } else { + msg.remoteExt = [mergedMessageNickKey: senderNick as Any, + mergedMessageAvatarKey: user.userInfo?.avatarUrl as Any] + } + + // 摘要信息 + if i < 3 { + let content = ChatMessageHelper.contentOfMessage(msg) + abstracts.append(["senderNick": senderNick as Any, + "content": content, + "userAccId": from]) + } + } + body.append(enter) + let data = NIMSDK.shared().conversationManager.encodeMessage(toData: msg) + if let stringData = String(data: data, encoding: .utf8) { + body.append(stringData) + } + group.leave() + } + } + + // 恢复扩展字段中的 回复、@ 信息 + msg.remoteExt = remoteExt + } + + group.notify(queue: .main, work: DispatchWorkItem(block: { + completion(body, abstracts) + })) + } + + public static func getFileChecksum(fileURL: URL) -> String? { + // 打开文件,创建文件句柄 + let file = FileHandle(forReadingAtPath: fileURL.path) + guard file != nil else { return nil } + + // 创建 CC_MD5_CTX 上下文对象 + var context = CC_MD5_CTX() + CC_MD5_Init(&context) + + // 读取文件数据并更新上下文对象 + while autoreleasepool(invoking: { + let data = file?.readData(ofLength: 1024) + if data?.count == 0 { + return false + } + data?.withUnsafeBytes { buffer in + CC_MD5_Update(&context, buffer.baseAddress, CC_LONG(buffer.count)) + } + return true + }) {} + + // 计算 MD5 值并关闭文件 + var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) + CC_MD5_Final(&digest, &context) + file?.closeFile() + + // 将 MD5 值转换为字符串格式 + let md5String = digest.map { String(format: "%02hhx", $0) }.joined() + return md5String + } + + // 检测语音消息是否下载,非漫游的云端消息不会自动下载语音文件,需要手动下载 + public static func downloadAudioFile(message: NIMMessage) { + if message.messageType == .audio { + if let audio = message.messageObject as? NIMAudioObject { + if let path = audio.path, FileManager.default.fileExists(atPath: path) == false { + repo.downloadMessageAttachment(message) { error in + } + } + } + } + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/MessageUtils.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/MessageUtils.swift index 97542349..1856b5a4 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/MessageUtils.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/MessageUtils.swift @@ -8,15 +8,15 @@ import NECoreIMKit import NIMSDK @objcMembers -public class MessageUtils: NSObject { - public class func textMessage(text: String) -> NIMMessage { +open class MessageUtils: NSObject { + open class func textMessage(text: String) -> NIMMessage { let message = NIMMessage() message.setting = messageSetting() message.text = text return message } - public class func textMessage(text: String, remoteExt: [String: Any]?) -> NIMMessage { + open class func textMessage(text: String, remoteExt: [String: Any]?) -> NIMMessage { let message = NIMMessage() message.setting = messageSetting() message.text = text @@ -26,15 +26,19 @@ public class MessageUtils: NSObject { return message } - public class func imageMessage(image: UIImage) -> NIMMessage { + open class func imageMessage(image: UIImage) -> NIMMessage { imageMessage(imageObject: NIMImageObject(image: image)) } - public class func imageMessage(path: String) -> NIMMessage { + open class func imageMessage(path: String) -> NIMMessage { imageMessage(imageObject: NIMImageObject(filepath: path)) } - public class func imageMessage(imageObject: NIMImageObject) -> NIMMessage { + open class func imageMessage(data: Data, ext: String) -> NIMMessage { + imageMessage(imageObject: NIMImageObject(data: data, extension: ext)) + } + + open class func imageMessage(imageObject: NIMImageObject) -> NIMMessage { let message = NIMMessage() let option = NIMImageOption() option.compressQuality = 0.8 @@ -45,7 +49,7 @@ public class MessageUtils: NSObject { return message } - public class func audioMessage(filePath: String) -> NIMMessage { + open class func audioMessage(filePath: String) -> NIMMessage { let messageObject = NIMAudioObject(sourcePath: filePath) let message = NIMMessage() message.messageObject = messageObject @@ -54,7 +58,7 @@ public class MessageUtils: NSObject { return message } - public class func videoMessage(filePath: String) -> NIMMessage { + open class func videoMessage(filePath: String) -> NIMMessage { let messageObject = NIMVideoObject(sourcePath: filePath) let message = NIMMessage() message.messageObject = messageObject @@ -63,7 +67,7 @@ public class MessageUtils: NSObject { return message } - public class func locationMessage(_ lat: Double, _ lng: Double, _ title: String, _ address: String) -> NIMMessage { + open class func locationMessage(_ lat: Double, _ lng: Double, _ title: String, _ address: String) -> NIMMessage { let messageObject = NIMLocationObject(latitude: lat, longitude: lng, title: address) let message = NIMMessage() message.messageObject = messageObject @@ -73,7 +77,7 @@ public class MessageUtils: NSObject { return message } - public class func fileMessage(filePath: String, displayName: String?) -> NIMMessage { + open class func fileMessage(filePath: String, displayName: String?) -> NIMMessage { let messageObject = NIMFileObject(sourcePath: filePath) if let dpName = displayName { messageObject.displayName = dpName @@ -85,7 +89,7 @@ public class MessageUtils: NSObject { return message } - public class func fileMessage(data: Data, displayName: String?) -> NIMMessage { + open class func fileMessage(data: Data, displayName: String?) -> NIMMessage { let dpName = displayName ?? "" let pointIndex = dpName.lastIndex(of: ".") ?? dpName.startIndex let suffix = dpName[dpName.index(after: pointIndex) ..< dpName.endIndex] @@ -98,10 +102,21 @@ public class MessageUtils: NSObject { return message } - public class func messageSetting() -> NIMMessageSetting { + open class func customMessage(attachment: NIMCustomAttachment?, + remoteExt: [String: Any]?, + apnsContent: String?) -> NIMMessage { + let messageObject = NIMCustomObject() + messageObject.attachment = attachment + let message = NIMMessage() + message.messageObject = messageObject + message.apnsContent = apnsContent + message.remoteExt = remoteExt + message.setting = messageSetting() + return message + } + + open class func messageSetting() -> NIMMessageSetting { let setting = NIMMessageSetting() - print("getMessageRead: \(SettingProvider.shared.getMessageRead())") -// FIXME: setting.teamReceiptEnabled = SettingProvider.shared.getMessageRead() return setting } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/NotificationMessageUtils.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/NotificationMessageUtils.swift index e526ea8a..2f8e97d8 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/NotificationMessageUtils.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/NotificationMessageUtils.swift @@ -14,8 +14,8 @@ public enum TeamType { case discussTeam } -public class NotificationMessageUtils: NSObject { - public class func textForNotification(message: NIMMessage) -> String { +open class NotificationMessageUtils: NSObject { + open class func textForNotification(message: NIMMessage) -> String { if message.messageType != .notification { return "" } @@ -37,7 +37,7 @@ public class NotificationMessageUtils: NSObject { } /// 是否是群通知 - public class func isDiscussSeniorTeamNoti(message: NIMMessage) -> Bool { + open class func isDiscussSeniorTeamNoti(message: NIMMessage) -> Bool { if let object = message.messageObject as? NIMNotificationObject, let _ = object.content as? NIMTeamNotificationContent { return true @@ -45,7 +45,7 @@ public class NotificationMessageUtils: NSObject { return false } - public class func isDiscussSeniorTeamUpdateCustomNoti(message: NIMMessage) -> Bool { + open class func isDiscussSeniorTeamUpdateCustomNoti(message: NIMMessage) -> Bool { if let object = message.messageObject as? NIMNotificationObject { guard let content = object.content as? NIMTeamNotificationContent else { return false @@ -73,7 +73,7 @@ public class NotificationMessageUtils: NSObject { return false } - public class func isTeamLeaveOrDismiss(message: NIMMessage) -> (isLeave: Bool, isDismiss: Bool) { + open class func isTeamLeaveOrDismiss(message: NIMMessage) -> (isLeave: Bool, isDismiss: Bool) { var leave = false var dismiss = false if let object = message.messageObject as? NIMNotificationObject, object.notificationType == .team { @@ -93,7 +93,7 @@ public class NotificationMessageUtils: NSObject { return (leave, dismiss) } - public class func textForTeamNotificationMessage(message: NIMMessage) -> String { + open class func textForTeamNotificationMessage(message: NIMMessage) -> String { var text = chatLocalizable("unknown_system_message") if let object = message.messageObject as? NIMNotificationObject { if let content = object.content as? NIMTeamNotificationContent { @@ -130,7 +130,7 @@ public class NotificationMessageUtils: NSObject { case .transferOwner: text = fromName + chatLocalizable("transfer") + toFirstName case .addManager: - text = toFirstName + chatLocalizable("added_manager") + text = toNamestext + chatLocalizable("added_manager") case .removeManager: text = toFirstName + chatLocalizable("removed_manager") case .acceptInvitation: @@ -154,34 +154,14 @@ public class NotificationMessageUtils: NSObject { return text } - // 获取展示的用户名字,p2p: 备注 > 昵称 > ID team: 备注 > 群昵称 > 昵称 > ID - public class func getShowName(userId: String, nimSession: NIMSession?) -> String { - let user = UserInfoProvider.shared.getUserInfo(userId: userId) - var fullName = userId - if let nickName = user?.userInfo?.nickName { - fullName = nickName - } - if let session = nimSession, session.sessionType == .team { - // team - let teamMember = TeamProvider.shared.teamMember(userId, session.sessionId) - if let teamNickname = teamMember?.nickname { - fullName = teamNickname - } - } - if let alias = user?.alias { - fullName = alias - } - return fullName - } - - public class func fromName(message: NIMMessage) -> String { + open class func fromName(message: NIMMessage) -> String { if let object = message.messageObject as? NIMNotificationObject { if let content = object.content as? NIMTeamNotificationContent { if content.sourceID == NIMSDK.shared().loginManager.currentAccount() { return chatLocalizable("You") + " " } else { if let sourceId = content.sourceID { - return getShowName(userId: sourceId, nimSession: message.session) + return ChatUserCache.getShowName(userId: sourceId, teamId: message.session?.sessionId) } } } @@ -189,7 +169,7 @@ public class NotificationMessageUtils: NSObject { return "" } - public class func toName(message: NIMMessage) -> [String] { + open class func toName(message: NIMMessage) -> [String] { var toNames = [String]() guard let object = message.messageObject as? NIMNotificationObject, let content = object.content as? NIMTeamNotificationContent, @@ -201,13 +181,13 @@ public class NotificationMessageUtils: NSObject { toNames.append(chatLocalizable("You") + " ") } else { toNames - .append(getShowName(userId: targetID, nimSession: message.session)) + .append(ChatUserCache.getShowName(userId: targetID, teamId: message.session?.sessionId)) } } return toNames } - public class func teamName(message: NIMMessage) -> String { + open class func teamName(message: NIMMessage) -> String { let teamtype = teamType(message: message) switch teamtype { case .advanceTeam: @@ -217,7 +197,7 @@ public class NotificationMessageUtils: NSObject { } } - public class func teamType(message: NIMMessage) -> TeamType { + open class func teamType(message: NIMMessage) -> TeamType { let team = TeamProvider.shared.getTeam(teamId: message.session?.sessionId ?? "") if team?.isDisscuss() == true { return .discussTeam diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ReplyMessageUtil.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ReplyMessageUtil.swift index c1892062..83e54bf7 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ReplyMessageUtil.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Helper/ReplyMessageUtil.swift @@ -5,35 +5,22 @@ import Foundation -public class ReplyMessageUtil: NSObject { +open class ReplyMessageUtil: NSObject { public static func textForReplyModel(model: MessageContentModel) -> String { - var text = "|" + var text = "" if let name = model.fullName { - text += name + text += name + ": " } - text += ": " - switch model.type { - case .text, .reply: - if let t = model.message?.text { - text += t - } else { - text = chatLocalizable("message_not_found") + + if model.type == .reply { + if let content = NECustomAttachment.contentOfRichText(message: model.message) { + return text + content } - case .image: - text += "[\(chatLocalizable("msg_image"))]" - case .audio: - text += "[\(chatLocalizable("msg_audio"))]" - case .video: - text += "[\(chatLocalizable("msg_video"))]" - case .file: - text += "[\(chatLocalizable("msg_file"))]" - case .custom: - text += "[\(chatLocalizable("msg_custom"))]" - case .location: - text += "[\(chatLocalizable("msg_location"))]" - default: - text += "[\(chatLocalizable("msg_unknown"))]" + text += "\(model.message?.text ?? chatLocalizable("message_not_found"))" + } else { + text += "\(ChatMessageHelper.contentOfMessage(model.message))" } + return text } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtCacheModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtCacheModel.swift index 2a789cb3..10e3646e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtCacheModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtCacheModel.swift @@ -5,7 +5,7 @@ import UIKit @objcMembers -public class MessageAtCacheModel: NSObject { +open class MessageAtCacheModel: NSObject { public var atModel: MessageAtInfoModel public var accid: String public var text: String? diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtInfoModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtInfoModel.swift index 97ec3da6..ce7358f0 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtInfoModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAtInfoModel.swift @@ -5,7 +5,7 @@ import UIKit @objcMembers -public class MessageAtInfoModel: NSObject { +open class MessageAtInfoModel: NSObject { public var start = 0 public var end = 0 public var broken = false diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAudioModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAudioModel.swift index e51515cd..78b8ddeb 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAudioModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageAudioModel.swift @@ -7,10 +7,11 @@ import Foundation import NIMSDK @objcMembers -class MessageAudioModel: MessageContentModel { +open class MessageAudioModel: MessageContentModel { public var duration: Int = 0 public var isPlaying = false - required init(message: NIMMessage?) { + + public required init(message: NIMMessage?) { super.init(message: message) type = .audio var audioW = 96.0 @@ -23,6 +24,6 @@ class MessageAudioModel: MessageContentModel { } } contentSize = CGSize(width: audioW, height: chat_min_h) - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCallRecordModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCallRecordModel.swift index 79800eab..56acfafe 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCallRecordModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCallRecordModel.swift @@ -8,10 +8,10 @@ import NIMSDK import UIKit @objcMembers -class MessageCallRecordModel: MessageContentModel { +open class MessageCallRecordModel: MessageContentModel { public var attributeStr: NSMutableAttributedString? - required init(message: NIMMessage?) { + public required init(message: NIMMessage?) { super.init(message: message) type = .rtcCallRecord var isAuiodRecord = false @@ -68,6 +68,6 @@ class MessageCallRecordModel: MessageContentModel { h = textSize.height + (isAuiodRecord ? 20 : 24) contentSize = CGSize(width: textSize.width + chat_cell_margin * 2, height: h) - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageContentModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageContentModel.swift index effad06b..5616d902 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageContentModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageContentModel.swift @@ -10,25 +10,38 @@ import NIMSDK import simd @objcMembers -public class MessageContentModel: NSObject, MessageModel { +open class MessageContentModel: NSObject, MessageModel { public var offset: CGFloat = 0 - public func cellHeight() -> CGFloat { + open func cellHeight() -> CGFloat { CGFloat(height) + offset } public var isReplay: Bool = false + public var showSelect: Bool = false // 多选按钮是否展示 + public var isSelected: Bool = false // 多选是否选中 + public var inMultiForward: Bool = false { // 是否是合并消息中的子消息 + didSet { +// fullNameHeight = 0 // 合并消息中的子消息不显示昵称 + fullNameHeight = 20 // 合并消息中的子消息显示昵称 + if inMultiForward { + height += fullNameHeight + } else if oldValue { + height -= fullNameHeight + } + } + } public var pinAccount: String? public var pinShowName: String? public var type: MessageType = .custom public var message: NIMMessage? public var contentSize = CGSize(width: 32.0, height: chat_min_h) - public var height: Float = 48 + public var height: CGFloat = 48 public var shortName: String? // 昵称 > uid public var fullName: String? // 备注 >(群昵称)> 昵称 > uid public var avatar: String? public var replyText: String? - public var fullNameHeight: Float = 0 + public var fullNameHeight: CGFloat = 0 public var isRevokedText: Bool = false public var timeOut = false @@ -59,11 +72,21 @@ public class MessageContentModel: NSObject, MessageModel { } else { contentSize = CGSize(width: 130, height: chat_min_h) } - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin + fullNameHeight + + // time + if let time = timeContent, !time.isEmpty { + height += chat_timeCellH + } } else { type = .custom contentSize = CGSize(width: 32.0, height: chat_min_h) - height = Float(chat_min_h + chat_content_margin) + fullNameHeight + height = chat_min_h + chat_content_margin + fullNameHeight + + // time + if let time = timeContent, !time.isEmpty { + height += chat_timeCellH + } } } } @@ -71,9 +94,18 @@ public class MessageContentModel: NSObject, MessageModel { public var isPined: Bool = false { didSet { if isPined { - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + Float(chat_pin_height) - } else { - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height += chat_pin_height + } else if oldValue { + height -= chat_pin_height + } + } + } + + // 是否显示时间 + public var timeContent: String? { + didSet { + if let time = timeContent, !time.isEmpty, time != oldValue { + height += chat_timeCellH } } } @@ -82,8 +114,8 @@ public class MessageContentModel: NSObject, MessageModel { self.message = message if message?.session?.sessionType == .team, !IMKitClient.instance.isMySelf(message?.from) { - fullNameHeight = 20 + fullNameHeight = NEKitChatConfig.shared.ui.messageProperties.showTeamMessageNick ? 20 : 0 } - print("self.fullNameHeight\(fullNameHeight)") + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCustomModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCustomModel.swift index c9d8e843..fcecc360 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCustomModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageCustomModel.swift @@ -6,9 +6,13 @@ import NIMSDK import UIKit @objc -public class MessageCustomModel: MessageContentModel { - required init(message: NIMMessage?) { +open class MessageCustomModel: MessageContentModel { + public required init(message: NIMMessage?) { super.init(message: message) type = .custom + if let attachment = NECustomAttachment.attachmentOfCustomMessage(message: message) { + contentSize = CGSize(width: 0, height: Int(attachment.cellHeight)) + height = contentSize.height + chat_content_margin * 2 + fullNameHeight + } } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageFileModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageFileModel.swift index 2f989053..4a64f250 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageFileModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageFileModel.swift @@ -7,7 +7,7 @@ import NIMSDK import UIKit @objcMembers -class MessageFileModel: MessageContentModel { +open class MessageFileModel: MessageContentModel { public var displayName: String? public var path: String? public var url: String? @@ -18,7 +18,7 @@ class MessageFileModel: MessageContentModel { public var state = DownloadState.Success public weak var cell: NEChatBaseCell? - required init(message: NIMMessage?) { + public required init(message: NIMMessage?) { super.init(message: message) type = .file if let fileObject = message?.messageObject as? NIMFileObject { @@ -28,6 +28,6 @@ class MessageFileModel: MessageContentModel { fileLength = fileObject.fileLength } contentSize = chat_file_size - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageImageModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageImageModel.swift index bb018124..ccb7bd0f 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageImageModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageImageModel.swift @@ -7,9 +7,10 @@ import Foundation import NIMSDK @objcMembers -class MessageImageModel: MessageContentModel { +open class MessageImageModel: MessageContentModel { public var imageUrl: String? - required init(message: NIMMessage?) { + + public required init(message: NIMMessage?) { super.init(message: message) type = .image if let imageObject = message?.messageObject as? NIMImageObject { @@ -26,6 +27,6 @@ class MessageImageModel: MessageContentModel { } else { contentSize = chat_pic_size } - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageLocationModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageLocationModel.swift index 4ee29b40..d193d92e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageLocationModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageLocationModel.swift @@ -5,12 +5,14 @@ import NIMSDK import UIKit -class MessageLocationModel: MessageContentModel { +@objcMembers +open class MessageLocationModel: MessageContentModel { public var lat: Double? public var lng: Double? public var title: String? public var subTitle: String? - required init(message: NIMMessage?) { + + public required init(message: NIMMessage?) { super.init(message: message) type = .location if let locationObject = message?.messageObject as? NIMLocationObject { @@ -20,6 +22,6 @@ class MessageLocationModel: MessageContentModel { title = message?.text contentSize = CGSize(width: 242, height: 140) } - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageModel.swift index 23a2041d..db8fb8a9 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageModel.swift @@ -22,6 +22,12 @@ public enum MessageType: Int { case time case revoke case reply + + /// 合并转发消息 + case multiForward + + /// 带标题的文本消息 + case richText } @objc @@ -29,7 +35,7 @@ public protocol MessageModel: NSObjectProtocol { var message: NIMMessage? { get set } // 气泡区域的大小 不包含气泡上下到cell上下的边距 var contentSize: CGSize { get set } - var height: Float { get set } + var height: CGFloat { get set } // 名字后2位 var shortName: String? { get set } // 名字全长 @@ -46,6 +52,11 @@ public protocol MessageModel: NSObjectProtocol { var replyText: String? { get set } var isRevokedText: Bool { get set } var isReplay: Bool { get set } + var showSelect: Bool { get set } // 多选按钮是否展示 + var isSelected: Bool { get set } // 多选是否选中 + var inMultiForward: Bool { get set } // 是否是合并消息中的子消息 + + var timeContent: String? { get set } // 具体时间 init(message: NIMMessage?) diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageRichTextModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageRichTextModel.swift new file mode 100644 index 00000000..ce115450 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageRichTextModel.swift @@ -0,0 +1,41 @@ + +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import Foundation +import NECommonKit +import NIMSDK + +@objcMembers +open class MessageRichTextModel: MessageTextModel { + public var titleAttributeStr: NSMutableAttributedString? + public var titleTextHeight: CGFloat = 0 + + public required init(message: NIMMessage?) { + guard let data = NECustomAttachment.dataOfCustomMessage(message: message), + let title = data["title"] as? String else { + super.init(message: message) + return + } + + let body = (data["body"] as? String) ?? "" + message?.text = body + super.init(message: message) + type = .custom + + let font = UIFont.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize, weight: .semibold) + titleAttributeStr = NEEmotionTool.getAttWithStr( + str: title, + font: font + ) + + let textSize = titleAttributeStr?.finalSize(font, CGSize(width: chat_text_maxW, height: CGFloat.greatestFiniteMagnitude)) ?? .zero + + titleTextHeight = textSize.height + contentSize = CGSize(width: max(contentSize.width, textSize.width + chat_content_margin * 2), + height: contentSize.height + titleTextHeight + + (body.isEmpty ? 0 : chat_content_margin)) + height = contentSize.height + chat_content_margin * 2 + fullNameHeight + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTextModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTextModel.swift index 14b6776d..0f92533a 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTextModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTextModel.swift @@ -8,11 +8,11 @@ import NECommonKit import NIMSDK @objcMembers -class MessageTextModel: MessageContentModel { +open class MessageTextModel: MessageContentModel { public var attributeStr: NSMutableAttributedString? public var textHeight: CGFloat = 0 - required init(message: NIMMessage?) { + public required init(message: NIMMessage?) { super.init(message: message) type = .text @@ -41,6 +41,6 @@ class MessageTextModel: MessageContentModel { textHeight = textSize.height contentSize = CGSize(width: textSize.width + chat_content_margin * 2, height: textHeight + chat_content_margin * 2) - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTipsModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTipsModel.swift index 641d7163..b2e1c071 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTipsModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageTipsModel.swift @@ -7,37 +7,15 @@ import Foundation import NIMSDK @objcMembers -class MessageTipsModel: NSObject, MessageModel { - var offset: CGFloat = 0 +open class MessageTipsModel: MessageContentModel { + var text: String? - func cellHeight() -> CGFloat { - CGFloat(height) + offset + public required init(message: NIMMessage?) { + super.init(message: message) + commonInit() } - var tipTimeStamp: TimeInterval? - - var isReplay: Bool = false - - var pinToAccount: String? - var pinFromAccount: String? - var isPined: Bool = false - var pinAccount: String? - var pinShowName: String? - var replyText: String? - var type: MessageType = .tip - var message: NIMMessage? - var contentSize: CGSize = .zero - var height: Float = 28 - var shortName: String? - var fullName: String? - var avatar: String? - var text: String? - var isRevoked: Bool = false - var replyedModel: MessageModel? - var isRevokedText: Bool = false - weak var tipMessage: NIMMessage? - - func commonInit(message: NIMMessage?) { + func setText() { if let msg = message { if msg.messageType == .notification { text = NotificationMessageUtils.textForNotification(message: msg) @@ -46,37 +24,19 @@ class MessageTipsModel: NSObject, MessageModel { text = msg.text type = .tip } - - tipMessage = msg - tipTimeStamp = msg.timestamp } - - var font: UIFont = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.timeTextSize) - - contentSize = String.getTextRectSize(text ?? "", - font: font, - size: CGSize(width: chat_text_maxW, height: CGFloat.greatestFiniteMagnitude)) - height = Float(max(contentSize.height + chat_content_margin, 28)) } - required init(message: NIMMessage?) { - super.init() - commonInit(message: message) - } + func commonInit() { + setText() + let font: UIFont = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.timeTextSize) - init(message: NIMMessage?, initType: MessageType = .tip, initText: String? = nil) { - super.init() - type = initType - text = initText - commonInit(message: message) - } + contentSize = text?.finalSize(font, CGSize(width: chat_content_maxW, height: CGFloat.greatestFiniteMagnitude)) ?? .zero + height = ceil(contentSize.height) - public func resetNotiText() { - if let msg = tipMessage { - if msg.messageType == .notification { - text = NotificationMessageUtils.textForNotification(message: msg) - type = .notification - } + // time + if let time = timeContent, !time.isEmpty { + height += chat_timeCellH } } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageVideoModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageVideoModel.swift index 23d57343..50fd4e6e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageVideoModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/MessageVideoModel.swift @@ -7,18 +7,18 @@ import NIMSDK import UIKit @objc -enum DownloadState: Int { +public enum DownloadState: Int { case Success = 1 case Downalod } @objcMembers -class MessageVideoModel: MessageContentModel { +open class MessageVideoModel: MessageContentModel { public var imageUrl: String? public var state = DownloadState.Success public var progress: Float = 0 public weak var cell: NEChatBaseCell? - required init(message: NIMMessage?) { + public required init(message: NIMMessage?) { super.init(message: message) type = .video if let videoObject = message?.messageObject as? NIMVideoObject { @@ -31,6 +31,6 @@ class MessageVideoModel: MessageContentModel { } else { contentSize = chat_pic_size } - height = Float(contentSize.height + chat_content_margin) + fullNameHeight + height = contentSize.height + chat_content_margin * 2 + fullNameHeight } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NECustomAttachmentProtocol.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NECustomAttachmentProtocol.swift deleted file mode 100644 index f925429f..00000000 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NECustomAttachmentProtocol.swift +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) 2022 NetEase, Inc. All rights reserved. -// Use of this source code is governed by a MIT license that can be -// found in the LICENSE file. - -import Foundation - -@objc -public protocol NECustomAttachmentProtocol: NSObjectProtocol { - var customType: Int { get set } - var cellHeight: CGFloat { get set } -} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NEMoreItemModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NEMoreItemModel.swift index 3d1debcf..b3c666b3 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NEMoreItemModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/NEMoreItemModel.swift @@ -5,7 +5,8 @@ import UIKit -public enum NEMoreActionType: Int { +@objc +public enum NEMoreActionType: NSInteger { case takePicture = 1 case location case rtc @@ -18,7 +19,7 @@ public enum NEMoreActionType: Int { @objc @objcMembers -public class NEMoreItemModel: NSObject { +open class NEMoreItemModel: NSObject { // 单元图标 public var image: UIImage? diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/OperationItem.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/OperationItem.swift index 9aa565a4..fad8d57b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/OperationItem.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/OperationItem.swift @@ -19,7 +19,7 @@ public enum OperationType: Int { } @objcMembers -public class OperationItem: NSObject { +open class OperationItem: NSObject { public var text: String = "" public var imageName: String = "" public var type: OperationType? @@ -64,15 +64,15 @@ public class OperationItem: NSObject { return item } -// static public func selectItem() -> OperationItem { -// OperationItem( -// text: chatLocalizable("operation_select"), -// imageName: "op_select", -// type: .multiSelect -// ) -// } + public static func selectItem() -> OperationItem { + let item = OperationItem() + item.text = chatLocalizable("operation_select") + item.imageName = "op_select" + item.type = .multiSelect + return item + } -// static public func collectionItem() -> OperationItem { +// static open func collectionItem() -> OperationItem { // OperationItem( // text: chatLocalizable("operation_collection"), // imageName: "op_collection", diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageFileModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageFileModel.swift new file mode 100644 index 00000000..c8b768ae --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageFileModel.swift @@ -0,0 +1,15 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonUIKit +import UIKit + +@objcMembers +open class PinMessageFileModel: NSObject { + public var progress: Float = 0 + public var size: Float = 0 + + public var state = DownloadState.Success + public weak var cell: NEBasePinMessageFileCell? +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageModel.swift index d7e38c4b..e1fe22af 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/PinMessageModel.swift @@ -7,12 +7,14 @@ import NECoreIMKit import NIMSDK import UIKit -public class PinMessageModel: NSObject { - var chatmodel: MessageModel? +@objcMembers +open class PinMessageModel: NSObject { + var chatmodel: MessageModel = MessageTextModel(message: nil) var message: NIMMessage var item: NIMMessagePinItem var session: NIMSession var repo = ChatRepo.shared + var pinFileModel: PinMessageFileModel? init(message: NIMMessage, item: NIMMessagePinItem) { self.message = message @@ -20,56 +22,23 @@ public class PinMessageModel: NSObject { self.item = item super.init() chatmodel = modelFromMessage(message: message) + if chatmodel.type == .file { + pinFileModel = PinMessageFileModel() + if let filemodel = chatmodel as? MessageFileModel { + pinFileModel?.size = filemodel.size + } + } } private func modelFromMessage(message: NIMMessage) -> MessageModel { - var model: MessageModel - switch message.messageType { - case .video: - model = MessageVideoModel(message: message) - case .text: - model = MessageTextModel(message: message) - case .image: - model = MessageImageModel(message: message) - case .audio: - model = MessageAudioModel(message: message) - case .notification: - model = MessageTipsModel(message: message) - case .file: - model = MessageFileModel(message: message) - case .tip: - model = MessageTipsModel(message: message) - case .location: - model = MessageLocationModel(message: message) - case .rtcCallRecord: - model = MessageCallRecordModel(message: message) - default: - // 未识别的消息类型,默认为文本消息类型,text为未知消息 - message.text = "未知消息" - model = MessageContentModel(message: message) - } + let model = ChatMessageHelper.modelFromMessage(message: message) if let uid = message.from { - let user = UserInfoProvider.shared.getUserInfo(userId: uid) - var fullName = uid - if let nickName = user?.userInfo?.nickName { - fullName = nickName - } + let user = ChatUserCache.getUserInfo(uid) + let fullName = ChatUserCache.getShowName(userId: uid, teamId: session.sessionId) model.avatar = user?.userInfo?.avatarUrl - if session.sessionType == .team { - // team - let teamMember = TeamProvider.shared.teamMember(uid, session.sessionId) - if let teamNickname = teamMember?.nickname { - fullName = teamNickname - } - } - if let alias = user?.alias { - fullName = alias - } model.fullName = fullName - model.shortName = fullName - .count > 2 ? String(fullName[fullName.index(fullName.endIndex, offsetBy: -2)...]) : - fullName + model.shortName = ChatUserCache.getShortName(name: user?.showName(false) ?? "", length: 2) } // model.replyedModel = getReplyMessageWithoutThread(message: message) @@ -84,37 +53,34 @@ public class PinMessageModel: NSObject { return model } - public func getMessageType() -> Int { - if message.messageType == .file || - message.messageType == .audio || - message.messageType == .text || - message.messageType == .image || - message.messageType == .video || - message.messageType == .location { - return message.messageType.rawValue - } - return PinMessageDefaultType - } - - public func cellHeight() -> CGFloat { - var height = chatmodel?.contentSize.height ?? 0 + open func cellHeight(pinContentMaxW: CGFloat) -> CGFloat { + var height = chatmodel.contentSize.height if let textModel = chatmodel as? MessageTextModel { - height = textModel.textHeight + // 文本消息最多显示 3 行 + let textSize = textModel.attributeStr?.finalSize(.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.pinMessageTextSize), CGSize(width: pinContentMaxW, height: CGFloat.greatestFiniteMagnitude), 3) ?? .zero + height = textSize.height } - height += 100 - if chatmodel?.type == .text, height > 162 { - height = 162 + if let textModel = chatmodel as? MessageRichTextModel { + // 换行消息中的标题最多显示 1 行 + let titleSize = textModel.titleAttributeStr?.finalSize(.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.pinMessageTextSize, weight: .semibold), CGSize(width: pinContentMaxW, height: CGFloat.greatestFiniteMagnitude), 1) ?? .zero + height = titleSize.height + + // 换行消息中的内容最多显示 2 行 + let textSize = textModel.attributeStr?.finalSize(.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.pinMessageTextSize), CGSize(width: pinContentMaxW, height: CGFloat.greatestFiniteMagnitude), 2) ?? .zero + height += textSize.height } - if chatmodel?.replyedModel?.isReplay == true { + height += 100 + + if chatmodel.replyedModel?.isReplay == true { height += 12 } return height } - public func getReplyMessageWithoutThread(message: NIMMessage) -> MessageModel? { + open func getReplyMessageWithoutThread(message: NIMMessage) -> MessageModel? { var replyId: String? = message.repliedMessageId if let yxReplyMsg = message.remoteExt?[keyReplyMsgKey] as? [String: Any] { replyId = yxReplyMsg["idClient"] as? String @@ -135,32 +101,4 @@ public class PinMessageModel: NSObject { model.isReplay = true return model } - - // 获取展示的用户名字,p2p: 备注 > 昵称 > ID team: 备注 > 群昵称 > 昵称 > ID - private func getShowName(userId: String, teamId: String?) -> String { - let user = getUserInfo(userId: userId) - var fullName = userId - if let nickName = user?.userInfo?.nickName { - fullName = nickName - } - if let tID = teamId, session.sessionType == .team { - // team - let teamMember = getTeamMember(userId: userId, teamId: tID) - if let teamNickname = teamMember?.nickname { - fullName = teamNickname - } - } - if let alias = user?.alias { - fullName = alias - } - return fullName - } - - public func getUserInfo(userId: String) -> User? { - repo.getUserInfo(userId: userId) - } - - public func getTeamMember(userId: String, teamId: String) -> NIMTeamMember? { - repo.getTeamMemberList(userId: userId, teamId: teamId) - } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/UserSettingCellModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/UserSettingCellModel.swift index 7c2be1eb..e276bf9c 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/UserSettingCellModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/Model/UserSettingCellModel.swift @@ -5,13 +5,13 @@ import Foundation -enum UserSettingType: Int { +public enum UserSettingType: Int { case SwitchType = 1 case SelectType = 2 } @objcMembers -public class UserSettingCellModel: NSObject { +open class UserSettingCellModel: NSObject { typealias SwitchChangeCompletion = (Bool) -> Void typealias CellClick = () -> Void var cellName: String? diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageCell.swift index 2fb2393f..e0c1ece7 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageCell.swift @@ -30,6 +30,9 @@ public protocol ChatBaseCellDelegate: NSObjectProtocol { // 单击已读未读按钮 func didTapReadView(_ cell: UITableViewCell, _ model: MessageContentModel?) + + // 单击多选按钮 + func didTapSelectButton(_ cell: UITableViewCell, _ model: MessageContentModel?) } @objc @@ -42,13 +45,14 @@ protocol ChatAudioCellProtocol { @objcMembers open class NEBaseChatMessageCell: NEChatBaseCell { - public var seletedBtn = UIButton(type: .custom) // 多选按钮 private let bubbleWidth: CGFloat = 218 // 气泡默认宽度 + private let pinLabelMaxWidth: CGFloat = 280 // pin 文案最大宽度 public weak var delegate: ChatBaseCellDelegate? public var contentModel: MessageContentModel? // 消息模型 /// Left public var avatarImageLeft = UIImageView() // 左侧头像 + public var avatarImageLeftAnchor: NSLayoutConstraint? // 左侧头像左侧布局依赖 public var nameLabelLeft = UILabel() // 左侧头像文字(无头像预设) public var bubbleImageLeft = UIImageView() // 左侧气泡 public var bubbleTopAnchorLeft: NSLayoutConstraint? // 左侧气泡顶部布局约束 @@ -56,6 +60,7 @@ open class NEBaseChatMessageCell: NEChatBaseCell { public var bubbleHLeft: NSLayoutConstraint? // 左侧气泡高度布局约束 public var pinImageLeft = UIImageView() // 左侧标记图片 public var pinLabelLeft = UILabel() // 左侧标记文案 + public var pinLabelLeftTopAnchor: NSLayoutConstraint? // 左侧标记文案顶部布局约束 private var pinLabelHLeft: NSLayoutConstraint? // 左侧标记文案宽度布局约束 private var pinLabelWLeft: NSLayoutConstraint? // 左侧标记文案高度布局约束 public var fullNameLabel = UILabel() // 群昵称(只在群聊中有效) @@ -69,13 +74,19 @@ open class NEBaseChatMessageCell: NEChatBaseCell { public var bubbleHRight: NSLayoutConstraint? // 右侧气泡高度布局约束 public var pinImageRight = UIImageView() // 右侧标记图片 public var pinLabelRight = UILabel() // 右侧标记文案 + public var pinLabelRightTopAnchor: NSLayoutConstraint? // 右侧标记文案顶部布局约束 private var pinLabelHRight: NSLayoutConstraint? // 右侧标记文案宽度布局约束 private var pinLabelWRight: NSLayoutConstraint? // 右侧标记文案高度布局约束 + // 已读未读视图 public var readView = CirleProgressView(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) + public var activityView = ChatActivityIndicatorView() // 消息状态视图 + public var seletedBtn = UIButton(type: .custom) // 多选按钮 + public var timeLabel = UILabel() // 消息时间 + public var timeLabelHeightAnchor: NSLayoutConstraint? // 消息时间高度约束 + // 已读未读点击手势 private var tapGesture: UITapGestureRecognizer? - public var activityView = ChatActivityIndicatorView() // 消息状态视图 override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) @@ -89,7 +100,20 @@ open class NEBaseChatMessageCell: NEChatBaseCell { fatalError("init(coder:) has not been implemented") } + deinit { + gestureRecognizers?.forEach { gestrue in + removeGestureRecognizer(gestrue) + } + } + open func initProperty() { + timeLabel.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.timeTextSize) + timeLabel.textColor = NEKitChatConfig.shared.ui.messageProperties.timeTextColor + timeLabel.textAlignment = .center + timeLabel.translatesAutoresizingMaskIntoConstraints = false + timeLabel.accessibilityIdentifier = "id.messageTipText" + timeLabel.backgroundColor = .white + // avatar avatarImageLeft.backgroundColor = UIColor(hexString: "#537FF4") avatarImageLeft.translatesAutoresizingMaskIntoConstraints = false @@ -126,14 +150,14 @@ open class NEBaseChatMessageCell: NEChatBaseCell { bubbleImageLeft.backgroundColor = NEKitChatConfig.shared.ui.messageProperties.receiveMessageBg var image = NEKitChatConfig.shared.ui.messageProperties.leftBubbleBg ?? UIImage.ne_imageNamed(name: "chat_message_receive") bubbleImageLeft.image = image? - .resizableImage(withCapInsets: UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25)) + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) bubbleImageLeft.translatesAutoresizingMaskIntoConstraints = false bubbleImageLeft.isUserInteractionEnabled = true bubbleImageRight.backgroundColor = NEKitChatConfig.shared.ui.messageProperties.selfMessageBg image = NEKitChatConfig.shared.ui.messageProperties.rightBubbleBg ?? UIImage.ne_imageNamed(name: "chat_message_send") bubbleImageRight.image = image? - .resizableImage(withCapInsets: UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25)) + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) bubbleImageRight.translatesAutoresizingMaskIntoConstraints = false bubbleImageRight.isUserInteractionEnabled = true @@ -142,30 +166,56 @@ open class NEBaseChatMessageCell: NEChatBaseCell { pinLabelLeft.font = UIFont.systemFont(ofSize: 12) pinLabelLeft.textAlignment = .left pinLabelLeft.lineBreakMode = .byTruncatingMiddle + pinLabelLeft.accessibilityIdentifier = "id.signal" pinLabelRight.translatesAutoresizingMaskIntoConstraints = false pinLabelRight.textColor = UIColor.ne_greenText pinLabelRight.font = UIFont.systemFont(ofSize: 12) pinLabelRight.textAlignment = .right pinLabelRight.lineBreakMode = .byTruncatingMiddle + pinLabelRight.accessibilityIdentifier = "id.signal" pinImageLeft.translatesAutoresizingMaskIntoConstraints = false pinImageLeft.contentMode = .scaleAspectFit pinImageRight.translatesAutoresizingMaskIntoConstraints = false pinImageRight.contentMode = .scaleAspectFit + + readView.translatesAutoresizingMaskIntoConstraints = false + readView.accessibilityIdentifier = "id.readView" + + activityView.accessibilityIdentifier = "id.status" + + seletedBtn.translatesAutoresizingMaskIntoConstraints = false + seletedBtn.setImage(.ne_imageNamed(name: "unselect"), for: .normal) + seletedBtn.setImage(.ne_imageNamed(name: "select"), for: .selected) + seletedBtn.addTarget(self, action: #selector(selectButtonClicked), for: .touchUpInside) } open func baseCommonUI() { - baseCommonUIRight() + selectionStyle = .none + backgroundColor = .clear + + // time + contentView.addSubview(timeLabel) + timeLabelHeightAnchor = timeLabel.heightAnchor.constraint(equalToConstant: chat_timeCellH) + NSLayoutConstraint.activate([ + timeLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0), + timeLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0), + timeLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -0), + timeLabelHeightAnchor!, + ]) + baseCommonUILeft() + baseCommonUIRight() } open func baseCommonUILeft() { contentView.addSubview(avatarImageLeft) + avatarImageLeftAnchor = avatarImageLeft.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16) NSLayoutConstraint.activate([ - avatarImageLeft.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4), - avatarImageLeft.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), + avatarImageLeft.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: chat_content_margin), + avatarImageLeftAnchor!, avatarImageLeft.widthAnchor.constraint(equalToConstant: 32), avatarImageLeft.heightAnchor.constraint(equalToConstant: 32), ]) @@ -200,10 +250,11 @@ open class NEBaseChatMessageCell: NEChatBaseCell { ]) contentView.addSubview(pinLabelLeft) + pinLabelLeftTopAnchor = pinLabelLeft.topAnchor.constraint(equalTo: bubbleImageLeft.bottomAnchor, constant: 4) pinLabelHLeft = pinLabelLeft.heightAnchor.constraint(equalToConstant: 0) - pinLabelWLeft = pinLabelLeft.widthAnchor.constraint(equalToConstant: 210) + pinLabelWLeft = pinLabelLeft.widthAnchor.constraint(equalToConstant: pinLabelMaxWidth) NSLayoutConstraint.activate([ - pinLabelLeft.topAnchor.constraint(equalTo: bubbleImageLeft.bottomAnchor, constant: 4), + pinLabelLeftTopAnchor!, pinLabelLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: 14), pinLabelWLeft!, pinLabelHLeft!, @@ -218,15 +269,12 @@ open class NEBaseChatMessageCell: NEChatBaseCell { } open func baseCommonUIRight() { - selectionStyle = .none - backgroundColor = .clear - contentView.addSubview(avatarImageRight) NSLayoutConstraint.activate([ avatarImageRight.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), avatarImageRight.widthAnchor.constraint(equalToConstant: 32), avatarImageRight.heightAnchor.constraint(equalToConstant: 32), - avatarImageRight.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4), + avatarImageRight.topAnchor.constraint(equalTo: avatarImageLeft.topAnchor, constant: 0), ]) contentView.addSubview(nameLabelRight) @@ -241,7 +289,7 @@ open class NEBaseChatMessageCell: NEChatBaseCell { bubbleWRight = bubbleImageRight.widthAnchor.constraint(equalToConstant: bubbleWidth) bubbleHRight = bubbleImageRight.heightAnchor.constraint(equalToConstant: bubbleWidth) NSLayoutConstraint.activate([ - bubbleImageRight.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4), + bubbleImageRight.topAnchor.constraint(equalTo: avatarImageRight.topAnchor, constant: 0), bubbleImageRight.rightAnchor.constraint(equalTo: avatarImageRight.leftAnchor, constant: -chat_content_margin), bubbleWRight!, bubbleHRight!, @@ -260,7 +308,6 @@ open class NEBaseChatMessageCell: NEChatBaseCell { // readView contentView.addSubview(readView) - readView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ readView.rightAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: -chat_content_margin), readView.bottomAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor, constant: 0), @@ -270,7 +317,6 @@ open class NEBaseChatMessageCell: NEChatBaseCell { // seletedBtn contentView.addSubview(seletedBtn) - seletedBtn.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ seletedBtn.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), seletedBtn.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0), @@ -279,10 +325,11 @@ open class NEBaseChatMessageCell: NEChatBaseCell { ]) contentView.addSubview(pinLabelRight) + pinLabelRightTopAnchor = pinLabelRight.topAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor, constant: 4) pinLabelHRight = pinLabelRight.heightAnchor.constraint(equalToConstant: 0) pinLabelWRight = pinLabelRight.widthAnchor.constraint(equalToConstant: 210) NSLayoutConstraint.activate([ - pinLabelRight.topAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor, constant: 4), + pinLabelRightTopAnchor!, pinLabelRight.rightAnchor.constraint(equalTo: bubbleImageRight.rightAnchor, constant: 0), pinLabelWRight!, pinLabelHRight!, @@ -298,14 +345,15 @@ open class NEBaseChatMessageCell: NEChatBaseCell { open func addGesture() { // avatar - let tapRight = UITapGestureRecognizer(target: self, action: #selector(tapAvatar)) - tapRight.cancelsTouchesInView = false - avatarImageRight.addGestureRecognizer(tapRight) - let tapLeft = UITapGestureRecognizer(target: self, action: #selector(tapAvatar)) - tapLeft.cancelsTouchesInView = false - avatarImageLeft.addGestureRecognizer(tapLeft) + let avatarTapRight = UITapGestureRecognizer(target: self, action: #selector(tapAvatar)) + avatarTapRight.cancelsTouchesInView = false + avatarImageRight.addGestureRecognizer(avatarTapRight) + let avatarTapLeft = UITapGestureRecognizer(target: self, action: #selector(tapAvatar)) + avatarTapLeft.cancelsTouchesInView = false + avatarImageLeft.addGestureRecognizer(avatarTapLeft) let avatarLongGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressAvatar)) + avatarLongGesture.cancelsTouchesInView = false avatarImageLeft.addGestureRecognizer(avatarLongGesture) let messageTapRight = UITapGestureRecognizer(target: self, action: #selector(tapMessage)) @@ -315,18 +363,13 @@ open class NEBaseChatMessageCell: NEChatBaseCell { messageTapLeft.cancelsTouchesInView = false bubbleImageLeft.addGestureRecognizer(messageTapLeft) - let messageLongPressRight = UILongPressGestureRecognizer( - target: self, - action: #selector(longPress) - ) + let messageLongPressRight = UILongPressGestureRecognizer(target: self, action: #selector(longPress)) bubbleImageRight.addGestureRecognizer(messageLongPressRight) - let messageLongPressLeft = UILongPressGestureRecognizer( - target: self, - action: #selector(longPress) - ) + let messageLongPressLeft = UILongPressGestureRecognizer(target: self, action: #selector(longPress)) bubbleImageLeft.addGestureRecognizer(messageLongPressLeft) let tapReadView = UITapGestureRecognizer(target: self, action: #selector(tapReadView)) + tapReadView.cancelsTouchesInView = false readView.addGestureRecognizer(tapReadView) tapGesture = tapReadView } @@ -392,12 +435,28 @@ open class NEBaseChatMessageCell: NEChatBaseCell { delegate?.didTapReadView(self, contentModel) } + open func selectButtonClicked() { + seletedBtn.isSelected = !seletedBtn.isSelected + if let model = contentModel { + model.isSelected = !model.isSelected + } + delegate?.didTapSelectButton(self, contentModel) + } + // MARK: set data + open func setSelect(_ model: MessageContentModel, _ enableSelect: Bool = false) { + // 多选框 + seletedBtn.isHidden = model.isRevoked || !enableSelect + seletedBtn.isSelected = model.isSelected + avatarImageLeftAnchor?.constant = enableSelect ? 42 : 16 + } + override open func setModel(_ model: MessageContentModel) { - guard let isSend = model.message?.isOutgoingMsg else { - return - } + setModel(model, model.message?.isOutgoingMsg ?? false) + } + + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { let bubbleW = isSend ? bubbleWRight : bubbleWLeft let bubbleH = isSend ? bubbleHRight : bubbleHLeft let nameLabel = isSend ? nameLabelRight : nameLabelLeft @@ -408,12 +467,23 @@ open class NEBaseChatMessageCell: NEChatBaseCell { showLeftOrRight(showRight: isSend) updatePinStatus(model) + // time + if let time = model.timeContent, !time.isEmpty { + timeLabelHeightAnchor?.constant = chat_timeCellH + timeLabel.text = time + timeLabel.isHidden = false + } else { + timeLabelHeightAnchor?.constant = 0 + timeLabel.text = "" + timeLabel.isHidden = true + } + bubbleW?.constant = model.contentSize.width bubbleH?.constant = model.contentSize.height // avatar nameLabel.text = model.shortName - if let avatarURL = model.avatar { + if let avatarURL = model.avatar, !avatarURL.isEmpty { avatarImage .sd_setImage(with: URL(string: avatarURL)) { image, error, type, url in if image != nil { @@ -445,19 +515,21 @@ open class NEBaseChatMessageCell: NEChatBaseCell { } fullNameH?.constant = CGFloat(model.fullNameHeight) - switch model.message?.deliveryState { - case .delivering: - activityView.messageStatus = .sending - case .deliveried: - // 同一个账号,在多端登录,被对方拉黑,需要根据isBlackListed判断,进而更新信息状态 - if let isBlackMsg = model.message?.isBlackListed, isBlackMsg { + if isSend { + switch model.message?.deliveryState { + case .delivering: + activityView.messageStatus = .sending + case .deliveried: + // 同一个账号,在多端登录,被对方拉黑,需要根据isBlackListed判断,进而更新信息状态 + if let isBlackMsg = model.message?.isBlackListed, isBlackMsg { + activityView.messageStatus = .failed + } else { + activityView.messageStatus = .successed + } + case .failed: activityView.messageStatus = .failed - } else { - activityView.messageStatus = .successed + default: break } - case .failed: - activityView.messageStatus = .failed - default: break } if isSend, model.message?.deliveryState == .deliveried { @@ -524,12 +596,12 @@ open class NEBaseChatMessageCell: NEChatBaseCell { pinLabelLeft.isHidden = showRight fullNameLabel.isHidden = showRight - activityView.isHidden = !showRight avatarImageRight.isHidden = !showRight nameLabelRight.isHidden = !showRight bubbleImageRight.isHidden = !showRight pinImageRight.isHidden = !showRight pinLabelRight.isHidden = !showRight + activityView.isHidden = !showRight readView.isHidden = !showRight } @@ -561,10 +633,10 @@ open class NEBaseChatMessageCell: NEChatBaseCell { let size = String.getTextRectSize( pinLabel.text ?? pinText, font: UIFont.systemFont(ofSize: 12.0), - size: CGSize(width: kScreenWidth - 56 - 22, height: CGFloat.greatestFiniteMagnitude) + size: CGSize(width: pinLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude) ) pinLabelH?.constant = CGFloat(chat_pin_height) - pinLabelW?.constant = size.width + 1 + pinLabelW?.constant = min(size.width + 1, pinLabelMaxWidth) } else { pinImage.image = nil pinLabelH?.constant = 0 diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageTipCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageTipCell.swift index 9ce2e8a9..fa9858c8 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageTipCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatMessageTipCell.swift @@ -7,7 +7,7 @@ import UIKit @objcMembers open class NEBaseChatMessageTipCell: UITableViewCell { - var timeLabelWidthAnchor: NSLayoutConstraint? + var timeLabelHeightAnchor: NSLayoutConstraint? // 消息时间高度约束 override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) @@ -21,19 +21,36 @@ open class NEBaseChatMessageTipCell: UITableViewCell { } open func commonUI() { - timeLabel.numberOfLines = 0 contentView.addSubview(timeLabel) + timeLabelHeightAnchor = timeLabel.heightAnchor.constraint(equalToConstant: 22) NSLayoutConstraint.activate([ - timeLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - timeLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + timeLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0), + timeLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), + timeLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), + timeLabelHeightAnchor!, + ]) + + contentView.addSubview(contentLabel) + NSLayoutConstraint.activate([ + contentLabel.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: 4), + contentLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + contentLabel.widthAnchor.constraint(equalToConstant: chat_content_maxW), ]) - timeLabelWidthAnchor = timeLabel.widthAnchor.constraint(equalToConstant: chat_content_maxW) - timeLabelWidthAnchor?.isActive = true } func setModel(_ model: MessageTipsModel) { - timeLabel.text = model.text - timeLabelWidthAnchor?.constant = model.contentSize.width + // time + if let time = model.timeContent, !time.isEmpty { + timeLabelHeightAnchor?.constant = chat_timeCellH + timeLabel.text = time + timeLabel.isHidden = false + } else { + timeLabelHeightAnchor?.constant = 0 + timeLabel.text = "" + timeLabel.isHidden = true + } + + contentLabel.text = model.text } public lazy var timeLabel: UILabel = { @@ -45,4 +62,15 @@ open class NEBaseChatMessageTipCell: UITableViewCell { label.accessibilityIdentifier = "id.messageTipText" return label }() + + public lazy var contentLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.timeTextSize) + label.textColor = NEKitChatConfig.shared.ui.messageProperties.timeTextColor + label.textAlignment = .center + label.numberOfLines = 0 + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.messageTipText" + return label + }() } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatTeamMemberCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatTeamMemberCell.swift index ec5223c2..334d7de9 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatTeamMemberCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseChatTeamMemberCell.swift @@ -27,7 +27,7 @@ open class NEBaseChatTeamMemberCell: UITableViewCell { return label }() - override public func setSelected(_ selected: Bool, animated: Bool) { + override open func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state @@ -61,7 +61,7 @@ open class NEBaseChatTeamMemberCell: UITableViewCell { } open func configure(_ model: ChatTeamMemberInfoModel) { - if let url = model.nimUser?.userInfo?.avatarUrl { + if let url = model.nimUser?.userInfo?.avatarUrl, !url.isEmpty { headerView.sd_setImage(with: URL(string: url), completed: nil) headerView.setTitle("") } else { diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingCell.swift index 6021a110..8d059d2e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingCell.swift @@ -31,17 +31,6 @@ open class NEBaseUserSettingCell: CornerCell { super.init(coder: coder) } - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - open func configure(_ anyModel: Any) { if let m = anyModel as? UserSettingCellModel { model = m diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingSwitchCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingSwitchCell.swift index 3058f94a..8dc4b4c0 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingSwitchCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/NEBaseUserSettingSwitchCell.swift @@ -15,17 +15,6 @@ open class NEBaseUserSettingSwitchCell: NEBaseUserSettingCell { return q }() - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/OperationCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/OperationCell.swift index ad08fbb3..86a43d98 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/OperationCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/OperationCell.swift @@ -23,6 +23,8 @@ open class OperationCell: UICollectionViewCell { override public init(frame: CGRect) { super.init(frame: frame) + contentView.accessibilityIdentifier = "id.menuCell" + imageView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(imageView) imageView.contentMode = .center diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageAudioCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageAudioCell.swift index b33504d0..a5ce8d4d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageAudioCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageAudioCell.swift @@ -10,6 +10,8 @@ open class NEBasePinMessageAudioCell: NEBasePinMessageCell { var audioTimeLabel = UILabel() public var bubbleImage = UIImageView() + public var isPlaying = false + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } @@ -23,7 +25,7 @@ open class NEBasePinMessageAudioCell: NEBasePinMessageCell { let image = NEKitChatConfig.shared.ui.messageProperties.leftBubbleBg ?? UIImage.ne_imageNamed(name: "chat_message_receive") bubbleImage.image = image? - .resizableImage(withCapInsets: UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25)) + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) bubbleImage.translatesAutoresizingMaskIntoConstraints = false bubbleImage.isUserInteractionEnabled = true backView.addSubview(bubbleImage) @@ -45,8 +47,14 @@ open class NEBasePinMessageAudioCell: NEBasePinMessageCell { audioImageView.widthAnchor.constraint(equalToConstant: 28), audioImageView.heightAnchor.constraint(equalToConstant: 28), ]) + audioImageView.animationDuration = 1 + if let leftImage1 = UIImage.ne_imageNamed(name: "left_play_1"), + let leftmage2 = UIImage.ne_imageNamed(name: "left_play_2"), + let leftmage3 = UIImage.ne_imageNamed(name: "left_play_3") { + audioImageView.animationImages = [leftImage1, leftmage2, leftmage3] + } - audioTimeLabel.font = UIFont.systemFont(ofSize: 14) + audioTimeLabel.font = UIFont.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.pinMessageTextSize) audioTimeLabel.textColor = UIColor.ne_darkText audioTimeLabel.textAlignment = .left audioTimeLabel.translatesAutoresizingMaskIntoConstraints = false @@ -57,12 +65,37 @@ open class NEBasePinMessageAudioCell: NEBasePinMessageCell { audioTimeLabel.rightAnchor.constraint(equalTo: bubbleImage.rightAnchor, constant: -12), audioTimeLabel.heightAnchor.constraint(equalToConstant: 28), ]) + + if let gesture = contentGesture { + bubbleImage.addGestureRecognizer(gesture) + } } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) if let m = item.chatmodel as? MessageAudioModel { audioTimeLabel.text = "\(m.duration)" + "s" + m.isPlaying == true ? startAnimation() : stopAnimation() + } + } + + open func startAnimation() { + if !audioImageView.isAnimating { + audioImageView.startAnimating() + } + if let m = pinModel?.chatmodel as? MessageAudioModel { + m.isPlaying = true + isPlaying = true + } + } + + open func stopAnimation() { + if audioImageView.isAnimating { + audioImageView.stopAnimating() + } + if let m = pinModel?.chatmodel as? MessageAudioModel { + m.isPlaying = false + isPlaying = false } } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageCell.swift index e7eab21f..1bdb169c 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageCell.swift @@ -10,6 +10,7 @@ import UIKit @objc public protocol PinMessageCellDelegate { func didClickMore(_ model: PinMessageModel?) + func didClickContent(_ model: PinMessageModel?, _ cell: NEBasePinMessageCell) } @objcMembers @@ -22,6 +23,8 @@ open class NEBasePinMessageCell: UITableViewCell { public var delegate: PinMessageCellDelegate? + public var contentGesture: UITapGestureRecognizer? + lazy var headerView: NEUserHeaderView = { let header = NEUserHeaderView(frame: .zero) header.titleLabel.font = NEConstant.defaultTextFont(12) @@ -29,7 +32,6 @@ open class NEBasePinMessageCell: UITableViewCell { header.layer.cornerRadius = 16 header.clipsToBounds = true header.translatesAutoresizingMaskIntoConstraints = false - header.accessibilityIdentifier = "id.avatar" return header }() @@ -66,6 +68,7 @@ open class NEBasePinMessageCell: UITableViewCell { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = .clear + contentGesture = UITapGestureRecognizer(target: self, action: #selector(contentClick)) setupUI() } @@ -153,20 +156,24 @@ open class NEBasePinMessageCell: UITableViewCell { line.backgroundColor = .ne_greyLine } - public func configure(_ item: PinMessageModel) { + open func configure(_ item: PinMessageModel) { pinModel = item - headerView.configHeadData(headUrl: item.chatmodel?.avatar, - name: item.chatmodel?.fullName ?? "", - uid: item.chatmodel?.message?.from ?? "") - nameLabel.text = item.chatmodel?.fullName + headerView.configHeadData(headUrl: item.chatmodel.avatar, + name: item.chatmodel.fullName ?? "", + uid: item.chatmodel.message?.from ?? "") + nameLabel.text = item.chatmodel.fullName print("config time : ", item.message.timestamp) timeLabel.text = String.stringFromDate(date: Date(timeIntervalSince1970: item.message.timestamp)) - contentWidth?.constant = item.chatmodel?.contentSize.width ?? 0 - contentHeight?.constant = item.chatmodel?.contentSize.height ?? 0 + contentWidth?.constant = item.chatmodel.contentSize.width + contentHeight?.constant = item.chatmodel.contentSize.height } func moreClick() { delegate?.didClickMore(pinModel) } + + open func contentClick() { + delegate?.didClickContent(pinModel, self) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageDefaultCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageDefaultCell.swift index 8740a3ca..524b562a 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageDefaultCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageDefaultCell.swift @@ -29,7 +29,7 @@ open class NEBasePinMessageDefaultCell: NEBasePinMessageTextCell { super.setupUI() } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) contentLabel.text = chatLocalizable("unkonw_pin_message") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageFileCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageFileCell.swift index cad66392..edab5229 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageFileCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageFileCell.swift @@ -7,6 +7,13 @@ import UIKit @objcMembers open class NEBasePinMessageFileCell: NEBasePinMessageCell { + public lazy var stateView: FileStateView = { + let state = FileStateView() + state.translatesAutoresizingMaskIntoConstraints = false + state.backgroundColor = .clear + return state + }() + public var bubbleImage = UIImageView() lazy var imgView: UIImageView = { @@ -95,7 +102,7 @@ open class NEBasePinMessageFileCell: NEBasePinMessageCell { bubbleImage.topAnchor.constraint(equalTo: line.bottomAnchor, constant: 12), ]) - backView.addSubview(imgView) + bubbleImage.addSubview(imgView) NSLayoutConstraint.activate([ imgView.leftAnchor.constraint(equalTo: bubbleImage.leftAnchor, constant: 10), imgView.topAnchor.constraint(equalTo: bubbleImage.topAnchor, constant: 10), @@ -103,18 +110,43 @@ open class NEBasePinMessageFileCell: NEBasePinMessageCell { imgView.heightAnchor.constraint(equalToConstant: 32), ]) - backView.addSubview(labelView) + bubbleImage.addSubview(labelView) NSLayoutConstraint.activate([ labelView.leftAnchor.constraint(equalTo: imgView.rightAnchor, constant: 15), labelView.topAnchor.constraint(equalTo: bubbleImage.topAnchor, constant: 10), labelView.rightAnchor.constraint(equalTo: bubbleImage.rightAnchor, constant: -10), labelView.bottomAnchor.constraint(equalTo: bubbleImage.bottomAnchor, constant: 0), ]) + + bubbleImage.addSubview(stateView) + NSLayoutConstraint.activate([ + stateView.leftAnchor.constraint(equalTo: bubbleImage.leftAnchor, constant: 10), + stateView.topAnchor.constraint(equalTo: bubbleImage.topAnchor, constant: 10), + stateView.widthAnchor.constraint(equalToConstant: 32), + stateView.heightAnchor.constraint(equalToConstant: 32), + ]) + + if let gesture = contentGesture { + bubbleImage.addGestureRecognizer(gesture) + } } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) if let fileObject = item.message.messageObject as? NIMFileObject { + if let fileModel = item.pinFileModel { + fileModel.cell = self + if fileModel.state == .Success { + stateView.state = .FileOpen + } else { + stateView.state = .FileDownload + stateView.setProgress(fileModel.progress) + if fileModel.progress >= 1 { + fileModel.state = .Success + } + } + } + var imageName = "file_unknown" var displayName = "未知文件" if let filePath = fileObject.path as? NSString { @@ -165,4 +197,8 @@ open class NEBasePinMessageFileCell: NEBasePinMessageCell { sizeLabel.text = size_str } } + + open func uploadProgress(progress: Float) { + stateView.setProgress(progress) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageImageCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageImageCell.swift index 29ca04ce..23198d9d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageImageCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageImageCell.swift @@ -15,8 +15,6 @@ open class NEBasePinMessageImageCell: NEBasePinMessageCell { override open func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) - - // Configure the view for the selected state } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { @@ -32,6 +30,7 @@ open class NEBasePinMessageImageCell: NEBasePinMessageCell { contentImageView.translatesAutoresizingMaskIntoConstraints = false contentImageView.contentMode = .scaleAspectFill contentImageView.clipsToBounds = true + contentImageView.isUserInteractionEnabled = true contentImageView.addCustomCorner( conrners: [.bottomLeft, .bottomRight, .topRight, .topLeft], radius: 8, @@ -46,9 +45,13 @@ open class NEBasePinMessageImageCell: NEBasePinMessageCell { contentWidth?.isActive = true contentHeight = contentImageView.heightAnchor.constraint(equalToConstant: 0) contentHeight?.isActive = true + + if let gesture = contentGesture { + contentImageView.addGestureRecognizer(gesture) + } } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) if let m = item.chatmodel as? MessageImageModel, let imageUrl = m.imageUrl { @@ -61,7 +64,8 @@ open class NEBasePinMessageImageCell: NEBasePinMessageCell { completed: nil ) } else { - contentImageView.image = UIImage(contentsOfFile: imageUrl) + let url = URL(fileURLWithPath: imageUrl) + contentImageView.sd_setImage(with: url) } } else { diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageLocationCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageLocationCell.swift index 824913af..517a4488 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageLocationCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageLocationCell.swift @@ -118,9 +118,13 @@ open class NEBasePinMessageLocationCell: NEBasePinMessageCell { emptyLabel.bottomAnchor.constraint(equalTo: back.bottomAnchor, constant: -40), ]) } + mapView?.isUserInteractionEnabled = false + if let gesture = contentGesture { + back.addGestureRecognizer(gesture) + } } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) if let m = item.chatmodel as? MessageLocationModel { locationTitleLabel.text = m.title diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageMultiForwardCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageMultiForwardCell.swift new file mode 100644 index 00000000..4498509b --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageMultiForwardCell.swift @@ -0,0 +1,191 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NIMSDK +import UIKit + +@objcMembers +open class NEBasePinMessageMultiForwardCell: NEBasePinMessageCell { + public let funMargin: CGFloat = 5.2 + let contentW: CGFloat = 248 + var titleLabelFontSize: CGFloat = 14 + var contentLabelFontSize: CGFloat = 14 + var contentLabelColor: UIColor = .ne_lightText + + override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + setupUI() + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func setupUI() { + super.setupUI() +// let image = UIImage.ne_imageNamed(name: "chat_message_receive") +// backViewLeft.image = image? +// .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) + backViewLeft.layer.cornerRadius = 8 + backViewLeft.layer.borderColor = multiForwardborderColor.cgColor + backViewLeft.layer.borderWidth = 1 + + backView.addSubview(backViewLeft) + NSLayoutConstraint.activate([ + backViewLeft.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 16), + backViewLeft.topAnchor.constraint(equalTo: line.bottomAnchor, constant: 12), + backViewLeft.widthAnchor.constraint(equalToConstant: 276), +// backViewLeft.heightAnchor.constraint(equalToConstant: 130), + backViewLeft.heightAnchor.constraint(equalToConstant: 100), + ]) + + if let gesture = contentGesture { + backViewLeft.addGestureRecognizer(gesture) + } + } + + override open func configure(_ item: PinMessageModel) { + super.configure(item) + guard let data = NECustomAttachment.dataOfCustomMessage(message: item.chatmodel.message) else { + return + } + + let font = UIFont.systemFont(ofSize: contentLabelFontSize) + let titleLabel = titleLabelLeft1 + let titleLabel2 = titleLabelLeft2 + let contentLabel1 = contentLabelLeft1 + let contentLabel2 = contentLabelLeft2 + let contentLabel3 = contentLabelLeft3 + + if let sessionName = data["sessionName"] as? String { + titleLabel.attributedText = + NEEmotionTool.getAttWithStr(str: sessionName, + font: .systemFont(ofSize: titleLabelFontSize), + color: .ne_darkText) + } else { + titleLabel2.text = chatLocalizable("chat_history") + } + + guard let abstracts = data["abstracts"] as? [[String: Any]] else { return } + + contentLabel2.attributedText = nil + contentLabel3.attributedText = nil + for i in 0 ..< abstracts.count { + var contentLabel = contentLabel1 + if i == 1 { + contentLabel = contentLabel2 + } else if i == 2 { + contentLabel = contentLabel3 + } + + var contentText = "" + if var senderNick = abstracts[i]["senderNick"] as? String { + if senderNick.count > 5 { + // 截取字符串 abcdefg -> ab...fg + let leftEndIndex = senderNick.index(senderNick.startIndex, offsetBy: 2) + let rightStartIndex = senderNick.index(senderNick.endIndex, offsetBy: -2) + senderNick = senderNick[senderNick.startIndex ..< leftEndIndex] + "..." + senderNick[rightStartIndex ..< senderNick.endIndex] + } + contentText = senderNick + if let content = abstracts[i]["content"] as? String { + contentText += ":" + content + } + } + + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = 1 // 设置行间距 + paragraphStyle.lineBreakMode = .byTruncatingTail + let attributedText = NEEmotionTool.getAttWithStr(str: contentText, + font: font, + color: contentLabelColor) + attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedText.length)) + contentLabel.attributedText = attributedText + } + + let numCount1 = String.calculateMaxLines(width: contentW, + attributeString: contentLabel1.attributedText, + font: font) + if numCount1 == 1 { + contentLabel2.numberOfLines = 2 + contentLabel2.isHidden = contentLabel2.attributedText == nil + let numCount2 = String.calculateMaxLines(width: contentW, + attributeString: contentLabel2.attributedText, + font: font) + contentLabel3.isHidden = !(contentLabel3.attributedText != nil && numCount2 == 1) + } else if numCount1 == 2 { + contentLabel2.numberOfLines = 1 + contentLabel2.isHidden = contentLabel3.attributedText != nil + contentLabel3.isHidden = true + } else { + contentLabel2.isHidden = true + contentLabel3.isHidden = true + } + } + + // MARK: - lazy load + + public lazy var backViewLeft: UIImageView = { + let view = UIImageView() + view.translatesAutoresizingMaskIntoConstraints = false + view.isUserInteractionEnabled = true + return view + }() + + public lazy var titleLabelLeft1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.name1" + return label + }() + + public lazy var titleLabelLeft2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("chat_history_by") + label.textColor = .ne_darkText + label.font = .systemFont(ofSize: titleLabelFontSize) + label.accessibilityIdentifier = "id.name2" + return label + }() + + public lazy var contentLabelLeft1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 3 + label.accessibilityIdentifier = "id.content1" + return label + }() + + public lazy var contentLabelLeft2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 2 + label.accessibilityIdentifier = "id.content2" + return label + }() + + public lazy var contentLabelLeft3: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.content3" + return label + }() + +// public lazy var dividerLineLeft: UIView = { +// let line = UIView() +// line.translatesAutoresizingMaskIntoConstraints = false +// line.backgroundColor = multiForwardLineColor +// return line +// }() +// +// public lazy var contentHistoryLeft: UILabel = { +// let label = UILabel() +// label.translatesAutoresizingMaskIntoConstraints = false +// label.font = .systemFont(ofSize: 12) +// label.textColor = .ne_lightText +// label.text = chatLocalizable("chat_history") +// label.accessibilityIdentifier = "id.contentHistoryLeft" +// return label +// }() +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageRichTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageRichTextCell.swift new file mode 100644 index 00000000..539049e7 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageRichTextCell.swift @@ -0,0 +1,57 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class NEBasePinMessageRichTextCell: NEBasePinMessageTextCell { + lazy var titleLabel: UILabel = { + let label = UILabel() + label.font = UIFont.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.pinMessageTextSize) + label.textColor = .ne_darkText + label.translatesAutoresizingMaskIntoConstraints = false + label.isUserInteractionEnabled = true + label.numberOfLines = 1 + return label + }() + + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + } + + public required init?(coder: NSCoder) { + super.init(coder: coder) + } + + override open func commonUI() { + backView.addSubview(titleLabel) + NSLayoutConstraint.activate([ + titleLabel.leftAnchor.constraint(equalTo: line.leftAnchor), + titleLabel.rightAnchor.constraint(equalTo: line.rightAnchor), + titleLabel.topAnchor.constraint(equalTo: line.bottomAnchor, constant: 12), + ]) + + contentLabel.numberOfLines = 2 + backView.addSubview(contentLabel) + NSLayoutConstraint.activate([ + contentLabel.leftAnchor.constraint(equalTo: line.leftAnchor), + contentLabel.rightAnchor.constraint(equalTo: line.rightAnchor), + contentLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 1), + ]) + + if let gesture = contentGesture { + contentLabel.addGestureRecognizer(gesture) + } + + let titleGesture = UITapGestureRecognizer(target: self, action: #selector(contentClick)) + titleLabel.addGestureRecognizer(titleGesture) + } + + override open func configure(_ item: PinMessageModel) { + super.configure(item) + if let model = item.chatmodel as? MessageRichTextModel { + titleLabel.attributedText = model.titleAttributeStr + } + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageTextCell.swift index 161c0324..74fcbc82 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageTextCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageTextCell.swift @@ -8,9 +8,10 @@ import UIKit open class NEBasePinMessageTextCell: NEBasePinMessageCell { lazy var contentLabel: UILabel = { let label = UILabel() - label.font = UIFont.systemFont(ofSize: 14.0) + label.font = UIFont.systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.pinMessageTextSize) label.textColor = .ne_darkText label.translatesAutoresizingMaskIntoConstraints = false + label.isUserInteractionEnabled = true label.numberOfLines = 3 return label }() @@ -38,6 +39,10 @@ open class NEBasePinMessageTextCell: NEBasePinMessageCell { override open func setupUI() { super.setupUI() + commonUI() + } + + open func commonUI() { replyLabel.font = UIFont.systemFont(ofSize: 12) replyLabel.textColor = UIColor(hexString: "#929299") replyLabel.translatesAutoresizingMaskIntoConstraints = false @@ -54,9 +59,12 @@ open class NEBasePinMessageTextCell: NEBasePinMessageCell { contentLabel.rightAnchor.constraint(equalTo: line.rightAnchor), contentLabel.topAnchor.constraint(equalTo: replyLabel.bottomAnchor, constant: 1), ]) + if let gesture = contentGesture { + contentLabel.addGestureRecognizer(gesture) + } } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) if let model = item.chatmodel as? MessageTextModel { contentLabel.attributedText = model.attributeStr diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageVideoCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageVideoCell.swift index 402b8c74..26b70bc1 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageVideoCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/PinCell/NEBasePinMessageVideoCell.swift @@ -47,7 +47,7 @@ open class NEBasePinMessageVideoCell: NEBasePinMessageImageCell { super.init(coder: coder) } - override public func setupUI() { + override open func setupUI() { super.setupUI() contentImageView.addSubview(stateView) contentImageView.addCustomCorner(conrners: [.topLeft], radius: 8, backcolor: .white) @@ -67,10 +67,10 @@ open class NEBasePinMessageVideoCell: NEBasePinMessageImageCell { stateView.isUserInteractionEnabled = false } - override public func configure(_ item: PinMessageModel) { + override open func configure(_ item: PinMessageModel) { super.configure(item) - if let videoObject = item.chatmodel?.message?.messageObject as? NIMVideoObject { + if let videoObject = item.chatmodel.message?.messageObject as? NIMVideoObject { if let path = videoObject.coverUrl { contentImageView.sd_setImage( with: URL(string: path), diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/UserBaseTableViewCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/UserBaseTableViewCell.swift index 46d6991a..93483e69 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/UserBaseTableViewCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/Cell/UserBaseTableViewCell.swift @@ -15,6 +15,7 @@ open class UserBaseTableViewCell: UITableViewCell { avatarImage.clipsToBounds = true avatarImage.isUserInteractionEnabled = true avatarImage.contentMode = .scaleAspectFill + avatarImage.accessibilityIdentifier = "id.avatar" return avatarImage }() @@ -25,6 +26,7 @@ open class UserBaseTableViewCell: UITableViewCell { nameLabel.font = UIFont.systemFont(ofSize: 12) nameLabel.textColor = .white nameLabel.text = "placeholder" + nameLabel.accessibilityIdentifier = "id.avatar" return nameLabel }() @@ -32,10 +34,11 @@ open class UserBaseTableViewCell: UITableViewCell { let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = "placeholder" + titleLabel.accessibilityIdentifier = "id.nickname" return titleLabel }() - public var userModel: User? + public var userModel: NEKitUser? override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) @@ -67,12 +70,12 @@ open class UserBaseTableViewCell: UITableViewCell { titleLabel.text = "placeholder" } - open func setModel(_ model: User) { + open func setModel(_ model: NEKitUser) { userModel = model nameLabel.text = model.shortName(showAlias: false, count: 2) titleLabel.text = model.showName() - if let avatarURL = model.userInfo?.avatarUrl { + if let avatarURL = model.userInfo?.avatarUrl, !avatarURL.isEmpty { avatarImage .sd_setImage(with: URL(string: avatarURL)) { [weak self] image, error, type, url in if image != nil { diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatActivityIndicatorView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatActivityIndicatorView.swift index 54bb3d74..d61d5336 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatActivityIndicatorView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatActivityIndicatorView.swift @@ -13,7 +13,7 @@ public enum ChatSendMessageStatus: Int { } @objcMembers -public class ChatActivityIndicatorView: UIView { +open class ChatActivityIndicatorView: UIView { public var messageStatus: ChatSendMessageStatus? { didSet { failBtn.isHidden = true @@ -44,7 +44,7 @@ public class ChatActivityIndicatorView: UIView { commonUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatBrokenNetworkView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatBrokenNetworkView.swift index 3e2a623a..a60b7cf4 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatBrokenNetworkView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatBrokenNetworkView.swift @@ -6,13 +6,13 @@ import UIKit @objcMembers -public class ChatBrokenNetworkView: UIView { +open class ChatBrokenNetworkView: UIView { override init(frame: CGRect) { super.init(frame: frame) commonUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -32,7 +32,7 @@ public class ChatBrokenNetworkView: UIView { label.font = DefaultTextFont(14) label.textColor = HexRGB(0xFC596A) label.textAlignment = .center - label.text = chatLocalizable("network_unavailable") + label.text = commonLocalizable("network_error") return label }() } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatRecordView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatRecordView.swift index 7a4c1c6b..87118f70 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatRecordView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ChatRecordView.swift @@ -14,7 +14,7 @@ public protocol ChatRecordViewDelegate: NSObjectProtocol { } @objcMembers -public class ChatRecordView: UIView, UIGestureRecognizerDelegate { +open class ChatRecordView: UIView, UIGestureRecognizerDelegate { var recordImageView = UIImageView() var topTipLabel = UILabel() var tipLabel = UILabel() @@ -25,7 +25,7 @@ public class ChatRecordView: UIView, UIGestureRecognizerDelegate { commonUI() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -99,7 +99,7 @@ public class ChatRecordView: UIView, UIGestureRecognizerDelegate { } } - public func stopRecordAnimation() { + open func stopRecordAnimation() { topTipLabel.isHidden = true recordImageView.stopAnimating() } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/CirleProgressView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/CirleProgressView.swift index a711a9df..df1b9fb5 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/CirleProgressView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/CirleProgressView.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class CirleProgressView: UIView { +open class CirleProgressView: UIView { // 0~1 public var progress: Float = 0 { didSet { @@ -40,7 +40,6 @@ public class CirleProgressView: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear - accessibilityIdentifier = "id.status" imageView.frame = bounds imageView.contentMode = .center addSubview(imageView) @@ -64,7 +63,7 @@ public class CirleProgressView: UIView { layer.addSublayer(sectorLayer) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/MessageOperationView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/MessageOperationView.swift index 03f74cdf..19b1b58c 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/MessageOperationView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/MessageOperationView.swift @@ -11,7 +11,7 @@ public protocol MessageOperationViewDelegate: AnyObject { } @objcMembers -public class MessageOperationView: UIView, UICollectionViewDataSource, UICollectionViewDelegate { +open class MessageOperationView: UIView, UICollectionViewDataSource, UICollectionViewDelegate { var collcetionView: UICollectionView public weak var delegate: MessageOperationViewDelegate? public var items = [OperationItem]() { @@ -56,19 +56,19 @@ public class MessageOperationView: UIView, UICollectionViewDataSource, UICollect addSubview(collcetionView) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UICollectionViewDataSource - public func collectionView(_ collectionView: UICollectionView, - numberOfItemsInSection section: Int) -> Int { + open func collectionView(_ collectionView: UICollectionView, + numberOfItemsInSection section: Int) -> Int { items.count } - public func collectionView(_ collectionView: UICollectionView, - cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + open func collectionView(_ collectionView: UICollectionView, + cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "\(OperationCell.self)", for: indexPath @@ -80,8 +80,8 @@ public class MessageOperationView: UIView, UICollectionViewDataSource, UICollect // MARK: UICollectionViewDelegate - public func collectionView(_ collectionView: UICollectionView, - didSelectItemAt indexPath: IndexPath) { + open func collectionView(_ collectionView: UICollectionView, + didSelectItemAt indexPath: IndexPath) { removeFromSuperview() delegate?.didSelectedItem(item: items[indexPath.row]) } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEBaseChatInputView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEBaseChatInputView.swift index bd6ce8e3..4d054363 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEBaseChatInputView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEBaseChatInputView.swift @@ -4,6 +4,7 @@ // found in the LICENSE file. import NECommonKit +import NECommonUIKit import NECoreKit import UIKit @@ -16,14 +17,28 @@ public enum ChatMenuType: Int { case addMore } +@objc +public enum ChatInputMode: Int { + case normal + case multipleSend + case multipleReturn +} + public let yxAtMsg = "yxAitMsg" public let atRangeOffset = 1 public let atSegmentsKey = "segments" public let atTextKey = "text" +public protocol ChatInputMultilineDelegate: NSObject { + func expandButtonDidClick() + func didHideMultipleButtonClick() +} + @objcMembers open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, - InputEmoticonContainerViewDelegate, UITextViewDelegate, NEMoreViewDelegate { + InputEmoticonContainerViewDelegate, UITextViewDelegate, NEMoreViewDelegate, UITextFieldDelegate { + public weak var multipleLineDelegate: ChatInputMultilineDelegate? + public weak var delegate: ChatInputViewDelegate? public var currentType: ChatMenuType = .text public var currentButton: UIButton? @@ -35,6 +50,13 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, public var nickAccidDic = [String: String]() + public var isMultipleLineMode = false // 是否是多行模式 + + public var chatInpuMode = ChatInputMode.normal + + // 换行输入框 标题限制字数 + public var textLimit = 20 + public var textView: NETextView = { let textView = NETextView() textView.placeholderLabel.numberOfLines = 1 @@ -52,6 +74,23 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return textView }() + lazy var backView: UIView = { + let back = UIView() + back.translatesAutoresizingMaskIntoConstraints = false + back.backgroundColor = .white + back.clipsToBounds = true + back.layer.cornerRadius = 8 + return back + }() + + // 展开按钮 + public var expandButton: ExpandButton = { + let button = ExpandButton() + button.translatesAutoresizingMaskIntoConstraints = false + button.backgroundColor = .clear + return button + }() + public var stackView = UIStackView() var contentView = UIView() public var contentSubView: UIView? @@ -77,30 +116,44 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, open func commonUI() {} - public func addRecordView() { + open func addRecordView() { currentType = .audio textView.resignFirstResponder() + titleField.resignFirstResponder() contentSubView?.isHidden = true contentSubView = recordView contentSubView?.isHidden = false } - public func addEmojiView() { + open func addEmojiView() { currentType = .emoji textView.resignFirstResponder() + titleField.resignFirstResponder() + contentSubView?.isHidden = true contentSubView = emojiView contentSubView?.isHidden = false } - public func addMoreActionView() { + open func addMoreActionView() { currentType = .addMore textView.resignFirstResponder() + titleField.resignFirstResponder() + contentSubView?.isHidden = true contentSubView = chatAddMoreView contentSubView?.isHidden = false } + open func sendText(textView: NETextView) { + guard let text = getRealSendText(textView.attributedText) else { + return + } + delegate?.sendText(text: text, attribute: textView.attributedText) + textView.text = "" + atCache?.clean() + } + // MARK: ===================== lazy method ===================== public lazy var emojiView: UIView = { @@ -126,27 +179,26 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return view }() - public func textViewDidChange(_ textView: UITextView) { - delegate?.textFieldDidChange(textView) + open func textViewDidChange(_ textView: UITextView) { + delegate?.textFieldDidChange(textView.text) } - public func textViewDidEndEditing(_ textView: UITextView) { - delegate?.textFieldDidEndEditing(textView) + open func textViewDidEndEditing(_ textView: UITextView) { + delegate?.textFieldDidEndEditing(textView.text) } - public func textViewDidBeginEditing(_ textView: UITextView) { - delegate?.textFieldDidBeginEditing(textView) + open func textViewDidBeginEditing(_ textView: UITextView) { + delegate?.textFieldDidBeginEditing(textView.text) } - public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { + open func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { currentType = .text return true } - public func checkRemoveAtMessage(range: NSRange, attribute: NSAttributedString) -> NSRange? { + open func checkRemoveAtMessage(range: NSRange, attribute: NSAttributedString) -> NSRange? { var temRange: NSRange? let start = range.location -// let end = range.location + range.length attribute.enumerateAttribute( NSAttributedString.Key.foregroundColor, in: NSMakeRange(0, attribute.length) @@ -161,23 +213,43 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, temRange = NSMakeRange(findRange.location, findRange.length + atRangeOffset) stop.pointee = true } - -// if (findRange.location <= start && start < findRange.location + findRange.length + atRangeOffset) || -// (findRange.location < end && end <= findRange.location + findRange.length + atRangeOffset) { -// temRange = NSMakeRange(findRange.location, findRange.length + atRangeOffset) -// stop.pointee = true -// } } return temRange } - public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, - replacementText text: String) -> Bool { - print("text view range : ", range) - print("select range : ", textView.selectedRange) + // 查找at消息位置并且根据光标位置距离高亮前段或者后端更近判断光标最终显示在前还是在后 + open func findShowPosition(range: NSRange, attribute: NSAttributedString) -> NSRange? { + var showRange: NSRange? + let start = range.location + attribute.enumerateAttribute( + NSAttributedString.Key.foregroundColor, + in: NSMakeRange(0, attribute.length) + ) { value, findRange, stop in + guard let findColor = value as? UIColor else { + return + } + if isEqualToColor(findColor, UIColor.ne_blueText) == false { + return + } + let findStart = findRange.location + let findEnd = findRange.location + findRange.length + atRangeOffset + if findStart <= start, start < findEnd { + if findEnd - start > start - findStart { + showRange = NSMakeRange(findStart, 0) + } else { + showRange = NSMakeRange(findRange.location, findRange.length + atRangeOffset) + } + stop.pointee = true + } + } + return showRange + } + + open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, + replacementText text: String) -> Bool { textView.typingAttributes = [NSAttributedString.Key.foregroundColor: UIColor.ne_darkText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)] - if text == "\n" { + if chatInpuMode == .normal || chatInpuMode == .multipleSend, text == "\n" { guard var realText = getRealSendText(textView.attributedText) else { return true } @@ -189,20 +261,20 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return false } - if textView.attributedText.length == 0, let pasteString = UIPasteboard.general.string, text.count > 0 { - if pasteString == text { - let muta = NSMutableAttributedString(string: text) - muta.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.ne_darkText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0)], range: NSMakeRange(0, text.count)) - textView.attributedText = muta - textView.selectedRange = NSMakeRange(text.count - 1, 0) - return false + // 处理粘贴,表情解析(存在表情则字符数量>=3) + if text.count >= 3 { + let mutaString = NSMutableAttributedString(attributedString: textView.attributedText) + let addString = NEEmotionTool.getAttWithStr(str: text, font: .systemFont(ofSize: 16)) + mutaString.replaceCharacters(in: range, with: addString) + textView.attributedText = mutaString + DispatchQueue.main.async { + textView.selectedRange = NSMakeRange(range.location + addString.length, 0) } + return false } if text.count == 0 { -// let selectRange = textView.selectedRange let temRange = checkRemoveAtMessage(range: range, attribute: textView.attributedText) - if let findRange = temRange { let mutableAttri = NSMutableAttributedString(attributedString: textView.attributedText) if mutableAttri.length >= findRange.location + findRange.length { @@ -228,28 +300,27 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return true } - public func textViewDidChangeSelection(_ textView: UITextView) { - print("textViewDidChangeSelection") + open func textViewDidChangeSelection(_ textView: UITextView) { let range = textView.selectedRange - if let findRange = checkRemoveAtMessage(range: range, attribute: textView.attributedText) { + if let findRange = findShowPosition(range: range, attribute: textView.attributedText) { textView.selectedRange = NSMakeRange(findRange.location + findRange.length, 0) } } @available(iOS 10.0, *) - public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { + open func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { print("action : ", interaction) return true } // @available(iOS 10.0, *) -// public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { +// open func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { // // return true // } - public func buttonEvent(button: UIButton) { + open func buttonEvent(button: UIButton) { button.isSelected = !button.isSelected if button.tag - 5 != 2, button != currentButton { currentButton?.isSelected = false @@ -273,7 +344,7 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, // MARK: NIMInputEmoticonContainerViewDelegate - public func selectedEmoticon(emoticonID: String, emotCatalogID: String, description: String) { + open func selectedEmoticon(emoticonID: String, emotCatalogID: String, description: String) { if emoticonID.isEmpty { // 删除键 textView.deleteBackward() print("delete ward") @@ -309,42 +380,37 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, } } - public func didPressSend(sender: UIButton) { - guard let text = getRealSendText(textView.attributedText) else { - return - } - delegate?.sendText(text: text, attribute: textView.attributedText) - textView.text = "" - atCache?.clean() + open func didPressSend(sender: UIButton) { + sendText(textView: textView) } - public func stopRecordAnimation() { + open func stopRecordAnimation() { greyView.isHidden = true recordView.stopRecordAnimation() } // MARK: NEMoreViewDelagate - public func moreViewDidSelectMoreCell(moreView: NEChatMoreActionView, cell: NEInputMoreCell) { + open func moreViewDidSelectMoreCell(moreView: NEChatMoreActionView, cell: NEInputMoreCell) { delegate?.didSelectMoreCell(cell: cell) } // MARK: ChatRecordViewDelegate - public func startRecord() { + open func startRecord() { greyView.isHidden = false delegate?.startRecord() } - public func moveOutView() { + open func moveOutView() { delegate?.moveOutView() } - public func moveInView() { + open func moveInView() { delegate?.moveInView() } - public func endRecord(insideView: Bool) { + open func endRecord(insideView: Bool) { greyView.isHidden = true delegate?.endRecord(insideView: insideView) } @@ -372,7 +438,7 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return muta as String } - public func getRemoteExtension(_ attri: NSAttributedString?) -> [String: Any]? { + open func getRemoteExtension(_ attri: NSAttributedString?) -> [String: Any]? { guard let attribute = attri else { return nil } @@ -425,7 +491,7 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return nil } - public func getAtRemoteExtension() -> [String: Any]? { + open func getAtRemoteExtension() -> [String: Any]? { var atDic = [String: Any]() NELog.infoLog(className(), desc: "at range cache : \(atRangeCache)") atRangeCache.forEach { (key: String, value: MessageAtCacheModel) in @@ -451,7 +517,7 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, return nil } - public func cleartAtCache() { + open func cleartAtCache() { nickAccidDic.removeAll() } @@ -483,4 +549,174 @@ open class NEBaseChatInputView: UIView, ChatRecordViewDelegate, func missClickEmoj() { print("click one px space") } + + open func textFieldDidEndEditing(_ textField: UITextField) { + delegate?.textFieldDidChange(textField.text) + } + + open func textFieldDidBeginEditing(_ textField: UITextField) { + currentType = .text + delegate?.textFieldDidBeginEditing(textField.text) + } + + open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + if textField == titleField { + if string == "\n" { + var realText = "" + if let text = getRealSendText(textView.attributedText) { + realText = text + } + delegate?.sendText(text: realText, attribute: textView.attributedText) + return false + } + } + + return true + } + + open func textFieldChange() { + delegate?.textFieldDidChange(titleField.text) + if titleField.text?.count ?? 0 <= 0 { + delegate?.titleTextDidClearEmpty() + } + guard let _ = titleField.markedTextRange else { + if let text = titleField.text, + text.utf16.count > textLimit { + titleField.text = String(text.prefix(textLimit)) + } + return + } + } + + public var multipleLineView: UIView = { + let view = UIView() + view.translatesAutoresizingMaskIntoConstraints = false + view.backgroundColor = UIColor.white + view.clipsToBounds = true + view.layer.cornerRadius = 6.0 + view.isHidden = true + + view.layer.shadowColor = UIColor.black.cgColor + view.layer.shadowOpacity = 0.5 + view.layer.shadowOffset = CGSize(width: 3, height: 3) + view.layer.shadowRadius = 5 + view.layer.masksToBounds = false + return view + }() + + public var titleField: UITextField = { + let text = UITextField() + text.translatesAutoresizingMaskIntoConstraints = false + text.font = UIFont.systemFont(ofSize: 18.0) + text.textColor = .ne_darkText + text.returnKeyType = .send + text.attributedPlaceholder = NSAttributedString(string: coreLoader.localizable("multiple_line_placleholder"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.ne_darkText]) + text.addTarget(self, action: #selector(textFieldChange), for: .editingChanged) + return text + }() + + public var multipleLineExpandButton: ExpandButton = { + let button = ExpandButton() + button.translatesAutoresizingMaskIntoConstraints = false + button.backgroundColor = .clear + return button + }() + + public var multipleSendButton: ExpandButton = { + let button = ExpandButton() + button.translatesAutoresizingMaskIntoConstraints = false + button.backgroundColor = .clear + button.setImage(coreLoader.loadImage("multiple_send_image"), for: .normal) + return button + }() + + public var multipleLineViewHeight: NSLayoutConstraint? + + func setupMultipleLineView() { + addSubview(multipleLineView) + multipleLineViewHeight = multipleLineView.heightAnchor.constraint(equalToConstant: 400) + NSLayoutConstraint.activate([ + multipleLineViewHeight!, + multipleLineView.leftAnchor.constraint(equalTo: leftAnchor), + multipleLineView.rightAnchor.constraint(equalTo: rightAnchor), + multipleLineView.topAnchor.constraint(equalTo: topAnchor, constant: -4), + ]) + + multipleLineView.addSubview(titleField) + titleField.delegate = self + NSLayoutConstraint.activate([ + titleField.leftAnchor.constraint(equalTo: multipleLineView.leftAnchor, constant: 16), + titleField.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: -56), + titleField.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 5), + titleField.heightAnchor.constraint(equalToConstant: 40), + ]) + + multipleLineView.addSubview(multipleLineExpandButton) + NSLayoutConstraint.activate([ + multipleLineExpandButton.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: 0), + multipleLineExpandButton.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 5), + multipleLineExpandButton.widthAnchor.constraint(equalToConstant: 44), + multipleLineExpandButton.heightAnchor.constraint(equalToConstant: 40), + ]) + multipleLineExpandButton.addTarget(self, action: #selector(didClickHideMultipleButton), for: .touchUpInside) + + let dividerLine = UIView() + dividerLine.translatesAutoresizingMaskIntoConstraints = false + dividerLine.backgroundColor = UIColor(hexString: "#ECECEC") + multipleLineView.addSubview(dividerLine) + NSLayoutConstraint.activate([ + dividerLine.leftAnchor.constraint(equalTo: multipleLineView.leftAnchor), + dividerLine.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor), + dividerLine.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 236), + dividerLine.heightAnchor.constraint(equalToConstant: 1), + ]) + + multipleLineView.addSubview(multipleSendButton) + NSLayoutConstraint.activate([ + multipleSendButton.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: -16), + multipleSendButton.topAnchor.constraint(equalTo: dividerLine.bottomAnchor, constant: 8), + multipleSendButton.widthAnchor.constraint(equalToConstant: 44), + multipleSendButton.heightAnchor.constraint(equalToConstant: 40), + ]) + multipleSendButton.addTarget(self, action: #selector(didClickSendButton), for: .touchUpInside) + } + + open func didClickExpandButton() { + multipleLineDelegate?.expandButtonDidClick() + } + + open func didClickSendButton() { + sendText(textView: textView) + } + + open func didClickHideMultipleButton() { + multipleLineDelegate?.didHideMultipleButtonClick() + } + + open func restoreNormalInputStyle() { + multipleLineView.isHidden = true + if titleField.text?.count ?? 0 > 0 { + chatInpuMode = .multipleSend + } else { + chatInpuMode = .normal + } + isMultipleLineMode = false + } + + open func changeToMultipleLineStyle() { + chatInpuMode = .multipleReturn + isMultipleLineMode = true + multipleLineView.isHidden = false + } + + open func setMuteInputStyle() { + cleartAtCache() + expandButton.isEnabled = false + textView.attributedText = nil + textView.text = nil + } + + open func setUnMuteInputStyle() { + expandButton.isEnabled = true + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEChatMoreActionView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEChatMoreActionView.swift index 803642f0..2498f77e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEChatMoreActionView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEChatMoreActionView.swift @@ -11,7 +11,7 @@ public protocol NEMoreViewDelegate: NSObjectProtocol { } @objcMembers -public class NEChatMoreActionView: UIView { +open class NEChatMoreActionView: UIView { private var sectionCount: Int = 1 private var itemsInSection: Int = 4 // 默认行数 @@ -31,7 +31,7 @@ public class NEChatMoreActionView: UIView { setupConstraints() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -103,15 +103,15 @@ public class NEChatMoreActionView: UIView { } extension NEChatMoreActionView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { - public func numberOfSections(in collectionView: UICollectionView) -> Int { + open func numberOfSections(in collectionView: UICollectionView) -> Int { sectionCount } - public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { itemsInSection } - public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: NEMoreCell_ReuseId, for: indexPath @@ -136,13 +136,13 @@ extension NEChatMoreActionView: UICollectionViewDataSource, UICollectionViewDele return cell ?? UICollectionViewCell() } - public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = (collectionView.cellForItem(at: indexPath) as? NEInputMoreCell) { delegate?.moreViewDidSelectMoreCell(moreView: self, cell: cell) } } - public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { NEInputMoreCell.getSize() } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEInputMoreCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEInputMoreCell.swift index 564d963a..7f151a83 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEInputMoreCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEInputMoreCell.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class NEInputMoreCell: UICollectionViewCell { +open class NEInputMoreCell: UICollectionViewCell { public var cellData: NEMoreItemModel? override init(frame: CGRect) { @@ -14,7 +14,7 @@ public class NEInputMoreCell: UICollectionViewCell { setupViews() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { super.init(coder: coder) } @@ -51,6 +51,7 @@ public class NEInputMoreCell: UICollectionViewCell { title.font = UIFont.systemFont(ofSize: 10) title.textAlignment = .center title.translatesAutoresizingMaskIntoConstraints = false + title.accessibilityIdentifier = "id.menuIcon" return title }() diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEMutilSelectBottomView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEMutilSelectBottomView.swift new file mode 100644 index 00000000..ce90656f --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/NEMutilSelectBottomView.swift @@ -0,0 +1,164 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import Foundation +import UIKit + +public protocol NEMutilSelectBottomViewDelegate: NSObjectProtocol { + func didClickSingleForwardButton() + func didClickMultiForwardButton() + func didClickDeleteButton() +} + +open class NEMutilSelectBottomView: UIView { + public weak var delegate: NEMutilSelectBottomViewDelegate? + public var buttonTopAnchor: NSLayoutConstraint? + + override public init(frame: CGRect) { + super.init(frame: frame) + setupSubview() + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + open func setupSubview() { + // 逐条转发 + addSubview(singleForwardButton) + buttonTopAnchor = singleForwardButton.topAnchor.constraint(equalTo: topAnchor, constant: 12) + NSLayoutConstraint.activate([ + buttonTopAnchor!, + singleForwardButton.centerXAnchor.constraint(equalTo: centerXAnchor), + singleForwardButton.widthAnchor.constraint(equalToConstant: 48), + singleForwardButton.heightAnchor.constraint(equalToConstant: 48), + ]) + + addSubview(singleForwardLabel) + NSLayoutConstraint.activate([ + singleForwardLabel.topAnchor.constraint(equalTo: singleForwardButton.bottomAnchor, constant: 3), + singleForwardLabel.centerXAnchor.constraint(equalTo: singleForwardButton.centerXAnchor), + singleForwardLabel.widthAnchor.constraint(equalToConstant: 48), + singleForwardLabel.heightAnchor.constraint(equalToConstant: 12), + ]) + + // 合并转发 + addSubview(multiForwardButton) + NSLayoutConstraint.activate([ + multiForwardButton.centerYAnchor.constraint(equalTo: singleForwardButton.centerYAnchor), + multiForwardButton.rightAnchor.constraint(equalTo: singleForwardButton.leftAnchor, constant: -52), + multiForwardButton.widthAnchor.constraint(equalToConstant: 48), + multiForwardButton.heightAnchor.constraint(equalToConstant: 48), + ]) + + addSubview(multiForwardLabel) + NSLayoutConstraint.activate([ + multiForwardLabel.centerYAnchor.constraint(equalTo: singleForwardLabel.centerYAnchor), + multiForwardLabel.centerXAnchor.constraint(equalTo: multiForwardButton.centerXAnchor), + multiForwardLabel.widthAnchor.constraint(equalToConstant: 48), + multiForwardLabel.heightAnchor.constraint(equalToConstant: 12), + ]) + + // 删除 + addSubview(deleteButton) + NSLayoutConstraint.activate([ + deleteButton.centerYAnchor.constraint(equalTo: singleForwardButton.centerYAnchor), + deleteButton.leftAnchor.constraint(equalTo: singleForwardButton.rightAnchor, constant: 52), + deleteButton.widthAnchor.constraint(equalToConstant: 48), + deleteButton.heightAnchor.constraint(equalToConstant: 48), + ]) + + addSubview(deleteLabel) + NSLayoutConstraint.activate([ + deleteLabel.centerYAnchor.constraint(equalTo: singleForwardLabel.centerYAnchor), + deleteLabel.centerXAnchor.constraint(equalTo: deleteButton.centerXAnchor), + deleteLabel.widthAnchor.constraint(equalToConstant: 48), + deleteLabel.heightAnchor.constraint(equalToConstant: 12), + ]) + } + + public lazy var singleForwardButton: UIButton = { + let button = UIButton() + button.translatesAutoresizingMaskIntoConstraints = false + button.setImage(.ne_imageNamed(name: "select_singleForward"), for: .normal) + button.setImage(.ne_imageNamed(name: "unselect_singleForward"), for: .disabled) + button.addTarget(self, action: #selector(singleForwardButtonAction), for: .touchUpInside) + return button + }() + + public lazy var singleForwardLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("select_per_item") + label.textColor = .ne_greyText + label.font = .systemFont(ofSize: 11) + label.textAlignment = .center + return label + }() + + public lazy var multiForwardButton: UIButton = { + let button = UIButton() + button.translatesAutoresizingMaskIntoConstraints = false + button.setImage(.ne_imageNamed(name: "select_multiForward"), for: .normal) + button.setImage(.ne_imageNamed(name: "unselect_multiForward"), for: .disabled) + button.addTarget(self, action: #selector(multiForwardButtonAction), for: .touchUpInside) + return button + }() + + public lazy var multiForwardLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("select_multi") + label.textColor = .ne_greyText + label.font = .systemFont(ofSize: 11) + label.textAlignment = .center + return label + }() + + public lazy var deleteButton: UIButton = { + let button = UIButton() + button.translatesAutoresizingMaskIntoConstraints = false + button.setImage(.ne_imageNamed(name: "select_delete"), for: .normal) + button.setImage(.ne_imageNamed(name: "unselect_delete"), for: .disabled) + button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside) + return button + }() + + public lazy var deleteLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("operation_delete") + label.textColor = .ne_greyText + label.font = .systemFont(ofSize: 11) + label.textAlignment = .center + return label + }() + + func setEnable(_ enable: Bool) { + multiForwardButton.isEnabled = enable + singleForwardButton.isEnabled = enable + deleteButton.isEnabled = enable + multiForwardLabel.isEnabled = enable + singleForwardLabel.isEnabled = enable + deleteLabel.isEnabled = enable + } + + func setLabelColor(color: UIColor) { + multiForwardLabel.textColor = color + singleForwardLabel.textColor = color + deleteLabel.textColor = color + } + + @objc func multiForwardButtonAction() { + delegate?.didClickMultiForwardButton() + } + + @objc func singleForwardButtonAction() { + delegate?.didClickSingleForwardButton() + } + + @objc func deleteButtonAction() { + delegate?.didClickDeleteButton() + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ReplyView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ReplyView.swift index 83d2e18f..380faa5a 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ReplyView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/ChatView/ReplyView.swift @@ -6,7 +6,7 @@ import UIKit @objcMembers -public class ReplyView: UIView { +open class ReplyView: UIView { var closeButton = UIButton(type: .custom) var line = UIView() var textLabel = UILabel() @@ -16,6 +16,7 @@ public class ReplyView: UIView { backgroundColor = UIColor(hexString: "#EFF1F2") closeButton.setImage(UIImage.ne_imageNamed(name: "close"), for: .normal) closeButton.translatesAutoresizingMaskIntoConstraints = false + closeButton.accessibilityIdentifier = "id.replyClose" // closeButton.addTarget(self, action: #selector(closeButtonEvent), for: .touchUpInside) addSubview(closeButton) NSLayoutConstraint.activate([ @@ -38,6 +39,7 @@ public class ReplyView: UIView { textLabel.font = UIFont.systemFont(ofSize: 12) textLabel.textColor = UIColor(hexString: "#929299") textLabel.translatesAutoresizingMaskIntoConstraints = false + textLabel.accessibilityIdentifier = "id.replyContent" addSubview(textLabel) NSLayoutConstraint.activate([ textLabel.leadingAnchor.constraint(equalTo: closeButton.trailingAnchor, constant: 8), @@ -47,7 +49,7 @@ public class ReplyView: UIView { ]) } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapAddressCell.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapAddressCell.swift index fd44700b..b60e2c77 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapAddressCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapAddressCell.swift @@ -6,14 +6,14 @@ import NEChatKit import UIKit @objcMembers -public class NEMapAddressCell: UITableViewCell { +open class NEMapAddressCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none setupSubviews() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapGuideBottomView.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapGuideBottomView.swift index a381cd9a..97f79ba7 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapGuideBottomView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/View/MapView/NEMapGuideBottomView.swift @@ -10,7 +10,7 @@ public protocol NEMapGuideBottomViewDelegate: NSObjectProtocol { } @objcMembers -public class NEMapGuideBottomView: UIView { +open class NEMapGuideBottomView: UIView { public weak var delegate: NEMapGuideBottomViewDelegate? override public init(frame: CGRect) { @@ -18,7 +18,7 @@ public class NEMapGuideBottomView: UIView { setupSubviews() } - required init?(coder: NSCoder) { + public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/ChatViewModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/ChatViewModel.swift index d6616f66..8637638b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/ChatViewModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/ChatViewModel.swift @@ -8,7 +8,6 @@ import NECommonKit import NECoreIMKit import NECoreKit import NIMSDK -// import NEKitContact @objc public enum LoadMessageDirection: Int { @@ -33,9 +32,11 @@ public protocol ChatViewModelDelegate: NSObjectProtocol { func didLeaveTeam() func didDismissTeam() func didRefreshTable() + func onTeamMemberChange(team: NIMTeam) - @objc optional - func getMessageModel(model: MessageModel) + @objc optional func showErrorToast(error: Error?) + @objc optional func getMessageModel(model: MessageModel) + @objc optional func selectedMessagesChanged(_ count: Int) } let revokeLocalMessage = "revoke_message_local" @@ -43,13 +44,22 @@ let revokeLocalMessageContent = "revoke_message_local_content" let removePinMessageNoti = "remove_pin_message_noti" @objcMembers -public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDelegate, - NIMConversationManagerDelegate, NIMSystemNotificationManagerDelegate, ChatExtendProviderDelegate, FriendProviderDelegate { +open class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDelegate, + NIMConversationManagerDelegate, NIMSystemNotificationManagerDelegate, ChatExtendProviderDelegate, FriendProviderDelegate, NIMTeamManagerDelegate { public var team: NIMTeam? + /// 当前成员的群成员对象类 + public var teamMember: NIMTeamMember? public var session: NIMSession public var messages = [MessageModel]() public weak var delegate: ChatViewModelDelegate? - public var newUserInfoDic = [String: User]() + + // 多选选中的消息 + public var selectedMessages = [NIMMessage]() { + didSet { + delegate?.selectedMessagesChanged?(selectedMessages.count) + } + } + // 上拉时间戳 private var newMsg: NIMMessage? // 下拉时间戳 @@ -57,10 +67,9 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel public var repo = ChatRepo.shared public var operationModel: MessageContentModel? - private var userInfo = [String: User]() public var isReplying = false public let messagPageNum: UInt = 100 - private let className = "ChatViewModel" + // 可信时间戳 public var credibleTimestamp: TimeInterval = 0 public var anchor: NIMMessage? @@ -72,7 +81,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel public var deletingMsgDic = Set() init(session: NIMSession) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId:" + session.sessionId) + NELog.infoLog(ModuleName + " ChatViewModel", desc: #function + ", sessionId:" + session.sessionId) self.session = session anchor = nil super.init() @@ -81,11 +90,12 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel repo.addSessionDelegate(delegate: self) repo.addSystemNotificationDelegate(delegate: self) repo.addChatExtendDelegate(delegate: self) + repo.addTeamDelegate(delegate: self) addObserver() } init(session: NIMSession, anchor: NIMMessage?) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId:" + session.sessionId) + NELog.infoLog(ModuleName + " ChatViewModel", desc: #function + ", sessionId:" + session.sessionId) self.session = session self.anchor = anchor super.init() @@ -97,11 +107,11 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel repo.addSessionDelegate(delegate: self) repo.addSystemNotificationDelegate(delegate: self) repo.addChatExtendDelegate(delegate: self) + repo.addTeamDelegate(delegate: self) addObserver() } func addObserver() { - NotificationCenter.default.addObserver(self, selector: #selector(updateFriendInfo), name: NotificationName.updateFriendInfo, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(removePinNoti), name: Notification.Name(removePinMessageNoti), object: nil) } @@ -112,8 +122,9 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func sendTextMessage(text: String, remoteExt: [String: Any]?, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", text.count: \(text.count)") + /// 发送文本消息(当前会话) + open func sendTextMessage(text: String, remoteExt: [String: Any]?, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", text.count: \(text.count)") if text.count <= 0 { return } @@ -124,15 +135,22 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel ) } - func updateFriendInfo(notification: Notification) { - if let user = notification.object as? User, - let uid = user.userId { - newUserInfoDic[uid] = user + /// 发送文本消息(当前会话) + open func sendTextMessage(text: String, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", text.count: \(text.count)") + if text.count <= 0 { + return } + repo.sendMessage( + message: MessageUtils.textMessage(text: text), + session: session, + completion + ) } - public func sendTextMessage(text: String, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", text.count: \(text.count)") + /// 发送文本消息(非当前会话) + open func sendTextMessage(text: String, session: NIMSession, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", text.count: \(text.count)") if text.count <= 0 { return } @@ -143,8 +161,12 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel ) } - public func sendAudioMessage(filePath: String, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", filePath:" + filePath) + open func sendAudioMessage(filePath: String, _ completion: @escaping (Error?) -> Void) { + if ChatDeduplicationHelper.instance.isRecordAudioSended(path: filePath) == true { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ",duplicate send audio at filePath:" + filePath) + return + } + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", filePath:" + filePath) repo.sendMessage( message: MessageUtils.audioMessage(filePath: filePath), session: session, @@ -152,9 +174,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel ) } - public func sendImageMessage(image: UIImage, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", image.size: \(image.size)") - // TODO: + open func sendImageMessage(image: UIImage, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", image.size: \(image.size)") repo.sendMessage( message: MessageUtils.imageMessage(image: image), session: session, @@ -162,30 +183,70 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel ) } - public func sendVideoMessage(url: URL, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", url.path:" + url.path) + open func sendImageMessage(data: Data, ext: String, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", image data count: \(data.count)") + repo.sendMessage( + message: MessageUtils.imageMessage(data: data, ext: ext), + session: session, + completion + ) + } + + open func sendImageMessage(path: String, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", image path: \(path)") + repo.sendMessage( + message: MessageUtils.imageMessage(path: path), + session: session, + completion + ) + } + + open func sendVideoMessage(url: URL, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ",video url.path:" + url.path) weak var weakSelf = self - VideoFormatConvert - .convertToMP4(with: url, avQuality: AVAssetExportPresetHighestQuality) { path, image in - if let p = path, let s = weakSelf?.session { - weakSelf?.repo.sendMessage( - message: MessageUtils.videoMessage(filePath: p), - session: s, - completion - ) + + convertVideoToMP4(videoURL: url) { url, error in + if let p = url?.path, let s = weakSelf?.session { + weakSelf?.repo.sendMessage( + message: MessageUtils.videoMessage(filePath: p), + session: s, + completion + ) + } else { + NELog.errorLog("chat veiw model", desc: "convert mov to mp4 failed") + } + } + } + + func convertVideoToMP4(videoURL: URL, completion: @escaping (URL?, Error?) -> Void) { + let outputFileName = NIMKitFileLocationHelper.genFilename(withExt: "mp4") + guard let outputPath = NIMKitFileLocationHelper.filepath(forVideo: outputFileName) else { + return + } + let asset = AVURLAsset(url: videoURL, options: nil) + let session = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) + let outputUrl = URL(fileURLWithPath: outputPath) + session?.outputURL = outputUrl + session?.outputFileType = AVFileType.mp4 + session?.shouldOptimizeForNetworkUse = true + session?.exportAsynchronously { + DispatchQueue.main.async { + if session?.status == AVAssetExportSession.Status.completed { + completion(outputUrl, nil) } else { - NELog.errorLog("chat veiw model", desc: "convert mov to mp4 failed") + completion(nil, nil) } } + } } - public func sendLocationMessage(_ model: ChatLocaitonModel, _ completion: @escaping (Error?) -> Void) { + open func sendLocationMessage(_ model: ChatLocaitonModel, _ completion: @escaping (Error?) -> Void) { let message = MessageUtils.locationMessage(model.lat, model.lng, model.title, model.address) repo.sendMessage(message: message, session: session, completion) } - public func sendFileMessage(filePath: String, displayName: String?, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", filePath:") + open func sendFileMessage(filePath: String, displayName: String?, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", filePath:\(filePath)") repo.sendMessage( message: MessageUtils.fileMessage(filePath: filePath, displayName: displayName), session: session, @@ -193,8 +254,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel ) } - public func sendFileMessage(data: Data, displayName: String?, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", filePath:") + open func sendFileMessage(data: Data, displayName: String?, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", data.count:\(data.count)") repo.sendMessage( message: MessageUtils.fileMessage(data: data, displayName: displayName), session: session, @@ -202,10 +263,69 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel ) } + /// 发送自定义消息(当前会话) + open func sendCustomMessage(attachment: NIMCustomAttachment, + remoteExt: [String: Any]?, + apnsConstent: String?, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", apnsConstent:\(String(describing: apnsConstent))") + repo.sendMessage( + message: MessageUtils.customMessage(attachment: attachment, + remoteExt: remoteExt, + apnsContent: apnsConstent), + session: session, + completion + ) + } + + /// 发送自定义消息 + open func sendCustomMessage(attachment: NIMCustomAttachment, + remoteExt: [String: Any]?, + apnsConstent: String?, + session: NIMSession, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", apnsConstent:\(String(describing: apnsConstent))") + repo.sendMessage( + message: MessageUtils.customMessage(attachment: attachment, + remoteExt: remoteExt, + apnsContent: apnsConstent), + session: session, + completion + ) + } + + open func sendBlackListTip(_ errorSession: NIMSession?, _ message: NIMMessage) { +// if DeduplicationHelper.instance.isBlackTipSended(messageId: message.messageId) == true { +// NELog.infoLog(ModuleName + " " + className(), desc: #function + "sendBlackListTip") +// return +// } + guard let eSession = errorSession else { + return + } + NELog.infoLog(ModuleName + " " + className(), desc: #function + "sendBlackListTip") + let content = chatLocalizable("black_list_tip") + let tip = NIMMessage() + let object = NIMTipObject(attach: nil, callbackExt: nil) + tip.messageObject = object + tip.text = content + let setting = NIMMessageSetting() + setting.shouldBeCounted = false + tip.setting = setting + repo.saveMessageToDB(tip, eSession) { [weak self] error in + NELog.infoLog(ModuleName + " " + (self?.className() ?? ""), desc: #function + "save black tip list tip result \(error?.localizedDescription ?? "")") + if let model = self?.modelFromMessage(message: tip) { + self?.messages.append(model) + if let currentSid = self?.session.sessionId, let errorSid = errorSession?.sessionId, currentSid == errorSid { + self?.delegate?.willSend(tip) + } + } + } + } + // 动态查询历史消息解决方案 - public func getMessagesModelDynamically(_ order: NIMMessageSearchOrder, message: NIMMessage?, - _ completion: @escaping (Error?, NSInteger, [MessageModel]?) - -> Void) { + open func getMessagesModelDynamically(_ order: NIMMessageSearchOrder, message: NIMMessage?, + _ completion: @escaping (Error?, NSInteger, [MessageModel]?) + -> Void) { let param = NIMGetMessagesDynamicallyParam() param.limit = messagPageNum param.session = session @@ -223,7 +343,6 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel repo.getMessagesDynamically(param) { error, isReliable, messages in if let messageArray = messages, messageArray.count > 0 { var count = 0 - var datas = messageArray var readMsg: NIMMessage? if order == .desc { weakSelf?.oldMsg = messageArray.last @@ -232,50 +351,54 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel readMsg = messageArray.last weakSelf?.newMsg = messageArray.last } - for (i, msg) in datas.enumerated() { - if let object = msg.messageObject as? NIMNotificationObject { - if let content = object.content as? NIMTeamNotificationContent, content.operationType == .invite { - if weakSelf?.filterInviteSet.contains(msg.messageId) == true { - continue - } else { - weakSelf?.filterInviteSet.insert(msg.messageId) - } + for msg in messageArray { + // 是否需要进行重复消息过滤 + var needFilter = msg.serverID.isEmpty + if let object = msg.messageObject as? NIMNotificationObject, + let content = object.content as? NIMTeamNotificationContent, + content.operationType == .invite { + needFilter = true + } + + if needFilter { + if weakSelf?.filterInviteSet.contains(msg.messageId) == true { + continue + } else { + weakSelf?.filterInviteSet.insert(msg.messageId) } } + print("message text : ", msg.text as Any) if let model = weakSelf?.modelFromMessage(message: msg), NotificationMessageUtils.isDiscussSeniorTeamUpdateCustomNoti(message: msg) == false { weakSelf?.filterRevokeMessage([model]) if order == .desc { - if weakSelf?.addTimeForHistoryMessage(msg) == true { - count += 1 - } - count += 1 + weakSelf?.addTimeForHistoryMessage(model) weakSelf?.messages.insert(model, at: 0) - - // 第一条消息默认显示时间 - if i == datas.count - 1 { - let timeText = String.stringFromDate(date: Date(timeIntervalSince1970: msg.timestamp)) - let model = MessageTipsModel(message: nil, - initType: .time, - initText: timeText) - weakSelf?.messages.insert(model, at: 0) - } + count += 1 } else { - if weakSelf?.addTimeMessage(msg) == true { - count += 1 + if let last = weakSelf?.messages.last { + ChatMessageHelper.addTimeMessage(model, last) } - count += 1 weakSelf?.messages.append(model) + count += 1 } } } + + // 第一条消息默认显示时间 + if let firstModel = weakSelf?.messages.first, + let msg = firstModel.message { + let timeText = String.stringFromDate(date: Date(timeIntervalSince1970: msg.timestamp)) + firstModel.timeContent = timeText + } + weakSelf?.checkAudioFile(messages: weakSelf?.messages) completion(error, count, weakSelf?.messages) if weakSelf?.session.sessionType == .P2P { if let nearMsg = readMsg { weakSelf?.markRead(messages: [nearMsg]) { error in NELog.infoLog( - ModuleName + " " + (weakSelf?.className ?? "ChatViewModel"), + ModuleName + " " + (weakSelf?.className() ?? "ChatViewModel"), desc: "CALLBACK markRead " + (error?.localizedDescription ?? "no error") ) } @@ -283,26 +406,48 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } else if weakSelf?.session.sessionType == .team { weakSelf?.markRead(messages: messageArray) { error in NELog.infoLog( - ModuleName + " " + (weakSelf?.className ?? "ChatViewModel"), + ModuleName + " " + (weakSelf?.className() ?? "ChatViewModel"), desc: "CALLBACK markRead " + (error?.localizedDescription ?? "no error") ) } weakSelf?.refreshReceipts(messages: messageArray) } + + let group = DispatchGroup() + for msg in messageArray { + if let object = msg.messageObject as? NIMNotificationObject, + let content = object.content as? NIMTeamNotificationContent { + let targetIDs = content.targetIDs ?? [] + targetIDs.forEach { uid in + if ChatUserCache.getUserInfo(uid) == nil { + group.enter() + ChatUserCache.getUserInfo(uid) { _, _ in + group.leave() + } + } + } + } + } + + group.notify(queue: .main) { + weakSelf?.delegate?.didRefreshTable() + } + } else { + weakSelf?.checkAudioFile(messages: weakSelf?.messages) completion(error, 0, weakSelf?.messages) } } } - public func queryRoamMsgHasMoreTime_v2(_ completion: @escaping (Error?, NSInteger, NSInteger, Int) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function) + open func queryRoamMsgHasMoreTime_v2(_ completion: @escaping (Error?, NSInteger, NSInteger, Int) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function) weak var weakSelf = self // 记录可信时间戳 if anchor == nil { weakSelf?.getMessagesModelDynamically(.desc, message: nil) { error, count, models in NELog.infoLog( - ModuleName + " " + self.className, + ModuleName + " " + self.className(), desc: "CALLBACK getMessageHistory " + (error?.localizedDescription ?? "no error") ) completion(error, count, 0, 0) @@ -340,7 +485,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } weakSelf?.getMessagesModelDynamically(.asc, message: weakSelf?.anchor) { error, value, models in NELog.infoLog( - ModuleName + " " + self.className, + ModuleName + " " + self.className(), desc: "CALLBACK pullRemoteRefresh " + (error?.localizedDescription ?? "no error") ) newEnd = value @@ -362,10 +507,10 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } // 查询本地历史消息 - public func getMessageHistory(_ message: NIMMessage?, - _ completion: @escaping (Error?, NSInteger, [MessageModel]?) - -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + (message?.messageId ?? "nil")) + open func getMessageHistory(_ message: NIMMessage?, + _ completion: @escaping (Error?, NSInteger, [MessageModel]?) + -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + (message?.messageId ?? "nil")) ChatProvider.shared.getMessageHistory( session: session, message: message, @@ -375,19 +520,20 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel self?.oldMsg = messageArray.first for msg in messageArray { if let model = self?.modelFromMessage(message: msg), NotificationMessageUtils.isDiscussSeniorTeamUpdateCustomNoti(message: msg) == false { - self?.addTimeMessage(msg) + if let last = self?.messages.last { + ChatMessageHelper.addTimeMessage(model, last) + } self?.filterRevokeMessage([model]) self?.messages.append(model) } } completion(error, messageArray.count, self?.messages) -// mark read + // mark read self?.markRead(messages: messageArray) { error in NELog.infoLog( - ModuleName + " " + (self?.className ?? "ChatViewModel"), + ModuleName + " " + (self?.className() ?? "ChatViewModel"), desc: "CALLBACK markRead " + (error?.localizedDescription ?? "no error") ) -// print("mark read \(error?.localizedDescription)") } } else { @@ -397,9 +543,9 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } // 查询更多本地历史消息 - public func getMoreMessageHistory(_ completion: @escaping (Error?, NSInteger, [MessageModel]?) + open func getMoreMessageHistory(_ completion: @escaping (Error?, NSInteger, [MessageModel]?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function) + NELog.infoLog(ModuleName + " " + className(), desc: #function) weak var weakSelf = self let messageParam = oldMsg ?? newMsg @@ -418,7 +564,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel if let isTrust = isCredible, isTrust { for msg in messageArray.reversed() { if let model = self?.modelFromMessage(message: msg), NotificationMessageUtils.isDiscussSeniorTeamUpdateCustomNoti(message: msg) == false { - self?.addTimeForHistoryMessage(msg) + self?.addTimeForHistoryMessage(model) self?.messages.insert(model, at: 0) } } @@ -439,12 +585,10 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel weakSelf?.markRead(messages: messageArray) { error in NELog.infoLog( - ModuleName + " " + (weakSelf?.className ?? "ChatViewModel"), + ModuleName + " " + (weakSelf?.className() ?? "ChatViewModel"), desc: "CALLBACK markRead " + (error?.localizedDescription ?? "no error") ) -// print("mark read \(error?.localizedDescription)") } - } else { if let messageArray = messages, messageArray.isEmpty, weakSelf?.credibleTimestamp ?? 0 > 0 { @@ -467,11 +611,11 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } // 查询远端历史消息 - public func getRemoteHistoryMessage(direction: LoadMessageDirection, updateCredible: Bool, - option: NIMHistoryMessageSearchOption, - _ completion: @escaping (Error?, NSInteger, - [MessageModel]?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", direction: \(direction.rawValue)") + open func getRemoteHistoryMessage(direction: LoadMessageDirection, updateCredible: Bool, + option: NIMHistoryMessageSearchOption, + _ completion: @escaping (Error?, NSInteger, + [MessageModel]?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", direction: \(direction.rawValue)") weak var weakSelf = self repo.getHistoryMessage(session: session, option: option) { error, messages in if error == nil { @@ -483,7 +627,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } for msg in messageArray { if let model = weakSelf?.modelFromMessage(message: msg), NotificationMessageUtils.isDiscussSeniorTeamUpdateCustomNoti(message: msg) == false { - weakSelf?.addTimeForHistoryMessage(msg) + weakSelf?.addTimeForHistoryMessage(model) weakSelf?.messages.insert(model, at: 0) } } @@ -495,7 +639,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel .updateIncompleteSessions(messages: [updateMessage]) { error, recentSessions in if error != nil { NELog.errorLog( - ModuleName + " " + (weakSelf?.className ?? "ChatViewModel"), + ModuleName + " " + (weakSelf?.className() ?? "ChatViewModel"), desc: "❌updateIncompleteSessions failed,error = \(error!)" ) } @@ -512,10 +656,10 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } // 下拉获取历史消息 - public func dropDownRemoteRefresh(_ completion: @escaping (Error?, NSInteger, [MessageModel]?) + open func dropDownRemoteRefresh(_ completion: @escaping (Error?, NSInteger, [MessageModel]?) -> Void) { - // 首次会话下拉,没有锚点消息,需要手动设置锚点消息 - if oldMsg == nil { + // 首次会话下拉,没有锚点消息 || 锚点消息被删除,需要手动设置锚点消息 + if oldMsg == nil || !messages.contains(where: { $0.message?.messageId == oldMsg?.messageId }) { for msg in messages { if let mmsg = msg.message { oldMsg = mmsg @@ -523,23 +667,28 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } } + + if messages.isEmpty { + oldMsg = nil + } + getMessagesModelDynamically(.desc, message: oldMsg, completion) - NELog.infoLog(ModuleName + " " + className, desc: #function) + NELog.infoLog(ModuleName + " " + className(), desc: #function) } // 上拉获取最新消息 - public func pullRemoteRefresh(_ completion: @escaping (Error?, NSInteger, [MessageModel]?) + open func pullRemoteRefresh(_ completion: @escaping (Error?, NSInteger, [MessageModel]?) -> Void) { getMessagesModelDynamically(.asc, message: newMsg, completion) - NELog.infoLog(ModuleName + " " + className, desc: #function) + NELog.infoLog(ModuleName + " " + className(), desc: #function) } // 搜索历史记录查询的本地消息 - public func searchMessageHistory(direction: LoadMessageDirection, startTime: TimeInterval, - endTime: TimeInterval, - _ completion: @escaping (Error?, NSInteger, [MessageModel]?) - -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", direction: \(direction.rawValue)") + open func searchMessageHistory(direction: LoadMessageDirection, startTime: TimeInterval, + endTime: TimeInterval, + _ completion: @escaping (Error?, NSInteger, [MessageModel]?) + -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", direction: \(direction.rawValue)") let option = NIMMessageSearchOption() option.startTime = startTime option.endTime = endTime @@ -557,7 +706,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } for msg in messageArray { if let model = weakSelf?.modelFromMessage(message: msg), NotificationMessageUtils.isDiscussSeniorTeamUpdateCustomNoti(message: msg) == false { - weakSelf?.addTimeMessage(msg) + ChatMessageHelper.addTimeMessage(model, weakSelf?.messages.last) weakSelf?.messages.append(model) } } @@ -572,39 +721,33 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } // 判断消息是否可信 - public func isMessageCredible(message: NIMMessage) -> Bool { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + open func isMessageCredible(message: NIMMessage) -> Bool { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) return credibleTimestamp <= 0 || message.timestamp >= credibleTimestamp } - public func markRead(messages: [NIMMessage], _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messages.count: \(messages.count)") -// if self.getMessageRead() { -// if self.session.sessionType == .P2P { -// self.markReadInP2P(messages: messages, completion) -// }else if self.session.sessionType == .team { -// self.markReadInTeam(messages: messages, completion) -// } -// } + open func markRead(messages: [NIMMessage], _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messages.count: \(messages.count)") if session.sessionType == .P2P { markReadInP2P(messages: messages, completion) } else if session.sessionType == .team { markReadInTeam(messages: messages, completion) } -// mark session read + // mark session read weak var weakself = self repo.markMessageRead(session) { error in if error != nil { NELog.errorLog( - ModuleName + " " + (weakself?.className ?? "ChatViewModel"), + ModuleName + " " + (weakself?.className() ?? "ChatViewModel"), desc: "❌markReadInSession failed,error = \(error!)" ) } } } + // 单人会话消息已读标记 private func markReadInP2P(messages: [NIMMessage], _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messages.count: \(messages.count)") + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messages.count: \(messages.count)") for message in messages.reversed() { if message.isReceivedMsg { let param = NIMMessageReceipt(message: message) @@ -615,8 +758,9 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel completion(nil) } + // 群消息已读标记 private func markReadInTeam(messages: [NIMMessage], _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messages.count: \(messages.count)") + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messages.count: \(messages.count)") var receipts = [NIMMessageReceipt]() for message in messages { let receiptEnable = message.setting?.teamReceiptEnabled ?? false @@ -634,8 +778,19 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func deleteMessage(message: NIMMessage, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + // 删除消息 + open func deleteMessage(_ completion: @escaping (Error?) -> Void) { + guard let message = operationModel?.message else { + NELog.errorLog(ModuleName + " " + className(), desc: #function + ", message is nil") + return + } + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) + + // 已撤回的消息不能删除 + if operationModel?.isRevoked == true { + return + } + if deletingMsgDic.contains(message.messageId) { return } @@ -648,6 +803,15 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel return } weak var weakSelf = self + + if message.serverID == "0" { + repo.deleteMessage(message: message) + deleteMessageUpdateUI(message) + weakSelf?.deletingMsgDic.remove(message.messageId) + completion(nil) + return + } + repo.deleteServerMessage(message: message, ext: nil) { error in if error == nil { weakSelf?.deleteMessageUpdateUI(message) @@ -658,25 +822,62 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func replyMessage(_ message: NIMMessage, _ target: NIMMessage, - _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + open func deleteMessages(messages: [NIMMessage], _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", message count:\(messages.count)") + var localMsgs = [NIMMessage]() + var remoteMsgs = [NIMMessage]() + for msg in messages { + if deletingMsgDic.contains(msg.messageId) { + continue + } + deletingMsgDic.insert(msg.messageId) + if msg.serverID.count <= 0 { + localMsgs.append(msg) + } else { + remoteMsgs.append(msg) + } + } + + localMsgs.forEach { msg in + repo.deleteMessage(message: msg) + deleteMessageUpdateUI(msg) + deletingMsgDic.remove(msg.messageId) + } + + weak var weakSelf = self + repo.deleteRemoteMessages(messages: remoteMsgs, exts: nil) { error in + if error == nil { + remoteMsgs.forEach { msg in + weakSelf?.deleteMessageUpdateUI(msg) + weakSelf?.deletingMsgDic.remove(msg.messageId) + } + } else { + completion(error) + } + } + } + + // 回复消息 + open func replyMessage(_ message: NIMMessage, _ target: NIMMessage, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) repo.replyMessage(message, target) { error in completion(error) } } - public func replyMessageWithoutThread(message: NIMMessage, - target: NIMMessage, - _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + open func replyMessageWithoutThread(message: NIMMessage, + target: NIMMessage, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) repo.replyMessageWithoutThread(message: message, session: session, target: target) { error in completion(error) } } - public func revokeMessage(message: NIMMessage, _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + // 撤回消息 + open func revokeMessage(message: NIMMessage, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) repo.revokeMessage(message: message) { error in if error == nil { self.revokeMessageUpdateUI(message) @@ -685,24 +886,31 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func resendMessage(message: NIMMessage) -> NSError? { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + // 消息重发 + @discardableResult + open func resendMessage(message: NIMMessage) -> NSError? { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) + ChatDeduplicationHelper.instance.clearCache() return repo.resendMessage(message: message) } - public func getUserInfo(userId: String) -> User? { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId:" + userId) + // 从本地获取用户信息 + open func getUserInfo(userId: String) -> NEKitUser? { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", userId:" + userId) return repo.getUserInfo(userId: userId) } - public func getTeamMember(userId: String, teamId: String) -> NIMTeamMember? { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId:" + userId) + // 获取指定的群成员 + open func getTeamMember(userId: String, teamId: String) -> NIMTeamMember? { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", userId:" + userId) return repo.getTeamMemberList(userId: userId, teamId: teamId) } - public func onReceive(_ notification: NIMCustomSystemNotification) { + // 系统通知回调 + // 自定义系统通知回调 + open func onReceive(_ notification: NIMCustomSystemNotification) { NELog.infoLog( - ModuleName + " " + className, + ModuleName + " " + className(), desc: #function + ", notification.description:" + notification.description ) print("on receive custom noti : ", notification) @@ -725,27 +933,21 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel // MARK: FriendProviderDelegate - public func onFriendChanged(user: User) { - if let uid = user.userId { - newUserInfoDic[uid] = user - delegate?.didRefreshTable() - } + open func onFriendChanged(user: NEKitUser) { + ChatUserCache.updateUserInfo(user) } - public func onUserInfoChanged(user: User) { - if let uid = user.userId { - newUserInfoDic[uid] = user - delegate?.didRefreshTable() - } + open func onUserInfoChanged(user: NEKitUser) { + ChatUserCache.updateUserInfo(user) } - public func onBlackListChanged() {} + open func onBlackListChanged() {} // MARK: NIMChatManagerDelegate // 收到消息 - public func onRecvMessages(_ messages: [NIMMessage]) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messages.count: \(messages.count)") + open func onRecvMessages(_ messages: [NIMMessage]) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messages.count: \(messages.count), first.messageID: \(messages.first?.messageId ?? "")") var count = 0 for msg in messages { if msg.session?.sessionId == session.sessionId { @@ -783,16 +985,16 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel count += 1 // 自定义消息处理 newMsg = msg - addTimeMessage(msg) let model = modelFromMessage(message: msg) + ChatMessageHelper.addTimeMessage(model, self.messages.last) self.messages.append(model) } } if count > 0 { delegate?.onRecvMessages(messages) } } - public func willSend(_ message: NIMMessage) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId:" + message.messageId) + open func willSend(_ message: NIMMessage) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId:" + message.messageId) print("\(#function)") if message.session?.sessionId != session.sessionId { @@ -813,8 +1015,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } if !isResend { - addTimeMessage(message) let model = modelFromMessage(message: message) + ChatMessageHelper.addTimeMessage(model, messages.last) filterRevokeMessage([model]) messages.append(model) } @@ -822,14 +1024,16 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel delegate?.willSend(message) } - public func send(_ message: NIMMessage, progress: Float) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + // 发送消息进度回调 + open func send(_ message: NIMMessage, progress: Float) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) print("\(#function) progress\(progress)") delegate?.send(message, progress: progress) } + // 发送消息完成回调 open func send(_ message: NIMMessage, didCompleteWithError error: Error?) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) print("\(#function) message deliveryState:\(message.deliveryState) error:\(error)") for (i, msg) in messages.enumerated() { if message.messageId == msg.message?.messageId { @@ -837,20 +1041,33 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel break } } + // 判断发送失败原因是否是因为在黑名单中 + if error != nil { + if let err = error as NSError? { + if err.code == inBlackListCode { + weak var weakSelf = self + DispatchQueue.main.async { + weakSelf?.sendBlackListTip(message.session, message) + } + } + } + } + delegate?.send(message, didCompleteWithError: error) } // MARK: ChatExtendProviderDelegate - public func onNotifyAddMessagePin(pinItem: NIMMessagePinItem) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + pinItem.messageId) + // 添加标记消息回调 + open func onNotifyAddMessagePin(pinItem: NIMMessagePinItem) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + pinItem.messageId) var index = -1 for (i, model) in messages.enumerated() { if pinItem.messageServerID == model.message?.serverID { messages[i].isPined = true let pinID = pinItem.accountID ?? NIMSDK.shared().loginManager.currentAccount() messages[i].pinAccount = pinID - messages[i].pinShowName = getShowName(userId: pinID, teamId: session.sessionId) + messages[i].pinShowName = ChatUserCache.getShowName(userId: pinID, teamId: session.sessionId) index = i break } @@ -860,8 +1077,9 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func onNotifyRemoveMessagePin(pinItem: NIMMessagePinItem) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + pinItem.messageId) + // 移除标记消息回调 + open func onNotifyRemoveMessagePin(pinItem: NIMMessagePinItem) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + pinItem.messageId) var index = -1 for (i, model) in messages.enumerated() { if pinItem.messageServerID == model.message?.serverID { @@ -880,17 +1098,17 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func onNotifySyncStickTopSessions(_ response: NIMSyncStickTopSessionResponse) {} + open func onNotifySyncStickTopSessions(_ response: NIMSyncStickTopSessionResponse) {} - public func onNotifyAddStickTopSession(_ newInfo: NIMStickTopSessionInfo) {} + open func onNotifyAddStickTopSession(_ newInfo: NIMStickTopSessionInfo) {} - public func onNotifyRemoveStickTopSession(_ removedInfo: NIMStickTopSessionInfo) {} + open func onNotifyRemoveStickTopSession(_ removedInfo: NIMStickTopSessionInfo) {} // MARK: collection func addColletion(_ message: NIMMessage, completion: @escaping (NSError?, NIMCollectInfo?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) let param = NIMAddCollectParams() var string: String? if message.messageType == .text { @@ -924,29 +1142,32 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel // MARK: revoke - public func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) { - NELog.infoLog(ModuleName + " " + className, desc: #function) + // 撤回消息回调 + open func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) { + NELog.infoLog(ModuleName + " " + className(), desc: #function) guard let msg = notification.message else { return } + NELog.infoLog(ModuleName + className(), desc: #function + "messageId:\(msg.messageId), serverID:\(msg.serverID)") + revokeMessageUpdateUI(msg) } - public func onRecvMessageReceipts(_ receipts: [NIMMessageReceipt]) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", receipts.count: \(receipts.count)") + open func onRecvMessageReceipts(_ receipts: [NIMMessageReceipt]) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", receipts.count: \(receipts.count)") print( "chatViewModel: :\(receipts.count) messageId:\(receipts.first?.messageId) messageId:\(receipts.first?.timestamp)" ) delegate?.didReadedMessageIndexs() } - public func avalibleOperationsForMessage(_ model: MessageContentModel?) -> [OperationItem]? { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", pinAccount: " + (model?.pinAccount ?? "nil")) - var pinItem = OperationItem.pinItem() + open func avalibleOperationsForMessage(_ model: MessageContentModel?) -> [OperationItem]? { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", pinAccount: " + (model?.pinAccount ?? "nil")) var items = [OperationItem]() - if model?.message?.deliveryState == .failed || model?.message?.deliveryState == .delivering, model?.message?.messageType != .rtcCallRecord { + /// 消息发送中的消息只能删除(文本可复制) + if model?.message?.deliveryState == .delivering { switch model?.message?.messageType { case .text: items.append(contentsOf: [ @@ -954,81 +1175,110 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel OperationItem.deleteItem(), ]) return items - case .audio, .video, .image, .location, .file: + default: + return [ + OperationItem.deleteItem(), + ] + } + } + + /// 发送失败 || 黑名单中的消息 || 话单消息 只能多选和删除(文本可复制) + if model?.message?.deliveryState == .failed || + model?.message?.messageType == .rtcCallRecord || + model?.message?.isBlackListed == true { + switch model?.message?.messageType { + case .text: items.append(contentsOf: [ + OperationItem.copyItem(), OperationItem.deleteItem(), + OperationItem.selectItem(), ]) return items default: - break + return [ + OperationItem.deleteItem(), + OperationItem.selectItem(), + ] } - - return nil } + + /// 消息发送成功 + let pinItem = model?.isPined == false ? OperationItem.pinItem() : OperationItem.removePinItem() switch model?.message?.messageType { case .location: - if let isPin = model?.isPined, isPin { - pinItem = OperationItem.removePinItem() - } items.append(contentsOf: [ OperationItem.replayItem(), OperationItem.forwardItem(), pinItem, OperationItem.deleteItem(), + OperationItem.selectItem(), ]) case .text: - if let isPin = model?.isPined, isPin { - pinItem = OperationItem.removePinItem() - } items = [ OperationItem.copyItem(), OperationItem.replayItem(), OperationItem.forwardItem(), pinItem, OperationItem.deleteItem(), + OperationItem.selectItem(), ] - case .image, .video, .file: - if let isPin = model?.isPined, isPin { - pinItem = OperationItem.removePinItem() - } items = [ OperationItem.replayItem(), OperationItem.forwardItem(), pinItem, OperationItem.deleteItem(), + OperationItem.selectItem(), ] case .audio: - if let isPin = model?.isPined, isPin { - pinItem = OperationItem.removePinItem() - } items = [ OperationItem.replayItem(), pinItem, OperationItem.deleteItem(), + OperationItem.selectItem(), ] - case .rtcCallRecord: - items = [OperationItem.deleteItem()] - - default: - if let isPin = model?.isPined, isPin { - pinItem = OperationItem.removePinItem() + case .custom: + if let attach = NECustomAttachment.attachmentOfCustomMessage(message: model?.message) { + if attach.customType == customRichTextType { + items = [ + OperationItem.copyItem(), + ] + } + items.append(contentsOf: [ + OperationItem.replayItem(), + OperationItem.forwardItem(), + pinItem, + OperationItem.deleteItem(), + OperationItem.selectItem(), + ]) + } else { + // 未知消息体 + items = [ + OperationItem.deleteItem(), + ] } + default: items = [ OperationItem.replayItem(), pinItem, OperationItem.deleteItem(), + OperationItem.selectItem(), ] } - if model?.message?.from == NIMSDK.shared().loginManager.currentAccount(), model?.message?.messageType != .rtcCallRecord { + // 自己发送且非未知消息可以撤回 + if model?.message?.from == NIMSDK.shared().loginManager.currentAccount() { + if model?.message?.messageType == .custom, + NECustomAttachment.dataOfCustomMessage(message: model?.message) == nil { + return items + } items.append(OperationItem.recallItem()) } return items } private func indexPathsForTeamMarkRead(_ receipts: [NIMMessageReceipt]) -> [IndexPath] { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", receipts.count: \(receipts.count)") + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", receipts.count: \(receipts.count)") var indexs = [IndexPath]() // find messages that need to update UI for receipt in receipts { @@ -1043,7 +1293,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } private func indexPathsForP2PMarkRead(_ receipts: [NIMMessageReceipt]) -> [IndexPath] { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", receipts.count: \(receipts.count)") + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", receipts.count: \(receipts.count)") var updateIndexs = [IndexPath]() // find messages that need to update UI var i = messages.count - 1 @@ -1059,116 +1309,44 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel return updateIndexs } - // history message insert message at first of messages, send message add last of messages - @discardableResult - private func addTimeMessage(_ message: NIMMessage) -> Bool { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - if NotificationMessageUtils.isDiscussSeniorTeamNoti(message: message) { - return false - } - - let lastTs = messages.last?.message?.timestamp ?? 0.0 - let curTs = message.timestamp - let dur = curTs - lastTs - if (dur / 60) > 5 { - messages.append(timeModel(message)) - return true + private func addTimeForHistoryMessage(_ model: MessageModel) { + guard let first = messages.first, + let firstMsg = first.message else { + NELog.errorLog(ModuleName + " " + className(), desc: #function + ", model.message is nil") + return } - return false - } - private func addTimeForHistoryMessage(_ message: NIMMessage) -> Bool { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - if NotificationMessageUtils.isDiscussSeniorTeamNoti(message: message) { - return false + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + firstMsg.messageId) + if NotificationMessageUtils.isDiscussSeniorTeamNoti(message: firstMsg) { + return } - let firstTs = messages.first?.message?.timestamp ?? 0.0 - let curTs = message.timestamp + let firstTs = firstMsg.timestamp + let curTs = model.message?.timestamp ?? 0.0 let dur = firstTs - curTs if (dur / 60) > 5 { let timeText = String.stringFromDate(date: Date(timeIntervalSince1970: firstTs)) - let model = MessageTipsModel(message: nil, - initType: .time, - initText: timeText) - messages.insert(model, at: 0) - return true - } - return false - } - - private func timeModel(_ message: NIMMessage) -> MessageModel { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - let curTs = message.timestamp - let timeText = String.stringFromDate(date: Date(timeIntervalSince1970: curTs)) - let model = MessageTipsModel(message: nil, - initType: .time, - initText: timeText) - return model - } - - private func tipsModel(_ message: NIMMessage) -> MessageModel { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - let model = MessageTipsModel(message: message) - return model + first.timeContent = timeText + } } - private func modelFromMessage(message: NIMMessage) -> MessageModel { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - var model: MessageModel - print("message type : ", message.messageType.rawValue) - switch message.messageType { - case .video: - model = MessageVideoModel(message: message) - case .text: - model = MessageTextModel(message: message) - case .image: - model = MessageImageModel(message: message) - case .audio: - model = MessageAudioModel(message: message) - case .notification, .tip: - model = MessageTipsModel(message: message) - case .file: - model = MessageFileModel(message: message) - case .custom: - model = MessageCustomModel(message: message) - case .location: - model = MessageLocationModel(message: message) - case .rtcCallRecord: - model = MessageCallRecordModel(message: message) - default: - // 未识别的消息类型,默认为文本消息类型,text为未知消息 - message.text = "未知消息" - model = MessageContentModel(message: message) - } + // 构建聊天页面UI显示model + open func modelFromMessage(message: NIMMessage) -> MessageModel { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) + let model = ChatMessageHelper.modelFromMessage(message: message) if let uid = message.from { - let user = getUserInfo(userId: uid) - var fullName = uid - var shortName = uid - if let nickName = user?.userInfo?.nickName { - fullName = nickName - shortName = nickName - } + let user = ChatUserCache.getUserInfo(uid) + let fullName = ChatUserCache.getShowName(userId: uid, teamId: session.sessionId) model.avatar = user?.userInfo?.avatarUrl - if session.sessionType == .team { - // team - let teamMember = getTeamMember(userId: uid, teamId: session.sessionId) - if let teamNickname = teamMember?.nickname { - fullName = teamNickname - } - } - if let alias = user?.alias { - fullName = alias - } model.fullName = fullName - model.shortName = getShortName(name: shortName, length: 2) + model.shortName = ChatUserCache.getShortName(name: user?.showName(false) ?? "", length: 2) } model.replyedModel = getReplyMessageWithoutThread(message: message) if let pin = repo.searchMessagePinHistory(message) { model.isPined = true model.pinAccount = pin.accountID let pinID = pin.accountID ?? NIMSDK.shared().loginManager.currentAccount() - model.pinShowName = getShowName(userId: pinID, teamId: session.sessionId) + model.pinShowName = ChatUserCache.getShowName(userId: pinID, teamId: session.sessionId) } else { model.isPined = false } @@ -1176,8 +1354,9 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel return model } - public func getReplyMessage(message: NIMMessage) -> MessageModel? { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + // 查找回复消息 + open func getReplyMessage(message: NIMMessage) -> MessageModel? { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) guard let id = message.repliedMessageId, id.count > 0 else { return nil } @@ -1193,8 +1372,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel return model } - public func getReplyMessageWithoutThread(message: NIMMessage) -> MessageModel? { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + open func getReplyMessageWithoutThread(message: NIMMessage) -> MessageModel? { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) var replyId: String? = message.repliedMessageId if let yxReplyMsg = message.remoteExt?[keyReplyMsgKey] as? [String: Any] { @@ -1217,53 +1396,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel return model } - public func getUserInfo(_ userId: String, _ completion: @escaping (User?, NSError?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId: " + userId) - if let user = newUserInfoDic[userId] { - completion(user, nil) - return - } - - UserInfoProvider.shared.fetchUserInfo([userId]) { [weak self] error, users in - if let user = users?.first { - self?.newUserInfoDic[userId] = user - completion(user, nil) - } else { - completion(nil, error) - } - } - } - -// 获取展示的用户名字,p2p: 备注 > 昵称 > ID team: 备注 > 群昵称 > 昵称 > ID - func getShowName(userId: String, teamId: String?, _ showAlias: Bool = true) -> String { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId: " + userId) - let user = getUserInfo(userId: userId) - var fullName = userId - if let nickName = user?.userInfo?.nickName { - fullName = nickName - } - if let tID = teamId, session.sessionType == .team { - // team - let teamMember = getTeamMember(userId: userId, teamId: tID) - if let teamNickname = teamMember?.nickname { - fullName = teamNickname - } - } - if showAlias, let alias = user?.alias { - fullName = alias - } - return fullName - } - -// 全名后几位 - func getShortName(name: String, length: Int) -> String { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", name: " + name) - return name - .count > length ? String(name[name.index(name.endIndex, offsetBy: -length)...]) : name - } - func deleteMessageUpdateUI(_ message: NIMMessage) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) var index = -1 var replyIndex = [Int]() var hasFind = false @@ -1312,7 +1446,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } func revokeMessageUpdateUI(_ message: NIMMessage) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) var index = -1 var replyIndex = [Int]() var hasFind = false @@ -1351,85 +1485,169 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel delegate?.onRevokeMessage(message, atIndexs: indexs) } - public func fetchMessageAttachment(_ message: NIMMessage, didCompleteWithError error: Error?) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - print("featch message completion : ", error as Any) + open func fetchMessageAttachment(_ message: NIMMessage, didCompleteWithError error: Error?) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) } - public func fetchMessageAttachment(_ message: NIMMessage, progress: Float) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) - print("fetchMessageAttachment progress : ", progress) - /* - var index = -1 - for (i, model) in self.messages.enumerated() { - if model.message?.serverID == message.serverID { - index = i - break - } - } - if index >= 0 { - let indexPath = IndexPath(row: index, section: 0) - delegate?.updateDownloadProgress(message, atIndex: indexPath, progress: progress) - } */ + open func fetchMessageAttachment(_ message: NIMMessage, progress: Float) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) } - public func fetchMessageAttachment(_ message: NIMMessage, - _ completion: @escaping (Error?) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + open func fetchMessageAttachment(_ message: NIMMessage, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) repo.downloadMessageAttachment(message, completion) } - public func downLoad(_ urlString: String, _ filePath: String, _ progress: NIMHttpProgressBlock?, - _ completion: NIMDownloadCompleteBlock?) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + urlString) + open func downLoad(_ urlString: String, _ filePath: String, _ progress: NIMHttpProgressBlock?, + _ completion: NIMDownloadCompleteBlock?) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + urlString) repo.downloadSource(urlString, filePath, progress, completion) } - public func getUrls() -> [String] { - NELog.infoLog(ModuleName + " " + className, desc: #function) - var urls = [String]() - messages.forEach { model in - if model.type == .image, let message = model.message?.messageObject as? NIMImageObject { - if let url = message.url { - urls.append(url) - } else { - if let path = message.path, FileManager.default.fileExists(atPath: path) { - urls.append(path) + // 转发消息 + open func forwardMessage(_ forwardMessages: [NIMMessage], + _ session: NIMSession, + _ comment: String?, + _ completion: @escaping (Error?) -> Void) { + for message in forwardMessages { + if let forwardMessage = repo.makeForwardMessage(message) { + ChatMessageHelper.clearForwardAtMark(forwardMessage) + repo.sendForwardMessage(forwardMessage, session) + } + } + if let text = comment, !text.isEmpty { + sendTextMessage(text: text, session: session, completion) + } else { + completion(nil) + } + } + + // 合并转发消息 + open func forwardMultiMessage(_ forwardMessages: [NIMMessage], + _ toSession: NIMSession, + _ depth: Int = 0, + _ comment: String?, + _ completion: @escaping (Error?) -> Void) { + if forwardMessages.count <= 0 { + if let text = comment, !text.isEmpty { + sendTextMessage(text: text, session: toSession, completion) + } else { + completion(nil) + } + return + } + + let fromSession = session + let header = ChatMessageHelper.buildHeader(messageCount: forwardMessages.count) + ChatMessageHelper.buildBody(messages: forwardMessages) { body, abstracts in + let multiForwardMsg = header + body + let fileName = multiForwardFileName + "\(Int(Date().timeIntervalSince1970))" + if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { + let filePath = documentsDirectory.appendingPathComponent("NEIMUIKit/\(fileName)") + if let multiForwardMsgData = multiForwardMsg.data(using: .utf8) { + do { + try multiForwardMsgData.write(to: filePath) + } catch { + completion(NSError(domain: chatLocalizable("forward_failed"), code: 414)) + print("Error writing string to file: \(error)") + return + } + } + + NIMSDK.shared().resourceManager.upload(filePath.path, progress: nil) { [weak self] url, error in + if let err = error { + completion(err) + } else if let url = url { + let md5 = ChatMessageHelper.getFileChecksum(fileURL: filePath) + + // 删除本地文件 + do { + try FileManager.default.removeItem(atPath: filePath.path) + } catch { + print("无法删除合并转发文件:\(error)") + } + + var data = [String: Any]() + data["sessionId"] = toSession.sessionId + data["sessionName"] = ChatMessageHelper.getSessionName(session: fromSession, showAlias: false) + data["url"] = url + data["md5"] = md5 + data["depth"] = depth + data["abstracts"] = abstracts + + var jsonData = [String: Any]() + jsonData["data"] = data + jsonData["messageType"] = "custom" + jsonData["type"] = customMultiForwardType + + let attah = NECustomAttachment(customType: customMultiForwardType, + cellHeight: customMultiForwardCellHeight, + data: jsonData) + self?.sendCustomMessage(attachment: attah, + remoteExt: nil, + apnsConstent: "[\(chatLocalizable("chat_history"))]", + session: toSession) { error in + if let err = error { + completion(err) + } else { + if let text = comment, !text.isEmpty { + self?.sendTextMessage(text: text, session: toSession, completion) + } else { + completion(nil) + } + } + } } } } } - print("urls:\(urls)") - return urls } - public func forwardUserMessage(_ message: NIMMessage, _ users: [NIMUser]) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + open func forwardUserMessage(_ users: [NIMUser], + _ isMultiForward: Bool, + _ depth: Int, + _ comment: String?, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messages.count: \(messages.count)") + + // 排序(发送时间正序) + let forwardMessages = selectedMessages.sorted { msg1, msg2 in + msg1.timestamp < msg2.timestamp + } + users.forEach { user in if let uid = user.userId { let session = NIMSession(uid, type: .P2P) - if let forwardMessage = repo.makeForwardMessage(message) { - clearForwardAtMark(forwardMessage) - repo.sendForwardMessage(forwardMessage, session) + if isMultiForward { + forwardMultiMessage(forwardMessages, session, depth, comment, completion) + } else { + forwardMessage(forwardMessages, session, comment, completion) } } } } - public func forwardTeamMessage(_ message: NIMMessage, _ team: NIMTeam) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + open func forwardTeamMessage(_ team: NIMTeam, + _ isMultiForward: Bool, + _ depth: Int, + _ comment: String?, + _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messages.count: \(messages.count)") if let tid = team.teamId { let session = NIMSession(tid, type: .team) - if let forwardMessage = repo.makeForwardMessage(message) { - clearForwardAtMark(forwardMessage) - repo.sendForwardMessage(forwardMessage, session) + if isMultiForward { + forwardMultiMessage(selectedMessages, session, depth, comment, completion) + } else { + forwardMessage(selectedMessages, session, comment, completion) } } } - public func pinMessage(_ message: NIMMessage, - _ completion: @escaping (Error?, NIMMessagePinItem?, Int) -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + // 标记消息 + open func pinMessage(_ message: NIMMessage, + _ completion: @escaping (Error?, NIMMessagePinItem?, Int) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) let item = NIMMessagePinItem(message: message) guard let _ = NIMSDK.shared().conversationManager.messages(in: session, messageIds: [message.messageId]) else { return @@ -1445,7 +1663,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel if message.messageId == model.message?.messageId, !messages[i].isPined { messages[i].isPined = true messages[i].pinAccount = NIMSDK.shared().loginManager.currentAccount() - messages[i].pinShowName = self?.getShowName( + messages[i].pinShowName = ChatUserCache.getShowName( userId: NIMSDK.shared().loginManager.currentAccount(), teamId: message.session?.sessionId ) @@ -1460,10 +1678,11 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func removePinMessage(_ message: NIMMessage, - _ completion: @escaping (Error?, NIMMessagePinItem?, Int) - -> Void) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", messageId: " + message.messageId) + // 取消消息标记 + open func removePinMessage(_ message: NIMMessage, + _ completion: @escaping (Error?, NIMMessagePinItem?, Int) + -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) guard let _ = NIMSDK.shared().conversationManager.messages(in: session, messageIds: [message.messageId]) else { return } @@ -1479,22 +1698,24 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func sendInputTypingState() { - NELog.infoLog(ModuleName + " " + className, desc: #function) + // 发送正在输入中状态 + open func sendInputTypingState() { + NELog.infoLog(ModuleName + " " + className(), desc: #function) if session.sessionType == .P2P { setTypingCustom(1) } } - public func sendInputTypingEndState() { - NELog.infoLog(ModuleName + " " + className, desc: #function) + // 发送结束输入中状态 + open func sendInputTypingEndState() { + NELog.infoLog(ModuleName + " " + className(), desc: #function) if session.sessionType == .P2P { setTypingCustom(0) } } func setTypingCustom(_ typing: Int) { - NELog.infoLog(ModuleName + " " + className, desc: #function + ", typing: \(typing)") + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", typing: \(typing)") let message = NIMMessage() if message.setting == nil { message.setting = NIMMessageSetting() @@ -1511,17 +1732,18 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func getHandSetEnable() -> Bool { - NELog.infoLog(ModuleName + " " + className, desc: #function) + open func getHandSetEnable() -> Bool { + NELog.infoLog(ModuleName + " " + className(), desc: #function) return repo.getHandsetMode() } - public func getMessageRead() -> Bool { - NELog.infoLog(ModuleName + " " + className, desc: #function) + open func getMessageRead() -> Bool { + NELog.infoLog(ModuleName + " " + className(), desc: #function) return repo.getMessageRead() } - public func saveRevokeMessage(_ message: NIMMessage, _ completion: @escaping (Error?) -> Void) { + // 本地保存撤回消息 + open func saveRevokeMessage(_ message: NIMMessage, _ completion: @escaping (Error?) -> Void) { let messageNew = NIMMessage() messageNew.text = chatLocalizable("message_recalled") var muta = [String: Any]() @@ -1529,6 +1751,14 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel if message.messageType == .text { muta[revokeLocalMessageContent] = message.text } + if message.messageType == .custom { + if let title = NECustomAttachment.titleOfRichText(message: message), !title.isEmpty { + muta[revokeLocalMessageContent] = title + } + if let body = NECustomAttachment.bodyOfRichText(message: message), !body.isEmpty { + muta[revokeLocalMessageContent] = body + } + } messageNew.timestamp = message.timestamp messageNew.from = message.from messageNew.localExt = muta @@ -1540,7 +1770,7 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel repo.saveMessageToDB(messageNew, session, completion) } - private func filterRevokeMessage(_ messages: [MessageModel]) { + open func filterRevokeMessage(_ messages: [MessageModel]) { messages.forEach { model in if let isRevoke = model.message?.localExt?[revokeLocalMessage] as? Bool, isRevoke == true { if let content = model.message?.localExt?[revokeLocalMessageContent] as? String, content.count > 0 { @@ -1552,7 +1782,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel } } - public func refreshReceipts(messages: [NIMMessage]) { + // 刷新已读回执 + open func refreshReceipts(messages: [NIMMessage]) { if session.sessionType != .team { return } @@ -1588,9 +1819,8 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel // MARK: NIMConversationManagerDelegate - // remote - public func onRecvMessagesDeleted(_ messages: [NIMMessage], exts: [String: String]?) { - var messageIDs = Set() + // 多端登录删除消息 + open func onRecvMessagesDeleted(_ messages: [NIMMessage], exts: [String: String]?) { messages.forEach { message in if message.session?.sessionId != session.sessionId { return @@ -1598,39 +1828,29 @@ public class ChatViewModel: NSObject, ChatRepoMessageDelegate, NIMChatManagerDel if message.messageId.count <= 0 { return } - messageIDs.insert(message.messageId) - } - if messageIDs.count > 0 { - self.messages.removeAll { model in - if let messageId = model.message?.messageId, messageId.count > 0 { - if messageIDs.contains(messageId) { - return true - } - } - return false - } - if let lastModel = self.messages.last as? MessageTipsModel, lastModel.type == .time { - self.messages.removeLast() - } - delegate?.didRefreshTable() + deleteMessageUpdateUI(message) } } - deinit { - print("deinit") + func fetchPinMessage(_ completion: @escaping () -> Void) { + repo.fetchPinMessage(session.sessionId, session.sessionType) { error, items in + completion() + } } - private func clearForwardAtMark(_ forwardMessage: NIMMessage) { - forwardMessage.remoteExt?.removeValue(forKey: yxAtMsg) - forwardMessage.remoteExt?.removeValue(forKey: keyReplyMsgKey) - if forwardMessage.remoteExt?.count ?? 0 <= 0 { - forwardMessage.remoteExt = nil + // 检查音频消息是否有附件 + open func checkAudioFile(messages: [MessageModel]?) { + messages?.forEach { model in + if let message = model.message { + ChatMessageHelper.downloadAudioFile(message: message) + } } } - func fetchPinMessage(_ completion: @escaping () -> Void) { - repo.fetchPinMessage(session.sessionId, session.sessionType) { error, items in - completion() + open func onTeamMemberChanged(_ team: NIMTeam) { + if session.sessionType == .team, session.sessionId == team.teamId { + self.team = team + delegate?.onTeamMemberChange(team: team) } } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/MultiForwardViewModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/MultiForwardViewModel.swift new file mode 100644 index 00000000..38b018c0 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/MultiForwardViewModel.swift @@ -0,0 +1,94 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK + +@objc +public protocol MultiForwardViewModelDelegate: NSObjectProtocol { + @objc optional + func getMessageModel(model: MessageModel) +} + +@objcMembers +open class MultiForwardViewModel: NSObject { + public weak var delegate: MultiForwardViewModelDelegate? + public var repo = ChatRepo.shared + public var messages = [MessageModel]() + + func loadData(_ messageAttachmentUrl: String?, + _ filePath: String, + _ md5: String?, + _ completion: @escaping (Error?) -> Void) { + if FileManager.default.fileExists(atPath: filePath) { + decodeMesssage(filePath: filePath, md5: md5, completion) + } else if let urlString = messageAttachmentUrl { + downLoad(urlString, filePath, nil) { [weak self] error in + self?.decodeMesssage(filePath: filePath, md5: md5, completion) + } + } + } + + func decodeMesssage(filePath: String, + md5: String?, + _ completion: (Error?) -> Void) { + // 校验文件 MD5 + if let filePath = URL(string: filePath), + let fileMD5 = ChatMessageHelper.getFileChecksum(fileURL: filePath) { + if fileMD5 != md5 { + completion(NSError(domain: chatLocalizable("file_check_failed"), code: 0)) + return + } + } + + do { + let data = try Data(contentsOf: URL(fileURLWithPath: filePath)) + let strData = String(data: data, encoding: .utf8) + let subStringData = strData?.components(separatedBy: "\n") + if let msgCount = subStringData?.count, msgCount > 1 { + for i in 1 ..< msgCount { + if let msgData = subStringData?[i].data(using: .utf8) { + let msg = NIMSDK.shared().conversationManager.decodeMessage(from: msgData) + let model = modelFromMessage(message: msg) + ChatMessageHelper.addTimeMessage(model, messages.last) + messages.append(model) + } + } + completion(nil) + } + } catch { + completion(error) + } + } + + open func modelFromMessage(message: NIMMessage) -> MessageModel { + var model: MessageModel + switch message.messageType { + case .audio: + message.text = chatLocalizable("msg_audio") + model = MessageTextModel(message: message) + case .rtcCallRecord: + message.text = chatLocalizable("msg_rtc_call") + if let object = message.messageObject as? NIMRtcCallRecordObject { + message.text = object.callType == .audio ? chatLocalizable("msg_rtc_audio") : chatLocalizable("msg_rtc_video") + } + model = MessageTextModel(message: message) + default: + model = ChatMessageHelper.modelFromMessage(message: message) + } + + model.fullName = message.remoteExt?[mergedMessageNickKey] as? String + model.shortName = ChatUserCache.getShortName(name: model.fullName ?? "", length: 2) + model.avatar = message.remoteExt?[mergedMessageAvatarKey] as? String + + delegate?.getMessageModel?(model: model) + return model + } + + open func downLoad(_ urlString: String, _ filePath: String, _ progress: NIMHttpProgressBlock?, + _ completion: NIMDownloadCompleteBlock?) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + urlString) + repo.downloadSource(urlString, filePath, progress, completion) + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/PinMessageViewModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/PinMessageViewModel.swift index 1757dbe9..4890d90d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/PinMessageViewModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/PinMessageViewModel.swift @@ -12,7 +12,7 @@ public protocol PinMessageViewModelDelegate: NSObjectProtocol { } @objcMembers -public class PinMessageViewModel: NSObject, ChatExtendProviderDelegate, NIMChatManagerDelegate, NIMConversationManagerDelegate { +open class PinMessageViewModel: NSObject, ChatExtendProviderDelegate, NIMChatManagerDelegate, NIMConversationManagerDelegate { public let chatRepo = ChatRepo.shared public var items = [PinMessageModel]() public var delegate: PinMessageViewModelDelegate? @@ -25,7 +25,7 @@ public class PinMessageViewModel: NSObject, ChatExtendProviderDelegate, NIMChatM NIMSDK.shared().conversationManager.add(self) } - public func onRecvMessagesDeleted(_ messages: [NIMMessage], exts: [String: String]?) { + open func onRecvMessagesDeleted(_ messages: [NIMMessage], exts: [String: String]?) { for message in messages { if message.session?.sessionId == session?.sessionId { delegate?.didNeedRefreshUI() @@ -34,7 +34,7 @@ public class PinMessageViewModel: NSObject, ChatExtendProviderDelegate, NIMChatM } } - public func getPinitems(session: NIMSession, _ completion: @escaping (Error?) -> Void) { + open func getPinitems(session: NIMSession, _ completion: @escaping (Error?) -> Void) { weak var weakSelf = self self.session = session chatRepo.fetchPinMessage(session.sessionId, session.sessionType) { error, pinItems in @@ -92,9 +92,9 @@ public class PinMessageViewModel: NSObject, ChatExtendProviderDelegate, NIMChatM } } - public func removePinMessage(_ message: NIMMessage, - _ completion: @escaping (Error?, NIMMessagePinItem?) - -> Void) { + open func removePinMessage(_ message: NIMMessage, + _ completion: @escaping (Error?, NIMMessagePinItem?) + -> Void) { NELog.infoLog("PinMessageViewModel", desc: #function + ", messageId: " + message.messageId) let item = NIMMessagePinItem(message: message) chatRepo.removeMessagePin(item) { error, pinItem in @@ -102,54 +102,83 @@ public class PinMessageViewModel: NSObject, ChatExtendProviderDelegate, NIMChatM } } - public func forwardUserMessage(_ message: NIMMessage, _ users: [NIMUser]) { + open func sendTextMessage(text: String, session: NIMSession, _ completion: @escaping (Error?) -> Void) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", text.count: \(text.count)") + if text.count <= 0 { + return + } + chatRepo.sendMessage( + message: MessageUtils.textMessage(text: text), + session: session, + completion + ) + } + + open func forwardUserMessage(_ message: NIMMessage, + _ users: [NIMUser], + _ comment: String?, + _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) users.forEach { user in if let uid = user.userId { let session = NIMSession(uid, type: .P2P) if let forwardMessage = chatRepo.makeForwardMessage(message) { - clearForwardAtMark(forwardMessage) + ChatMessageHelper.clearForwardAtMark(forwardMessage) chatRepo.sendForwardMessage(forwardMessage, session) } + if let text = comment { + sendTextMessage(text: text, session: session) { error in + print("sendTextMessage error: \(String(describing: error))") + } + } } } } - public func forwardTeamMessage(_ message: NIMMessage, _ team: NIMTeam) { + open func forwardTeamMessage(_ message: NIMMessage, + _ team: NIMTeam, + _ comment: String?, + _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + message.messageId) if let tid = team.teamId { let session = NIMSession(tid, type: .team) if let forwardMessage = chatRepo.makeForwardMessage(message) { - clearForwardAtMark(forwardMessage) + ChatMessageHelper.clearForwardAtMark(forwardMessage) chatRepo.sendForwardMessage(forwardMessage, session) } + if let text = comment { + sendTextMessage(text: text, session: session, completion) + } } } // MARK: NIMChatManagerDelegate - public func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) { + open func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) { // items = [PinMessageModel]() delegate?.didNeedRefreshUI() } // MARK: ChatExtendProviderDelegate - public func onNotifyAddMessagePin(pinItem: NIMMessagePinItem) { + open func onNotifyAddMessagePin(pinItem: NIMMessagePinItem) { // items = [PinMessageModel]() delegate?.didNeedRefreshUI() } - public func onNotifyRemoveMessagePin(pinItem: NIMMessagePinItem) { + open func onNotifyRemoveMessagePin(pinItem: NIMMessagePinItem) { // items = [PinMessageModel]() delegate?.didNeedRefreshUI() } - private func clearForwardAtMark(_ forwardMessage: NIMMessage) { - forwardMessage.remoteExt?.removeValue(forKey: yxAtMsg) - forwardMessage.remoteExt?.removeValue(forKey: keyReplyMsgKey) - if forwardMessage.remoteExt?.count ?? 0 <= 0 { - forwardMessage.remoteExt = nil - } + open func downLoad(_ urlString: String, _ filePath: String, _ progress: NIMHttpProgressBlock?, + _ completion: NIMDownloadCompleteBlock?) { + NELog.infoLog(ModuleName + " " + className(), desc: #function + ", messageId: " + urlString) + chatRepo.downloadSource(urlString, filePath, progress, completion) + } + + open func getHandSetEnable() -> Bool { + NELog.infoLog(ModuleName + " " + className(), desc: #function) + return chatRepo.getHandsetMode() } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamChatViewModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamChatViewModel.swift index 52a74c90..22885f04 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamChatViewModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamChatViewModel.swift @@ -4,6 +4,7 @@ import CoreText import Foundation +import NEChatKit import NECoreIMKit import NIMSDK @@ -15,37 +16,23 @@ public protocol TeamChatViewModelDelegate: ChatViewModelDelegate { } @objcMembers -public class TeamChatViewModel: ChatViewModel, NIMTeamManagerDelegate { +open class TeamChatViewModel: ChatViewModel { private let className = "TeamChatViewModel" -// override init(session: NIMSession) { -// super.init(session: session) -// repo.addTeamDelegate(delegate: self) -// -// } override init(session: NIMSession, anchor: NIMMessage?) { super.init(session: session, anchor: anchor) NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId: " + session.sessionId) repo.addTeamDelegate(delegate: self) -// self.session = session -// self.anchor = anchor -// super.init() -// if anchor != nil { -// isHistoryChat = true -// } -// repo.addChatDelegate(delegate: self) -// repo.addConversationDelegate(delegate: self) -// repo.addSystemNotiDelegate(delegate: self) -// repo.addChatExtDelegate(delegate: self) + getTeamMember() } - public func getTeam(teamId: String) -> NIMTeam? { + open func getTeam(teamId: String) -> NIMTeam? { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId: " + teamId) return repo.getTeamInfo(teamId: teamId) } - public func fetchTeamInfo(teamId: String, - _ completion: @escaping (NSError?, NIMTeam?) -> Void) { + open func fetchTeamInfo(teamId: String, + _ completion: @escaping (NSError?, NIMTeam?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId: " + teamId) repo.getTeamInfo(teamId: teamId) { [weak self] error, team in if error == nil { @@ -57,7 +44,7 @@ public class TeamChatViewModel: ChatViewModel, NIMTeamManagerDelegate { // MARK: NIMTeamManagerDelegate - public func onTeamRemoved(_ team: NIMTeam) { + open func onTeamRemoved(_ team: NIMTeam) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId: " + (team.teamId ?? "nil")) if session.sessionId == team.teamId { if let delegate = delegate as? TeamChatViewModelDelegate { @@ -66,7 +53,7 @@ public class TeamChatViewModel: ChatViewModel, NIMTeamManagerDelegate { } } - public func onTeamUpdated(_ team: NIMTeam) { + open func onTeamUpdated(_ team: NIMTeam) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId: " + (team.teamId ?? "nil")) if session.sessionId == team.teamId { self.team = team @@ -76,16 +63,21 @@ public class TeamChatViewModel: ChatViewModel, NIMTeamManagerDelegate { } } - public func onTeamMemberUpdated(_ team: NIMTeam, withMembers memberIDs: [String]?) { + open func onTeamMemberUpdated(_ team: NIMTeam, withMembers memberIDs: [String]?) { guard let membersIds = memberIDs else { return } for memberId in membersIds { - let user = UserInfoProvider.shared.getUserInfo(userId: memberId) - newUserInfoDic[memberId] = user + if let user = UserInfoProvider.shared.getUserInfo(userId: memberId) { + ChatUserCache.updateUserInfo(user) + } } if let delegate = delegate as? TeamChatViewModelDelegate { delegate.onTeamMemberUpdate(team: team) } } + + public func getTeamMember() { + teamMember = getTeamMember(userId: IMKitClient.instance.imAccid(), teamId: session.sessionId) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamMemberSelectVM.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamMemberSelectVM.swift index 4a63304d..6eb70637 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamMemberSelectVM.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/TeamMemberSelectVM.swift @@ -8,12 +8,12 @@ import NECoreIMKit import NIMSDK @objcMembers -public class TeamMemberSelectVM: NSObject { +open class TeamMemberSelectVM: NSObject { public var chatRepo = ChatRepo.shared private let className = "TeamMemberSelectVM" - public func fetchTeamMembers(sessionId: String, - _ completion: @escaping (Error?, ChatTeamInfoModel?) -> Void) { + open func fetchTeamMembers(sessionId: String, + _ completion: @escaping (Error?, ChatTeamInfoModel?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId: " + sessionId) chatRepo.getTeamInfo(sessionId, completion) } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/UserSettingViewModel.swift b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/UserSettingViewModel.swift index 6c3d1b62..2cf6919b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/UserSettingViewModel.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Chat/ViewModel/UserSettingViewModel.swift @@ -13,10 +13,10 @@ protocol UserSettingViewModelDelegate: NSObjectProtocol { } @objcMembers -public class UserSettingViewModel: NSObject { +open class UserSettingViewModel: NSObject { var repo = ChatRepo.shared - var userInfo: User? + var userInfo: NEKitUser? var cellDatas = [UserSettingCellModel]() @@ -69,6 +69,9 @@ public class UserSettingViewModel: NSObject { if let uid = weakSelf?.userInfo?.userId { let session = NIMSession(uid, type: .P2P) if isOpen { + if weakSelf?.getRecenterSession() == nil { + weakSelf?.addRecentetSession() + } let params = NIMAddStickTopSessionParams(session: session) weakSelf?.repo.chatExtendProvider .addStickTopSession(params: params) { error, info in @@ -96,28 +99,21 @@ public class UserSettingViewModel: NSObject { } } } - - /* - let blackList = UserSettingCellModel() - blackList.cornerType = .bottomRight.union(.bottomLeft) - blackList.cellName = "加入黑名单" - if let isBlack = user.imUser?.isInMyBlackList() { - blackList.switchOpen = isBlack - } - blackList.swichChange = { isOpen in - if let uid = weakSelf?.userInfo?.userId { - if isOpen { - weakSelf?.repo.addBlackList(account: uid, { error in - print("add black list : ", error as Any) - }) - }else { - weakSelf?.repo.removeFromBlackList(account: uid, { error in - print("remo black list : ", error as Any) - }) - } - } - } - */ cellDatas.append(contentsOf: [mark, remind, setTop]) } + + public func addRecentetSession() { + if let uid = userInfo?.userId { + let currentSession = NIMSession(uid, type: .P2P) + repo.addRecentSession(currentSession) + } + } + + public func getRecenterSession() -> NIMRecentSession? { + if let uid = userInfo?.userId { + let currentSession = NIMSession(uid, type: .P2P) + return repo.getRecentSession(currentSession) + } + return nil + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/ChatConfig/ChatUIConfig.swift b/NEChatUIKit/NEChatUIKit/Classes/ChatConfig/ChatUIConfig.swift index ba722371..a891a613 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/ChatConfig/ChatUIConfig.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/ChatConfig/ChatUIConfig.swift @@ -77,16 +77,24 @@ public class MessageProperties: NSObject { // 接收到的消息体的背景色 public var receiveMessageBg: UIColor = .clear + // 背景图片拉伸参数(边距偏移) + public var backgroundImageCapInsets = UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25) + // 不设置头像的用户所展示的文字头像中的文字颜色 public var userNickColor: UIColor = .white // 不设置头像的用户所展示的文字头像中的文字字体大小 public var userNickTextSize: CGFloat = 12 + // 标记列表字体大小(文本类型) + public var pinMessageTextSize: CGFloat = 14 + // 单聊中是否展示已读未读状态 public var showP2pMessageStatus: Bool = true // 群聊中是否展示已读未读状态 public var showTeamMessageStatus: Bool = true + // 群聊中是否展示好友昵称 + public var showTeamMessageNick: Bool = true // 会话界面是否展示标题栏 public var showTitleBar: Bool = true // 是否展示标题栏右侧图标按钮 diff --git a/NEChatUIKit/NEChatUIKit/Classes/ChatRouter/NEBaseChatRouter.swift b/NEChatUIKit/NEChatUIKit/Classes/ChatRouter/NEBaseChatRouter.swift index 69b20770..44f6c34e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/ChatRouter/NEBaseChatRouter.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/ChatRouter/NEBaseChatRouter.swift @@ -11,7 +11,7 @@ import SDWebImageSVGKitPlugin import SDWebImageWebPCoder @objcMembers -public class ChatRouter: NSObject { +open class ChatRouter: NSObject { public static func setupInit() { NIMKitFileLocationHelper.setStaticAppkey(NIMSDK.shared().appKey()) NIMKitFileLocationHelper.setStaticUserId(NIMSDK.shared().loginManager.currentAccount()) diff --git a/NEChatUIKit/NEChatUIKit/Classes/Common/ChatCellConstantValue.swift b/NEChatUIKit/NEChatUIKit/Classes/Common/ChatCellConstantValue.swift index 17070440..d38eb966 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Common/ChatCellConstantValue.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Common/ChatCellConstantValue.swift @@ -6,13 +6,14 @@ import Foundation // 距离cell边缘的距离 -public let chat_cell_margin = 16.0 +public let chat_cell_margin: CGFloat = 16.0 // 控件之间的间距 -public let chat_content_margin = 8.0 +public let chat_content_margin: CGFloat = 8.0 // 头像宽高 -public let chat_headWH = 32.0 +public let chat_headWH: CGFloat = 32.0 + // 时间cell的高度(固定) -public let chat_timeCellH = 21.0 +public let chat_timeCellH: CGFloat = 22.0 // 图片最大宽高 public let chat_pic_size = CGSize(width: 150, height: 200) @@ -21,19 +22,19 @@ public let chat_pic_size = CGSize(width: 150, height: 200) public let chat_file_size = CGSize(width: 254, height: 56) // 单行气泡高度 -public let chat_min_h = 40.0 +public let chat_min_h: CGFloat = 40.0 // 回复消息replyLabel高度 -public let chat_reply_height = 16.0 +public let chat_reply_height: CGFloat = 16.0 // 气泡最大宽度 -public let chat_content_maxW = (kScreenWidth - 136) +public let chat_content_maxW: CGFloat = (kScreenWidth - 136) // 文本内容最大宽度 -public let chat_text_maxW = chat_content_maxW - 2 * chat_content_margin +public let chat_text_maxW: CGFloat = chat_content_maxW - 2 * chat_content_margin // pin消息需要增加的高度 -public let chat_pin_height = 16.0 +public let chat_pin_height: CGFloat = 16.0 -// 群聊起泡上方用户名label高度,p2p无此展示,高度为0 -public let chat_full_name_height = 16.0 +// 群聊气泡上方用户名label高度,p2p无此展示,高度为0 +public let chat_full_name_height: CGFloat = 16.0 diff --git a/NEChatUIKit/NEChatUIKit/Classes/Common/ChatConstant.swift b/NEChatUIKit/NEChatUIKit/Classes/Common/ChatConstant.swift index 2bf471bd..6a473b6c 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Common/ChatConstant.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Common/ChatConstant.swift @@ -4,6 +4,7 @@ // found in the LICENSE file. import Foundation +import NEChatKit @_exported import NECommonKit @_exported import NECommonUIKit @_exported import NECoreIMKit @@ -14,7 +15,7 @@ func chatLocalizable(_ key: String) -> String { coreLoader.localizable(key) } -func getJSONStringFromDictionary(_ dictionary: [String: Any]) -> String { +public func getJSONStringFromDictionary(_ dictionary: [String: Any]) -> String { if !JSONSerialization.isValidJSONObject(dictionary) { print("not parse to json string") return "" @@ -26,7 +27,7 @@ func getJSONStringFromDictionary(_ dictionary: [String: Any]) -> String { return "" } -func getDictionaryFromJSONString(_ jsonString: String) -> NSDictionary? { +public func getDictionaryFromJSONString(_ jsonString: String) -> NSDictionary? { if let jsonData = jsonString.data(using: .utf8), let dict = try? JSONSerialization.jsonObject( with: jsonData, @@ -112,6 +113,9 @@ let DefaultTextFont: ((Float) -> UIFont) = { let TextNormalColor: UIColor = HexRGB(0x333333) let SubTextColor: UIColor = HexRGB(0x666666) let PlaceholderTextColor: UIColor = HexRGB(0xA6ADB6) +let multiForwardLineColor: UIColor = HexRGB(0xF0F1F5) +let forwardLineColor: UIColor = HexRGB(0xE1E6E8) +let multiForwardborderColor: UIColor = HexRGB(0xE4E9F2) let HexRGB: ((Int) -> UIColor) = { (rgbValue: Int) -> UIColor in HexRGBAlpha(rgbValue, 1.0) @@ -128,8 +132,7 @@ let HexRGBAlpha: ((Int, Float) -> UIColor) = { (rgbValue: Int, alpha: Float) -> // MARK: notificationkey -enum NotificationName { - static let updateFriendInfo = Notification.Name("chat.updateFriendInfo") +extension NENotificationName { // 参数 serverId: string static let createServer = Notification.Name(rawValue: "qchat.createServer") // param channel: ChatChannel @@ -137,6 +140,7 @@ enum NotificationName { static let updateChannel = Notification.Name(rawValue: "qchat.updateChannel") static let deleteChannel = Notification.Name(rawValue: "qchat.deleteChannel") static let leaveTeamBySelf = Notification.Name(rawValue: "team.leaveTeamBySelf") + static let popGroupChatVC = Notification.Name(rawValue: "team.popGroupChatVC") // static let login = Notification.Name(rawValue:"qchat.login") static let logout = Notification.Name(rawValue: "qchat.logout") diff --git a/NEChatUIKit/NEChatUIKit/Classes/Common/NEChatUIKitClient.swift b/NEChatUIKit/NEChatUIKit/Classes/Common/NEChatUIKitClient.swift index 16a7ce23..18a155ad 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Common/NEChatUIKitClient.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Common/NEChatUIKitClient.swift @@ -8,7 +8,7 @@ import UIKit @objc @objcMembers -public class NEChatUIKitClient: NSObject { +open class NEChatUIKitClient: NSObject { public static let instance = NEChatUIKitClient() private var customRegisterDic = [String: UITableViewCell.Type]() public var moreAction = [NEMoreItemModel]() @@ -43,7 +43,7 @@ public class NEChatUIKitClient: NSObject { /// 获取更多面板数据 /// - Returns: 返回更多操作数据 - public func getMoreActionData(sessionType: NIMSessionType) -> [NEMoreItemModel] { + open func getMoreActionData(sessionType: NIMSessionType) -> [NEMoreItemModel] { var more = [NEMoreItemModel]() moreAction.forEach { model in if model.type != .rtc { @@ -61,13 +61,13 @@ public class NEChatUIKitClient: NSObject { } /// 新增聊天页针对自定义消息的cell扩展,以及现有cell样式覆盖 - public func regsiterCustomCell(_ registerDic: [String: UITableViewCell.Type]) { + open func regsiterCustomCell(_ registerDic: [String: UITableViewCell.Type]) { registerDic.forEach { (key: String, value: UITableViewCell.Type) in customRegisterDic[key] = value } } - public func getRegisterCustomCell() -> [String: UITableViewCell.Type] { + open func getRegisterCustomCell() -> [String: UITableViewCell.Type] { customRegisterDic } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Extension/ChatStringExtension.swift b/NEChatUIKit/NEChatUIKit/Classes/Extension/ChatStringExtension.swift index fe86ebc8..1bca66c5 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Extension/ChatStringExtension.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Extension/ChatStringExtension.swift @@ -13,7 +13,7 @@ var tempLabelForCalc: UILabel = { }() extension String { - // 计算文字size + /// 计算 string 的 size static func getTextRectSize(_ text: String, font: UIFont, size: CGSize) -> CGSize { let attributes = [NSAttributedString.Key.font: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin @@ -23,10 +23,19 @@ extension String { } /// 计算 string 的行数,使用 font 的 lineHeight - static func calculateMaxLines(width: CGFloat, string: String, font: UIFont) -> Int { + static func calculateMaxLines(width: CGFloat, string: String?, font: UIFont) -> Int { let maxSize = CGSize(width: width, height: CGFloat(Float.infinity)) let charSize = font.lineHeight - let textSize = getTextRectSize(string, font: font, size: maxSize) + let textSize = string?.finalSize(font, maxSize) ?? .zero + let lines = Int(textSize.height / charSize) + return lines + } + + /// 计算 label 的行数,使用 font 的 lineHeight + static func calculateMaxLines(width: CGFloat, attributeString: NSAttributedString?, font: UIFont) -> Int { + let maxSize = CGSize(width: width, height: CGFloat(Float.infinity)) + let charSize = font.lineHeight + let textSize = attributeString?.finalSize(font, maxSize) ?? .zero let lines = Int(textSize.height / charSize) return lines } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageAudioCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageAudioCell.swift index 9f649440..f09afd29 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageAudioCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageAudioCell.swift @@ -126,11 +126,8 @@ open class FunChatMessageAudioCell: FunChatMessageBaseCell, ChatAudioCellProtoco timeLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) if let m = model as? MessageAudioModel { if isSend { timeLabelRight.text = "\(m.duration)" + "″" diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageBaseCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageBaseCell.swift index 06eeacb3..f586fed8 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageBaseCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageBaseCell.swift @@ -9,16 +9,20 @@ open class FunChatMessageBaseCell: NEBaseChatMessageCell { public let funMargin: CGFloat = 5.2 override open func initProperty() { super.initProperty() + timeLabel.backgroundColor = .funChatBackgroundColor + readView.borderLayer.strokeColor = UIColor.funChatThemeColor.cgColor readView.sectorLayer.fillColor = UIColor.funChatThemeColor.cgColor var image = NEKitChatConfig.shared.ui.messageProperties.leftBubbleBg ?? UIImage.ne_imageNamed(name: "chat_message_receive_fun") bubbleImageLeft.image = image? - .resizableImage(withCapInsets: UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25)) + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) image = NEKitChatConfig.shared.ui.messageProperties.rightBubbleBg ?? UIImage.ne_imageNamed(name: "chat_message_send_fun") bubbleImageRight.image = image? - .resizableImage(withCapInsets: UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25)) + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) + + seletedBtn.setImage(.ne_imageNamed(name: "fun_select"), for: .selected) } override open func baseCommonUI() { @@ -26,8 +30,7 @@ open class FunChatMessageBaseCell: NEBaseChatMessageCell { setAvatarImgSize(size: 42) contentView.updateLayoutConstraint(firstItem: fullNameLabel, seconedItem: avatarImageLeft, attribute: .left, constant: 8 + funMargin) - contentView.removeLayoutConstraint(firstItem: fullNameLabel, seconedItem: avatarImageLeft, attribute: .top) - fullNameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true + contentView.updateLayoutConstraint(firstItem: fullNameLabel, seconedItem: avatarImageLeft, attribute: .top, constant: -4) } override open func initSubviewsLayout() { diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageCallCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageCallCell.swift index bc5fe7a6..ee526efc 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageCallCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageCallCell.swift @@ -62,11 +62,8 @@ open class FunChatMessageCallCell: FunChatMessageBaseCell { contentLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentLabel = isSend ? contentLabelRight : contentLabelLeft if let m = model as? MessageCallRecordModel { contentLabel.attributedText = m.attributeStr diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageFileCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageFileCell.swift index c9545d24..5dedf7ea 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageFileCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageFileCell.swift @@ -14,6 +14,7 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { let view_img = UIImageView() view_img.translatesAutoresizingMaskIntoConstraints = false view_img.backgroundColor = .clear + view_img.accessibilityIdentifier = "id.fileType" return view_img }() @@ -21,6 +22,7 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { let state = FileStateView() state.translatesAutoresizingMaskIntoConstraints = false state.backgroundColor = .clear + state.accessibilityIdentifier = "id.fileStatus" return state }() @@ -69,6 +71,7 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { let view_img = UIImageView() view_img.translatesAutoresizingMaskIntoConstraints = false view_img.backgroundColor = .clear + view_img.accessibilityIdentifier = "id.fileType" return view_img }() @@ -76,6 +79,7 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { let state = FileStateView() state.translatesAutoresizingMaskIntoConstraints = false state.backgroundColor = .clear + state.accessibilityIdentifier = "id.fileStatus" return state }() @@ -149,10 +153,10 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { imgViewLeft.heightAnchor.constraint(equalToConstant: 32), ]) - addSubview(stateViewLeft) + imgViewLeft.addSubview(stateViewLeft) NSLayoutConstraint.activate([ - stateViewLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: 10), - stateViewLeft.topAnchor.constraint(equalTo: bubbleImageLeft.topAnchor, constant: 10), + stateViewLeft.leftAnchor.constraint(equalTo: imgViewLeft.leftAnchor, constant: 0), + stateViewLeft.topAnchor.constraint(equalTo: imgViewLeft.topAnchor, constant: 0), stateViewLeft.widthAnchor.constraint(equalToConstant: 32), stateViewLeft.heightAnchor.constraint(equalToConstant: 32), ]) @@ -181,10 +185,10 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { imgViewRight.heightAnchor.constraint(equalToConstant: 32), ]) - addSubview(stateViewRight) + imgViewRight.addSubview(stateViewRight) NSLayoutConstraint.activate([ - stateViewRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: 10), - stateViewRight.topAnchor.constraint(equalTo: bubbleImageRight.topAnchor, constant: 10), + stateViewRight.leftAnchor.constraint(equalTo: imgViewRight.leftAnchor, constant: 0), + stateViewRight.topAnchor.constraint(equalTo: imgViewRight.topAnchor, constant: 0), stateViewRight.widthAnchor.constraint(equalToConstant: 32), stateViewRight.heightAnchor.constraint(equalToConstant: 32), ]) @@ -209,11 +213,8 @@ open class FunChatMessageFileCell: FunChatMessageBaseCell { labelViewRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let stateView = isSend ? stateViewRight : stateViewLeft let imgView = isSend ? imgViewRight : imgViewLeft let titleLabel = isSend ? titleLabelRight : titleLabelLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageImageCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageImageCell.swift index ea828db0..0c5e1790 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageImageCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageImageCell.swift @@ -59,11 +59,8 @@ open class FunChatMessageImageCell: FunChatMessageBaseCell { contentImageViewRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentImageView = isSend ? contentImageViewRight : contentImageViewLeft if let m = model as? MessageImageModel, let imageUrl = m.imageUrl { @@ -76,7 +73,8 @@ open class FunChatMessageImageCell: FunChatMessageBaseCell { completed: nil ) } else { - contentImageView.image = UIImage(contentsOfFile: imageUrl) + let url = URL(fileURLWithPath: imageUrl) + contentImageView.sd_setImage(with: url) } } else { contentImageView.image = nil diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageLocationCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageLocationCell.swift index e729138c..8e2c9509 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageLocationCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageLocationCell.swift @@ -89,6 +89,7 @@ open class FunChatMessageLocationCell: FunChatMessageBaseCell { backgroundViewLeft.layer.cornerRadius = 4 backgroundViewLeft.layer.borderWidth = 1 backgroundViewLeft.layer.borderColor = UIColor.ne_outlineColor.cgColor + backgroundViewLeft.accessibilityIdentifier = "id.mapView" let messageLongPress = UILongPressGestureRecognizer( target: self, @@ -104,6 +105,7 @@ open class FunChatMessageLocationCell: FunChatMessageBaseCell { ]) let messageTap = UITapGestureRecognizer(target: self, action: #selector(tapMessage)) + messageTap.cancelsTouchesInView = false backgroundViewLeft.addGestureRecognizer(messageTap) backgroundViewLeft.addSubview(titleLabelLeft) @@ -158,6 +160,8 @@ open class FunChatMessageLocationCell: FunChatMessageBaseCell { backgroundViewRight.layer.cornerRadius = 4 backgroundViewRight.layer.borderWidth = 1 backgroundViewRight.layer.borderColor = UIColor.ne_outlineColor.cgColor + backgroundViewRight.accessibilityIdentifier = "id.mapView" + let messageLongPress = UILongPressGestureRecognizer( target: self, action: #selector(longPress) @@ -171,6 +175,7 @@ open class FunChatMessageLocationCell: FunChatMessageBaseCell { backgroundViewRight.bottomAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor), ]) let messageTap = UITapGestureRecognizer(target: self, action: #selector(tapMessage)) + messageTap.cancelsTouchesInView = false backgroundViewRight.addGestureRecognizer(messageTap) backgroundViewRight.addSubview(titleLabelRight) @@ -222,11 +227,8 @@ open class FunChatMessageLocationCell: FunChatMessageBaseCell { backgroundViewRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let titleLabel = isSend ? titleLabelRight : titleLabelLeft let subTitleLabel = isSend ? subTitleLabelRight : subTitleLabelLeft let mapView = isSend ? mapViewRight : mapViewLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageMultiForwardCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageMultiForwardCell.swift new file mode 100644 index 00000000..15ba90b3 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageMultiForwardCell.swift @@ -0,0 +1,384 @@ + +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonKit +import NIMSDK +import UIKit + +@objcMembers +open class FunChatMessageMultiForwardCell: FunChatMessageBaseCell { + let contentWidth: CGFloat = 228 + let titleLabelFontSize: CGFloat = 16 + let contentLabelFontSize: CGFloat = 12 + + override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + setupUI() + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + open func setupUI() { + setupUIRight() + setupUILeft() + } + + open func setupUILeft() { + bubbleImageLeft.image = nil + let image = UIImage.ne_imageNamed(name: "multiForward_message_receive_fun") + backViewLeft.image = image? + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) + + bubbleImageLeft.addSubview(backViewLeft) + NSLayoutConstraint.activate([ + backViewLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: 0), + backViewLeft.topAnchor.constraint(equalTo: bubbleImageLeft.topAnchor, constant: 0), + backViewLeft.bottomAnchor.constraint(equalTo: bubbleImageLeft.bottomAnchor, constant: -0), + backViewLeft.rightAnchor.constraint(equalTo: bubbleImageLeft.rightAnchor, constant: -0), + ]) + + backViewLeft.addSubview(titleLabelLeft1) + NSLayoutConstraint.activate([ + titleLabelLeft1.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: 12 + funMargin), + titleLabelLeft1.rightAnchor.constraint(lessThanOrEqualTo: backViewLeft.rightAnchor, constant: -102), + titleLabelLeft1.topAnchor.constraint(equalTo: backViewLeft.topAnchor, constant: 12), + titleLabelLeft1.heightAnchor.constraint(equalToConstant: 22), + ]) + + backViewLeft.addSubview(titleLabelLeft2) + NSLayoutConstraint.activate([ + titleLabelLeft2.leftAnchor.constraint(equalTo: titleLabelLeft1.rightAnchor), + titleLabelLeft2.centerYAnchor.constraint(equalTo: titleLabelLeft1.centerYAnchor), + titleLabelLeft2.heightAnchor.constraint(equalToConstant: 22), + titleLabelLeft2.widthAnchor.constraint(equalToConstant: 88), + ]) + + backViewLeft.addSubview(contentLabelLeft1) + NSLayoutConstraint.activate([ + contentLabelLeft1.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), + contentLabelLeft1.topAnchor.constraint(equalTo: titleLabelLeft1.bottomAnchor, constant: 4), + contentLabelLeft1.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelLeft1.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft2) + NSLayoutConstraint.activate([ + contentLabelLeft2.leftAnchor.constraint(equalTo: contentLabelLeft1.leftAnchor), + contentLabelLeft2.topAnchor.constraint(equalTo: contentLabelLeft1.bottomAnchor), + contentLabelLeft2.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelLeft2.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft3) + NSLayoutConstraint.activate([ + contentLabelLeft3.leftAnchor.constraint(equalTo: contentLabelLeft2.leftAnchor), + contentLabelLeft3.topAnchor.constraint(equalTo: contentLabelLeft2.bottomAnchor), + contentLabelLeft3.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelLeft3.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentHistoryLeft) + NSLayoutConstraint.activate([ + contentHistoryLeft.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), + contentHistoryLeft.bottomAnchor.constraint(equalTo: backViewLeft.bottomAnchor, constant: -8), + contentHistoryLeft.widthAnchor.constraint(equalToConstant: 60), + contentHistoryLeft.heightAnchor.constraint(equalToConstant: 14), + ]) + + backViewLeft.addSubview(dividerLineLeft) + NSLayoutConstraint.activate([ + dividerLineLeft.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: funMargin), + dividerLineLeft.rightAnchor.constraint(equalTo: backViewLeft.rightAnchor), + dividerLineLeft.topAnchor.constraint(equalTo: contentHistoryLeft.topAnchor, constant: -8), + dividerLineLeft.heightAnchor.constraint(equalToConstant: 1), + ]) + } + + open func setupUIRight() { + bubbleImageRight.image = nil + let image = UIImage.ne_imageNamed(name: "multiForward_message_send_fun") + backViewRight.image = image? + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) + + bubbleImageRight.addSubview(backViewRight) + NSLayoutConstraint.activate([ + backViewRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: 0), + backViewRight.topAnchor.constraint(equalTo: bubbleImageRight.topAnchor, constant: 0), + backViewRight.bottomAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor, constant: -0), + backViewRight.rightAnchor.constraint(equalTo: bubbleImageRight.rightAnchor, constant: -0), + ]) + + backViewRight.addSubview(titleLabelRight1) + NSLayoutConstraint.activate([ + titleLabelRight1.leftAnchor.constraint(equalTo: backViewRight.leftAnchor, constant: 12), + titleLabelRight1.rightAnchor.constraint(lessThanOrEqualTo: backViewRight.rightAnchor, constant: -102), + titleLabelRight1.topAnchor.constraint(equalTo: backViewRight.topAnchor, constant: 12), + titleLabelRight1.heightAnchor.constraint(equalToConstant: 22), + ]) + + backViewRight.addSubview(titleLabelRight2) + NSLayoutConstraint.activate([ + titleLabelRight2.leftAnchor.constraint(equalTo: titleLabelRight1.rightAnchor), + titleLabelRight2.centerYAnchor.constraint(equalTo: titleLabelRight1.centerYAnchor), + titleLabelRight2.heightAnchor.constraint(equalToConstant: 22), + titleLabelRight2.widthAnchor.constraint(equalToConstant: 88), + ]) + + backViewRight.addSubview(contentLabelRight1) + NSLayoutConstraint.activate([ + contentLabelRight1.leftAnchor.constraint(equalTo: titleLabelRight1.leftAnchor), + contentLabelRight1.topAnchor.constraint(equalTo: titleLabelRight1.bottomAnchor, constant: 4), + contentLabelRight1.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelRight1.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewRight.addSubview(contentLabelRight2) + NSLayoutConstraint.activate([ + contentLabelRight2.leftAnchor.constraint(equalTo: contentLabelRight1.leftAnchor), + contentLabelRight2.topAnchor.constraint(equalTo: contentLabelRight1.bottomAnchor), + contentLabelRight2.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelRight2.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewRight.addSubview(contentLabelRight3) + NSLayoutConstraint.activate([ + contentLabelRight3.leftAnchor.constraint(equalTo: contentLabelRight2.leftAnchor), + contentLabelRight3.topAnchor.constraint(equalTo: contentLabelRight2.bottomAnchor), + contentLabelRight3.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelRight3.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewRight.addSubview(contentHistoryRight) + NSLayoutConstraint.activate([ + contentHistoryRight.leftAnchor.constraint(equalTo: titleLabelRight1.leftAnchor), + contentHistoryRight.bottomAnchor.constraint(equalTo: backViewRight.bottomAnchor, constant: -8), + contentHistoryRight.widthAnchor.constraint(equalToConstant: 60), + contentHistoryRight.heightAnchor.constraint(equalToConstant: 14), + ]) + + backViewRight.addSubview(dividerLineRight) + NSLayoutConstraint.activate([ + dividerLineRight.leftAnchor.constraint(equalTo: backViewRight.leftAnchor), + dividerLineRight.rightAnchor.constraint(equalTo: backViewRight.rightAnchor, constant: -funMargin), + dividerLineRight.topAnchor.constraint(equalTo: contentHistoryRight.topAnchor, constant: -8), + dividerLineRight.heightAnchor.constraint(equalToConstant: 1), + ]) + } + + override open func showLeftOrRight(showRight: Bool) { + super.showLeftOrRight(showRight: showRight) + } + + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) + guard let data = NECustomAttachment.dataOfCustomMessage(message: model.message) else { + return + } + + let font = UIFont.systemFont(ofSize: contentLabelFontSize) + let bubbleW = isSend ? bubbleWRight : bubbleWLeft + let bubbleH = isSend ? bubbleHRight : bubbleHLeft + let titleLabel = isSend ? titleLabelRight1 : titleLabelLeft1 + let titleLabel2 = isSend ? titleLabelRight2 : titleLabelLeft2 + let contentLabel1 = isSend ? contentLabelRight1 : contentLabelLeft1 + let contentLabel2 = isSend ? contentLabelRight2 : contentLabelLeft2 + let contentLabel3 = isSend ? contentLabelRight3 : contentLabelLeft3 + + bubbleW?.constant = 256 + bubbleH?.constant = 130 + + if let sessionName = data["sessionName"] as? String { + titleLabel.attributedText = + NEEmotionTool.getAttWithStr(str: sessionName, + font: .systemFont(ofSize: titleLabelFontSize), + color: .ne_darkText) + } else { + titleLabel2.text = chatLocalizable("chat_history") + } + + guard let abstracts = data["abstracts"] as? [[String: Any]] else { return } + + contentLabel2.attributedText = nil + contentLabel3.attributedText = nil + for i in 0 ..< abstracts.count { + var contentLabel = contentLabel1 + if i == 1 { + contentLabel = contentLabel2 + } else if i == 2 { + contentLabel = contentLabel3 + } + + var contentText = "" + if var senderNick = abstracts[i]["senderNick"] as? String { + if senderNick.count > 5 { + // 截取字符串 abcdefg -> ab...fg + let leftEndIndex = senderNick.index(senderNick.startIndex, offsetBy: 2) + let rightStartIndex = senderNick.index(senderNick.endIndex, offsetBy: -2) + senderNick = senderNick[senderNick.startIndex ..< leftEndIndex] + "..." + senderNick[rightStartIndex ..< senderNick.endIndex] + } + contentText = senderNick + if let content = abstracts[i]["content"] as? String { + contentText += ":" + content + } + } + + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = 1 // 设置行间距 + paragraphStyle.lineBreakMode = .byTruncatingTail + let attributedText = NEEmotionTool.getAttWithStr(str: contentText, + font: font, + color: .funChatMultiForwardContentColor) + attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedText.length)) + contentLabel.attributedText = attributedText + } + + let numCount1 = String.calculateMaxLines(width: contentWidth, + attributeString: contentLabel1.attributedText, + font: font) + if numCount1 == 1 { + contentLabel2.numberOfLines = 2 + contentLabel2.isHidden = contentLabel2.attributedText == nil + let numCount2 = String.calculateMaxLines(width: contentWidth, + attributeString: contentLabel2.attributedText, + font: font) + contentLabel3.isHidden = contentLabel3.attributedText == nil || numCount2 >= 2 + } else if numCount1 == 2 { + contentLabel2.numberOfLines = 1 + contentLabel2.isHidden = contentLabel2.attributedText == nil + contentLabel3.isHidden = true + } else { + contentLabel2.isHidden = true + contentLabel3.isHidden = true + } + } + + // MARK: - lazy load + + public lazy var backViewLeft: UIImageView = { + let view = UIImageView() + view.translatesAutoresizingMaskIntoConstraints = false + return view + }() + + public lazy var titleLabelLeft1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.name1" + return label + }() + + public lazy var titleLabelLeft2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("chat_history_by") + label.textColor = .ne_darkText + label.accessibilityIdentifier = "id.name2" + return label + }() + + public lazy var contentLabelLeft1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 3 + label.accessibilityIdentifier = "id.content1" + return label + }() + + public lazy var contentLabelLeft2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 2 + label.accessibilityIdentifier = "id.content2" + return label + }() + + public lazy var contentLabelLeft3: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.content3" + return label + }() + + public lazy var dividerLineLeft: UIView = { + let line = UIView() + line.translatesAutoresizingMaskIntoConstraints = false + line.backgroundColor = multiForwardLineColor + return line + }() + + public lazy var contentHistoryLeft: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.font = .systemFont(ofSize: 12) + label.textColor = .ne_lightText + label.text = chatLocalizable("chat_history") + label.accessibilityIdentifier = "id.contentHistoryLeft" + return label + }() + + public lazy var backViewRight: UIImageView = { + let view = UIImageView() + view.translatesAutoresizingMaskIntoConstraints = false + return view + }() + + public lazy var titleLabelRight1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.name1" + return label + }() + + public lazy var titleLabelRight2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("chat_history_by") + label.textColor = .ne_darkText + label.accessibilityIdentifier = "id.name2" + return label + }() + + public lazy var contentLabelRight1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 3 + label.accessibilityIdentifier = "id.content1" + return label + }() + + public lazy var contentLabelRight2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 2 + label.accessibilityIdentifier = "id.content2" + return label + }() + + public lazy var contentLabelRight3: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.content3" + return label + }() + + public lazy var dividerLineRight: UIView = { + let line = UIView() + line.translatesAutoresizingMaskIntoConstraints = false + line.backgroundColor = multiForwardLineColor + return line + }() + + public lazy var contentHistoryRight: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.font = .systemFont(ofSize: 12) + label.textColor = .ne_lightText + label.text = chatLocalizable("chat_history") + label.accessibilityIdentifier = "id.contentHistoryRight" + return label + }() +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageReplyCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageReplyCell.swift index 11b6dd7e..57cd1925 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageReplyCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageReplyCell.swift @@ -9,10 +9,9 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { public lazy var replyLabelLeft: UILabel = { let replyLabelLeft = UILabel() replyLabelLeft.numberOfLines = 2 - replyLabelLeft.textColor = UIColor(hexString: "#666666") // 换肤颜色提取 + replyLabelLeft.textColor = .ne_greyText replyLabelLeft.translatesAutoresizingMaskIntoConstraints = false replyLabelLeft.font = UIFont.systemFont(ofSize: 13) - replyLabelLeft.textAlignment = .justified return replyLabelLeft }() @@ -21,6 +20,7 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { replyTextView.translatesAutoresizingMaskIntoConstraints = false replyTextView.backgroundColor = .funChatInputReplyBg replyTextView.layer.cornerRadius = 4 + replyTextView.accessibilityIdentifier = "id.replyTextView" return replyTextView }() @@ -32,7 +32,6 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { replyLabelRight.textColor = .ne_greyText replyLabelRight.translatesAutoresizingMaskIntoConstraints = false replyLabelRight.font = UIFont.systemFont(ofSize: 13) - replyLabelRight.textAlignment = .justified return replyLabelRight }() @@ -41,9 +40,13 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { replyTextView.translatesAutoresizingMaskIntoConstraints = false replyTextView.backgroundColor = .funChatInputReplyBg replyTextView.layer.cornerRadius = 4 + replyTextView.accessibilityIdentifier = "id.replyTextView" return replyTextView }() + public var funPinLabelLeftTopAnchor: NSLayoutConstraint? // 左侧标记文案顶部布局约束 + public var funPinLabelRightTopAnchor: NSLayoutConstraint? // 右侧标记文案顶部布局约束 + override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonUI() @@ -69,9 +72,10 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { replyTextViewLeft.widthAnchor.constraint(lessThanOrEqualToConstant: chat_content_maxW - funMargin), ]) - contentView.removeLayoutConstraint(firstItem: pinLabelLeft, seconedItem: bubbleImageLeft, attribute: .top) contentView.updateLayoutConstraint(firstItem: pinLabelLeft, seconedItem: bubbleImageLeft, attribute: .left, constant: 14 + funMargin) - pinLabelLeft.topAnchor.constraint(equalTo: replyTextViewLeft.bottomAnchor, constant: 4).isActive = true + pinLabelLeftTopAnchor?.isActive = false + funPinLabelLeftTopAnchor = pinLabelLeft.topAnchor.constraint(equalTo: replyTextViewLeft.bottomAnchor, constant: 4) + funPinLabelLeftTopAnchor?.isActive = true replyTextViewLeft.addSubview(replyLabelLeft) NSLayoutConstraint.activate([ @@ -91,9 +95,10 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { replyTextViewRight.widthAnchor.constraint(lessThanOrEqualToConstant: chat_content_maxW - funMargin), ]) - contentView.removeLayoutConstraint(firstItem: pinLabelRight, seconedItem: bubbleImageRight, attribute: .top) contentView.updateLayoutConstraint(firstItem: pinLabelRight, seconedItem: bubbleImageRight, attribute: .right, constant: -funMargin) - pinLabelRight.topAnchor.constraint(equalTo: replyTextViewRight.bottomAnchor, constant: 4).isActive = true + pinLabelRightTopAnchor?.isActive = false + funPinLabelRightTopAnchor = pinLabelRight.topAnchor.constraint(equalTo: replyTextViewRight.bottomAnchor, constant: 4) + funPinLabelRightTopAnchor?.isActive = true replyTextViewRight.addSubview(replyLabelRight) NSLayoutConstraint.activate([ @@ -112,8 +117,11 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { open func addReplyGesture() { let replyViewTapLeft = UITapGestureRecognizer(target: self, action: #selector(tapReplyView(tap:))) + replyViewTapLeft.cancelsTouchesInView = false replyTextViewLeft.addGestureRecognizer(replyViewTapLeft) + let replyViewTapRight = UITapGestureRecognizer(target: self, action: #selector(tapReplyView(tap:))) + replyViewTapRight.cancelsTouchesInView = false replyTextViewRight.addGestureRecognizer(replyViewTapRight) } @@ -122,19 +130,15 @@ open class FunChatMessageReplyCell: FunChatMessageTextCell { delegate?.didTapMessageView(self, contentModel) } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let replyLabel = isSend ? replyLabelRight : replyLabelLeft if let text = model.replyText, let font = replyLabel.font { - let normalReplyText = NEEmotionTool.getAttWithStr(str: text, - font: font, - color: replyLabel.textColor) - replyLabel.attributedText = normalReplyText.attributedSubstring(from: NSRange(location: 1, length: normalReplyText.length - 1)) + replyLabel.attributedText = NEEmotionTool.getAttWithStr(str: text, + font: font, + color: replyLabel.textColor) } } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRevokeCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRevokeCell.swift index 405c928f..33dd595e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRevokeCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRevokeCell.swift @@ -35,7 +35,7 @@ open class FunChatMessageRevokeCell: FunChatMessageBaseCell { NSLayoutConstraint.activate([ revokeLabelLeft.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), revokeLabelLeft.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), - revokeLabelLeft.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + revokeLabelLeft.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: 6), revokeLabelLeft.heightAnchor.constraint(equalToConstant: 16), ]) } @@ -50,7 +50,7 @@ open class FunChatMessageRevokeCell: FunChatMessageBaseCell { revokeLabelRightXAnchor?.isActive = true NSLayoutConstraint.activate([ revokeLabelRight.widthAnchor.constraint(equalToConstant: 120), - revokeLabelRight.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + revokeLabelRight.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: 6), revokeLabelRight.heightAnchor.constraint(equalToConstant: 16), ]) @@ -69,22 +69,27 @@ open class FunChatMessageRevokeCell: FunChatMessageBaseCell { } override open func showLeftOrRight(showRight: Bool) { - super.showLeftOrRight(showRight: showRight) - revokeLabelLeft.isHidden = showRight - reeditButton.isHidden = !showRight - revokeLabelRight.isHidden = !showRight avatarImageLeft.isHidden = true + nameLabelLeft.isHidden = true bubbleImageLeft.isHidden = true + pinImageLeft.isHidden = true + pinLabelLeft.isHidden = true + fullNameLabel.isHidden = true + avatarImageRight.isHidden = true + nameLabelRight.isHidden = true bubbleImageRight.isHidden = true - seletedBtn.isHidden = true - pinLabelLeft.isHidden = true - pinImageLeft.isHidden = true - pinLabelRight.isHidden = true pinImageRight.isHidden = true + pinLabelRight.isHidden = true + activityView.isHidden = true + readView.isHidden = true + seletedBtn.isHidden = true + + revokeLabelLeft.isHidden = showRight + revokeLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { if let time = model.message?.timestamp { let date = Date() let currentTime = date.timeIntervalSince1970 @@ -93,14 +98,11 @@ open class FunChatMessageRevokeCell: FunChatMessageBaseCell { } } - guard let isSend = model.message?.isOutgoingMsg else { - return - } let revokeLabel = isSend ? revokeLabelRight : revokeLabelLeft model.contentSize = CGSize(width: kScreenWidth, height: 0) - super.setModel(model) - fullNameLabel.isHidden = true + super.setModel(model, isSend) + showLeftOrRight(showRight: isSend) revokeLabel.textColor = .funChatInputViewPlaceholderTextColor if isSend { @@ -108,7 +110,6 @@ open class FunChatMessageRevokeCell: FunChatMessageBaseCell { } else { revokeLabel.text = (model.fullName ?? "") + " " + chatLocalizable("withdrew_message") } - reeditButton.setTitle(chatLocalizable("message_reedit"), for: .normal) if isSend, model.isRevokedText == true { if model.timeOut == true { @@ -116,10 +117,12 @@ open class FunChatMessageRevokeCell: FunChatMessageBaseCell { revokeLabelRightXAnchor?.constant = 0 } else { reeditButton.isHidden = false + reeditButton.setTitle(chatLocalizable("message_reedit"), for: .normal) revokeLabelRightXAnchor?.constant = -32 } } else { reeditButton.isHidden = true + revokeLabelRightXAnchor?.constant = 0 } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRichTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRichTextCell.swift new file mode 100644 index 00000000..90300fee --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageRichTextCell.swift @@ -0,0 +1,117 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class FunChatMessageRichTextCell: FunChatMessageReplyCell { + public lazy var titleLabelLeft: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.isEnabled = false + label.numberOfLines = 0 + label.isUserInteractionEnabled = false + label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize, weight: .semibold) + label.backgroundColor = .clear + return label + }() + + public lazy var titleLabelRight: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.isEnabled = false + label.numberOfLines = 0 + label.isUserInteractionEnabled = false + label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize, weight: .semibold) + label.backgroundColor = .clear + return label + }() + + public var titleLabelLeftHeightAnchor: NSLayoutConstraint? + public var titleLabelRightHeightAnchor: NSLayoutConstraint? + public var contentLabelLeftHeightAnchor: NSLayoutConstraint? + public var contentLabelRightHeightAnchor: NSLayoutConstraint? + + override open func commonUI() { + /// left + bubbleImageLeft.addSubview(titleLabelLeft) + titleLabelLeftHeightAnchor = titleLabelLeft.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + titleLabelLeft.rightAnchor.constraint(equalTo: bubbleImageLeft.rightAnchor, constant: -chat_content_margin), + titleLabelLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: chat_content_margin + funMargin), + titleLabelLeft.topAnchor.constraint(equalTo: bubbleImageLeft.topAnchor, constant: chat_content_margin), + titleLabelLeftHeightAnchor!, + ]) + + bubbleImageLeft.addSubview(contentLabelLeft) + contentLabelLeftHeightAnchor = contentLabelLeft.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + contentLabelLeft.rightAnchor.constraint(equalTo: titleLabelLeft.rightAnchor, constant: -0), + contentLabelLeft.leftAnchor.constraint(equalTo: titleLabelLeft.leftAnchor, constant: 0), + contentLabelLeft.topAnchor.constraint(equalTo: titleLabelLeft.bottomAnchor, constant: chat_content_margin), + contentLabelLeftHeightAnchor!, + ]) + + commonUILeft() + + /// right + bubbleImageRight.addSubview(titleLabelRight) + titleLabelRightHeightAnchor = titleLabelRight.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + titleLabelRight.rightAnchor.constraint(equalTo: bubbleImageRight.rightAnchor, constant: -chat_content_margin - funMargin), + titleLabelRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: chat_content_margin), + titleLabelRight.topAnchor.constraint(equalTo: bubbleImageRight.topAnchor, constant: chat_content_margin), + titleLabelRightHeightAnchor!, + ]) + + bubbleImageRight.addSubview(contentLabelRight) + contentLabelRightHeightAnchor = contentLabelRight.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + contentLabelRight.rightAnchor.constraint(equalTo: titleLabelRight.rightAnchor, constant: -0), + contentLabelRight.leftAnchor.constraint(equalTo: titleLabelRight.leftAnchor, constant: 0), + contentLabelRight.topAnchor.constraint(equalTo: titleLabelRight.bottomAnchor, constant: chat_content_margin), + contentLabelRightHeightAnchor!, + ]) + + commonUIRight() + } + + override open func showLeftOrRight(showRight: Bool) { + super.showLeftOrRight(showRight: showRight) + titleLabelLeft.isHidden = showRight + titleLabelRight.isHidden = !showRight + } + + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) + let replyView = isSend ? replyTextViewRight : replyTextViewLeft + let titleLabel = isSend ? titleLabelRight : titleLabelLeft + let titleLabelHeightAnchor = isSend ? titleLabelRightHeightAnchor : titleLabelLeftHeightAnchor + let contentLabelHeightAnchor = isSend ? contentLabelRightHeightAnchor : contentLabelLeftHeightAnchor + let pinLabelTopAnchor = isSend ? pinLabelRightTopAnchor : pinLabelLeftTopAnchor + let funPinLabelTopAnchor = isSend ? funPinLabelRightTopAnchor : funPinLabelLeftTopAnchor + + if model.replyText == nil || model.replyText!.isEmpty { + replyView.isHidden = true + funPinLabelTopAnchor?.isActive = false + pinLabelTopAnchor?.isActive = true + } else { + replyView.isHidden = false + funPinLabelTopAnchor?.isActive = true + pinLabelTopAnchor?.isActive = false + } + + if let m = model as? MessageTextModel { + contentLabelHeightAnchor?.constant = m.textHeight + } + + if let m = model as? MessageRichTextModel { + titleLabel.attributedText = m.titleAttributeStr + titleLabelHeightAnchor?.constant = m.titleTextHeight + if m.message?.text?.isEmpty == true { + titleLabelHeightAnchor?.constant = 26 + } + } + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTextCell.swift index 7ae9c753..19656f6e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTextCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTextCell.swift @@ -14,7 +14,6 @@ open class FunChatMessageTextCell: FunChatMessageBaseCell { label.isUserInteractionEnabled = false label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize) label.backgroundColor = .clear - label.textAlignment = .justified return label }() @@ -26,7 +25,6 @@ open class FunChatMessageTextCell: FunChatMessageBaseCell { label.isUserInteractionEnabled = false label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize) label.backgroundColor = .clear - label.textAlignment = .justified return label }() @@ -65,11 +63,8 @@ open class FunChatMessageTextCell: FunChatMessageBaseCell { contentLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentLabel = isSend ? contentLabelRight : contentLabelLeft let bubbleW = isSend ? bubbleWRight : bubbleWLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTipCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTipCell.swift index d607b0d7..04e46c6d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTipCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageTipCell.swift @@ -9,7 +9,7 @@ import UIKit open class FunChatMessageTipCell: NEBaseChatMessageTipCell { override open func commonUI() { super.commonUI() - timeLabel.font = .systemFont(ofSize: 14) - timeLabel.textColor = .funRecordAudioTextColor + contentLabel.font = .systemFont(ofSize: 14) + contentLabel.textColor = .funRecordAudioTextColor } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageVideoCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageVideoCell.swift index 157f09b5..c5b900dc 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageVideoCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/FunChatMessageVideoCell.swift @@ -120,11 +120,8 @@ open class FunChatMessageVideoCell: FunChatMessageImageCell { ]) } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentImageView = isSend ? contentImageViewRight : contentImageViewLeft let timeView = isSend ? timeViewRight : timeViewLeft let timeLabel = isSend ? timeLabelRight : timeLabelLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageAudioCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageAudioCell.swift index c88c50d8..e07ecd30 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageAudioCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageAudioCell.swift @@ -15,6 +15,6 @@ open class FunPinMessageAudioCell: NEBasePinMessageAudioCell { headerView.layer.cornerRadius = 4.0 let image = NEKitChatConfig.shared.ui.messageProperties.leftBubbleBg ?? UIImage.ne_imageNamed(name: "fun_pin_message_audio_bg") bubbleImage.image = image? - .resizableImage(withCapInsets: UIEdgeInsets(top: 35, left: 25, bottom: 10, right: 25)) + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageImageCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageImageCell.swift index 9e8f6925..e468d395 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageImageCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageImageCell.swift @@ -1,3 +1,4 @@ + // Copyright (c) 2022 NetEase, Inc. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageMultiForwardCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageMultiForwardCell.swift new file mode 100644 index 00000000..89491e67 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageMultiForwardCell.swift @@ -0,0 +1,76 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class FunPinMessageMultiForwardCell: NEBasePinMessageMultiForwardCell { + override open func setupUI() { + super.setupUI() + backLeftConstraint?.constant = 0 + backRightConstraint?.constant = 0 + backView.layer.cornerRadius = 0 + headerView.layer.cornerRadius = 4.0 + + titleLabelFontSize = 16 + contentLabelFontSize = 12 + contentLabelColor = .funChatMultiForwardContentColor + + backViewLeft.addSubview(titleLabelLeft1) + NSLayoutConstraint.activate([ + titleLabelLeft1.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: 12 + funMargin), + titleLabelLeft1.rightAnchor.constraint(lessThanOrEqualTo: backViewLeft.rightAnchor, constant: -102), + titleLabelLeft1.topAnchor.constraint(equalTo: backViewLeft.topAnchor, constant: 12), + titleLabelLeft1.heightAnchor.constraint(equalToConstant: 22), + ]) + + backViewLeft.addSubview(titleLabelLeft2) + NSLayoutConstraint.activate([ + titleLabelLeft2.leftAnchor.constraint(equalTo: titleLabelLeft1.rightAnchor), + titleLabelLeft2.centerYAnchor.constraint(equalTo: titleLabelLeft1.centerYAnchor), + titleLabelLeft2.heightAnchor.constraint(equalToConstant: 22), + titleLabelLeft2.widthAnchor.constraint(equalToConstant: 88), + ]) + + backViewLeft.addSubview(contentLabelLeft1) + NSLayoutConstraint.activate([ + contentLabelLeft1.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), + contentLabelLeft1.topAnchor.constraint(equalTo: titleLabelLeft1.bottomAnchor, constant: 4), + contentLabelLeft1.widthAnchor.constraint(equalToConstant: contentW), + contentLabelLeft1.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft2) + NSLayoutConstraint.activate([ + contentLabelLeft2.leftAnchor.constraint(equalTo: contentLabelLeft1.leftAnchor), + contentLabelLeft2.topAnchor.constraint(equalTo: contentLabelLeft1.bottomAnchor), + contentLabelLeft2.widthAnchor.constraint(equalToConstant: contentW), + contentLabelLeft2.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft3) + NSLayoutConstraint.activate([ + contentLabelLeft3.leftAnchor.constraint(equalTo: contentLabelLeft2.leftAnchor), + contentLabelLeft3.topAnchor.constraint(equalTo: contentLabelLeft2.bottomAnchor), + contentLabelLeft3.widthAnchor.constraint(equalToConstant: contentW), + contentLabelLeft3.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + +// backViewLeft.addSubview(contentHistoryLeft) +// NSLayoutConstraint.activate([ +// contentHistoryLeft.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), +// contentHistoryLeft.bottomAnchor.constraint(equalTo: backViewLeft.bottomAnchor, constant: -8), +// contentHistoryLeft.widthAnchor.constraint(equalToConstant: 60), +// contentHistoryLeft.heightAnchor.constraint(equalToConstant: 14), +// ]) +// +// backViewLeft.addSubview(dividerLineLeft) +// NSLayoutConstraint.activate([ +// dividerLineLeft.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: funMargin), +// dividerLineLeft.rightAnchor.constraint(equalTo: backViewLeft.rightAnchor), +// dividerLineLeft.topAnchor.constraint(equalTo: contentHistoryLeft.topAnchor, constant: -8), +// dividerLineLeft.heightAnchor.constraint(equalToConstant: 1), +// ]) + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageRichTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageRichTextCell.swift new file mode 100644 index 00000000..8af629c1 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Cell/PinCell/FunPinMessageRichTextCell.swift @@ -0,0 +1,16 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class FunPinMessageRichTextCell: NEBasePinMessageRichTextCell { + override open func setupUI() { + super.setupUI() + backLeftConstraint?.constant = 0 + backRightConstraint?.constant = 0 + backView.layer.cornerRadius = 0 + headerView.layer.cornerRadius = 4.0 + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunChatViewController.swift index 18265aed..a95e4c6c 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunChatViewController.swift @@ -2,6 +2,7 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit import NECommonKit import NIMSDK import UIKit @@ -9,22 +10,10 @@ import UIKit @objcMembers open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, NIMUserManagerDelegate, FunChatRecordViewDelegate { public weak var recordView: FunRecordAudioView? - public var currentKeyboardHeight: CGFloat = 0 override public init(session: NIMSession) { super.init(session: session) - cellRegisterDic = [ - "\(MessageType.text.rawValue)": FunChatMessageTextCell.self, - "\(MessageType.rtcCallRecord.rawValue)": FunChatMessageCallCell.self, - "\(MessageType.audio.rawValue)": FunChatMessageAudioCell.self, - "\(MessageType.image.rawValue)": FunChatMessageImageCell.self, - "\(MessageType.revoke.rawValue)": FunChatMessageRevokeCell.self, - "\(MessageType.video.rawValue)": FunChatMessageVideoCell.self, - "\(MessageType.file.rawValue)": FunChatMessageFileCell.self, - "\(MessageType.reply.rawValue)": FunChatMessageReplyCell.self, - "\(MessageType.location.rawValue)": FunChatMessageLocationCell.self, - "\(MessageType.time.rawValue)": FunChatMessageTipCell.self, - ] + cellRegisterDic = ChatMessageHelper.getChatCellRegisterDic(isFun: true) normalInputHeight = 90 brokenNetworkViewHeight = 48 @@ -45,25 +34,9 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, getFunInputView()?.funDelegate = self } - override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { - let m = viewmodel.messages[indexPath.row] - if m.type == .custom { - if let object = m.message?.messageObject as? NIMCustomObject, let custom = object.attachment as? NECustomAttachmentProtocol { - return custom.cellHeight - } - } - - if let contentModel = m as? MessageContentModel { - if contentModel.type == .revoke { - return 28 - } - } - - return m.cellHeight() - } - override open func getMenuView() -> NEBaseChatInputView { let input = FunChatInputView() + input.multipleLineDelegate = self let gesture = UILongPressGestureRecognizer(target: self, action: #selector(holdToSpeak(gesture:))) input.holdToSpeakView.addGestureRecognizer(gesture) return input @@ -73,24 +46,49 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, FunForwardAlertViewController() } + override open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + FunMultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } + override func getUserSelectVC() -> NEBaseSelectUserViewController { FunSelectUserViewController(sessionId: viewmodel.session.sessionId, showSelf: false) } - override func getTextViewController(text: String) -> TextViewController { - let textViewController = super.getTextViewController(text: text) + override func getTextViewController(title: String?, body: String?) -> TextViewController { + let textViewController = super.getTextViewController(title: title, body: body) textViewController.view.backgroundColor = .funChatBackgroundColor return textViewController } open func recordModeChangeDidClick() { normalOffset = 0 + if chatInputView.chatInpuMode == .multipleSend { + normalInputHeight = 90 + if let inputView = chatInputView as? FunChatInputView { + inputView.setRecordNormalStyle() + } + } + layoutInputView(offset: 0) + UIApplication.shared.keyWindow?.endEditing(true) } + open func didHideRecordMode() { + if chatInputView.chatInpuMode == .multipleSend { + normalInputHeight = 130 + if let inputView = chatInputView as? FunChatInputView { + inputView.resotreMutipleModeFromRecordMode() + } + layoutInputView(offset: 0) + } + } + open func didHideReplyMode() { viewmodel.isReplying = false + if currentKeyboardHeight > 0 { normalOffset = 30 } else { @@ -99,7 +97,7 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, layoutInputView(offset: currentKeyboardHeight) } - public func didShowReplyMode() { + open func didShowReplyMode() { viewmodel.isReplying = true chatInputView.textView.becomeFirstResponder() } @@ -141,50 +139,19 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, showCustomActionSheet([videoCallAction, audioCallAction]) } - override open func forwardMessage() { - if let message = viewmodel.operationModel?.message { - if IMKitClient.instance.getConfigCenter().teamEnable { - weak var weakSelf = self - let userAction = NECustomAlertAction(title: chatLocalizable("contact_user")) { - weakSelf?.forwardMessageToUser(message: message) - } - - let teamAction = NECustomAlertAction(title: chatLocalizable("team")) { - weakSelf?.forwardMessageToTeam(message: message) - } + override func getUserSettingViewController() -> NEBaseUserSettingViewController { + FunUserSettingViewController(userId: viewmodel.session.sessionId) + } - showCustomActionSheet([teamAction, userAction]) + override open func keyBoardWillShow(_ notification: Notification) { + if chatInputView.chatInpuMode == .normal || chatInputView.chatInpuMode == .multipleSend { + if viewmodel.isReplying { + normalOffset = -10 } else { - forwardMessageToUser(message: message) + normalOffset = 30 } } - } - - /// 设置按钮点击事件 - override open func toSetting() { - if let block = NEKitChatConfig.shared.ui.messageProperties.titleBarRightClick { - block() - return - } - if viewmodel.session.sessionType == .team { - Router.shared.use( - TeamSettingViewRouter, - parameters: ["nav": navigationController as Any, - "teamid": viewmodel.session.sessionId], - closure: nil - ) - } else if viewmodel.session.sessionType == .P2P { - let userSetting = FunUserSettingViewController(userId: viewmodel.session.sessionId) - navigationController?.pushViewController(userSetting, animated: true) - } - } - override open func keyBoardWillShow(_ notification: Notification) { - if viewmodel.isReplying { - normalOffset = -10 - } else { - normalOffset = 30 - } let keyboardRect = (notification .userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue currentKeyboardHeight = keyboardRect.height @@ -192,11 +159,14 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, } override open func keyBoardWillHide(_ notification: Notification) { - if viewmodel.isReplying { - normalOffset = -30 - } else { - normalOffset = 0 + if chatInputView.chatInpuMode == .normal || chatInputView.chatInpuMode == .multipleSend { + if viewmodel.isReplying { + normalOffset = -30 + } else { + normalOffset = 0 + } } + currentKeyboardHeight = 0 super.keyBoardWillHide(notification) } @@ -276,7 +246,7 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, recordView = nil } - public func didEndRecord(view: FunRecordAudioView) { + open func didEndRecord(view: FunRecordAudioView) { endRecord(insideView: true) view.removeFromSuperview() if let hodlToSpeakView = getFunInputView()?.holdToSpeakView { @@ -285,12 +255,24 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, } func getFunInputView() -> FunChatInputView? { - if let funInput = inputView as? FunChatInputView { + if let funInput = chatInputView as? FunChatInputView { return funInput } return nil } + override open func setMutilSelectBottomView() { + mutilSelectBottomView.backgroundColor = .white + mutilSelectBottomView.buttonTopAnchor?.constant = 6 + mutilSelectBottomView.multiForwardButton.setImage(.ne_imageNamed(name: "fun_select_multiForward"), for: .normal) + mutilSelectBottomView.multiForwardButton.setImage(.ne_imageNamed(name: "fun_unselect_multiForward"), for: .disabled) + mutilSelectBottomView.singleForwardButton.setImage(.ne_imageNamed(name: "fun_select_singleForward"), for: .normal) + mutilSelectBottomView.singleForwardButton.setImage(.ne_imageNamed(name: "fun_unselect_singleForward"), for: .disabled) + mutilSelectBottomView.deleteButton.setImage(.ne_imageNamed(name: "fun_select_delete"), for: .normal) + mutilSelectBottomView.deleteButton.setImage(.ne_imageNamed(name: "fun_unselect_delete"), for: .disabled) + mutilSelectBottomView.setLabelColor(color: .funChatInputHoldspeakTextColor) + } + override open func closeReply(button: UIButton?) { viewmodel.isReplying = false getFunInputView()?.hideReplyMode() @@ -312,38 +294,18 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, } else { var text = chatLocalizable("msg_reply") if let uid = message.from { - var showName = viewmodel.getShowName(userId: uid, teamId: viewmodel.session.sessionId, false) + var showName = ChatUserCache.getShowName(userId: uid, teamId: viewmodel.session.sessionId, false) if viewmodel.session.sessionType != .P2P, !IMKitClient.instance.isMySelf(uid) { addToAtUsers(addText: "@" + showName + "", isReply: true, accid: uid) } let user = viewmodel.getUserInfo(userId: uid) - if let alias = user?.alias { + if let alias = user?.alias, !alias.isEmpty { showName = alias } text += " " + showName } - text += ": " - switch message.messageType { - case .text: - if let t = message.text { - text += t - } - case .image: - text += "[\(chatLocalizable("msg_image"))]" - case .audio: - text += "[\(chatLocalizable("msg_audio"))]" - case .video: - text += "[\(chatLocalizable("msg_video"))]" - case .file: - text += "[\(chatLocalizable("msg_file"))]" - case .location: - text += "[\(chatLocalizable("msg_location"))]" - case .custom: - text += "[\(chatLocalizable("msg_custom"))]" - default: - text += "[\(chatLocalizable("msg_unknown"))]" - } + text += ": \(ChatMessageHelper.contentOfMessage(message))" getFunInputView()?.replyLabel.attributedText = NEEmotionTool.getAttWithStr(str: text, font: .systemFont(ofSize: 13), color: .ne_greyText) @@ -357,14 +319,31 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, } } - override open func didTapReadView(_ cell: UITableViewCell, _ model: MessageContentModel?) { - if let msg = model?.message, msg.session?.sessionType == .team { - let readVC = FunReadViewController(message: msg) - navigationController?.pushViewController(readVC, animated: true) + override open func getReadView(_ message: NIMMessage) -> NEBaseReadViewController { + FunReadViewController(message: message) + } + + override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + let model = viewmodel.messages[indexPath.row] + + if let contentModel = model as? MessageContentModel { + if let tipModel = model as? MessageTipsModel { + tipModel.commonInit() + return tipModel.cellHeight() + chat_content_margin + } + + if contentModel.type == .revoke { + if let time = contentModel.timeContent, !time.isEmpty { + return 28 + chat_timeCellH + } + return 28 + } } + + return model.cellHeight() } - public func getMessageModel(model: MessageModel) { + open func getMessageModel(model: MessageModel) { if model.type == .tip || model.type == .notification || model.type == .time { @@ -372,7 +351,7 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, tipModel.contentSize = String.getTextRectSize(tipModel.text ?? "", font: .systemFont(ofSize: 14), size: CGSize(width: chat_text_maxW, height: CGFloat.greatestFiniteMagnitude)) - tipModel.height = Float(max(tipModel.contentSize.height + chat_content_margin, 28)) + tipModel.height = max(tipModel.contentSize.height + chat_content_margin, 28) } return } @@ -402,4 +381,99 @@ open class FunChatViewController: ChatViewController, FunChatInputViewDelegate, getFunInputView()?.hideRecordMode() super.addToAtUsers(addText: addText, isReply: isReply, accid: accid, isLongPress) } + + // MARK: NEMutilSelectBottomViewDelegate + + override open func multiForwardForward(_ depth: Int) { + weak var weakSelf = self + if IMKitClient.instance.getConfigCenter().teamEnable { + let userAction = NECustomAlertAction(title: chatLocalizable("contact_user")) { + weakSelf?.forwardMessageToUser(isMultiForward: true, depth: depth) { + weakSelf?.cancelMutilSelect() + } + } + + let teamAction = NECustomAlertAction(title: chatLocalizable("team")) { + weakSelf?.forwardMessageToTeam(isMultiForward: true, depth: depth) { + weakSelf?.cancelMutilSelect() + } + } + + showCustomActionSheet([teamAction, userAction]) + } else { + forwardMessageToUser(isMultiForward: true, depth: depth) { + weakSelf?.cancelMutilSelect() + } + } + } + + override open func singleForward() { + weak var weakSelf = self + if IMKitClient.instance.getConfigCenter().teamEnable { + let userAction = NECustomAlertAction(title: chatLocalizable("contact_user")) { + weakSelf?.forwardMessageToUser { + weakSelf?.cancelMutilSelect() + } + } + + let teamAction = NECustomAlertAction(title: chatLocalizable("team")) { + weakSelf?.forwardMessageToTeam { + weakSelf?.cancelMutilSelect() + } + } + + showCustomActionSheet([teamAction, userAction]) + } else { + forwardMessageToUser { + weakSelf?.cancelMutilSelect() + } + } + } + + override open func expandButtonDidClick() { + super.expandButtonDidClick() + print("expandButtonDidClick ") + chatInputView.changeToMultipleLineStyle() + normalInputHeight = 295 + bottomViewTopAnchor?.constant = -normalInputHeight + } + + override open func didHideMultipleButtonClick() { + super.didHideMultipleButtonClick() + setInputValue() + layoutInputViewWithAnimation(offset: 0) + } + + override open func titleTextDidClearEmpty() { + if chatInputView.chatInpuMode == .multipleSend { + chatInputView.chatInpuMode = .normal + setInputValue() + chatInputView.restoreNormalInputStyle() + chatInputView.textView.becomeFirstResponder() + layoutInputViewWithAnimation(offset: currentKeyboardHeight) + } + } + + func setInputValue() { + if chatInputView.chatInpuMode == .normal { + normalInputHeight = 90 + } else if chatInputView.chatInpuMode == .multipleSend { + normalInputHeight = 130 + } + + if viewmodel.isReplying { + normalOffset = -30 + } else { + normalOffset = 0 + } + } + + // 不隐藏键盘 + override open func didHideMultiple() { + normalInputHeight = 90 + if currentKeyboardHeight > 0 { + normalOffset = 30 + } + layoutInputViewWithAnimation(offset: currentKeyboardHeight) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunForwardAlertViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunForwardAlertViewController.swift index e7baeaae..0d583f0d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunForwardAlertViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunForwardAlertViewController.swift @@ -8,7 +8,7 @@ import NECommonUIKit import UIKit @objcMembers -public class FunForwardUserCell: NEBaseForwardUserCell { +open class FunForwardUserCell: NEBaseForwardUserCell { override func setupUI() { super.setupUI() userHeader.layer.cornerRadius = 4 @@ -16,8 +16,8 @@ public class FunForwardUserCell: NEBaseForwardUserCell { } @objcMembers -public class FunForwardAlertViewController: NEBaseForwardAlertViewController { - override public func setupUI() { +open class FunForwardAlertViewController: NEBaseForwardAlertViewController { + override open func setupUI() { super.setupUI() tip.font = .systemFont(ofSize: 16, weight: .semibold) oneUserHead.layer.cornerRadius = 4.0 @@ -28,7 +28,7 @@ public class FunForwardAlertViewController: NEBaseForwardAlertViewController { ) } - override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "\(FunForwardUserCell.self)", for: indexPath diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunGroupChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunGroupChatViewController.swift index f52f99fa..33b4726b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunGroupChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunGroupChatViewController.swift @@ -2,13 +2,16 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit import NIMSDK import UIKit @objcMembers open class FunGroupChatViewController: FunChatViewController, TeamChatViewModelDelegate { - private var isLeaveTeamBySelf = false // 是否是主动退出群聊 + private var isLeaveTeamByOther = false // 是否被移出群聊 + private var isLeaveTeamBySelf = false // 是否多端登录另一端退出群聊 private var isdismissTeam = false // 群聊是否已解散 + private var isdismissDiscuss = false // 讨论组是否已解散 private var onCurrentPage = false // 是否位于聊天详情页 public init(session: NIMSession, anchor: NIMMessage?) { @@ -28,12 +31,30 @@ open class FunGroupChatViewController: FunChatViewController, TeamChatViewModelD fatalError("init(coder:) has not been implemented") } + deinit { + NotificationCenter.default.removeObserver(self) + } + override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) onCurrentPage = true - // 被动解散群聊 + + // 多端登录另一端解散、退出讨论组 + // 多端登录另一端退出群聊 + if isdismissDiscuss || isLeaveTeamBySelf { + popGroupChatVC() + } + + weak var weakSelf = self + // 被移除群聊 + if isLeaveTeamByOther { + showSingleAlert(message: chatLocalizable("team_has_been_quit")) { + weakSelf?.navigationController?.popViewController(animated: true) + } + } + + // 解散群聊 if isdismissTeam { - weak var weakSelf = self showSingleAlert(message: chatLocalizable("team_has_been_removed")) { weakSelf?.navigationController?.popViewController(animated: true) } @@ -47,7 +68,7 @@ open class FunGroupChatViewController: FunChatViewController, TeamChatViewModelD override open func viewDidLoad() { super.viewDidLoad() - NotificationCenter.default.addObserver(self, selector: #selector(leaveTeamBySelf), name: NotificationName.leaveTeamBySelf, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(popGroupChatVC), name: NENotificationName.popGroupChatVC, object: nil) } override open func getSessionInfo(session: NIMSession) { @@ -60,9 +81,21 @@ open class FunGroupChatViewController: FunChatViewController, TeamChatViewModelD // MARK: private method - func leaveTeamBySelf(noti: Notification) { - if let flag = noti.object as? Bool { - isLeaveTeamBySelf = flag + func popGroupChatVC() { + var beforeChat: UIViewController? + var loopCount = 0 + for vc in navigationController?.viewControllers ?? [] { + if vc.isKind(of: ChatViewController.self) { + if loopCount <= 1 { + navigationController?.popToRootViewController(animated: true) + return + } + navigationController?.popToViewController(beforeChat!, animated: true) + return + } else { + beforeChat = vc + loopCount += 1 + } } } @@ -79,51 +112,83 @@ open class FunGroupChatViewController: FunChatViewController, TeamChatViewModelD open func updateTeamInfo(team: NIMTeam) { title = team.getShowName() - if team.inAllMuteMode(), team.owner != NIMSDK.shared().loginManager.currentAccount() { + if team.inAllMuteMode(), viewmodel.teamMember?.type != .manager, viewmodel.teamMember?.type != .owner { // 群禁言 + isMute = true chatInputView.textView.attributedPlaceholder = getPlaceHolder(text: chatLocalizable("team_mute")) chatInputView.textView.backgroundColor = .funChatInputViewBackgroundColorInMute layoutInputView(offset: 0) getFunInputView()?.hideRecordMode() chatInputView.isUserInteractionEnabled = false + chatInputView.setMuteInputStyle() + if chatInputView.chatInpuMode != .normal { + chatInputView.titleField.text = nil + didHideMultipleButtonClick() + } + if getFunInputView()?.replyLabel.text?.count ?? 0 > 0 { + getFunInputView()?.hideReplyMode() + } } else { // 解除群禁言 + isMute = false chatInputView.textView.attributedPlaceholder = getPlaceHolder(text: chatLocalizable("fun_chat_input_placeholder")) chatInputView.textView.backgroundColor = .white chatInputView.isUserInteractionEnabled = true + chatInputView.setUnMuteInputStyle() } } - // MARK: TeamChatViewModelDelegate - - open func onTeamRemoved(team: NIMTeam) { - // 退出讨论组 - if team.isDisscuss() == true { - navigationController?.popViewController(animated: true) - return - } + override open func onRecvMessages(_ messages: [NIMMessage]) { + super.onRecvMessages(messages) + for message in messages { + if let object = message.messageObject as? NIMNotificationObject, + let content = object.content as? NIMTeamNotificationContent { + if content.operationType == .leave, + IMKitClient.instance.isMySelf(content.sourceID) { + isLeaveTeamBySelf = true + if onCurrentPage { + popGroupChatVC() + } + } else if content.operationType == .kick, + let targetIDs = content.targetIDs, + targetIDs.contains(IMKitClient.instance.imAccid()) { + // 被移出群聊 + isLeaveTeamByOther = true + if onCurrentPage { + showSingleAlert(message: chatLocalizable("team_has_been_quit")) { [weak self] in + self?.navigationController?.popViewController(animated: true) + } + } + } else if content.operationType == .dismiss { + if isdismissDiscuss { + return + } - // 离开群聊 - if team.teamId == viewmodel.session.sessionId { - if team.owner != NIMSDK.shared().loginManager.currentAccount() { // 退出群聊 - if isLeaveTeamBySelf { - navigationController?.popViewController(animated: true) - } else { + // 解散群聊 isdismissTeam = true - // 被动解散群聊 if onCurrentPage { - weak var weakSelf = self - showSingleAlert(message: chatLocalizable("team_has_been_removed")) { - weakSelf?.navigationController?.popViewController(animated: true) + showSingleAlert(message: chatLocalizable("team_has_been_removed")) { [weak self] in + self?.navigationController?.popViewController(animated: true) } } } - } else { // 主动解散 - navigationController?.popViewController(animated: true) } } } + // MARK: TeamChatViewModelDelegate + + open func onTeamRemoved(team: NIMTeam) { + // 多端登录另一端解散、退出讨论组 + if team.isDisscuss() == true { + isdismissDiscuss = true + if onCurrentPage { + popGroupChatVC() + } + return + } + } + open func onTeamUpdate(team: NIMTeam) { if team.teamId != viewmodel.session.sessionId { return @@ -131,7 +196,15 @@ open class FunGroupChatViewController: FunChatViewController, TeamChatViewModelD updateTeamInfo(team: team) } - public func onTeamMemberUpdate(team: NIMTeam) { + open func onTeamMemberUpdate(team: NIMTeam) { didRefreshTable() } + + override public func onTeamMemberChange(team: NIMTeam) { + if viewmodel.session.sessionId != team.teamId { + return + } + (viewmodel as? TeamChatViewModel)?.getTeamMember() + updateTeamInfo(team: team) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunMultiForwardViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunMultiForwardViewController.swift new file mode 100644 index 00000000..390085f0 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunMultiForwardViewController.swift @@ -0,0 +1,69 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonKit +import NIMSDK +import UIKit + +@objcMembers +open class FunMultiForwardViewController: MultiForwardViewController { + override public init(_ attachmentUrl: String?, + _ attachmentFilePath: String, + _ attachmentMD5: String?) { + super.init(attachmentUrl, attachmentFilePath, attachmentMD5) + brokenNetworkViewHeight = 48 + cellRegisterDic = ChatMessageHelper.getChatCellRegisterDic(isFun: true) + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .funChatBackgroundColor // 换肤颜色提取 + brokenNetworkView.errorIcon.isHidden = false + brokenNetworkView.backgroundColor = .funChatNetworkBrokenBackgroundColor + brokenNetworkView.content.textColor = .funChatNetworkBrokenTitleColor + navigationView.backgroundColor = .funChatBackgroundColor + navigationView.titleBarBottomLine.backgroundColor = .funChatNavigationBottomLineColor + } + + override open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + FunMultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } + + override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + viewmodel.messages[indexPath.row].cellHeight() + } + + open func getMessageModel(model: MessageModel) { + if model.type == .tip || + model.type == .notification || + model.type == .time { + if let tipModel = model as? MessageTipsModel { + tipModel.contentSize = String.getTextRectSize(tipModel.text ?? "", + font: .systemFont(ofSize: 14), + size: CGSize(width: chat_text_maxW, height: CGFloat.greatestFiniteMagnitude)) + tipModel.height = max(tipModel.contentSize.height + chat_content_margin, 28) + } + return + } + + let contentWidth = model.contentSize.width + let contentHeight = model.contentSize.height + if contentHeight < 42 { + let subHeight = 42 - contentHeight + model.contentSize = CGSize(width: contentWidth, height: 42) + model.offset = CGFloat(subHeight) + } + + if model.type == .rtcCallRecord { + model.contentSize = CGSize(width: contentWidth, height: contentHeight - 2) + model.offset = -2 + } + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunP2PChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunP2PChatViewController.swift index eb8282d6..733572a6 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunP2PChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunP2PChatViewController.swift @@ -21,7 +21,7 @@ open class FunP2PChatViewController: FunChatViewController { override open func getSessionInfo(session: NIMSession) { var showName = session.sessionId - viewmodel.getUserInfo(session.sessionId) { [weak self] user, error in + ChatUserCache.getUserInfo(session.sessionId) { [weak self] user, error in if let name = user?.showName() { showName = name } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunPinMessageViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunPinMessageViewController.swift index 7e87e147..1a942c49 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunPinMessageViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunPinMessageViewController.swift @@ -7,23 +7,23 @@ import UIKit @objcMembers open class FunPinMessageViewController: NEBasePinMessageViewController { - override public func viewDidLoad() { + override public init(session: NIMSession) { + super.init(session: session) + pin_content_maxW = (kScreenWidth - 32) + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .funChatBackgroundColor emptyView.setEmptyImage(name: "fun_user_empty") } - override open func getRegisterCellDic() -> [Int: NEBasePinMessageCell.Type] { - let cellClassDic = [ - NIMMessageType.text.rawValue: FunPinMessageTextCell.self, - NIMMessageType.image.rawValue: FunPinMessageImageCell.self, - NIMMessageType.audio.rawValue: FunPinMessageAudioCell.self, - NIMMessageType.video.rawValue: FunPinMessageVideoCell.self, - NIMMessageType.location.rawValue: FunPinMessageLocationCell.self, - NIMMessageType.file.rawValue: FunPinMessageFileCell.self, - PinMessageDefaultType: FunPinMessageDefaultCell.self, - ] - return cellClassDic + override open func getRegisterCellDic() -> [String: NEBasePinMessageCell.Type] { + ChatMessageHelper.getPinCellRegisterDic(isFun: true) } override open func showAction(item: PinMessageModel) { @@ -71,4 +71,10 @@ open class FunPinMessageViewController: NEBasePinMessageViewController { forwardMessageToUser(message) } } + + override open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + FunMultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunReadViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunReadViewController.swift index 513e8cfd..ccd2b5c8 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunReadViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunReadViewController.swift @@ -9,7 +9,7 @@ import UIKit @objcMembers open class FunReadViewController: NEBaseReadViewController { - override public func commonUI() { + override open func commonUI() { super.commonUI() navigationController?.navigationBar.backgroundColor = .white navigationView.backgroundColor = .white @@ -26,13 +26,13 @@ open class FunReadViewController: NEBaseReadViewController { emptyView.setEmptyImage(name: "fun_emptyView") } - override public func readButtonEvent(button: UIButton) { + override open func readButtonEvent(button: UIButton) { super.readButtonEvent(button: button) readButton.setTitleColor(UIColor.funChatThemeColor, for: .normal) unreadButton.setTitleColor(UIColor.ne_darkText, for: .normal) } - override public func unreadButtonEvent(button: UIButton) { + override open func unreadButtonEvent(button: UIButton) { super.unreadButtonEvent(button: button) readButton.setTitleColor(UIColor.ne_darkText, for: .normal) unreadButton.setTitleColor(UIColor.funChatThemeColor, for: .normal) diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunSelectUserViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunSelectUserViewController.swift index d02183e8..d7816365 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunSelectUserViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunSelectUserViewController.swift @@ -34,11 +34,11 @@ open class FunSelectUserViewController: NEBaseSelectUserViewController { withIdentifier: "\(FunChatTeamMemberCell.self)", for: indexPath ) as! FunChatTeamMemberCell - if indexPath.row == 0 { + if indexPath.section == 0 { cell.headerView.image = UIImage.ne_imageNamed(name: "fun_all") cell.nameLabel.text = chatLocalizable("user_select_all") } else { - if let model = teamInfo?.users[indexPath.row - 1] { + if let model = teamInfo?.users[indexPath.row] { cell.configure(model) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunUserSettingViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunUserSettingViewController.swift index f3994163..e53c3c03 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunUserSettingViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/Controller/FunUserSettingViewController.swift @@ -20,7 +20,7 @@ open class FunUserSettingViewController: NEBaseUserSettingViewController { fatalError("init(coder:) has not been implemented") } - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .funChatBackgroundColor viewmodel.cellDatas.forEach { cellModel in @@ -38,7 +38,7 @@ open class FunUserSettingViewController: NEBaseUserSettingViewController { contentTable.rowHeight = 56 } - override public func headerView() -> UIView { + override open func headerView() -> UIView { let header = UIView(frame: CGRect(x: 0, y: 0, width: view.width, height: 117)) header.backgroundColor = .clear let cornerBack = UIView() @@ -59,7 +59,7 @@ open class FunUserSettingViewController: NEBaseUserSettingViewController { tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 - if let url = viewmodel.userInfo?.userInfo?.avatarUrl { + if let url = viewmodel.userInfo?.userInfo?.avatarUrl, !url.isEmpty { userHeader.sd_setImage(with: URL(string: url), completed: nil) userHeader.setTitle("") userHeader.backgroundColor = .clear @@ -116,7 +116,7 @@ open class FunUserSettingViewController: NEBaseUserSettingViewController { return header } - override public func filterStackViewController() -> [UIViewController]? { + override open func filterStackViewController() -> [UIViewController]? { navigationController?.viewControllers.filter { if $0.isKind(of: FunP2PChatViewController.self) || $0 .isKind(of: FunUserSettingViewController.self) { diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatRouter.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatRouter.swift index 058971e3..bae3339b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatRouter.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatRouter.swift @@ -25,7 +25,8 @@ public extension ChatRouter { return } let anchor = param["anchor"] as? NIMMessage - var p2pChatVC = FunP2PChatViewController(session: session, anchor: anchor) + let p2pChatVC = FunP2PChatViewController(session: session, anchor: anchor) + for (i, vc) in (nav?.viewControllers ?? []).enumerated() { if vc.isKind(of: ChatViewController.self) { nav?.viewControllers[i] = p2pChatVC @@ -33,6 +34,11 @@ public extension ChatRouter { return } } + + if let remove = param["removeUserVC"] as? Bool, remove { + nav?.viewControllers.removeLast() + } + nav?.pushViewController(p2pChatVC, animated: true) } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatUIColor.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatUIColor.swift index 88f81456..08f003f8 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatUIColor.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/FunChatUIColor.swift @@ -26,4 +26,6 @@ public extension UIColor { static let funChatInputViewBackgroundColorInMute = UIColor(hexString: "#E0E0E0") static let funChatNetworkBrokenBackgroundColor = UIColor(hexString: "#FCEEEE") static let funChatNetworkBrokenTitleColor = UIColor(white: 0, alpha: 0.5) + + static let funChatMultiForwardContentColor = UIColor(hexString: "#BBBBBB") } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunChatInputView.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunChatInputView.swift index 80e94f83..38cc86cd 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunChatInputView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunChatInputView.swift @@ -11,6 +11,7 @@ let showPhotoTag = 2 @objc public protocol FunChatInputViewDelegate: NSObjectProtocol { func recordModeChangeDidClick() + func didHideRecordMode() func didHideReplyMode() func didShowReplyMode() // 内部状态转换的回调,上次是回复UI样式,转转成录音模式后再转换回来,还要保持回复样式,此场景下对外回调 } @@ -31,10 +32,18 @@ open class FunChatInputView: NEBaseChatInputView { var defaultReplyTopSpace: CGFloat = 8 + var multipleReplyTopSpace: CGFloat = 48 + + public var backViewHeightConstaint: NSLayoutConstraint? + + public var textViewTop: NSLayoutConstraint? + +// public var textViewHeight: NSLayoutConstraint? + public var replyBackView: UIView = { let back = UIView() back.translatesAutoresizingMaskIntoConstraints = false - back.layer.cornerRadius = 4.0 + back.layer.cornerRadius = 8.0 back.clipsToBounds = true back.backgroundColor = UIColor.funChatInputReplyBg return back @@ -111,23 +120,43 @@ open class FunChatInputView: NEBaseChatInputView { textView.layer.cornerRadius = 4.0 textView.delegate = self textviewLeftConstraint = textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 48) - textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -88) + textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -132) + textViewTop = textView.topAnchor.constraint(equalTo: topAnchor, constant: 8) NSLayoutConstraint.activate([ textviewLeftConstraint!, textviewRightConstraint!, - textView.topAnchor.constraint(equalTo: topAnchor, constant: 8), + textViewTop!, textView.heightAnchor.constraint(equalToConstant: 40), ]) textInput = textView - insertSubview(replyBackView, belowSubview: textView) + addSubview(expandButton) + NSLayoutConstraint.activate([ + expandButton.topAnchor.constraint(equalTo: topAnchor, constant: 8), + expandButton.rightAnchor.constraint(equalTo: rightAnchor, constant: -88), + expandButton.heightAnchor.constraint(equalToConstant: 40), + expandButton.widthAnchor.constraint(equalToConstant: 44.0), + ]) + expandButton.setImage(coreLoader.loadImage("fun_input_unfold"), for: .normal) + expandButton.addTarget(self, action: #selector(didClickExpandButton), for: .touchUpInside) + + backViewHeightConstaint = backView.heightAnchor.constraint(equalToConstant: 40) + insertSubview(backView, belowSubview: textView) + NSLayoutConstraint.activate([ + backView.leftAnchor.constraint(equalTo: leftAnchor, constant: 48), + backView.rightAnchor.constraint(equalTo: rightAnchor, constant: -88), + backView.topAnchor.constraint(equalTo: topAnchor, constant: 8), + backViewHeightConstaint!, + ]) + + insertSubview(replyBackView, belowSubview: backView) replyViewTopConstraint = replyBackView.topAnchor.constraint(equalTo: topAnchor, constant: defaultReplyTopSpace) NSLayoutConstraint.activate([ replyViewTopConstraint!, replyBackView.heightAnchor.constraint(equalToConstant: 40), - replyBackView.leftAnchor.constraint(equalTo: textView.leftAnchor), - replyBackView.rightAnchor.constraint(equalTo: textView.rightAnchor), + replyBackView.leftAnchor.constraint(equalTo: leftAnchor, constant: 48), + replyBackView.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: 0), ]) replyBackView.addSubview(replyLabel) @@ -201,12 +230,15 @@ open class FunChatInputView: NEBaseChatInputView { addSubview(holdToSpeakView) NSLayoutConstraint.activate([ - holdToSpeakView.leftAnchor.constraint(equalTo: textView.leftAnchor), - holdToSpeakView.rightAnchor.constraint(equalTo: textView.rightAnchor), - holdToSpeakView.topAnchor.constraint(equalTo: textView.topAnchor), - holdToSpeakView.bottomAnchor.constraint(equalTo: textView.bottomAnchor), + holdToSpeakView.leftAnchor.constraint(equalTo: leftAnchor, constant: 48), + holdToSpeakView.rightAnchor.constraint(equalTo: backView.rightAnchor), + holdToSpeakView.topAnchor.constraint(equalTo: backView.topAnchor), + holdToSpeakView.bottomAnchor.constraint(equalTo: backView.bottomAnchor), ]) holdToSpeakView.isHidden = true + + setupMultipleLineView() + multipleLineExpandButton.setImage(coreLoader.loadImage("fun_input_fold"), for: .normal) } open func changeToRecordMode(_ button: UIButton) { @@ -214,6 +246,7 @@ open class FunChatInputView: NEBaseChatInputView { if button.isSelected == true { showRecordMode() } else { + funDelegate?.didHideRecordMode() hideRecordMode() } } @@ -240,7 +273,11 @@ open class FunChatInputView: NEBaseChatInputView { } open func showReplyMode() { - replyViewTopConstraint?.constant = 52 + if chatInpuMode == .normal { + replyViewTopConstraint?.constant = 52 + } else { + replyViewTopConstraint?.constant = 90 + } if replyLabel.attributedText == nil { hideRecordMode() } else if let replyText = replyLabel.attributedText, replyText.length <= 0 { @@ -252,7 +289,11 @@ open class FunChatInputView: NEBaseChatInputView { if let topSpace = replyViewTopConstraint?.constant, topSpace == defaultReplyTopSpace { return } - replyViewTopConstraint?.constant = 8 + if chatInpuMode == .normal { + replyViewTopConstraint?.constant = 8 + } else { + replyViewTopConstraint?.constant = multipleReplyTopSpace + } funDelegate?.didHideReplyMode() } @@ -262,6 +303,9 @@ open class FunChatInputView: NEBaseChatInputView { @objc private func moreBtnClick() { + if changeRecordModeBtn.isSelected == true, chatInpuMode == .multipleSend { + funDelegate?.didHideRecordMode() + } hideRecordMode() changeRecordModeBtn.isSelected = false buttonEvent(button: showMoreActionBtn) @@ -269,8 +313,117 @@ open class FunChatInputView: NEBaseChatInputView { @objc private func emojBtnClick() { + if changeRecordModeBtn.isSelected == true, chatInpuMode == .multipleSend { + funDelegate?.didHideRecordMode() + } hideRecordMode() changeRecordModeBtn.isSelected = false buttonEvent(button: showEmojBtn) } + + override open func restoreNormalInputStyle() { + super.restoreNormalInputStyle() + + contentSubView?.isHidden = true + textView.returnKeyType = .send + textView.removeAllAutoLayout() + insertSubview(textView, belowSubview: holdToSpeakView) + textView.removeConstraints(textView.constraints) + + if chatInpuMode == .normal { + textviewLeftConstraint = textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 48) + textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -132) + textViewTop = textView.topAnchor.constraint(equalTo: topAnchor, constant: 8) + NSLayoutConstraint.activate([ + textviewLeftConstraint!, + textviewRightConstraint!, + textViewTop!, + textView.heightAnchor.constraint(equalToConstant: 40), + ]) + backViewHeightConstaint?.constant = 40 + if let replyText = replyLabel.attributedText, replyText.length > 0 { + replyViewTopConstraint?.constant = 51 + } else { + replyViewTopConstraint?.constant = defaultReplyTopSpace + } + } else if chatInpuMode == .multipleSend { + titleField.removeAllAutoLayout() + insertSubview(titleField, aboveSubview: backView) + NSLayoutConstraint.activate([ + titleField.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 4), + titleField.rightAnchor.constraint(equalTo: expandButton.leftAnchor, constant: 2), + titleField.topAnchor.constraint(equalTo: backView.topAnchor), + titleField.heightAnchor.constraint(equalToConstant: 40), + ]) + + textviewLeftConstraint = textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 48) + textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -132) + textViewTop = textView.topAnchor.constraint(equalTo: topAnchor, constant: 40) + + NSLayoutConstraint.activate([ + textviewLeftConstraint!, + textviewRightConstraint!, + textViewTop!, + textView.heightAnchor.constraint(equalToConstant: 40), + ]) + backViewHeightConstaint?.constant = 80 + if let replyText = replyLabel.attributedText, replyText.length > 0 { + replyViewTopConstraint?.constant = 90 + } else { + replyViewTopConstraint?.constant = multipleReplyTopSpace + } + } + } + + override open func changeToMultipleLineStyle() { + super.changeToMultipleLineStyle() + textView.removeAllAutoLayout() + textView.returnKeyType = .default + multipleLineView.addSubview(textView) + NSLayoutConstraint.activate([ + textView.leftAnchor.constraint(equalTo: multipleLineView.leftAnchor, constant: 13), + textView.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: -16), + textView.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 48), + textView.heightAnchor.constraint(equalToConstant: 183), + ]) + + if titleField.superview == nil || titleField.superview != multipleLineView { + titleField.removeAllAutoLayout() + multipleLineView.addSubview(titleField) + NSLayoutConstraint.activate([ + titleField.leftAnchor.constraint(equalTo: multipleLineView.leftAnchor, constant: 16), + titleField.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: -56), + titleField.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 5), + titleField.heightAnchor.constraint(equalToConstant: 40), + ]) + } + } + + override open func setMuteInputStyle() { + super.setMuteInputStyle() + backView.backgroundColor = .funChatInputViewBackgroundColorInMute + } + + override open func setUnMuteInputStyle() { + super.setUnMuteInputStyle() + backView.backgroundColor = .white + } + + // 多行输入模式下进入录音模式,切换回单行样式 + open func setRecordNormalStyle() { + backViewHeightConstaint?.constant = 40 + textViewTop?.constant = 8 + replyViewTopConstraint?.constant = defaultReplyTopSpace + } + + // 从录音模式切换回多行模式 + open func resotreMutipleModeFromRecordMode() { + backViewHeightConstaint?.constant = 80 + textViewTop?.constant = 40 + if let replyText = replyLabel.attributedText, replyText.length > 0 { + replyViewTopConstraint?.constant = 90 + } else { + replyViewTopConstraint?.constant = multipleReplyTopSpace + } + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunRecordAudioView.swift b/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunRecordAudioView.swift index 5c66cc9f..8b298f69 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunRecordAudioView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/FunUI/View/FunRecordAudioView.swift @@ -219,7 +219,7 @@ open class FunRecordAudioView: UIView { return windowWidth / 375.0 * 128.0 } - public func changeToCancelStyle() { + open func changeToCancelStyle() { if releaseToSendLabel.isHidden == true { return } @@ -231,7 +231,7 @@ open class FunRecordAudioView: UIView { triangleView.backgroundColor = UIColor.funRecordAudioProgressCancelColor } - public func changeToNormalStyle() { + open func changeToNormalStyle() { if releaseToSendLabel.isHidden == false { return } @@ -243,7 +243,7 @@ open class FunRecordAudioView: UIView { triangleView.backgroundColor = UIColor.funRecordAudioProgressNormalColor } - public func isRecordNormalStyle() -> Bool { + open func isRecordNormalStyle() -> Bool { if releaseToSendLabel.isHidden == false { return true } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageAudioCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageAudioCell.swift index 4948d4d4..7bf3d4be 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageAudioCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageAudioCell.swift @@ -131,11 +131,8 @@ open class ChatMessageAudioCell: NormalChatMessageBaseCell, ChatAudioCellProtoco timeLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) if let m = model as? MessageAudioModel { if isSend { timeLabelRight.text = "\(m.duration)" + "s" diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageCallCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageCallCell.swift index 7cb6175b..b77bd2ad 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageCallCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageCallCell.swift @@ -66,14 +66,11 @@ open class ChatMessageCallCell: NormalChatMessageBaseCell { contentLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) if let m = model as? MessageCallRecordModel { - if let isSend = model.message?.isOutgoingMsg, isSend { - contentLabelRight.attributedText = m.attributeStr - return - } - contentLabelLeft.attributedText = m.attributeStr + let contentLabel = isSend ? contentLabelRight : contentLabelLeft + contentLabel.attributedText = m.attributeStr } } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageFileCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageFileCell.swift index 361cdc24..619af615 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageFileCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageFileCell.swift @@ -23,6 +23,7 @@ open class ChatMessageFileCell: NormalChatMessageBaseCell { let state = FileStateView() state.translatesAutoresizingMaskIntoConstraints = false state.backgroundColor = .clear + state.accessibilityIdentifier = "id.fileStatus" return state }() @@ -81,6 +82,7 @@ open class ChatMessageFileCell: NormalChatMessageBaseCell { let state = FileStateView() state.translatesAutoresizingMaskIntoConstraints = false state.backgroundColor = .clear + state.accessibilityIdentifier = "id.fileStatus" return state }() @@ -156,10 +158,10 @@ open class ChatMessageFileCell: NormalChatMessageBaseCell { imgViewLeft.heightAnchor.constraint(equalToConstant: 32), ]) - contentView.addSubview(stateViewLeft) + imgViewLeft.addSubview(stateViewLeft) NSLayoutConstraint.activate([ - stateViewLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: 10), - stateViewLeft.topAnchor.constraint(equalTo: bubbleImageLeft.topAnchor, constant: 10), + stateViewLeft.leftAnchor.constraint(equalTo: imgViewLeft.leftAnchor, constant: 0), + stateViewLeft.topAnchor.constraint(equalTo: imgViewLeft.topAnchor, constant: 0), stateViewLeft.widthAnchor.constraint(equalToConstant: 32), stateViewLeft.heightAnchor.constraint(equalToConstant: 32), ]) @@ -188,10 +190,10 @@ open class ChatMessageFileCell: NormalChatMessageBaseCell { imgViewRight.heightAnchor.constraint(equalToConstant: 32), ]) - contentView.addSubview(stateViewRight) + imgViewRight.addSubview(stateViewRight) NSLayoutConstraint.activate([ - stateViewRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: 10), - stateViewRight.topAnchor.constraint(equalTo: bubbleImageRight.topAnchor, constant: 10), + stateViewRight.leftAnchor.constraint(equalTo: imgViewRight.leftAnchor, constant: 0), + stateViewRight.topAnchor.constraint(equalTo: imgViewRight.topAnchor, constant: 0), stateViewRight.widthAnchor.constraint(equalToConstant: 32), stateViewRight.heightAnchor.constraint(equalToConstant: 32), ]) @@ -216,11 +218,8 @@ open class ChatMessageFileCell: NormalChatMessageBaseCell { labelViewRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let stateView = isSend ? stateViewRight : stateViewLeft let imgView = isSend ? imgViewRight : imgViewLeft let titleLabel = isSend ? titleLabelRight : titleLabelLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageImageCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageImageCell.swift index 2f01c523..f1d21e87 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageImageCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageImageCell.swift @@ -75,11 +75,8 @@ open class ChatMessageImageCell: NormalChatMessageBaseCell { contentImageViewRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentImageView = isSend ? contentImageViewRight : contentImageViewLeft if let m = model as? MessageImageModel, let imageUrl = m.imageUrl { @@ -92,7 +89,8 @@ open class ChatMessageImageCell: NormalChatMessageBaseCell { completed: nil ) } else { - contentImageView.image = UIImage(contentsOfFile: imageUrl) + let url = URL(fileURLWithPath: imageUrl) + contentImageView.sd_setImage(with: url) } } else { contentImageView.image = nil diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageLocationCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageLocationCell.swift index dfe0b813..b7305f54 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageLocationCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageLocationCell.swift @@ -93,6 +93,7 @@ open class ChatMessageLocationCell: NormalChatMessageBaseCell { backgroundViewLeft.layer.cornerRadius = 4 backgroundViewLeft.layer.borderWidth = 1 backgroundViewLeft.layer.borderColor = UIColor.ne_outlineColor.cgColor + backgroundViewLeft.accessibilityIdentifier = "id.mapView" let messageLongPress = UILongPressGestureRecognizer( target: self, @@ -108,6 +109,7 @@ open class ChatMessageLocationCell: NormalChatMessageBaseCell { ]) let messageTap = UITapGestureRecognizer(target: self, action: #selector(tapMessage)) + messageTap.cancelsTouchesInView = false backgroundViewLeft.addGestureRecognizer(messageTap) backgroundViewLeft.addSubview(titleLabelLeft) @@ -162,6 +164,8 @@ open class ChatMessageLocationCell: NormalChatMessageBaseCell { backgroundViewRight.layer.cornerRadius = 4 backgroundViewRight.layer.borderWidth = 1 backgroundViewRight.layer.borderColor = UIColor.ne_outlineColor.cgColor + backgroundViewRight.accessibilityIdentifier = "id.mapView" + let messageLongPress = UILongPressGestureRecognizer( target: self, action: #selector(longPress) @@ -175,6 +179,7 @@ open class ChatMessageLocationCell: NormalChatMessageBaseCell { backgroundViewRight.bottomAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor), ]) let messageTap = UITapGestureRecognizer(target: self, action: #selector(tapMessage)) + messageTap.cancelsTouchesInView = false backgroundViewRight.addGestureRecognizer(messageTap) backgroundViewRight.addSubview(titleLabelRight) @@ -226,11 +231,8 @@ open class ChatMessageLocationCell: NormalChatMessageBaseCell { backgroundViewRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let titleLabel = isSend ? titleLabelRight : titleLabelLeft let subTitleLabel = isSend ? subTitleLabelRight : subTitleLabelLeft let mapView = isSend ? mapViewRight : mapViewLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageMultiForwardCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageMultiForwardCell.swift new file mode 100644 index 00000000..587fd1ff --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageMultiForwardCell.swift @@ -0,0 +1,382 @@ + +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonKit +import NIMSDK +import UIKit + +@objcMembers +open class ChatMessageMultiForwardCell: NormalChatMessageBaseCell { + let contentWidth: CGFloat = 234 + let titleLabelFontSize: CGFloat = 14 + override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + setupUI() + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + open func setupUI() { + setupUIRight() + setupUILeft() + } + + open func setupUILeft() { + bubbleImageLeft.image = nil + let image = UIImage.ne_imageNamed(name: "multiForward_message_receive") + backViewLeft.image = image? + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) + bubbleImageLeft.addSubview(backViewLeft) + NSLayoutConstraint.activate([ + backViewLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor), + backViewLeft.topAnchor.constraint(equalTo: bubbleImageLeft.topAnchor), + backViewLeft.bottomAnchor.constraint(equalTo: bubbleImageLeft.bottomAnchor), + backViewLeft.rightAnchor.constraint(equalTo: bubbleImageLeft.rightAnchor), + ]) + + backViewLeft.addSubview(titleLabelLeft1) + NSLayoutConstraint.activate([ + titleLabelLeft1.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: 16), + titleLabelLeft1.rightAnchor.constraint(lessThanOrEqualTo: backViewLeft.rightAnchor, constant: -84), + titleLabelLeft1.topAnchor.constraint(equalTo: backViewLeft.topAnchor, constant: 10), + titleLabelLeft1.heightAnchor.constraint(equalToConstant: 22), + ]) + + backViewLeft.addSubview(titleLabelLeft2) + NSLayoutConstraint.activate([ + titleLabelLeft2.leftAnchor.constraint(equalTo: titleLabelLeft1.rightAnchor), + titleLabelLeft2.centerYAnchor.constraint(equalTo: titleLabelLeft1.centerYAnchor), + titleLabelLeft2.heightAnchor.constraint(equalToConstant: 22), + titleLabelLeft2.widthAnchor.constraint(equalToConstant: 74), + ]) + + backViewLeft.addSubview(contentLabelLeft1) + NSLayoutConstraint.activate([ + contentLabelLeft1.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), + contentLabelLeft1.topAnchor.constraint(equalTo: titleLabelLeft1.bottomAnchor, constant: 2), + contentLabelLeft1.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelLeft1.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft2) + NSLayoutConstraint.activate([ + contentLabelLeft2.leftAnchor.constraint(equalTo: contentLabelLeft1.leftAnchor), + contentLabelLeft2.topAnchor.constraint(equalTo: contentLabelLeft1.bottomAnchor), + contentLabelLeft2.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelLeft2.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft3) + NSLayoutConstraint.activate([ + contentLabelLeft3.leftAnchor.constraint(equalTo: contentLabelLeft2.leftAnchor), + contentLabelLeft3.topAnchor.constraint(equalTo: contentLabelLeft2.bottomAnchor), + contentLabelLeft3.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelLeft3.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentHistoryLeft) + NSLayoutConstraint.activate([ + contentHistoryLeft.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), + contentHistoryLeft.bottomAnchor.constraint(equalTo: backViewLeft.bottomAnchor, constant: -12), + contentHistoryLeft.widthAnchor.constraint(equalToConstant: 60), + contentHistoryLeft.heightAnchor.constraint(equalToConstant: 14), + ]) + + backViewLeft.addSubview(dividerLineLeft) + NSLayoutConstraint.activate([ + dividerLineLeft.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: 6), + dividerLineLeft.rightAnchor.constraint(equalTo: backViewLeft.rightAnchor, constant: -6), + dividerLineLeft.topAnchor.constraint(equalTo: contentHistoryLeft.topAnchor, constant: -6), + dividerLineLeft.heightAnchor.constraint(equalToConstant: 1), + ]) + } + + open func setupUIRight() { + bubbleImageRight.image = nil + let image = UIImage.ne_imageNamed(name: "multiForward_message_send") + backViewRight.image = image? + .resizableImage(withCapInsets: NEKitChatConfig.shared.ui.messageProperties.backgroundImageCapInsets) + bubbleImageRight.addSubview(backViewRight) + NSLayoutConstraint.activate([ + backViewRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor), + backViewRight.topAnchor.constraint(equalTo: bubbleImageRight.topAnchor), + backViewRight.bottomAnchor.constraint(equalTo: bubbleImageRight.bottomAnchor), + backViewRight.rightAnchor.constraint(equalTo: bubbleImageRight.rightAnchor), + ]) + + backViewRight.addSubview(titleLabelRight1) + NSLayoutConstraint.activate([ + titleLabelRight1.leftAnchor.constraint(equalTo: backViewRight.leftAnchor, constant: 16), + titleLabelRight1.rightAnchor.constraint(lessThanOrEqualTo: backViewRight.rightAnchor, constant: -84), + titleLabelRight1.topAnchor.constraint(equalTo: backViewRight.topAnchor, constant: 10), + titleLabelRight1.heightAnchor.constraint(equalToConstant: 22), + ]) + + backViewRight.addSubview(titleLabelRight2) + NSLayoutConstraint.activate([ + titleLabelRight2.leftAnchor.constraint(equalTo: titleLabelRight1.rightAnchor), + titleLabelRight2.centerYAnchor.constraint(equalTo: titleLabelRight1.centerYAnchor), + titleLabelRight2.heightAnchor.constraint(equalToConstant: 22), + titleLabelRight2.widthAnchor.constraint(equalToConstant: 74), + ]) + + backViewRight.addSubview(contentLabelRight1) + NSLayoutConstraint.activate([ + contentLabelRight1.leftAnchor.constraint(equalTo: titleLabelRight1.leftAnchor), + contentLabelRight1.topAnchor.constraint(equalTo: titleLabelRight1.bottomAnchor, constant: 2), + contentLabelRight1.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelRight1.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewRight.addSubview(contentLabelRight2) + NSLayoutConstraint.activate([ + contentLabelRight2.leftAnchor.constraint(equalTo: contentLabelRight1.leftAnchor), + contentLabelRight2.topAnchor.constraint(equalTo: contentLabelRight1.bottomAnchor), + contentLabelRight2.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelRight2.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewRight.addSubview(contentLabelRight3) + NSLayoutConstraint.activate([ + contentLabelRight3.leftAnchor.constraint(equalTo: contentLabelRight2.leftAnchor), + contentLabelRight3.topAnchor.constraint(equalTo: contentLabelRight2.bottomAnchor), + contentLabelRight3.widthAnchor.constraint(equalToConstant: contentWidth), + contentLabelRight3.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewRight.addSubview(contentHistoryRight) + NSLayoutConstraint.activate([ + contentHistoryRight.leftAnchor.constraint(equalTo: titleLabelRight1.leftAnchor), + contentHistoryRight.bottomAnchor.constraint(equalTo: backViewRight.bottomAnchor, constant: -12), + contentHistoryRight.widthAnchor.constraint(equalToConstant: 60), + contentHistoryRight.heightAnchor.constraint(equalToConstant: 14), + ]) + + backViewRight.addSubview(dividerLineRight) + NSLayoutConstraint.activate([ + dividerLineRight.leftAnchor.constraint(equalTo: backViewRight.leftAnchor, constant: 6), + dividerLineRight.rightAnchor.constraint(equalTo: backViewRight.rightAnchor, constant: -6), + dividerLineRight.topAnchor.constraint(equalTo: contentHistoryRight.topAnchor, constant: -6), + dividerLineRight.heightAnchor.constraint(equalToConstant: 1), + ]) + } + + override open func showLeftOrRight(showRight: Bool) { + super.showLeftOrRight(showRight: showRight) + } + + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) + guard let data = NECustomAttachment.dataOfCustomMessage(message: model.message) else { + return + } + + let font = UIFont.systemFont(ofSize: titleLabelFontSize) + let bubbleW = isSend ? bubbleWRight : bubbleWLeft + let bubbleH = isSend ? bubbleHRight : bubbleHLeft + let titleLabel = isSend ? titleLabelRight1 : titleLabelLeft1 + let titleLabel2 = isSend ? titleLabelRight2 : titleLabelLeft2 + let contentLabel1 = isSend ? contentLabelRight1 : contentLabelLeft1 + let contentLabel2 = isSend ? contentLabelRight2 : contentLabelLeft2 + let contentLabel3 = isSend ? contentLabelRight3 : contentLabelLeft3 + + bubbleW?.constant = 266 + bubbleH?.constant = 130 + + if let sessionName = data["sessionName"] as? String { + titleLabel.attributedText = + NEEmotionTool.getAttWithStr(str: sessionName, + font: .systemFont(ofSize: titleLabelFontSize, weight: .semibold), + color: .ne_darkText) + } else { + titleLabel2.text = chatLocalizable("chat_history") + } + + guard let abstracts = data["abstracts"] as? [[String: Any]] else { return } + + contentLabel2.attributedText = nil + contentLabel3.attributedText = nil + for i in 0 ..< abstracts.count { + var contentLabel = contentLabel1 + if i == 1 { + contentLabel = contentLabel2 + } else if i == 2 { + contentLabel = contentLabel3 + } + + var contentText = "" + if var senderNick = abstracts[i]["senderNick"] as? String { + if senderNick.count > 5 { + // 截取字符串 abcdefg -> ab...fg + let leftEndIndex = senderNick.index(senderNick.startIndex, offsetBy: 2) + let rightStartIndex = senderNick.index(senderNick.endIndex, offsetBy: -2) + senderNick = senderNick[senderNick.startIndex ..< leftEndIndex] + "..." + senderNick[rightStartIndex ..< senderNick.endIndex] + } + contentText = senderNick + if let content = abstracts[i]["content"] as? String { + contentText += ":" + content + } + } + + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.lineSpacing = 1 // 设置行间距 + paragraphStyle.lineBreakMode = .byTruncatingTail + let attributedText = NEEmotionTool.getAttWithStr(str: contentText, + font: font, + color: .ne_lightText) + attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedText.length)) + contentLabel.attributedText = attributedText + } + + let numCount1 = String.calculateMaxLines(width: contentWidth, + attributeString: contentLabel1.attributedText, + font: font) + if numCount1 == 1 { + contentLabel2.numberOfLines = 2 + contentLabel2.isHidden = contentLabel2.attributedText == nil + let numCount2 = String.calculateMaxLines(width: contentWidth, + attributeString: contentLabel2.attributedText, + font: font) + contentLabel3.isHidden = contentLabel3.attributedText == nil || numCount2 >= 2 + } else if numCount1 == 2 { + contentLabel2.numberOfLines = 1 + contentLabel2.isHidden = contentLabel2.attributedText == nil + contentLabel3.isHidden = true + } else { + contentLabel2.isHidden = true + contentLabel3.isHidden = true + } + } + + // MARK: - lazy load + + public lazy var backViewLeft: UIImageView = { + let view = UIImageView() + view.translatesAutoresizingMaskIntoConstraints = false + return view + }() + + public lazy var titleLabelLeft1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.name1" + return label + }() + + public lazy var titleLabelLeft2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("chat_history_by") + label.textColor = .ne_darkText + label.font = .systemFont(ofSize: titleLabelFontSize, weight: .semibold) + label.accessibilityIdentifier = "id.name2" + return label + }() + + public lazy var contentLabelLeft1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 3 + label.accessibilityIdentifier = "id.content1" + return label + }() + + public lazy var contentLabelLeft2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 2 + label.accessibilityIdentifier = "id.content2" + return label + }() + + public lazy var contentLabelLeft3: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.content3" + return label + }() + + public lazy var dividerLineLeft: UIView = { + let line = UIView() + line.translatesAutoresizingMaskIntoConstraints = false + line.backgroundColor = multiForwardLineColor + return line + }() + + public lazy var contentHistoryLeft: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.font = .systemFont(ofSize: 12) + label.textColor = .ne_lightText + label.text = chatLocalizable("chat_history") + label.accessibilityIdentifier = "id.contentHistoryLeft" + return label + }() + + public lazy var backViewRight: UIImageView = { + let view = UIImageView() + view.translatesAutoresizingMaskIntoConstraints = false + return view + }() + + public lazy var titleLabelRight1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.name1" + return label + }() + + public lazy var titleLabelRight2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = chatLocalizable("chat_history_by") + label.textColor = .ne_darkText + label.font = .systemFont(ofSize: titleLabelFontSize, weight: .semibold) + label.accessibilityIdentifier = "id.name2" + return label + }() + + public lazy var contentLabelRight1: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 3 + label.accessibilityIdentifier = "id.content1" + return label + }() + + public lazy var contentLabelRight2: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.numberOfLines = 2 + label.accessibilityIdentifier = "id.content2" + return label + }() + + public lazy var contentLabelRight3: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.accessibilityIdentifier = "id.content3" + return label + }() + + public lazy var dividerLineRight: UIView = { + let line = UIView() + line.translatesAutoresizingMaskIntoConstraints = false + line.backgroundColor = multiForwardLineColor + return line + }() + + public lazy var contentHistoryRight: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.font = .systemFont(ofSize: 12) + label.textColor = .ne_lightText + label.text = chatLocalizable("chat_history") + label.accessibilityIdentifier = "id.contentHistoryRight" + return label + }() +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageReplyCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageReplyCell.swift index 30ff3250..7a38dfa1 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageReplyCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageReplyCell.swift @@ -11,8 +11,8 @@ open class ChatMessageReplyCell: ChatMessageTextCell { let replyLabel = UILabel() replyLabel.font = UIFont.systemFont(ofSize: 13) replyLabel.textColor = UIColor(hexString: "#929299") - replyLabel.textAlignment = .justified replyLabel.translatesAutoresizingMaskIntoConstraints = false + replyLabel.accessibilityIdentifier = "id.messageReply" return replyLabel }() @@ -20,8 +20,8 @@ open class ChatMessageReplyCell: ChatMessageTextCell { let replyLabel = UILabel() replyLabel.font = UIFont.systemFont(ofSize: 13) replyLabel.textColor = UIColor(hexString: "#929299") - replyLabel.textAlignment = .justified replyLabel.translatesAutoresizingMaskIntoConstraints = false + replyLabel.accessibilityIdentifier = "id.messageReply" return replyLabel }() @@ -81,15 +81,12 @@ open class ChatMessageReplyCell: ChatMessageTextCell { replyLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { let replyLabel = isSend ? replyLabelRight : replyLabelLeft if let text = model.replyText, let font = replyLabel.font { - replyLabel.attributedText = NEEmotionTool.getAttWithStr(str: text, + replyLabel.attributedText = NEEmotionTool.getAttWithStr(str: "| " + text, font: font, color: replyLabel.textColor) if let attriText = replyLabel.attributedText { @@ -98,6 +95,6 @@ open class ChatMessageReplyCell: ChatMessageTextCell { } } - super.setModel(model) + super.setModel(model, isSend) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRevokeCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRevokeCell.swift index 2960f211..0ed2ed6d 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRevokeCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRevokeCell.swift @@ -37,6 +37,7 @@ open class ChatMessageRevokeCell: NormalChatMessageBaseCell { revokeLabelLeft.translatesAutoresizingMaskIntoConstraints = false revokeLabelLeft.textColor = UIColor.ne_greyText revokeLabelLeft.font = UIFont.systemFont(ofSize: 16.0) + revokeLabelLeft.accessibilityIdentifier = "id.messageText" bubbleImageLeft.addSubview(revokeLabelLeft) NSLayoutConstraint.activate([ revokeLabelLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: 16), @@ -50,6 +51,7 @@ open class ChatMessageRevokeCell: NormalChatMessageBaseCell { revokeLabelRight.translatesAutoresizingMaskIntoConstraints = false revokeLabelRight.textColor = UIColor.ne_greyText revokeLabelRight.font = UIFont.systemFont(ofSize: 16.0) + revokeLabelRight.accessibilityIdentifier = "id.messageText" bubbleImageRight.addSubview(revokeLabelRight) NSLayoutConstraint.activate([ revokeLabelRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: 16), @@ -59,6 +61,7 @@ open class ChatMessageRevokeCell: NormalChatMessageBaseCell { ]) reeditButton.translatesAutoresizingMaskIntoConstraints = false + reeditButton.accessibilityIdentifier = "id.reeditButton" reeditButton.setImage(UIImage.ne_imageNamed(name: "right_arrow"), for: .normal) reeditButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0) reeditButton.setTitleColor(UIColor.ne_blueText, for: .normal) @@ -80,6 +83,10 @@ open class ChatMessageRevokeCell: NormalChatMessageBaseCell { super.showLeftOrRight(showRight: showRight) revokeLabelLeft.isHidden = showRight revokeLabelRight.isHidden = !showRight +// reeditButton.isHidden = !showRight + + activityView.isHidden = true + readView.isHidden = true seletedBtn.isHidden = true pinLabelLeft.isHidden = true pinImageLeft.isHidden = true @@ -87,7 +94,7 @@ open class ChatMessageRevokeCell: NormalChatMessageBaseCell { pinImageRight.isHidden = true } - override open func setModel(_ model: MessageContentModel) { + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { if let time = model.message?.timestamp { let date = Date() let currentTime = date.timeIntervalSince1970 @@ -95,24 +102,22 @@ open class ChatMessageRevokeCell: NormalChatMessageBaseCell { model.timeOut = true } } - if let isSend = model.message?.isOutgoingMsg, isSend, model.isRevokedText == true, model.timeOut == false { + if isSend, + model.isRevokedText == true, + model.timeOut == false { reeditButtonW?.constant = 86 reeditButton.isHidden = false + reeditButton.setTitle(chatLocalizable("message_reedit"), for: .normal) model.contentSize = CGSize(width: 218, height: chat_min_h) } else { reeditButtonW?.constant = 0 reeditButton.isHidden = true model.contentSize = CGSize(width: 130, height: chat_min_h) } - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + super.setModel(model, isSend) let revokeLabel = isSend ? revokeLabelRight : revokeLabelLeft - - revokeLabel.text = chatLocalizable("message_has_be_withdrawn") - reeditButton.setTitle(chatLocalizable("message_reedit"), for: .normal) + revokeLabel.text = chatLocalizable("message_recalled") } func reeditEvent(button: UIButton) { diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRichTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRichTextCell.swift new file mode 100644 index 00000000..b6c4956f --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageRichTextCell.swift @@ -0,0 +1,134 @@ + +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class ChatMessageRichTextCell: ChatMessageReplyCell { + public lazy var titleLabelLeft: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.isEnabled = false + label.numberOfLines = 0 + label.isUserInteractionEnabled = false + label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize, weight: .semibold) + label.backgroundColor = .clear + label.accessibilityIdentifier = "id.messageTitle" + return label + }() + + public lazy var titleLabelRight: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.isEnabled = false + label.numberOfLines = 0 + label.isUserInteractionEnabled = false + label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize, weight: .semibold) + label.backgroundColor = .clear + label.accessibilityIdentifier = "id.messageTitle" + return label + }() + + public var replyLabelLeftHeightAnchor: NSLayoutConstraint? + public var replyLabelRightHeightAnchor: NSLayoutConstraint? + public var titleLabelLeftTopAnchor: NSLayoutConstraint? + public var titleLabelLeftHeightAnchor: NSLayoutConstraint? + public var titleLabelRightTopAnchor: NSLayoutConstraint? + public var titleLabelRightHeightAnchor: NSLayoutConstraint? + public var contentLabelLeftHeightAnchor: NSLayoutConstraint? + public var contentLabelRightHeightAnchor: NSLayoutConstraint? + + override open func commonUI() { + /// left + bubbleImageLeft.addSubview(replyLabelLeft) + replyLabelLeftHeightAnchor = replyLabelLeft.heightAnchor.constraint(equalToConstant: 16.0) + NSLayoutConstraint.activate([ + replyLabelLeft.leadingAnchor.constraint(equalTo: bubbleImageLeft.leadingAnchor, constant: chat_content_margin), + replyLabelLeft.topAnchor.constraint(equalTo: bubbleImageLeft.topAnchor, constant: chat_content_margin), + replyLabelLeftHeightAnchor!, + replyLabelLeft.trailingAnchor.constraint(equalTo: bubbleImageLeft.trailingAnchor, constant: -chat_content_margin), + ]) + + bubbleImageLeft.addSubview(titleLabelLeft) + titleLabelLeftTopAnchor = titleLabelLeft.topAnchor.constraint(equalTo: replyLabelLeft.bottomAnchor, constant: chat_content_margin) + titleLabelLeftHeightAnchor = titleLabelLeft.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + titleLabelLeft.rightAnchor.constraint(equalTo: bubbleImageLeft.rightAnchor, constant: -chat_content_margin), + titleLabelLeft.leftAnchor.constraint(equalTo: bubbleImageLeft.leftAnchor, constant: chat_content_margin), + titleLabelLeftTopAnchor!, + titleLabelLeftHeightAnchor!, + ]) + + bubbleImageLeft.addSubview(contentLabelLeft) + contentLabelLeftHeightAnchor = contentLabelLeft.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + contentLabelLeft.rightAnchor.constraint(equalTo: titleLabelLeft.rightAnchor, constant: 0), + contentLabelLeft.leftAnchor.constraint(equalTo: titleLabelLeft.leftAnchor, constant: 0), + contentLabelLeft.topAnchor.constraint(equalTo: titleLabelLeft.bottomAnchor, constant: chat_content_margin), + contentLabelLeftHeightAnchor!, + ]) + + /// right + bubbleImageRight.addSubview(replyLabelRight) + replyLabelRightHeightAnchor = replyLabelRight.heightAnchor.constraint(equalToConstant: 16.0) + NSLayoutConstraint.activate([ + replyLabelRight.leadingAnchor.constraint(equalTo: bubbleImageRight.leadingAnchor, constant: chat_content_margin), + replyLabelRight.topAnchor.constraint(equalTo: bubbleImageRight.topAnchor, constant: chat_content_margin), + replyLabelRightHeightAnchor!, + replyLabelRight.trailingAnchor.constraint(equalTo: bubbleImageRight.trailingAnchor, constant: -chat_content_margin), + ]) + + bubbleImageRight.addSubview(titleLabelRight) + titleLabelRightTopAnchor = titleLabelRight.topAnchor.constraint(equalTo: replyLabelRight.bottomAnchor, constant: chat_content_margin) + titleLabelRightHeightAnchor = titleLabelRight.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + titleLabelRight.rightAnchor.constraint(equalTo: bubbleImageRight.rightAnchor, constant: -chat_content_margin), + titleLabelRight.leftAnchor.constraint(equalTo: bubbleImageRight.leftAnchor, constant: chat_content_margin), + titleLabelRightTopAnchor!, + titleLabelRightHeightAnchor!, + ]) + + bubbleImageRight.addSubview(contentLabelRight) + contentLabelRightHeightAnchor = contentLabelRight.heightAnchor.constraint(equalToConstant: CGFloat.greatestFiniteMagnitude) + NSLayoutConstraint.activate([ + contentLabelRight.rightAnchor.constraint(equalTo: titleLabelRight.rightAnchor, constant: -0), + contentLabelRight.leftAnchor.constraint(equalTo: titleLabelRight.leftAnchor, constant: 0), + contentLabelRight.topAnchor.constraint(equalTo: titleLabelRight.bottomAnchor, constant: chat_content_margin), + contentLabelRightHeightAnchor!, + ]) + } + + override open func showLeftOrRight(showRight: Bool) { + super.showLeftOrRight(showRight: showRight) + titleLabelLeft.isHidden = showRight + titleLabelRight.isHidden = !showRight + } + + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) + let replyLabelHeightAnchor = isSend ? replyLabelRightHeightAnchor : replyLabelLeftHeightAnchor + let titleLabel = isSend ? titleLabelRight : titleLabelLeft + let titleLabelTopAnchor = isSend ? titleLabelRightTopAnchor : titleLabelLeftTopAnchor + let titleLabelHeightAnchor = isSend ? titleLabelRightHeightAnchor : titleLabelLeftHeightAnchor + let contentLabelHeightAnchor = isSend ? contentLabelRightHeightAnchor : contentLabelLeftHeightAnchor + + if let text = model.replyText { + replyLabelHeightAnchor?.constant = 16 + titleLabelTopAnchor?.constant = chat_content_margin + } else { + replyLabelHeightAnchor?.constant = 0 + titleLabelTopAnchor?.constant = 0 + } + + if let m = model as? MessageTextModel { + contentLabelHeightAnchor?.constant = m.textHeight + } + + if let m = model as? MessageRichTextModel { + titleLabel.attributedText = m.titleAttributeStr + titleLabelHeightAnchor?.constant = m.titleTextHeight + } + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageTextCell.swift index a5bb8cac..219e816a 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageTextCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageTextCell.swift @@ -15,7 +15,6 @@ open class ChatMessageTextCell: NormalChatMessageBaseCell { label.isUserInteractionEnabled = false label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize) label.backgroundColor = .clear - label.textAlignment = .justified label.accessibilityIdentifier = "id.messageText" return label }() @@ -28,7 +27,6 @@ open class ChatMessageTextCell: NormalChatMessageBaseCell { label.isUserInteractionEnabled = false label.font = .systemFont(ofSize: NEKitChatConfig.shared.ui.messageProperties.messageTextSize) label.backgroundColor = .clear - label.textAlignment = .justified label.accessibilityIdentifier = "id.messageText" return label }() @@ -66,13 +64,9 @@ open class ChatMessageTextCell: NormalChatMessageBaseCell { contentLabelRight.isHidden = !showRight } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentLabel = isSend ? contentLabelRight : contentLabelLeft - if let m = model as? MessageTextModel { contentLabel.attributedText = m.attributeStr } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageVideoCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageVideoCell.swift index 5cf8151c..91a481b5 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageVideoCell.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/ChatMessageVideoCell.swift @@ -123,11 +123,8 @@ open class ChatMessageVideoCell: ChatMessageImageCell { ]) } - override open func setModel(_ model: MessageContentModel) { - super.setModel(model) - guard let isSend = model.message?.isOutgoingMsg else { - return - } + override open func setModel(_ model: MessageContentModel, _ isSend: Bool) { + super.setModel(model, isSend) let contentImageView = isSend ? contentImageViewRight : contentImageViewLeft let timeView = isSend ? timeViewRight : timeViewLeft let timeLabel = isSend ? timeLabelRight : timeLabelLeft diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/PinCell/PinMessageMultiForwardCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/PinCell/PinMessageMultiForwardCell.swift new file mode 100644 index 00000000..38540682 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/PinCell/PinMessageMultiForwardCell.swift @@ -0,0 +1,68 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NIMSDK +import UIKit + +@objcMembers +open class PinMessageMultiForwardCell: NEBasePinMessageMultiForwardCell { + override open func setupUI() { + super.setupUI() + backViewLeft.addSubview(titleLabelLeft1) + NSLayoutConstraint.activate([ + titleLabelLeft1.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: 16), + titleLabelLeft1.rightAnchor.constraint(lessThanOrEqualTo: backViewLeft.rightAnchor, constant: -84), + titleLabelLeft1.topAnchor.constraint(equalTo: backViewLeft.topAnchor, constant: 10), + titleLabelLeft1.heightAnchor.constraint(equalToConstant: 22), + ]) + + backViewLeft.addSubview(titleLabelLeft2) + NSLayoutConstraint.activate([ + titleLabelLeft2.leftAnchor.constraint(equalTo: titleLabelLeft1.rightAnchor), + titleLabelLeft2.centerYAnchor.constraint(equalTo: titleLabelLeft1.centerYAnchor), + titleLabelLeft2.heightAnchor.constraint(equalToConstant: 22), + titleLabelLeft2.widthAnchor.constraint(equalToConstant: 74), + ]) + + backViewLeft.addSubview(contentLabelLeft1) + NSLayoutConstraint.activate([ + contentLabelLeft1.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), + contentLabelLeft1.topAnchor.constraint(equalTo: titleLabelLeft1.bottomAnchor, constant: 2), + contentLabelLeft1.widthAnchor.constraint(equalToConstant: contentW), + contentLabelLeft1.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft2) + NSLayoutConstraint.activate([ + contentLabelLeft2.leftAnchor.constraint(equalTo: contentLabelLeft1.leftAnchor), + contentLabelLeft2.topAnchor.constraint(equalTo: contentLabelLeft1.bottomAnchor), + contentLabelLeft2.widthAnchor.constraint(equalToConstant: contentW), + contentLabelLeft2.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + + backViewLeft.addSubview(contentLabelLeft3) + NSLayoutConstraint.activate([ + contentLabelLeft3.leftAnchor.constraint(equalTo: contentLabelLeft2.leftAnchor), + contentLabelLeft3.topAnchor.constraint(equalTo: contentLabelLeft2.bottomAnchor), + contentLabelLeft3.widthAnchor.constraint(equalToConstant: contentW), + contentLabelLeft3.heightAnchor.constraint(greaterThanOrEqualToConstant: 20), + ]) + +// backViewLeft.addSubview(contentHistoryLeft) +// NSLayoutConstraint.activate([ +// contentHistoryLeft.leftAnchor.constraint(equalTo: titleLabelLeft1.leftAnchor), +// contentHistoryLeft.bottomAnchor.constraint(equalTo: backViewLeft.bottomAnchor, constant: -12), +// contentHistoryLeft.widthAnchor.constraint(equalToConstant: 60), +// contentHistoryLeft.heightAnchor.constraint(equalToConstant: 14), +// ]) +// +// backViewLeft.addSubview(dividerLineLeft) +// NSLayoutConstraint.activate([ +// dividerLineLeft.leftAnchor.constraint(equalTo: backViewLeft.leftAnchor, constant: 6), +// dividerLineLeft.rightAnchor.constraint(equalTo: backViewLeft.rightAnchor, constant: -6), +// dividerLineLeft.topAnchor.constraint(equalTo: contentHistoryLeft.topAnchor, constant: -6), +// dividerLineLeft.heightAnchor.constraint(equalToConstant: 1), +// ]) + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/PinCell/PinMessageRichTextCell.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/PinCell/PinMessageRichTextCell.swift new file mode 100644 index 00000000..137c9d09 --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Cell/PinCell/PinMessageRichTextCell.swift @@ -0,0 +1,8 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class PinMessageRichTextCell: NEBasePinMessageRichTextCell {} diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ForwardAlertViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ForwardAlertViewController.swift index 77e904b0..1df9eb9e 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ForwardAlertViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ForwardAlertViewController.swift @@ -8,7 +8,7 @@ import NECommonUIKit import UIKit @objcMembers -public class ForwardUserCell: NEBaseForwardUserCell { +open class ForwardUserCell: NEBaseForwardUserCell { override func setupUI() { super.setupUI() userHeader.layer.cornerRadius = 16 @@ -16,8 +16,8 @@ public class ForwardUserCell: NEBaseForwardUserCell { } @objcMembers -public class ForwardAlertViewController: NEBaseForwardAlertViewController { - override public func setupUI() { +open class ForwardAlertViewController: NEBaseForwardAlertViewController { + override open func setupUI() { super.setupUI() oneUserHead.layer.cornerRadius = 16.0 userCollection.register( @@ -26,7 +26,7 @@ public class ForwardAlertViewController: NEBaseForwardAlertViewController { ) } - override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "\(ForwardUserCell.self)", for: indexPath diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/GroupChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/GroupChatViewController.swift index ff512a0a..e30091d5 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/GroupChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/GroupChatViewController.swift @@ -3,14 +3,17 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit import NECoreIMKit import NIMSDK import UIKit @objcMembers open class GroupChatViewController: NormalChatViewController, TeamChatViewModelDelegate { - private var isLeaveTeamBySelf = false // 是否是主动退出群聊 + private var isLeaveTeamByOther = false // 是否被移出群聊 + private var isLeaveTeamBySelf = false // 是否多端登录另一端退出群聊 private var isdismissTeam = false // 群聊是否已解散 + private var isdismissDiscuss = false // 讨论组是否已解散 private var onCurrentPage = false // 是否位于聊天详情页 public init(session: NIMSession, anchor: NIMMessage?) { @@ -31,12 +34,30 @@ open class GroupChatViewController: NormalChatViewController, TeamChatViewModelD fatalError("init(coder:) has not been implemented") } + deinit { + NotificationCenter.default.removeObserver(self) + } + override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) onCurrentPage = true - // 被动解散群聊 + + // 多端登录另一端解散、退出讨论组 + // 多端登录另一端退出群聊 + if isdismissDiscuss || isLeaveTeamBySelf { + popGroupChatVC() + } + + weak var weakSelf = self + // 被移除群聊 + if isLeaveTeamByOther { + showSingleAlert(message: chatLocalizable("team_has_been_quit")) { + weakSelf?.navigationController?.popViewController(animated: true) + } + } + + // 解散群聊 if isdismissTeam { - weak var weakSelf = self showSingleAlert(message: chatLocalizable("team_has_been_removed")) { weakSelf?.navigationController?.popViewController(animated: true) } @@ -50,7 +71,7 @@ open class GroupChatViewController: NormalChatViewController, TeamChatViewModelD override open func viewDidLoad() { super.viewDidLoad() - NotificationCenter.default.addObserver(self, selector: #selector(leaveTeamBySelf), name: NotificationName.leaveTeamBySelf, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(popGroupChatVC), name: NENotificationName.popGroupChatVC, object: nil) } override open func getSessionInfo(session: NIMSession) { @@ -63,9 +84,21 @@ open class GroupChatViewController: NormalChatViewController, TeamChatViewModelD // MARK: private method - func leaveTeamBySelf(noti: Notification) { - if let flag = noti.object as? Bool { - isLeaveTeamBySelf = flag + func popGroupChatVC() { + var beforeChat: UIViewController? + var loopCount = 0 + for vc in navigationController?.viewControllers ?? [] { + if vc.isKind(of: ChatViewController.self) { + if loopCount <= 1 { + navigationController?.popToRootViewController(animated: true) + return + } + navigationController?.popToViewController(beforeChat!, animated: true) + return + } else { + beforeChat = vc + loopCount += 1 + } } } @@ -82,50 +115,84 @@ open class GroupChatViewController: NormalChatViewController, TeamChatViewModelD open func updateTeamInfo(team: NIMTeam) { title = team.getShowName() - if team.inAllMuteMode(), team.owner != NIMSDK.shared().loginManager.currentAccount() { + + if team.inAllMuteMode(), viewmodel.teamMember?.type != .manager, viewmodel.teamMember?.type != .owner { + // 群禁言 + isMute = true chatInputView.textView.isEditable = false chatInputView.textView.attributedPlaceholder = getPlaceHolder(text: chatLocalizable("team_mute")) chatInputView.textView.backgroundColor = UIColor(hexString: "#E3E4E4") layoutInputView(offset: 0) chatInputView.stackView.isUserInteractionEnabled = false + chatInputView.setMuteInputStyle() + if chatInputView.chatInpuMode != .normal { + chatInputView.titleField.text = nil + didHideMultipleButtonClick() + } + closeReply(button: nil) } else { + // 解除群禁言 + isMute = false chatInputView.textView.isEditable = true chatInputView.textView.attributedPlaceholder = getPlaceHolder(text: "\(chatLocalizable("send_to"))\(team.getShowName())") + chatInputView.textView.backgroundColor = .white chatInputView.stackView.isUserInteractionEnabled = true + chatInputView.setUnMuteInputStyle() } } - // MARK: TeamChatViewModelDelegate - - open func onTeamRemoved(team: NIMTeam) { - // 退出讨论组 - if team.isDisscuss() == true { - navigationController?.popViewController(animated: true) - return - } + override open func onRecvMessages(_ messages: [NIMMessage]) { + super.onRecvMessages(messages) + for message in messages { + if let object = message.messageObject as? NIMNotificationObject, + let content = object.content as? NIMTeamNotificationContent { + if content.operationType == .leave, + IMKitClient.instance.isMySelf(content.sourceID) { + isLeaveTeamBySelf = true + if onCurrentPage { + popGroupChatVC() + } + } else if content.operationType == .kick, + let targetIDs = content.targetIDs, + targetIDs.contains(IMKitClient.instance.imAccid()) { + // 被移出群聊 + isLeaveTeamByOther = true + if onCurrentPage { + showSingleAlert(message: chatLocalizable("team_has_been_quit")) { [weak self] in + self?.navigationController?.popViewController(animated: true) + } + } + } else if content.operationType == .dismiss { + if isdismissDiscuss { + return + } - // 离开群聊 - if team.teamId == viewmodel.session.sessionId { - if team.owner != NIMSDK.shared().loginManager.currentAccount() { // 退出群聊 - if isLeaveTeamBySelf { - navigationController?.popViewController(animated: true) - } else { + // 解散群聊 isdismissTeam = true - // 被动解散群聊 if onCurrentPage { - weak var weakSelf = self - showSingleAlert(message: chatLocalizable("team_has_been_removed")) { - weakSelf?.navigationController?.popViewController(animated: true) + showSingleAlert(message: chatLocalizable("team_has_been_removed")) { [weak self] in + self?.navigationController?.popViewController(animated: true) } } } - } else { // 主动解散 - navigationController?.popViewController(animated: true) } } } + // MARK: TeamChatViewModelDelegate + + open func onTeamRemoved(team: NIMTeam) { + // 多端登录另一端解散、退出讨论组 + if team.isDisscuss() == true { + isdismissDiscuss = true + if onCurrentPage { + popGroupChatVC() + } + return + } + } + open func onTeamUpdate(team: NIMTeam) { if team.teamId != viewmodel.session.sessionId { return @@ -133,7 +200,15 @@ open class GroupChatViewController: NormalChatViewController, TeamChatViewModelD updateTeamInfo(team: team) } - public func onTeamMemberUpdate(team: NIMTeam) { + open func onTeamMemberUpdate(team: NIMTeam) { didRefreshTable() } + + override public func onTeamMemberChange(team: NIMTeam) { + if viewmodel.session.sessionId != team.teamId { + return + } + (viewmodel as? TeamChatViewModel)?.getTeamMember() + updateTeamInfo(team: team) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalChatViewController.swift index 0d74d428..1aa5b508 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalChatViewController.swift @@ -11,18 +11,7 @@ open class NormalChatViewController: ChatViewController { super.init(session: session) navigationView.backgroundColor = .white navigationController?.navigationBar.backgroundColor = .white - cellRegisterDic = [ - "\(MessageType.text.rawValue)": ChatMessageTextCell.self, - "\(MessageType.rtcCallRecord.rawValue)": ChatMessageCallCell.self, - "\(MessageType.audio.rawValue)": ChatMessageAudioCell.self, - "\(MessageType.image.rawValue)": ChatMessageImageCell.self, - "\(MessageType.revoke.rawValue)": ChatMessageRevokeCell.self, - "\(MessageType.video.rawValue)": ChatMessageVideoCell.self, - "\(MessageType.file.rawValue)": ChatMessageFileCell.self, - "\(MessageType.reply.rawValue)": ChatMessageReplyCell.self, - "\(MessageType.location.rawValue)": ChatMessageLocationCell.self, - "\(MessageType.time.rawValue)": ChatMessageTipCell.self, - ] + cellRegisterDic = ChatMessageHelper.getChatCellRegisterDic(isFun: false) } public required init?(coder: NSCoder) { @@ -34,50 +23,116 @@ open class NormalChatViewController: ChatViewController { } override open func getMenuView() -> NEBaseChatInputView { - ChatInputView() + let chat = ChatInputView() + chat.multipleLineDelegate = self + return chat } override open func getForwardAlertController() -> NEBaseForwardAlertViewController { ForwardAlertViewController() } + override open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + NormalMultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } + override func getUserSelectVC() -> NEBaseSelectUserViewController { SelectUserViewController(sessionId: viewmodel.session.sessionId, showSelf: false) } - override open func toSetting() { - if let block = NEKitChatConfig.shared.ui.messageProperties.titleBarRightClick { - block() - return - } - if viewmodel.session.sessionType == .team { - Router.shared.use( - TeamSettingViewRouter, - parameters: ["nav": navigationController as Any, - "teamid": viewmodel.session.sessionId], - closure: nil + open func getMessageModel(model: MessageModel) { + if model.type == .reply { + let normalMoreHeight = chat_reply_height + chat_content_margin + model.contentSize = CGSize( + width: model.contentSize.width, + height: model.contentSize.height + normalMoreHeight ) - } else if viewmodel.session.sessionType == .P2P { - let userSetting = UserSettingViewController(userId: viewmodel.session.sessionId) - navigationController?.pushViewController(userSetting, animated: true) + model.height += normalMoreHeight } } - override open func didTapReadView(_ cell: UITableViewCell, _ model: MessageContentModel?) { - if let msg = model?.message, msg.session?.sessionType == .team { - let readVC = ReadViewController(message: msg) - navigationController?.pushViewController(readVC, animated: true) + override open func expandButtonDidClick() { + print("expandButtonDidClick ") + super.expandButtonDidClick() + chatInputView.changeToMultipleLineStyle() + normalInputHeight = 296 + bottomViewTopAnchor?.constant = -normalInputHeight + chatInputView.textView.resignFirstResponder() + chatInputView.titleField.resignFirstResponder() + checkAndRemoveReplyView() + } + + override open func didHideMultipleButtonClick() { + super.didHideMultipleButtonClick() + + if chatInputView.chatInpuMode == .normal { + normalInputHeight = 100 + } else { + normalInputHeight = 150 } + bottomViewTopAnchor?.constant = -normalInputHeight + checkAndRestoreReplyView() } - public func getMessageModel(model: MessageModel) { - if model.type == .reply { - let normalMoreHeight = chat_reply_height + chat_content_margin - model.contentSize = CGSize( - width: model.contentSize.width, - height: model.contentSize.height + normalMoreHeight - ) - model.height += Float(normalMoreHeight) + // 切换到多行消息模式隐藏回复 + func checkAndRemoveReplyView() { + if chatInputView.chatInpuMode == .multipleReturn { + if replyView.superview != nil { + replyView.removeFromSuperview() + } + } + } + + // 切换到单行输入框如果有回复显示回复视图 + func checkAndRestoreReplyView() { + if viewmodel.isReplying == true, replyView.superview == nil { + view.addSubview(replyView) + replyView.closeButton.addTarget(self, action: #selector(closeReply), for: .touchUpInside) + replyView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + replyView.leadingAnchor.constraint(equalTo: chatInputView.leadingAnchor), + replyView.trailingAnchor.constraint(equalTo: chatInputView.trailingAnchor), + replyView.bottomAnchor.constraint(equalTo: chatInputView.topAnchor), + replyView.heightAnchor.constraint(equalToConstant: 36), + ]) + } + } + + override open func titleTextDidClearEmpty() { + if chatInputView.chatInpuMode == .multipleSend { + chatInputView.chatInpuMode = .normal + if chatInputView.chatInpuMode == .normal { + normalInputHeight = 100 + } else { + normalInputHeight = 150 + } + chatInputView.restoreNormalInputStyle() + layoutInputViewWithAnimation(offset: currentKeyboardHeight) + chatInputView.textView.becomeFirstResponder() + } + } + + override open func keyBoardWillShow(_ notification: Notification) { + let keyboardRect = (notification + .userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue + currentKeyboardHeight = keyboardRect.height + super.keyBoardWillShow(notification) + } + + override open func keyBoardWillHide(_ notification: Notification) { + currentKeyboardHeight = 0 + super.keyBoardWillHide(notification) + } + + // 减小多行输入框高度,不收回键盘 + override open func didHideMultiple() { + if chatInputView.chatInpuMode == .normal { + normalInputHeight = 100 + } else { + normalInputHeight = 150 } + bottomViewTopAnchor?.constant = -(normalInputHeight + currentKeyboardHeight) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalMultiForwardViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalMultiForwardViewController.swift new file mode 100644 index 00000000..ff2087df --- /dev/null +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/NormalMultiForwardViewController.swift @@ -0,0 +1,28 @@ +// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NIMSDK +import UIKit + +@objcMembers +open class NormalMultiForwardViewController: MultiForwardViewController { + override public init(_ attachmentUrl: String?, + _ attachmentFilePath: String, + _ attachmentMD5: String?) { + super.init(attachmentUrl, attachmentFilePath, attachmentMD5) + navigationView.backgroundColor = .white + navigationController?.navigationBar.backgroundColor = .white + cellRegisterDic = ChatMessageHelper.getChatCellRegisterDic(isFun: false) + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + NormalMultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } +} diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/P2PChatViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/P2PChatViewController.swift index a68daf8f..eb1b6ad1 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/P2PChatViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/P2PChatViewController.swift @@ -22,7 +22,7 @@ open class P2PChatViewController: NormalChatViewController { override open func getSessionInfo(session: NIMSession) { var showName = session.sessionId - viewmodel.getUserInfo(session.sessionId) { [weak self] user, error in + ChatUserCache.getUserInfo(session.sessionId) { [weak self] user, error in if let name = user?.showName() { showName = name } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/PinMessageViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/PinMessageViewController.swift index 9f2b85d5..eaa75e12 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/PinMessageViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/PinMessageViewController.swift @@ -7,27 +7,24 @@ import UIKit @objcMembers open class PinMessageViewController: NEBasePinMessageViewController { - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .ne_lightBackgroundColor navigationView.backgroundColor = .ne_lightBackgroundColor navigationController?.navigationBar.backgroundColor = .ne_lightBackgroundColor } - override open func getRegisterCellDic() -> [Int: NEBasePinMessageCell.Type] { - let cellClassDic = [ - NIMMessageType.text.rawValue: PinMessageTextCell.self, - NIMMessageType.image.rawValue: PinMessageImageCell.self, - NIMMessageType.audio.rawValue: PinMessageAudioCell.self, - NIMMessageType.video.rawValue: PinMessageVideoCell.self, - NIMMessageType.location.rawValue: PinMessageLocationCell.self, - NIMMessageType.file.rawValue: PinMessageFileCell.self, - PinMessageDefaultType: PinMessageDefaultCell.self, - ] - return cellClassDic + override open func getRegisterCellDic() -> [String: NEBasePinMessageCell.Type] { + ChatMessageHelper.getPinCellRegisterDic(isFun: false) } override open func getForwardAlertController() -> NEBaseForwardAlertViewController { ForwardAlertViewController() } + + override open func getMultiForwardViewController(_ messageAttachmentUrl: String?, + _ messageAttachmentFilePath: String, + _ messageAttachmentMD5: String?) -> MultiForwardViewController { + NormalMultiForwardViewController(messageAttachmentUrl, messageAttachmentFilePath, messageAttachmentMD5) + } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ReadViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ReadViewController.swift index 2fe49747..06781a12 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ReadViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/ReadViewController.swift @@ -20,7 +20,7 @@ open class ReadViewController: NEBaseReadViewController { fatalError("init(coder:) has not been implemented") } - override public func commonUI() { + override open func commonUI() { super.commonUI() navigationView.titleBarBottomLine.isHidden = false readButton.setTitleColor(UIColor.ne_darkText, for: .normal) diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/SelectUserViewController.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/SelectUserViewController.swift index 896ab813..9e9db17b 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/SelectUserViewController.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/Controller/SelectUserViewController.swift @@ -34,11 +34,11 @@ open class SelectUserViewController: NEBaseSelectUserViewController { withIdentifier: "\(ChatTeamMemberCell.self)", for: indexPath ) as! ChatTeamMemberCell - if indexPath.row == 0 { + if indexPath.section == 0 { cell.headerView.image = UIImage.ne_imageNamed(name: "chat_team") cell.nameLabel.text = chatLocalizable("user_select_all") } else { - if let model = teamInfo?.users[indexPath.row - 1] { + if let model = teamInfo?.users[indexPath.row] { cell.configure(model) } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/NormalChatRouter.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/NormalChatRouter.swift index 69c6a80c..932a3f18 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/NormalChatRouter.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/NormalChatRouter.swift @@ -40,7 +40,8 @@ public extension ChatRouter { return } let anchor = param["anchor"] as? NIMMessage - var p2pChatVC = P2PChatViewController(session: session, anchor: anchor) + let p2pChatVC = P2PChatViewController(session: session, anchor: anchor) + for (i, vc) in (nav?.viewControllers ?? []).enumerated() { if vc.isKind(of: ChatViewController.self) { nav?.viewControllers[i] = p2pChatVC @@ -48,6 +49,11 @@ public extension ChatRouter { return } } + + if let remove = param["removeUserVC"] as? Bool, remove { + nav?.viewControllers.removeLast() + } + nav?.pushViewController(p2pChatVC, animated: true) } diff --git a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/View/ChatInpuView.swift b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/View/ChatInpuView.swift index 110df866..45559500 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/NormalUI/View/ChatInpuView.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/NormalUI/View/ChatInpuView.swift @@ -6,12 +6,15 @@ import Foundation @objcMembers open class ChatInputView: NEBaseChatInputView { - override public func commonUI() { + public var backViewHeightConstraint: NSLayoutConstraint? + public var toolsBarTopMargin: NSLayoutConstraint? + + override open func commonUI() { backgroundColor = UIColor.normalChatInputBg addSubview(textView) textView.delegate = self textviewLeftConstraint = textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 7) - textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -7) + textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -44) NSLayoutConstraint.activate([ textviewLeftConstraint!, textviewRightConstraint!, @@ -20,6 +23,25 @@ open class ChatInputView: NEBaseChatInputView { ]) textInput = textView + backViewHeightConstraint = backView.heightAnchor.constraint(equalToConstant: 40) + insertSubview(backView, belowSubview: textView) + NSLayoutConstraint.activate([ + backView.leftAnchor.constraint(equalTo: leftAnchor, constant: 7), + backView.rightAnchor.constraint(equalTo: rightAnchor, constant: -7), + backView.topAnchor.constraint(equalTo: topAnchor, constant: 6), + backViewHeightConstraint!, + ]) + + addSubview(expandButton) + NSLayoutConstraint.activate([ + expandButton.topAnchor.constraint(equalTo: topAnchor, constant: 7), + expandButton.rightAnchor.constraint(equalTo: rightAnchor, constant: 0), + expandButton.heightAnchor.constraint(equalToConstant: 40), + expandButton.widthAnchor.constraint(equalToConstant: 44.0), + ]) + expandButton.setImage(coreLoader.loadImage("normal_input_unfold"), for: .normal) + expandButton.addTarget(self, action: #selector(didClickExpandButton), for: .touchUpInside) + let imageNames = ["mic", "emoji", "photo", "add"] let imageNamesSelected = ["mic_selected", "emoji_selected", "photo", "add_selected"] @@ -42,23 +64,25 @@ open class ChatInputView: NEBaseChatInputView { stackView = UIStackView(arrangedSubviews: items) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .fillEqually + + toolsBarTopMargin = stackView.topAnchor.constraint(equalTo: topAnchor, constant: 46) addSubview(stackView) NSLayoutConstraint.activate([ stackView.leftAnchor.constraint(equalTo: leftAnchor), stackView.rightAnchor.constraint(equalTo: rightAnchor), stackView.heightAnchor.constraint(equalToConstant: 54), - stackView.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 0), + toolsBarTopMargin!, ]) greyView.translatesAutoresizingMaskIntoConstraints = false - greyView.backgroundColor = UIColor(hexString: "#EFF1F3") + greyView.backgroundColor = .ne_backgroundColor greyView.isHidden = true addSubview(greyView) NSLayoutConstraint.activate([ greyView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0), greyView.topAnchor.constraint(equalTo: topAnchor, constant: 0), greyView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0), - greyView.heightAnchor.constraint(equalToConstant: 100), + greyView.heightAnchor.constraint(equalToConstant: 400), ]) addSubview(contentView) @@ -85,5 +109,86 @@ open class ChatInputView: NEBaseChatInputView { contentView.addSubview(emojiView) contentView.addSubview(chatAddMoreView) + + setupMultipleLineView() + multipleLineExpandButton.setImage(coreLoader.loadImage("normal_input_fold"), for: .normal) + } + + override open func restoreNormalInputStyle() { + super.restoreNormalInputStyle() + textView.returnKeyType = .send + textView.removeAllAutoLayout() + textView.removeConstraints(textView.constraints) + insertSubview(textView, aboveSubview: backView) + textviewLeftConstraint = textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 7) + textviewRightConstraint = textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -44) + if chatInpuMode == .normal { + NSLayoutConstraint.activate([ + textviewLeftConstraint!, + textviewRightConstraint!, + textView.topAnchor.constraint(equalTo: topAnchor, constant: 6), + textView.heightAnchor.constraint(equalToConstant: 40), + ]) + backViewHeightConstraint?.constant = 46 + toolsBarTopMargin?.constant = 46 + titleField.isHidden = true + } else if chatInpuMode == .multipleSend { + titleField.isHidden = false + NSLayoutConstraint.activate([ + textviewLeftConstraint!, + textviewRightConstraint!, + textView.topAnchor.constraint(equalTo: topAnchor, constant: 45), + textView.heightAnchor.constraint(equalToConstant: 45), + ]) + + titleField.removeAllAutoLayout() + insertSubview(titleField, belowSubview: textView) + NSLayoutConstraint.activate([ + titleField.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 4), + titleField.rightAnchor.constraint(equalTo: expandButton.leftAnchor), + titleField.topAnchor.constraint(equalTo: backView.topAnchor), + titleField.heightAnchor.constraint(equalToConstant: 40), + ]) + + backViewHeightConstraint?.constant = 100 + toolsBarTopMargin?.constant = 100 + } + } + + override open func changeToMultipleLineStyle() { + super.changeToMultipleLineStyle() + textView.removeAllAutoLayout() + multipleLineView.addSubview(textView) + textView.removeConstraints(textView.constraints) + textView.returnKeyType = .default + titleField.isHidden = false + + NSLayoutConstraint.activate([ + textView.leftAnchor.constraint(equalTo: multipleLineView.leftAnchor, constant: 13), + textView.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: -16), + textView.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 48), + textView.heightAnchor.constraint(equalToConstant: 183), + ]) + + if titleField.superview == nil || titleField.superview != multipleLineView { + titleField.removeAllAutoLayout() + multipleLineView.addSubview(titleField) + NSLayoutConstraint.activate([ + titleField.leftAnchor.constraint(equalTo: multipleLineView.leftAnchor, constant: 16), + titleField.rightAnchor.constraint(equalTo: multipleLineView.rightAnchor, constant: -56), + titleField.topAnchor.constraint(equalTo: multipleLineView.topAnchor, constant: 5), + titleField.heightAnchor.constraint(equalToConstant: 40), + ]) + } + } + + override open func setMuteInputStyle() { + super.setMuteInputStyle() + backView.backgroundColor = UIColor(hexString: "#E3E4E4") + } + + override open func setUnMuteInputStyle() { + super.setUnMuteInputStyle() + backView.backgroundColor = .white } } diff --git a/NEChatUIKit/NEChatUIKit/Classes/Protocol/ChatInputViewDelegate.swift b/NEChatUIKit/NEChatUIKit/Classes/Protocol/ChatInputViewDelegate.swift index 4adcef46..c4a72527 100644 --- a/NEChatUIKit/NEChatUIKit/Classes/Protocol/ChatInputViewDelegate.swift +++ b/NEChatUIKit/NEChatUIKit/Classes/Protocol/ChatInputViewDelegate.swift @@ -17,7 +17,8 @@ public protocol ChatInputViewDelegate: NSObjectProtocol { func moveOutView() func moveInView() func endRecord(insideView: Bool) - func textFieldDidChange(_ textField: UITextView) - func textFieldDidEndEditing(_ textField: UITextView) - func textFieldDidBeginEditing(_ textField: UITextView) + func textFieldDidChange(_ text: String?) + func textFieldDidEndEditing(_ text: String?) + func textFieldDidBeginEditing(_ text: String?) + func titleTextDidClearEmpty() } diff --git a/NEContactUIKit/NEContactUIKit.podspec b/NEContactUIKit/NEContactUIKit.podspec index 4e12d7f4..39a52c66 100644 --- a/NEContactUIKit/NEContactUIKit.podspec +++ b/NEContactUIKit/NEContactUIKit.podspec @@ -8,7 +8,7 @@ Pod::Spec.new do |s| s.name = 'NEContactUIKit' - s.version = '9.6.5' + s.version = '9.7.0' s.summary = 'Netease XKit' # This description is used to generate tags and improve search results. diff --git a/NEContactUIKit/NEContactUIKit/Classes/Base/NEBaseContactViewCell.swift b/NEContactUIKit/NEContactUIKit/Classes/Base/NEBaseContactViewCell.swift index edd1ad32..88fc284c 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Base/NEBaseContactViewCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Base/NEBaseContactViewCell.swift @@ -35,6 +35,7 @@ open class NEBaseContactViewCell: UITableViewCell { label.layer.cornerRadius = 9 label.clipsToBounds = true label.isHidden = true + label.accessibilityIdentifier = "id.unread" return label }() @@ -45,7 +46,7 @@ open class NEBaseContactViewCell: UITableViewCell { name.textAlignment = .center name.font = UIFont.systemFont(ofSize: 14.0) name.adjustsFontSizeToFitWidth = true - name.accessibilityIdentifier = "id.avatar" + name.accessibilityIdentifier = "id.noAvatar" return name }() @@ -71,17 +72,6 @@ open class NEBaseContactViewCell: UITableViewCell { var leftConstraint: NSLayoutConstraint? - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none diff --git a/NEContactUIKit/NEContactUIKit/Classes/BlackList/Cell/NEBaseBlackListCell.swift b/NEContactUIKit/NEContactUIKit/Classes/BlackList/Cell/NEBaseBlackListCell.swift index 7290e1f1..7b9b28ab 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/BlackList/Cell/NEBaseBlackListCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/BlackList/Cell/NEBaseBlackListCell.swift @@ -14,7 +14,7 @@ protocol BlackListCellDelegate: AnyObject { open class NEBaseBlackListCell: NEBaseTeamTableViewCell { weak var delegate: BlackListCellDelegate? var index = 0 - private var model: User? + private var model: NEKitUser? var button = UIButton() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) @@ -58,8 +58,8 @@ open class NEBaseBlackListCell: NEBaseTeamTableViewCell { delegate?.removeUser(account: model?.userId, index: index) } - override public func setModel(_ model: Any) { - guard let user = model as? User else { + override open func setModel(_ model: Any) { + guard let user = model as? NEKitUser else { return } self.model = user @@ -68,7 +68,7 @@ open class NEBaseBlackListCell: NEBaseTeamTableViewCell { titleLabel.text = user.showName() // avatar - if let imageUrl = user.userInfo?.avatarUrl { + if let imageUrl = user.userInfo?.avatarUrl, !imageUrl.isEmpty { nameLabel.text = "" avatarImage.sd_setImage(with: URL(string: imageUrl), completed: nil) avatarImage.backgroundColor = .clear diff --git a/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewController/NEBaseBlackListViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewController/NEBaseBlackListViewController.swift index 6e2bce8e..ba573f1b 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewController/NEBaseBlackListViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewController/NEBaseBlackListViewController.swift @@ -14,10 +14,10 @@ open class NEBaseBlackListViewController: UIViewController, UITableViewDelegate, public let navigationView = NENavigationView() var tableView = UITableView(frame: .zero, style: .plain) var viewModel = BlackListViewModel() - public var blackList: [User]? + public var blackList: [NEKitUser]? var className = "BlackListBaseViewController" - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white navigationController?.interactivePopGestureRecognizer?.delegate = self @@ -96,12 +96,12 @@ open class NEBaseBlackListViewController: UIViewController, UITableViewDelegate, tableView.reloadData() } - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { blackList?.count ?? 0 } - public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { UITableViewCell() } @@ -117,7 +117,7 @@ open class NEBaseBlackListViewController: UIViewController, UITableViewDelegate, let contactSelectVC = getContactSelectVC() navigationController?.pushViewController(contactSelectVC, animated: true) contactSelectVC.callBack = { [weak self] selectMemberarray in - var users = [User]() + var users = [NEKitUser]() selectMemberarray.forEach { memberInfo in if let u = memberInfo.user { users.append(u) @@ -127,9 +127,9 @@ open class NEBaseBlackListViewController: UIViewController, UITableViewDelegate, } } - func addBlackUsers(users: [User]) { + func addBlackUsers(users: [NEKitUser]) { var num = users.count - var suc = [User]() + var suc = [NEKitUser]() for user in users { viewModel.addBlackList(account: user.userId ?? "") { [weak self] error in NELog.infoLog( @@ -179,9 +179,9 @@ open class NEBaseBlackListViewController: UIViewController, UITableViewDelegate, // MARK: FriendProviderDelegate extension NEBaseBlackListViewController: FriendProviderDelegate { - public func onFriendChanged(user: NECoreIMKit.User) {} + public func onFriendChanged(user: NECoreIMKit.NEKitUser) {} - public func onUserInfoChanged(user: NECoreIMKit.User) {} + public func onUserInfoChanged(user: NECoreIMKit.NEKitUser) {} public func onBlackListChanged() { loadData() diff --git a/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewModel/BlackListViewModel.swift b/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewModel/BlackListViewModel.swift index 92a760a8..93c45992 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewModel/BlackListViewModel.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/BlackList/ViewModel/BlackListViewModel.swift @@ -8,7 +8,7 @@ import NECoreIMKit import NECoreKit @objcMembers -public class BlackListViewModel: NSObject, FriendProviderDelegate { +open class BlackListViewModel: NSObject, FriendProviderDelegate { var contactRepo = ContactRepo.shared public weak var delegate: FriendProviderDelegate? private let className = "BlackListViewModel" @@ -19,7 +19,7 @@ public class BlackListViewModel: NSObject, FriendProviderDelegate { contactRepo.addContactDelegate(delegate: self) } - func getBlackList() -> [User]? { + func getBlackList() -> [NEKitUser]? { NELog.infoLog(ModuleName + " " + className, desc: #function) return contactRepo.getBlackList() } @@ -36,12 +36,12 @@ public class BlackListViewModel: NSObject, FriendProviderDelegate { // MARK: callback - public func onFriendChanged(user: User) { + public func onFriendChanged(user: NEKitUser) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId:\(user.userId ?? "nil")") delegate?.onFriendChanged(user: user) } - public func onUserInfoChanged(user: User) { + public func onUserInfoChanged(user: NEKitUser) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId:\(user.userId ?? "nil")") delegate?.onUserInfoChanged(user: user) } @@ -51,7 +51,7 @@ public class BlackListViewModel: NSObject, FriendProviderDelegate { delegate?.onBlackListChanged() } - public func onRecieveNotification(notification: XNotification) { + public func onRecieveNotification(notification: NENotification) { NELog.infoLog(ModuleName + " " + className, desc: #function) print(#file + #function) } diff --git a/NEContactUIKit/NEContactUIKit/Classes/Common/ContactConst.swift b/NEContactUIKit/NEContactUIKit/Classes/Common/ContactConst.swift index 1f5c61cd..c43dccce 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Common/ContactConst.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Common/ContactConst.swift @@ -22,9 +22,3 @@ func localizable(_ key: String) -> String { } public let ModuleName = "NEContactUIKit" - -// MARK: notificationkey - -enum NotificationName { - static let updateFriendInfo = Notification.Name("chat.updateFriendInfo") -} diff --git a/NEContactUIKit/NEContactUIKit/Classes/Common/NEBaseContactRouter.swift b/NEContactUIKit/NEContactUIKit/Classes/Common/NEBaseContactRouter.swift index 057af4b5..addd0380 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Common/NEBaseContactRouter.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Common/NEBaseContactRouter.swift @@ -9,4 +9,4 @@ import NECoreKit import NIMSDK @objcMembers -public class ContactRouter: NSObject {} +open class ContactRouter: NSObject {} diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/Cell/FunContactTableViewCell.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/Cell/FunContactTableViewCell.swift index dae4c46b..bd6c2984 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/Cell/FunContactTableViewCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/Cell/FunContactTableViewCell.swift @@ -22,6 +22,8 @@ open class FunContactTableViewCell: NEBaseContactTableViewCell { override open func commonUI() { super.commonUI() bottomLine.backgroundColor = .funContactLineBorderColor + contentView.removeLayoutConstraint(firstItem: redAngleView, seconedItem: arrow, attribute: .right) + redAngleView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true } override open func initSubviewsLayout() { diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/FunContactRouter.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/FunContactRouter.swift index a404f3f3..508b2a8f 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/FunContactRouter.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/FunContactRouter.swift @@ -13,10 +13,8 @@ public extension ContactRouter { Router.shared.register(ContactUserSelectRouter) { param in print("param:\(param)") let nav = param["nav"] as? UINavigationController - let contactSelectVC = FunContactsSelectedViewController() - if let fiters = param["filters"] as? Set { - contactSelectVC.filterUsers = fiters - } + let filters = param["filters"] as? Set + let contactSelectVC = FunContactsSelectedViewController(filterUsers: filters) if let limit = param["limit"] as? Int, limit > 0 { contactSelectVC.limit = limit } @@ -34,10 +32,10 @@ public extension ContactRouter { Router.shared.register(ContactUserInfoPageRouter) { param in if let nav = param["nav"] as? UINavigationController { - if let user = param["user"] as? User { + if let user = param["user"] as? NEKitUser { let userInfoVC = FunContactUserViewController(user: user) nav.pushViewController(userInfoVC, animated: true) - } else if let nimUser = param["nim_user"] as? User { + } else if let nimUser = param["nim_user"] as? NEKitUser { let userInfoVC = FunContactUserViewController(user: nimUser) nav.pushViewController(userInfoVC, animated: true) } else if let uid = param["uid"] as? String { diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/View/FunUserInfoHeaderView.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/View/FunUserInfoHeaderView.swift index e06be1f8..3ec4e7df 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/View/FunUserInfoHeaderView.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/View/FunUserInfoHeaderView.swift @@ -7,7 +7,7 @@ import UIKit @objcMembers open class FunUserInfoHeaderView: NEBaseUserInfoHeaderView { - override public func commonUI() { + override open func commonUI() { super.commonUI() avatarImage.layer.cornerRadius = 4 @@ -19,7 +19,7 @@ open class FunUserInfoHeaderView: NEBaseUserInfoHeaderView { ]) } - override public func setData(user: User?) { + override open func setData(user: NEKitUser?) { super.setData(user: user) guard let u = user else { return diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunBlackListViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunBlackListViewController.swift index 1e10cadc..e33964a0 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunBlackListViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunBlackListViewController.swift @@ -28,7 +28,7 @@ open class FunBlackListViewController: NEBaseBlackListViewController { tableView.rowHeight = 64 } - override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: "\(NSStringFromClass(FunBlackListCell.self))", for: indexPath @@ -39,7 +39,7 @@ open class FunBlackListViewController: NEBaseBlackListViewController { return cell } - override public func getContactSelectVC() -> NEBaseContactsSelectedViewController { + override open func getContactSelectVC() -> NEBaseContactsSelectedViewController { FunContactsSelectedViewController() } } diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactUserViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactUserViewController.swift index 904d4bcc..13b2a39e 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactUserViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactUserViewController.swift @@ -14,7 +14,7 @@ open class FunContactUserViewController: NEBaseContactUserViewController { headerView = FunUserInfoHeaderView() } - override public init(user: User?) { + override public init(user: NEKitUser?) { super.init(user: user) initFun() } @@ -56,11 +56,11 @@ open class FunContactUserViewController: NEBaseContactUserViewController { return 46 } - override public func getContactRemakNameViewController() -> NEBaseContactRemakNameViewController { + override open func getContactRemakNameViewController() -> NEBaseContactRemakNameViewController { FunContactRemakNameViewController() } - override public func deleteFriend(user: User?) { + override open func deleteFriend(user: NEKitUser?) { let titleAction = NECustomAlertAction(title: String(format: localizable("delete_title"), user?.showName(true) ?? "")) {} titleAction.contentText.font = .systemFont(ofSize: 13) titleAction.contentText.textColor = UIColor(hexString: "#8F8F8F") diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactsSelectedViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactsSelectedViewController.swift index 4436ca01..bdc26ed0 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactsSelectedViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunContactsSelectedViewController.swift @@ -8,8 +8,8 @@ import UIKit @objcMembers open class FunContactsSelectedViewController: NEBaseContactsSelectedViewController { - override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { - super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + override init(filterUsers: Set? = nil) { + super.init(filterUsers: filterUsers) customCells = [ContactCellType.ContactPerson.rawValue: FunContactSelectedCell.self] view.backgroundColor = .funContactBackgroundColor } diff --git a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunTeamListViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunTeamListViewController.swift index b7c5ef7c..3623240a 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunTeamListViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/FunUI/ViewController/FunTeamListViewController.swift @@ -18,8 +18,8 @@ open class FunTeamListViewController: NEBaseTeamListViewController { tableView.rowHeight = 72 } - override public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + override open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: "\(NSStringFromClass(FunTeamTableViewCell.self))", for: indexPath diff --git a/NEContactUIKit/NEContactUIKit/Classes/Model/ContactInfo.swift b/NEContactUIKit/NEContactUIKit/Classes/Model/ContactInfo.swift index 5504ed86..9ffbfeee 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Model/ContactInfo.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Model/ContactInfo.swift @@ -8,13 +8,18 @@ import NECoreIMKit import NECoreKit import UIKit +/* + 通讯录 cell 数据模型 + // contactCellType: 自定义 UI 类型,其在注册会话列表 cell 时作为 key 与自定义 cell 进行绑定 + // localExtension: 本地扩展字段,可根据业务需求添加数据,与 contactCellType 结合可实现多种自定义 cell 的展示 + */ @objcMembers open class ContactInfo: NSObject { func getRowHeight() -> CGFloat? { nil } - public var user: User? + public var user: NEKitUser? public var contactCellType = ContactCellType.ContactPerson.rawValue public var router = ContactPersonRouter public var isSelected = false diff --git a/NEContactUIKit/NEContactUIKit/Classes/Model/ContactSection.swift b/NEContactUIKit/NEContactUIKit/Classes/Model/ContactSection.swift index 456f2523..d2eee358 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Model/ContactSection.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Model/ContactSection.swift @@ -7,6 +7,11 @@ import Foundation import NEChatKit import NECoreIMKit +/* + 通讯录 section 数据模型 + // initial: tableView 对应 section 的标题 + // contacts: tableView 对应 section 的数据 + */ @objcMembers open class ContactSection { public var initial: String diff --git a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/NromalContactRouter.swift b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/NromalContactRouter.swift index 601161a6..20486958 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/NromalContactRouter.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/NromalContactRouter.swift @@ -13,10 +13,8 @@ public extension ContactRouter { Router.shared.register(ContactUserSelectRouter) { param in print("param:\(param)") let nav = param["nav"] as? UINavigationController - let contactSelectVC = ContactsSelectedViewController() - if let fiters = param["filters"] as? Set { - contactSelectVC.filterUsers = fiters - } + let filters = param["filters"] as? Set + let contactSelectVC = ContactsSelectedViewController(filterUsers: filters) if let limit = param["limit"] as? Int, limit > 0 { contactSelectVC.limit = limit } @@ -34,10 +32,10 @@ public extension ContactRouter { Router.shared.register(ContactUserInfoPageRouter) { param in if let nav = param["nav"] as? UINavigationController { - if let user = param["user"] as? User { + if let user = param["user"] as? NEKitUser { let userInfoVC = ContactUserViewController(user: user) nav.pushViewController(userInfoVC, animated: true) - } else if let nimUser = param["nim_user"] as? User { + } else if let nimUser = param["nim_user"] as? NEKitUser { let userInfoVC = ContactUserViewController(user: nimUser) nav.pushViewController(userInfoVC, animated: true) } else if let uid = param["uid"] as? String { diff --git a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/View/UserInfoHeaderView.swift b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/View/UserInfoHeaderView.swift index b3efc216..c390bcb2 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/View/UserInfoHeaderView.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/View/UserInfoHeaderView.swift @@ -8,7 +8,7 @@ import UIKit @objcMembers open class UserInfoHeaderView: NEBaseUserInfoHeaderView { - override public func commonUI() { + override open func commonUI() { super.commonUI() avatarImage.layer.cornerRadius = 30 @@ -20,7 +20,7 @@ open class UserInfoHeaderView: NEBaseUserInfoHeaderView { ]) } - override public func setData(user: User?) { + override open func setData(user: NEKitUser?) { super.setData(user: user) guard let u = user else { return diff --git a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/BlackListViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/BlackListViewController.swift index b4b3e5e9..093dcd78 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/BlackListViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/BlackListViewController.swift @@ -34,7 +34,7 @@ open class BlackListViewController: NEBaseBlackListViewController { ContactsSelectedViewController() } - override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: "\(NSStringFromClass(BlackListCell.self))", for: indexPath diff --git a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactUserViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactUserViewController.swift index afb59116..52cd8e37 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactUserViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactUserViewController.swift @@ -15,7 +15,7 @@ open class ContactUserViewController: NEBaseContactUserViewController { headerView = UserInfoHeaderView() } - override public init(user: User?) { + override public init(user: NEKitUser?) { super.init(user: user) initNormal() } @@ -34,7 +34,7 @@ open class ContactUserViewController: NEBaseContactUserViewController { tableView.rowHeight = 62 } - override public func getContactRemakNameViewController() -> NEBaseContactRemakNameViewController { + override open func getContactRemakNameViewController() -> NEBaseContactRemakNameViewController { ContactRemakNameViewController() } } diff --git a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactsSelectedViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactsSelectedViewController.swift index 71928f50..db8c3f96 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactsSelectedViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/ContactsSelectedViewController.swift @@ -8,8 +8,8 @@ import UIKit @objcMembers open class ContactsSelectedViewController: NEBaseContactsSelectedViewController { - override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { - super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + override init(filterUsers: Set? = nil) { + super.init(filterUsers: filterUsers) customCells = [ContactCellType.ContactPerson.rawValue: ContactSelectedCell.self] view.backgroundColor = .ne_backcolor navigationView.backgroundColor = .white diff --git a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/TeamListViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/TeamListViewController.swift index de64abf2..8d715237 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/TeamListViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/NormalUI/ViewController/TeamListViewController.swift @@ -20,8 +20,8 @@ open class TeamListViewController: NEBaseTeamListViewController { tableView.rowHeight = 62 } - override public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + override open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: "\(NSStringFromClass(TeamTableViewCell.self))", for: indexPath diff --git a/NEContactUIKit/NEContactUIKit/Classes/Team/Cell/NEBaseTeamTableViewCell.swift b/NEContactUIKit/NEContactUIKit/Classes/Team/Cell/NEBaseTeamTableViewCell.swift index 609446eb..7798afdf 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Team/Cell/NEBaseTeamTableViewCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Team/Cell/NEBaseTeamTableViewCell.swift @@ -69,8 +69,8 @@ open class NEBaseTeamTableViewCell: UITableViewCell { // ]) } - public func setModel(_ model: Any) { - guard let team = model as? Team else { + open func setModel(_ model: Any) { + guard let team = model as? NETeam else { return } guard let name = team.teamName else { @@ -78,7 +78,7 @@ open class NEBaseTeamTableViewCell: UITableViewCell { } titleLabel.text = name // self.nameLabel.text = name.count > 2 ? String(name[name.index(name.endIndex, offsetBy: -2)...]) : name - if let url = team.thumbAvatarUrl { + if let url = team.thumbAvatarUrl, !url.isEmpty { avatarImage.sd_setImage(with: URL(string: url), completed: nil) avatarImage.backgroundColor = .clear } else { diff --git a/NEContactUIKit/NEContactUIKit/Classes/Team/ViewController/NEBaseTeamListViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Team/ViewController/NEBaseTeamListViewController.swift index 5588d158..672b98eb 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Team/ViewController/NEBaseTeamListViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Team/ViewController/NEBaseTeamListViewController.swift @@ -14,7 +14,7 @@ open class NEBaseTeamListViewController: UIViewController, UITableViewDelegate, var viewModel = TeamListViewModel() var isClickCallBack = false - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white navigationController?.interactivePopGestureRecognizer?.delegate = self @@ -76,16 +76,16 @@ open class NEBaseTeamListViewController: UIViewController, UITableViewDelegate, tableView.reloadData() } - public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel.teamList.count } - public func tableView(_ tableView: UITableView, - cellForRowAt indexPath: IndexPath) -> UITableViewCell { + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { UITableViewCell() } - public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = viewModel.teamList[indexPath.row] if isClickCallBack == true { Router.shared.use( diff --git a/NEContactUIKit/NEContactUIKit/Classes/Team/ViewModel/TeamListViewModel.swift b/NEContactUIKit/NEContactUIKit/Classes/Team/ViewModel/TeamListViewModel.swift index 03d0f459..dc08705b 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Team/ViewModel/TeamListViewModel.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Team/ViewModel/TeamListViewModel.swift @@ -8,10 +8,10 @@ import NECoreIMKit import NECoreKit @objcMembers -public class TeamListViewModel: NSObject, NIMTeamManagerDelegate { +open class TeamListViewModel: NSObject, NIMTeamManagerDelegate { var contactRepo = ContactRepo.shared var refresh: () -> Void = {} - public var teamList = [Team]() + public var teamList = [NETeam]() private let className = "TeamListViewModel" override public init() { @@ -23,7 +23,7 @@ public class TeamListViewModel: NSObject, NIMTeamManagerDelegate { contactRepo.removeTeamDelegate(delegate: self) } - func getTeamList() -> [Team]? { + func getTeamList() -> [NETeam]? { NELog.infoLog(ModuleName + " " + className, desc: #function) teamList = contactRepo.getTeamList() teamList.sort(by: { team1, team2 in @@ -35,14 +35,14 @@ public class TeamListViewModel: NSObject, NIMTeamManagerDelegate { // MARK: NIMTeamManagerDelegate public func onTeamAdded(_ team: NIMTeam) { - teamList.insert(Team(teamInfo: team), at: 0) + teamList.insert(NETeam(teamInfo: team), at: 0) refresh() } public func onTeamUpdated(_ team: NIMTeam) { for (i, t) in teamList.enumerated() { if t.teamId == team.teamId { - teamList[i] = Team(teamInfo: team) + teamList[i] = NETeam(teamInfo: team) refresh() break } diff --git a/NEContactUIKit/NEContactUIKit/Classes/Validation/Controller/NEBaseValidationMessageViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Validation/Controller/NEBaseValidationMessageViewController.swift index a0c17c8f..02b3820c 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Validation/Controller/NEBaseValidationMessageViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Validation/Controller/NEBaseValidationMessageViewController.swift @@ -97,7 +97,7 @@ open class NEBaseValidationMessageViewController: NEBaseContactViewController { } } - public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { viewModel.clearNotiUnreadCount() return true } @@ -120,8 +120,8 @@ extension NEBaseValidationMessageViewController: UITableViewDelegate, UITableVie } extension NEBaseValidationMessageViewController: SystemNotificationCellDelegate { - public func changeValidationStatus(notifiModel: XNotification, notiStatus: IMHandleStatus) { - var notifiModels = [XNotification]() + open func changeValidationStatus(notifiModel: NENotification, notiStatus: NEHandleStatus) { + var notifiModels = [NENotification]() if let msgList = notifiModel.msgList, msgList.count > 0 { for msg in msgList { @@ -141,7 +141,7 @@ extension NEBaseValidationMessageViewController: SystemNotificationCellDelegate loadData() } - open func onAccept(_ notifiModel: XNotification) { + open func onAccept(_ notifiModel: NENotification) { weak var weakSelf = self guard let teamId = notifiModel.targetID, let invitorId = notifiModel.sourceID else { return @@ -157,7 +157,7 @@ extension NEBaseValidationMessageViewController: SystemNotificationCellDelegate NELog.infoLog(ModuleName + " " + (weakSelf?.tag ?? "ValidationMessageViewController"), desc: "❌CALLBACK acceptInviteWithTeam failed,error = \(error!.localizedDescription)") if err.code == 807 || err.code == 809 { weakSelf?.showToast(localizable("validate_processed")) - } else if err.code == 803 { + } else if err.code == teamNotExistCode { weakSelf?.showToast(localizable("team_not_exist")) } else { weakSelf?.showToast(localizable("failed_operation")) @@ -186,7 +186,7 @@ extension NEBaseValidationMessageViewController: SystemNotificationCellDelegate } } - open func onRefuse(_ notifiModel: XNotification) { + open func onRefuse(_ notifiModel: NENotification) { weak var weakSelf = self guard let teamId = notifiModel.targetID, let invitorId = notifiModel.sourceID else { return @@ -202,7 +202,7 @@ extension NEBaseValidationMessageViewController: SystemNotificationCellDelegate NELog.infoLog(ModuleName + " " + (weakSelf?.tag ?? "ValidationMessageViewController"), desc: "❌CALLBACK rejectInviteWithTeam failed,error = \(error!.localizedDescription)") if err.code == 807 || err.code == 809 { weakSelf?.showToast(localizable("validate_processed")) - } else if err.code == 803 { + } else if err.code == teamNotExistCode { weakSelf?.showToast(localizable("team_not_exist")) } else { weakSelf?.showToast(localizable("failed_operation")) diff --git a/NEContactUIKit/NEContactUIKit/Classes/Validation/ViewModel/ValidationMessageViewModel.swift b/NEContactUIKit/NEContactUIKit/Classes/Validation/ViewModel/ValidationMessageViewModel.swift index a85ab45b..4c6265dd 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Validation/ViewModel/ValidationMessageViewModel.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Validation/ViewModel/ValidationMessageViewModel.swift @@ -8,13 +8,13 @@ import NECoreIMKit import NECoreKit @objcMembers -public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate { +open class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate { typealias DataRefresh = () -> Void var dataRefresh: DataRefresh? private let className = "ValidationMessageViewModel" let contactRepo = ContactRepo.shared - var datas = [XNotification]() + var datas = [NENotification]() override init() { NELog.infoLog(ModuleName + " " + className, desc: #function) @@ -22,10 +22,10 @@ public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate contactRepo.notiDelegate = self } - public func onNotificationUnreadCountChanged(_ count: Int) {} + open func onNotificationUnreadCountChanged(_ count: Int) {} // 内容待完善 -// public func onRecieveNotification(_ notification: XNotification) { +// open func onRecieveNotification(_ notification: XNotification) { // NELog.infoLog(className, desc: #function) // var isInsert = true // for notify in datas { @@ -56,7 +56,7 @@ public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate // } // } - func isExist(xNoti: inout XNotification, list: inout [XNotification]) -> Bool { + func isExist(xNoti: inout NENotification, list: inout [NENotification]) -> Bool { for loopList in list { if xNoti.isEqualTo(noti: loopList) { if loopList.msgList == nil { @@ -83,7 +83,7 @@ public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate return false } - public func onRecieveNotification(_ notification: XNotification) { + open func onRecieveNotification(_ notification: NENotification) { NELog.infoLog(ModuleName + " " + className, desc: #function) var noti = notification if !isExist(xNoti: ¬i, list: &datas) { @@ -100,7 +100,7 @@ public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate func getValidationMessage(_ completin: @escaping () -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function) contactRepo.getNotificationList(limit: 500) { [weak self] xNotiList in - var data = [XNotification]() + var data = [NENotification]() let dateNow = Date().timeIntervalSince1970 for xNoti in xNotiList { var noti = xNoti @@ -140,21 +140,21 @@ public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate completion() } - public func acceptInviteWithTeam(_ teamId: String, _ invitorId: String, - _ completion: @escaping (Error?) -> Void) { + open func acceptInviteWithTeam(_ teamId: String, _ invitorId: String, + _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:\(teamId)") contactRepo.acceptTeamInvite(teamId, invitorId, completion) } - public func rejectInviteWithTeam(_ teamId: String, _ invitorId: String, - _ completion: @escaping (Error?) -> Void) { + open func rejectInviteWithTeam(_ teamId: String, _ invitorId: String, + _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:\(teamId)") contactRepo.rejectTeamInvite(teamId, invitorId, completion) } func agreeRequest(_ account: String, _ completion: @escaping (NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account:\(account)") - let request = AddFriendRequest() + let request = NEAddFriendRequest() request.account = account request.operationType = .verify contactRepo.addFriend(request: request, completion) @@ -163,7 +163,7 @@ public class ValidationMessageViewModel: NSObject, ContactRepoSystemNotiDelegate func refuseRequest(_ account: String, _ completion: @escaping (NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account:\(account)") print("account : ", account) - let request = AddFriendRequest() + let request = NEAddFriendRequest() request.account = account request.operationType = .reject contactRepo.addFriend(request: request, completion) diff --git a/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseSystemNotificationCell.swift b/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseSystemNotificationCell.swift index 577d3c24..09ef5d3d 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseSystemNotificationCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseSystemNotificationCell.swift @@ -11,7 +11,7 @@ import UIKit @objcMembers open class NEBaseSystemNotificationCell: NEBaseValidationCell { - private var notifModel: XNotification? + private var notifModel: NENotification? public weak var delegate: SystemNotificationCellDelegate? override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { @@ -58,7 +58,7 @@ open class NEBaseSystemNotificationCell: NEBaseValidationCell { ]) } - override open func confige(_ model: XNotification) { + override open func confige(_ model: NENotification) { super.confige(model) notifModel = model let hideActionButton = shouldHideActionButton() diff --git a/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseValidationCell.swift b/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseValidationCell.swift index d932a19e..d8dab8b7 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseValidationCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Validation/Views/NEBaseValidationCell.swift @@ -8,8 +8,8 @@ import NIMSDK import UIKit public protocol SystemNotificationCellDelegate: AnyObject { - func onAccept(_ notifiModel: XNotification) - func onRefuse(_ notifiModel: XNotification) + func onAccept(_ notifiModel: NENotification) + func onRefuse(_ notifiModel: NENotification) } enum NotificationHandleType: Int { @@ -24,17 +24,6 @@ open class NEBaseValidationCell: NEBaseContactViewCell { public var titleLabelRightMargin: NSLayoutConstraint? let line = UIView() - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() @@ -83,7 +72,7 @@ open class NEBaseValidationCell: NEBaseContactViewCell { line.backgroundColor = UIColor(hexString: "#F5F8FC") } - open func confige(_ model: XNotification) { + open func confige(_ model: NENotification) { var optionLabelContent = "" var nickName = "" var teamName = "" @@ -99,9 +88,9 @@ open class NEBaseValidationCell: NEBaseContactViewCell { if model.userInfo == nil, let uid = model.sourceID { let user = NIMSDK.shared().userManager.userInfo(uid) - if let alias = user?.alias { + if let alias = user?.alias, !alias.isEmpty { nickName = alias - } else if let nick = user?.userInfo?.nickName { + } else if let nick = user?.userInfo?.nickName, !nick.isEmpty { nickName = nick } } diff --git a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactGroup.swift b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactGroup.swift index bfbec8e0..0818080f 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactGroup.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactGroup.swift @@ -6,4 +6,4 @@ import Foundation @objcMembers -public class ContactGroup {} +open class ContactGroup {} diff --git a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactUserViewModel.swift b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactUserViewModel.swift index e13150e0..ad7bd690 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactUserViewModel.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactUserViewModel.swift @@ -9,52 +9,52 @@ import NECoreIMKit import NECoreKit @objcMembers -public class ContactUserViewModel: NSObject { +open class ContactUserViewModel: NSObject { let contactRepo = ContactRepo.shared private let className = "ContactUserViewModel" func addFriend(_ account: String, _ completion: @escaping (NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account: " + account) - let request = AddFriendRequest() + let request = NEAddFriendRequest() request.account = account request.operationType = .addRequest contactRepo.addFriend(request: request, completion) } - public func deleteFriend(account: String, _ completion: @escaping (NSError?) -> Void) { + open func deleteFriend(account: String, _ completion: @escaping (NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account: " + account) contactRepo.deleteFriend(account: account, completion) } - public func isFriend(account: String) -> Bool { + open func isFriend(account: String) -> Bool { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account: " + account) return contactRepo.isFriend(account: account) } - public func isBlack(account: String) -> Bool { + open func isBlack(account: String) -> Bool { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account: " + account) return contactRepo.isBlackList(account: account) } - public func removeBlackList(account: String, _ completion: @escaping (NSError?) -> Void) { + open func removeBlackList(account: String, _ completion: @escaping (NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", account: " + account) return contactRepo.removeBlackList(account: account, completion) } - public func update(_ user: User, _ completion: @escaping (Error?) -> Void) { + open func update(_ user: NEKitUser, _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId: " + (user.userId ?? "nil")) contactRepo.updateUser(user, completion) } - public func getUserInfo(_ uid: String, _ completion: @escaping (Error?, User?) -> Void) { + open func getUserInfo(_ uid: String, _ completion: @escaping (Error?, NEKitUser?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", uid: " + uid) contactRepo.getUserInfo(uid) { error, users in completion(error, users?.first) } } - public func fetchUserInfo(accountList: [String], - _ completion: @escaping ([User]?, NSError?) -> Void) { + open func fetchUserInfo(accountList: [String], + _ completion: @escaping ([NEKitUser]?, NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", uid: \(accountList)") contactRepo.fetchUserInfo(accountList: accountList) { users, error in completion(users, error) diff --git a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactViewModel.swift b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactViewModel.swift index e7be32c9..579710d7 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactViewModel.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/ContactViewModel.swift @@ -9,7 +9,7 @@ import NECoreKit import UIKit @objcMembers -public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { +open class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { typealias RefreshBlock = () -> Void public var contacts: [ContactSection] = [] public var indexs: [String]? @@ -32,7 +32,7 @@ public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { self.contactHeaders = contactHeaders } - public func onNotificationUnreadCountChanged(_ count: Int) { + open func onNotificationUnreadCountChanged(_ count: Int) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", count: \(count)") print("onNotificationUnreadCountChanged : ", count) unreadCount = count @@ -41,14 +41,14 @@ public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { } } - public func onRecieveNotification(_ notification: XNotification) {} + open func onRecieveNotification(_ notification: NENotification) {} func loadData(fetch: Bool = false, _ filters: Set? = nil, completion: @escaping (NSError?, Int) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function) weak var weakSelf = self getContactList(fetch, filters) { contacts, error in if let users = contacts { - NELog.infoLog("contact loadData", desc: "contact data:\(contacts)") + NELog.infoLog("contact loadData", desc: "contact data:\(users)") weakSelf?.contacts = users weakSelf?.indexs = self.getIndexs(contactSections: users) if let headSection = weakSelf?.headerSection(headerItem: weakSelf?.contactHeaders) { @@ -59,10 +59,6 @@ public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { } } - func reLoadData(completion: @escaping (NSError?, Int) -> Void) { - loadData(fetch: true, completion: completion) - } - func getContactList(_ fetch: Bool = false, _ filters: Set? = nil, _ completion: @escaping ([ContactSection]?, NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", filters.count: \(filters?.count ?? 0)") var contactList: [ContactSection] = [] @@ -73,7 +69,7 @@ public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { } contactRepo.getFriendList(fetch, local: local) { friends, error in if var users = friends { - NELog.infoLog("contact bar getFriendList", desc: "friend count:\(friends?.count)") + NELog.infoLog("contact bar getFriendList", desc: "friend count:\(users.count)") weakSelf?.initalDict = [String: [ContactInfo]]() if let filterUsers = filters { users = users.filter { user in @@ -87,16 +83,15 @@ public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { if users.isEmpty { completion(contactList, nil) return -// return contactList } let digitRegular = NSPredicate(format: "SELF MATCHES %@", "[0-9]") let azRegular = NSPredicate(format: "SELF MATCHES %@", "[A-Z]") var digitList = [ContactInfo]() var specialCharList = [ContactInfo]() - for contact: User in users { + for contact: NEKitUser in users { // get inital of name - var name = contact.alias != nil ? contact.alias : contact.userInfo?.nickName + var name = contact.alias?.isEmpty == false ? contact.alias : contact.userInfo?.nickName if name == nil { name = contact.userId } @@ -158,9 +153,9 @@ public class ContactViewModel: NSObject, ContactRepoSystemNotiDelegate { } var infos: [ContactInfo] = [] for item in header { - let user = User() + let user = NEKitUser() user.alias = item.name - let userInfo = UserInfo(nickName: "", avatar: item.imageName) + let userInfo = NEKitUserInfo(nickName: "", avatar: item.imageName) user.userInfo = userInfo let info = ContactInfo() diff --git a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/FindFriendViewModel.swift b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/FindFriendViewModel.swift index 3f1f5eb4..3bc5bcf8 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/ViewModel/FindFriendViewModel.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/ViewModel/FindFriendViewModel.swift @@ -8,11 +8,11 @@ import NECoreIMKit import NECoreKit @objcMembers -public class FindFriendViewModel: NSObject { +open class FindFriendViewModel: NSObject { let contactRepo = ContactRepo.shared private let className = "FindFriendViewModel" - func searchFriend(_ text: String, _ completion: @escaping ([User]?, NSError?) -> Void) { + func searchFriend(_ text: String, _ completion: @escaping ([NEKitUser]?, NSError?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", text: \(text.count)") contactRepo.fetchUserInfo(accountList: [text], completion) } diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactSelectedCell.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactSelectedCell.swift index cb8e2180..c61d8f08 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactSelectedCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactSelectedCell.swift @@ -10,17 +10,6 @@ open class NEBaseContactSelectedCell: NEBaseContactTableViewCell { var sModel: ContactInfo? - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override open func commonUI() { super.commonUI() leftConstraint?.constant = 50 @@ -30,7 +19,7 @@ open class NEBaseContactSelectedCell: NEBaseContactTableViewCell { sImage.accessibilityIdentifier = "id.selector" } - override public func setModel(_ model: ContactInfo) { + override open func setModel(_ model: ContactInfo) { super.setModel(model) if model.isSelected == false { sImage.isHighlighted = false diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactTableViewCell.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactTableViewCell.swift index 3fbc0b60..7830549b 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactTableViewCell.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/Cell/NEBaseContactTableViewCell.swift @@ -4,6 +4,7 @@ // found in the LICENSE file. import Foundation +import NEChatKit import NECoreIMKit import NECoreKit import UIKit @@ -63,8 +64,9 @@ open class NEBaseContactTableViewCell: NEBaseContactViewCell, ContactCellDataPro contentView.addSubview(redAngleView) NSLayoutConstraint.activate([ - redAngleView.centerYAnchor.constraint(equalTo: arrow.centerYAnchor), + redAngleView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), redAngleView.rightAnchor.constraint(equalTo: arrow.leftAnchor, constant: -10), + redAngleView.heightAnchor.constraint(equalToConstant: 18), ]) } @@ -85,11 +87,15 @@ open class NEBaseContactTableViewCell: NEBaseContactViewCell, ContactCellDataPro } open func setModel(_ model: ContactInfo) { - guard let user = model.user else { + guard var user = model.user else { return } setConfig() + if let userId = user.userId, let u = ChatUserCache.getUserInfo(userId) { + user = u + } + if model.contactCellType == 1 { NELog.infoLog("contact other cell configData", desc: "\(user.alias), image name:\(user.userInfo?.avatarUrl)") nameLabel.text = "" diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactRemakNameViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactRemakNameViewController.swift index a3cb1c48..bb6bd6e7 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactRemakNameViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactRemakNameViewController.swift @@ -3,16 +3,17 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit import NECoreIMKit import NECoreKit import UIKit @objcMembers open class NEBaseContactRemakNameViewController: NEBaseContactViewController, UITextFieldDelegate { - typealias ModifyBlock = (_ user: User) -> Void + typealias ModifyBlock = (_ user: NEKitUser) -> Void var completion: ModifyBlock? - var user: User? + var user: NEKitUser? let viewmodel = ContactUserViewModel() let textLimit = 15 lazy var aliasInput: UITextField = { @@ -42,7 +43,7 @@ open class NEBaseContactRemakNameViewController: NEBaseContactViewController, UI // return btn // }() - override public func viewDidLoad() { + override open func viewDidLoad() { super.viewDidLoad() setupUI() } @@ -58,7 +59,7 @@ open class NEBaseContactRemakNameViewController: NEBaseContactViewController, UI view.addSubview(aliasInput) aliasInput.placeholder = localizable("input_noteName") - if let alias = user?.alias { + if let alias = user?.alias, !alias.isEmpty { aliasInput.text = alias } } @@ -82,7 +83,11 @@ open class NEBaseContactRemakNameViewController: NEBaseContactViewController, UI return } - user?.alias = aliasInput.text + if user?.alias != aliasInput.text { + user?.alias = aliasInput.text + NotificationCenter.default.post(name: NENotificationName.updateFriendInfo, object: user) + } + if let u = user { view.makeToastActivity(.center) viewmodel.update(u) { error in @@ -117,7 +122,7 @@ open class NEBaseContactRemakNameViewController: NEBaseContactViewController, UI } */ - public func textFieldChange() { + open func textFieldChange() { guard let _ = aliasInput.markedTextRange else { if let text = aliasInput.text, text.count > textLimit { diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactUserViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactUserViewController.swift index 01ba9f47..3c3afa2d 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactUserViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactUserViewController.swift @@ -3,6 +3,7 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit import NECoreIMKit import NECoreKit import NIMSDK @@ -11,7 +12,7 @@ import UIKit @objcMembers open class NEBaseContactUserViewController: NEBaseContactViewController, UITableViewDelegate, UITableViewDataSource { - var user: User? + var user: NEKitUser? var uid: String? public var isBlack: Bool = false var className = "ContactUserViewController" @@ -21,7 +22,7 @@ open class NEBaseContactUserViewController: NEBaseContactViewController, UITable var data = [[UserItem]]() public var headerView = NEBaseUserInfoHeaderView() - public init(user: User?) { + public init(user: NEKitUser?) { super.init(nibName: nil, bundle: nil) self.user = user uid = user?.userId @@ -56,7 +57,7 @@ open class NEBaseContactUserViewController: NEBaseContactViewController, UITable weakSelf?.showToast(err.localizedDescription) } else if let u = users?.first { weakSelf?.user = u - NotificationCenter.default.post(name: NotificationName.updateFriendInfo, object: u) + ChatUserCache.updateUserInfo(u) weakSelf?.loadData() } } @@ -233,24 +234,24 @@ open class NEBaseContactUserViewController: NEBaseContactViewController, UITable return cell } - public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } return 6.0 } - public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { + open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView() header.backgroundColor = UIColor.clear return header } - public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { + open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { 0 } - public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { + open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { nil } @@ -291,7 +292,7 @@ open class NEBaseContactUserViewController: NEBaseContactViewController, UITable remark.completion = { [weak self] u in self?.user = u self?.headerView.setData(user: u) - NotificationCenter.default.post(name: NotificationName.updateFriendInfo, object: u) + ChatUserCache.updateUserInfo(u) } navigationController?.pushViewController(remark, animated: true) @@ -339,25 +340,20 @@ open class NEBaseContactUserViewController: NEBaseContactViewController, UITable } } - func chat(user: User?) { + func chat(user: NEKitUser?) { guard let accid = self.user?.userId else { return } + let session = NIMSession(accid, type: .P2P) Router.shared.use( PushP2pChatVCRouter, - parameters: ["nav": navigationController as Any, "session": session], + parameters: ["nav": navigationController as Any, "session": session, "removeUserVC": true], closure: nil ) - - // 移除当前页面 - if let selfVCIndex = navigationController?.viewControllers.firstIndex(of: self), - selfVCIndex > 0 { - navigationController?.viewControllers.remove(at: selfVCIndex) - } } - func deleteFriendAction(user: User?) { + func deleteFriendAction(user: NEKitUser?) { weak var weakSelf = self if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { weakSelf?.showToast(commonLocalizable("network_error")) @@ -372,13 +368,14 @@ open class NEBaseContactUserViewController: NEBaseContactViewController, UITable if error != nil { self.showToast(error?.localizedDescription ?? "") } else { + ChatUserCache.removeUserInfo(userId) self.navigationController?.popViewController(animated: true) } } } } - open func deleteFriend(user: User?) { + open func deleteFriend(user: NEKitUser?) { let alertTitle = String(format: localizable("delete_title"), user?.showName(true) ?? "") let alertController = UIAlertController( title: alertTitle, diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsSelectedViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsSelectedViewController.swift index 41b99150..c29e1b79 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsSelectedViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsSelectedViewController.swift @@ -67,14 +67,13 @@ open class NEBaseContactsSelectedViewController: NEBaseContactViewController, UI var tableViewTopAnchor: NSLayoutConstraint? - override open func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - weak var weakSelf = self - viewModel.loadData(filterUsers) { error, userSectionCount in - weakSelf?.emptyView.isHidden = userSectionCount > 0 - weakSelf?.tableView.reloadData() - weakSelf?.emptyView.isHidden = (weakSelf?.viewModel.contacts.count ?? 0) > 0 - } + init(filterUsers: Set? = nil) { + super.init(nibName: nil, bundle: nil) + self.filterUsers = filterUsers + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { @@ -84,6 +83,12 @@ open class NEBaseContactsSelectedViewController: NEBaseContactViewController, UI emptyView.settingContent(content: localizable("no_friend")) setupUI() setupNavRightItem() + + weak var weakSelf = self + viewModel.loadData(filterUsers) { error, userSectionCount in + weakSelf?.emptyView.isHidden = userSectionCount > 0 + weakSelf?.tableView.reloadData() + } } open func setupUI() { @@ -176,7 +181,10 @@ open class NEBaseContactsSelectedViewController: NEBaseContactViewController, UI if let completion = callBack { completion(selectArray) + navigationController?.popViewController(animated: true) + return } + var accids = [String]() var names = [String]() diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsViewController.swift index 25c53333..4f418728 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseContactsViewController.swift @@ -2,6 +2,7 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit import NECoreIMKit import NECoreKit import UIKit @@ -13,7 +14,7 @@ public protocol NEBaseContactsViewControllerDelegate { @objcMembers open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, - SystemMessageProviderDelegate, FriendProviderDelegate, TabNavigationViewDelegate { + SystemMessageProviderDelegate, FriendProviderDelegate, TabNavigationViewDelegate, UIGestureRecognizerDelegate { public var delegate: NEBaseContactsViewControllerDelegate? // custom ui cell @@ -51,12 +52,19 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, } override open func viewWillAppear(_ animated: Bool) { - // 刷新数据 - viewModel.reLoadData { [weak self] error, userSectionCount in - self?.emptyView.isHidden = userSectionCount > 0 - if error == nil { - self?.delegate?.onDataLoaded() - self?.tableView.reloadData() + super.viewWillAppear(animated) + + // 通讯录异步进行远端加载 + if IMKitConfigCenter.shared.contactAsyncLoadEnable { + DispatchQueue.main.async { + self.loadData(fetch: true) + } + } + if navigationController?.viewControllers.count ?? 0 > 0 { + if let root = navigationController?.viewControllers[0] as? UIViewController { + if root.isKind(of: NEBaseContactsViewController.self) { + navigationController?.interactivePopGestureRecognizer?.delegate = self + } } } } @@ -66,8 +74,12 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, showTitleBar() commonUI() viewModel.refresh = { [weak self] in - self?.tableView.reloadData() + self?.didRefreshTable() } + + loadData(fetch: true) + + NotificationCenter.default.addObserver(self, selector: #selector(didRefreshTable), name: NENotificationName.updateFriendInfo, object: nil) } deinit { @@ -145,6 +157,16 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, } } + open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if let navigationController = navigationController, + navigationController.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)), + gestureRecognizer == navigationController.interactivePopGestureRecognizer, + navigationController.visibleViewController == navigationController.viewControllers.first { + return false + } + return true + } + // MARK: lazy load public lazy var navigationView: TabNavigationView = { @@ -236,12 +258,12 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, return view }() - open func loadData() { - viewModel.loadData { [weak self] error, userSectionCount in + open func loadData(fetch: Bool = false) { + viewModel.loadData(fetch: fetch) { [weak self] error, userSectionCount in self?.emptyView.isHidden = userSectionCount > 0 if error == nil { self?.delegate?.onDataLoaded() - self?.tableView.reloadData() + self?.didRefreshTable() } } } @@ -360,9 +382,13 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, } } + func didRefreshTable() { + tableView.reloadData() + } + // MARK: SystemMessageProviderDelegate - open func onRecieveNotification(notification: XNotification) { + open func onRecieveNotification(notification: NENotification) { print("onRecieveNotification type:\(notification.type)") if notification.type == .addFriendDirectly { loadData() @@ -372,12 +398,12 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, open func onNotificationUnreadCountChanged(count: Int) { print("unread count:\(count)") viewModel.unreadCount = count - tableView.reloadData() + didRefreshTable() } // MARK: FriendProviderDelegate - open func onFriendChanged(user: User) { + open func onFriendChanged(user: NEKitUser) { print("onFriendChanged:\(user.userId)") loadData() } @@ -387,7 +413,7 @@ open class NEBaseContactsViewController: UIViewController, UITableViewDelegate, loadData() } - open func onUserInfoChanged(user: User) { + open func onUserInfoChanged(user: NEKitUser) { print("onUserInfoChanged:\(user.userId)") loadData() } @@ -404,12 +430,12 @@ extension NEBaseContactsViewController { NEBaseFindFriendViewController() } - @objc public func goToFindFriend() { + @objc open func goToFindFriend() { let findFriendController = getFindFriendViewController() navigationController?.pushViewController(findFriendController, animated: true) } - @objc public func searchContact() { + @objc open func searchContact() { Router.shared.use( SearchContactPageRouter, parameters: ["nav": navigationController as Any], diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseFindFriendViewController.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseFindFriendViewController.swift index 51005b01..9ce375e1 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseFindFriendViewController.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseFindFriendViewController.swift @@ -85,7 +85,7 @@ open class NEBaseFindFriendViewController: NEBaseContactViewController, UITextFi ]) } - public func textFieldShouldReturn(_ textField: UITextField) -> Bool { + open func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let text = textField.text else { return false } diff --git a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseUserInfoHeaderView.swift b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseUserInfoHeaderView.swift index 8f84d9ee..6878dfae 100644 --- a/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseUserInfoHeaderView.swift +++ b/NEContactUIKit/NEContactUIKit/Classes/Views/NEBaseUserInfoHeaderView.swift @@ -146,7 +146,7 @@ open class NEBaseUserInfoHeaderView: UIView { updateConstraintsIfNeeded() } - open func setData(user: User?) { + open func setData(user: NEKitUser?) { guard let user = user else { return } diff --git a/NEConversationUIKit/NEConversationUIKit.podspec b/NEConversationUIKit/NEConversationUIKit.podspec index 972776ca..ee0ea46a 100644 --- a/NEConversationUIKit/NEConversationUIKit.podspec +++ b/NEConversationUIKit/NEConversationUIKit.podspec @@ -8,7 +8,7 @@ Pod::Spec.new do |s| s.name = 'NEConversationUIKit' - s.version = '9.6.5' + s.version = '9.7.0' s.summary = 'Netease XKit' # This description is used to generate tags and improve search results. diff --git a/NEConversationUIKit/NEConversationUIKit/Assets/en.lproj/Localizable.strings b/NEConversationUIKit/NEConversationUIKit/Assets/en.lproj/Localizable.strings index 15eea0dc..0fbc65a4 100644 --- a/NEConversationUIKit/NEConversationUIKit/Assets/en.lproj/Localizable.strings +++ b/NEConversationUIKit/NEConversationUIKit/Assets/en.lproj/Localizable.strings @@ -31,6 +31,8 @@ "file"="[File Message]"; "internet_phone"="[Audio_Chat]"; "video_chat"="[Video_Chat]"; +"custom"="[Custom Message]"; +"chat_history"="[Chat History]"; "unknown"="[Unknown Message]"; "appName"="CommsEase IM"; @@ -40,3 +42,8 @@ // error toast "network_error"="Network is not available, please check"; + + +"tip"="[tip message]"; +"leave_team"="离开群聊"; +"leave_team_desc"="您已被移除群聊或群聊已解散"; diff --git a/NEConversationUIKit/NEConversationUIKit/Assets/zh-Hans.lproj/Localizable.strings b/NEConversationUIKit/NEConversationUIKit/Assets/zh-Hans.lproj/Localizable.strings index 26c79f20..6369c851 100644 --- a/NEConversationUIKit/NEConversationUIKit/Assets/zh-Hans.lproj/Localizable.strings +++ b/NEConversationUIKit/NEConversationUIKit/Assets/zh-Hans.lproj/Localizable.strings @@ -29,8 +29,10 @@ "location"="[地理位置]"; "notification"="[通知消息]"; "file"="[文件消息]"; -"internet_phone"="[音频通话]"; +"internet_phone"="[语音通话]"; "video_chat"="[视频通话]"; +"custom"="[自定义消息]"; +"chat_history"="[聊天记录]"; "unknown"="[未知消息体]"; "appName"="云信IM"; @@ -41,3 +43,7 @@ // error toast "network_error"="当前网络不可用,请检查你的网络设置"; + +"tip"="[提醒消息]"; +"leave_team"="离开群聊"; +"leave_team_desc"="您已被移除群聊或群聊已解散"; diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Common/ConversationDeduplicationHelper.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Common/ConversationDeduplicationHelper.swift new file mode 100644 index 00000000..3350b588 --- /dev/null +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Common/ConversationDeduplicationHelper.swift @@ -0,0 +1,50 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import Foundation +import NIMSDK +@objcMembers +public class ConversationDeduplicationHelper: NSObject, NIMLoginManagerDelegate { + // 单例变量 + static let instance = ConversationDeduplicationHelper() + // 最多缓存数量,可外部修改 + public var limit = 100 + // 撤回消息记录 + public var revokeMessageIds = Set() + + override private init() { + super.init() + NIMSDK.shared().loginManager.add(self) + } + + deinit { + NIMSDK.shared().loginManager.remove(self) + } + + public func onLogin(_ step: NIMLoginStep) { + if step == .logout { + clearCache() + } + } + + public func onKickout(_ result: NIMLoginKickoutResult) { + clearCache() + } + + public func clearCache() { + revokeMessageIds.removeAll() + } + + // 是否已经保存过此撤回消息,防止重复保存本地撤回记录 + public func isRevokeMessageSaved(messageId: String) -> Bool { + if revokeMessageIds.contains(messageId) { + return true + } + if revokeMessageIds.count > limit { + revokeMessageIds.removeAll() + } + revokeMessageIds.insert(messageId) + return false + } +} diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationListCell.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationListCell.swift index b545372d..0cd25e6b 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationListCell.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationListCell.swift @@ -63,9 +63,14 @@ open class NEBaseConversationListCell: UITableViewCell { open func configData(sessionModel: ConversationListModel?) { guard let conversationModel = sessionModel else { return } + if let userId = conversationModel.userInfo?.userId, + let user = ChatUserCache.getUserInfo(userId) { + conversationModel.userInfo = user + } + if conversationModel.recentSession?.session?.sessionType == .P2P { // p2p head image - if let imageName = conversationModel.userInfo?.userInfo?.avatarUrl { + if let imageName = conversationModel.userInfo?.userInfo?.avatarUrl, !imageName.isEmpty { headImge.setTitle("") headImge.sd_setImage(with: URL(string: imageName), completed: nil) headImge.backgroundColor = .clear @@ -86,7 +91,7 @@ open class NEBaseConversationListCell: UITableViewCell { } else if conversationModel.recentSession?.session?.sessionType == .team { // team head image - if let imageName = conversationModel.teamInfo?.avatarUrl { + if let imageName = conversationModel.teamInfo?.avatarUrl, !imageName.isEmpty { headImge.setTitle("") headImge.sd_setImage(with: URL(string: imageName), completed: nil) headImge.backgroundColor = .clear @@ -119,6 +124,8 @@ open class NEBaseConversationListCell: UITableViewCell { } } subTitle.attributedText = mutaAttri // contentForRecentSession(message: lastMessage) + } else { + subTitle.attributedText = nil } // unRead message count @@ -153,11 +160,15 @@ open class NEBaseConversationListCell: UITableViewCell { if let lastMessage = recentSession.lastMessage { return lastMessage.timestamp } - // 服务端时间戳以毫秒为单位,需要转化 - return recentSession.updateTime / 1000 + + return 0 } func dealTime(time: TimeInterval) -> String { + if time <= 0 { + return "" + } + let targetDate = Date(timeIntervalSince1970: time) let fmt = DateFormatter() diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationSearchCell.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationSearchCell.swift index 97e115e9..10be5e15 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationSearchCell.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Cell/NEBaseConversationSearchCell.swift @@ -22,7 +22,7 @@ open class NEBaseConversationSearchCell: TextBaseCell { titleLabel.text = userInfo.showName() subTitleLabel.text = userInfo.userId - if let imageName = userInfo.userInfo?.avatarUrl { + if let imageName = userInfo.userInfo?.avatarUrl, !imageName.isEmpty { headImge.setTitle("") headImge.sd_setImage(with: URL(string: imageName), completed: nil) headImge.backgroundColor = .clear @@ -35,7 +35,7 @@ open class NEBaseConversationSearchCell: TextBaseCell { if let teamInfo = searchModel?.teamInfo { titleLabel.text = teamInfo.getShowName() subTitleLabel.text = nil - if let imageName = teamInfo.avatarUrl { + if let imageName = teamInfo.avatarUrl, !imageName.isEmpty { headImge.setTitle("") headImge.sd_setImage(with: URL(string: imageName), completed: nil) headImge.backgroundColor = .clear @@ -51,10 +51,10 @@ open class NEBaseConversationSearchCell: TextBaseCell { public var searchText: String = "" { didSet { - if let titleText = titleLabel.text, - let range = titleText.findAllIndex(searchText).first { + if let titleText = titleLabel.text { let attributedStr = NSMutableAttributedString(string: titleText) - // range必须要加,参数分别表示从索引几开始取几个字符 + // range 表示从索引几开始取几个字符 + let range = attributedStr.mutableString.range(of: searchText) attributedStr.addAttribute( .foregroundColor, value: getRangeTextColor(), @@ -65,10 +65,11 @@ open class NEBaseConversationSearchCell: TextBaseCell { titleLabelTopAnchor?.isActive = false subTitleLabel.isHidden = true } - if let subTitleText = subTitleLabel.text, - let range = subTitleText.findAllIndex(searchText).first { + + if let subTitleText = subTitleLabel.text { let attributedStr = NSMutableAttributedString(string: subTitleText) - // range必须要加,参数分别表示从索引几开始取几个字符 + // range 表示从索引几开始取几个字符 + let range = attributedStr.mutableString.range(of: searchText) attributedStr.addAttribute( .foregroundColor, value: getRangeTextColor(), diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationController.swift index f8a5b7f9..708b4de6 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationController.swift @@ -14,7 +14,7 @@ public protocol NEBaseConversationControllerDelegate { } @objcMembers -open class NEBaseConversationController: UIViewController, NIMChatManagerDelegate { +open class NEBaseConversationController: UIViewController, NIMChatManagerDelegate, UIGestureRecognizerDelegate { var className = "NEBaseConversationController" public var deleteBottonBackgroundColor: UIColor = NEConstant.hexRGB(0xA8ABB6) @@ -23,7 +23,7 @@ open class NEBaseConversationController: UIViewController, NIMChatManagerDelegat private var bodyBottomViewHeightAnchor: NSLayoutConstraint? public var contentViewTopAnchor: NSLayoutConstraint? public var topConstant: CGFloat = 0 - public var popListController = NEBasePopListViewController() + public var popListView = NEBasePopListView() public var delegate: NEBaseConversationControllerDelegate? @@ -76,6 +76,14 @@ open class NEBaseConversationController: UIViewController, NIMChatManagerDelegat self?.contentViewTopAnchor?.constant = 0 } } + + if navigationController?.viewControllers.count ?? 0 > 0 { + if let root = navigationController?.viewControllers[0] as? UIViewController { + if root.isKind(of: NEBaseConversationController.self) { + navigationController?.interactivePopGestureRecognizer?.delegate = self + } + } + } } override open func viewDidLoad() { @@ -85,16 +93,27 @@ open class NEBaseConversationController: UIViewController, NIMChatManagerDelegat requestData() initialConfig() NIMSDK.shared().chatManager.add(self) + NotificationCenter.default.addObserver(self, selector: #selector(didRefreshTable), name: NENotificationName.updateFriendInfo, object: nil) } override open func viewWillDisappear(_ animated: Bool) { - popListController.removeSelf() + popListView.removeSelf() } deinit { NIMSDK.shared().chatManager.remove(self) } + open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if let navigationController = navigationController, + navigationController.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)), + gestureRecognizer == navigationController.interactivePopGestureRecognizer, + navigationController.visibleViewController == navigationController.viewControllers.first { + return false + } + return true + } + open func showTitleBar() { if let useSystemNav = NEConfigManager.instance.getParameter(key: useSystemNav) as? Bool, useSystemNav { navigationView.isHidden = true @@ -366,8 +385,8 @@ extension NEBaseConversationController: TabNavigationViewDelegate { ) } - open func getPopListController() -> NEBasePopListViewController { - NEBasePopListViewController() + open func getPopListView() -> NEBasePopListView { + NEBasePopListView() } open func getPopListItems() -> [PopListItem] { @@ -411,10 +430,10 @@ extension NEBaseConversationController: TabNavigationViewDelegate { } if IMKitClient.instance.getConfigCenter().teamEnable { - popListController.itemDatas = getPopListItems() - popListController.view.frame = CGRect(origin: .zero, size: view.frame.size) - popListController.removeSelf() - view.addSubview(popListController.view) + popListView.itemDatas = getPopListItems() + popListView.frame = CGRect(origin: .zero, size: view.frame.size) + popListView.removeSelf() + view.addSubview(popListView) } else { Router.shared.use( ContactAddFriendRouter, @@ -485,7 +504,11 @@ extension NEBaseConversationController: TabNavigationViewDelegate { guard let msg = notification.message else { return } - saveRevokeMessage(msg) { error in + + if ConversationDeduplicationHelper.instance.isRevokeMessageSaved(messageId: msg.messageId) { + return + } + saveRevokeMessage(msg) { [weak self] error in } } @@ -580,7 +603,7 @@ extension NEBaseConversationController: UITableViewDelegate, UITableViewDataSour /* @available(iOS 11.0, *) - public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { + open func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { var rowActions = [UIContextualAction]() @@ -692,8 +715,7 @@ extension NEBaseConversationController: UITableViewDelegate, UITableViewDataSour desc: "✅CALLBACK removeStickTopSession SUCCESS" ) weakSelf?.viewModel.stickTopInfos[session] = nil - weakSelf?.viewModel.sortRecentSession() - weakSelf?.tableView.reloadData() + weakSelf?.reloadTableView() completion(nil, topSessionInfo) } } @@ -711,8 +733,7 @@ extension NEBaseConversationController: UITableViewDelegate, UITableViewDataSour NELog.infoLog(ModuleName + " " + (weakSelf?.className ?? "ConversationController"), desc: "✅CALLBACK addStickTopSession callback SUCCESS") weakSelf?.viewModel.stickTopInfos[session] = newInfo - weakSelf?.viewModel.sortRecentSession() - weakSelf?.tableView.reloadData() + weakSelf?.reloadTableView() completion(nil, newInfo) } } @@ -771,9 +792,7 @@ extension NEBaseConversationController { extension NEBaseConversationController: ConversationViewModelDelegate { open func didAddRecentSession() { NELog.infoLog("ConversationController", desc: "didAddRecentSession") - emptyView.isHidden = (viewModel.conversationListArray?.count ?? 0) > 0 - viewModel.sortRecentSession() - tableView.reloadData() + reloadTableView() } open func didUpdateRecentSession(index: Int) { @@ -785,9 +804,13 @@ extension NEBaseConversationController: ConversationViewModelDelegate { delegate?.onDataLoaded() } + open func didRefreshTable() { + tableView.reloadData() + } + open func reloadTableView() { emptyView.isHidden = (viewModel.conversationListArray?.count ?? 0) > 0 viewModel.sortRecentSession() - tableView.reloadData() + didRefreshTable() } } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationNavigationController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationNavigationController.swift index b58564e4..b642412c 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationNavigationController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationNavigationController.swift @@ -10,7 +10,7 @@ open class NEBaseConversationNavigationController: UIViewController, UIGestureRe var topConstant: CGFloat = 0 public let navigationView = NENavigationView() - override open var title: String? { + override public var title: String? { get { super.title } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationSearchController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationSearchController.swift index b0a596e4..66b23264 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationSearchController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBaseConversationSearchController.swift @@ -172,6 +172,7 @@ open class NEBaseConversationSearchController: NEBaseConversationNavigationContr } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + weak var weakSelf = self if indexPath.section == 0 { let searchModel = viewModel.searchResult?.friend[indexPath.row] if let userId = searchModel?.userInfo?.userId { @@ -186,22 +187,44 @@ open class NEBaseConversationSearchController: NEBaseConversationNavigationContr } else if indexPath.section == 1 { let searchModel = viewModel.searchResult?.contactGroup[indexPath.row] if let teamId = searchModel?.teamInfo?.teamId { - let session = NIMSession(teamId, type: .team) - Router.shared.use( - PushTeamChatVCRouter, - parameters: ["nav": navigationController as Any, "session": session as Any], - closure: nil - ) + TeamRepo.shared.fetchTeamInfo(teamId) { error, teamInfo in + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else { + weakSelf?.showSingleAlert(title: localizable("leave_team"), message: localizable("leave_team_desc")) {} + } + } else { + let session = NIMSession(teamId, type: .team) + Router.shared.use( + PushTeamChatVCRouter, + parameters: ["nav": weakSelf?.navigationController as Any, + "session": session as Any], + closure: nil + ) + } + } } } else { let searchModel = viewModel.searchResult?.seniorGroup[indexPath.row] if let teamId = searchModel?.teamInfo?.teamId { - let session = NIMSession(teamId, type: .team) - Router.shared.use( - PushTeamChatVCRouter, - parameters: ["nav": navigationController as Any, "session": session as Any], - closure: nil - ) + TeamRepo.shared.fetchTeamInfo(teamId) { error, teamInfo in + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else { + weakSelf?.showSingleAlert(title: localizable("leave_team"), message: localizable("leave_team_desc")) {} + } + } else { + let session = NIMSession(teamId, type: .team) + Router.shared.use( + PushTeamChatVCRouter, + parameters: ["nav": weakSelf?.navigationController as Any, + "session": session as Any], + closure: nil + ) + } + } } } } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBasePopListViewController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBasePopListView.swift similarity index 87% rename from NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBasePopListViewController.swift rename to NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBasePopListView.swift index 09627be4..a956c346 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBasePopListViewController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/Controller/NEBasePopListView.swift @@ -19,7 +19,7 @@ open class PopListItem: NSObject { } @objcMembers -open class NEBasePopListViewController: UIViewController { +open class NEBasePopListView: UIView { public let shadowView = UIView() public var buttonHeight: CGFloat = 32.0 let popView = UIView() @@ -31,27 +31,25 @@ open class NEBasePopListViewController: UIViewController { public var itemDatas = [PopListItem]() { didSet { popViewHeight = CGFloat(itemDatas.count) * 32 + 16 + setupUI() } } - override public func viewDidLoad() { - super.viewDidLoad() + override init(frame: CGRect) { + super.init(frame: frame) if let useSystemNav = NEConfigManager.instance.getParameter(key: useSystemNav) as? Bool, useSystemNav { - navigationController?.isNavigationBarHidden = false topConstant = 10 } else { topConstant = NEConstant.navigationAndStatusHeight } - setupUI() } - override public func viewDidDisappear(_ animated: Bool) { - super.viewDidDisappear(animated) - removeSelf() + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") } func setupUI() { - view.backgroundColor = .clear + backgroundColor = .clear shadowView.translatesAutoresizingMaskIntoConstraints = false shadowView.backgroundColor = .clear @@ -60,7 +58,7 @@ open class NEBasePopListViewController: UIViewController { shadowView.layer.shadowColor = UIColor.ne_operationBorderColor.cgColor shadowView.layer.shadowOpacity = 0.25 shadowView.layer.shadowRadius = 7 - view.addSubview(shadowView) + addSubview(shadowView) NSLayoutConstraint.activate([ shadowView.widthAnchor.constraint(equalToConstant: popViewWidth), @@ -79,6 +77,7 @@ open class NEBasePopListViewController: UIViewController { popView.bottomAnchor.constraint(equalTo: shadowView.bottomAnchor), ]) + popView.subviews.forEach { $0.removeFromSuperview() } let offset: CGFloat = 8 for index in 0 ..< itemDatas.count { let item = itemDatas[index] @@ -119,11 +118,11 @@ open class NEBasePopListViewController: UIViewController { removeSelf() } - public func removeSelf() { - view.removeFromSuperview() + open func removeSelf() { + removeFromSuperview() } - override public func touchesBegan(_ touches: Set, with event: UIEvent?) { + override open func touchesBegan(_ touches: Set, with event: UIEvent?) { print("pop list view touchesBegan") removeSelf() } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationSearchViewModel.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationSearchViewModel.swift index 9e924ebd..15469be7 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationSearchViewModel.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationSearchViewModel.swift @@ -6,7 +6,7 @@ import NIMSDK import UIKit @objcMembers -public class ConversationSearchViewModel: NSObject { +open class ConversationSearchViewModel: NSObject { let repo = ConversationRepo.shared public var searchResult: ( friend: [ConversationSearchListModel], @@ -23,12 +23,12 @@ public class ConversationSearchViewModel: NSObject { /// - Parameters: /// - searchStr: 搜索的内容 /// - completion: 回调结果 - public func doSearch(searchStr: String, - _ completion: @escaping (NSError?, ( - friend: [ConversationSearchListModel], - contactGroup: [ConversationSearchListModel], - seniorGroup: [ConversationSearchListModel] - )?) -> Void) { + open func doSearch(searchStr: String, + _ completion: @escaping (NSError?, ( + friend: [ConversationSearchListModel], + contactGroup: [ConversationSearchListModel], + seniorGroup: [ConversationSearchListModel] + )?) -> Void) { NELog.infoLog( ModuleName + " " + className, desc: #function + ", searchStr.count:\(searchStr.count)" diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationViewModel.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationViewModel.swift index 901e7929..9225ca5a 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationViewModel.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Conversation/ViewModel/ConversationViewModel.swift @@ -19,7 +19,7 @@ public protocol ConversationViewModelDelegate: NSObjectProtocol { } @objcMembers -public class ConversationViewModel: NSObject, ConversationRepoDelegate, +open class ConversationViewModel: NSObject, ConversationRepoDelegate, NIMConversationManagerDelegate, NIMTeamManagerDelegate, NIMUserManagerDelegate, NIMChatManagerDelegate { public var conversationListArray: [ConversationListModel]? public var stickTopInfos = [NIMSession: NIMStickTopSessionInfo]() @@ -35,21 +35,30 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, super.init() repo.delegate = self repo.addSessionDelegate(delegate: self) - repo.chatProvider.addDelegate(delegate: self) + repo.addChatDelegate(delegate: self) repo.addTeamDelegate(delegate: self) stickTopInfos = repo.getStickTopInfos() NIMSDK.shared().userManager.add(self) NotificationCenter.default.addObserver(self, selector: #selector(atMessageChange), name: Notification.Name(AtMessageChangeNoti), object: nil) } + deinit { + NELog.infoLog(ModuleName + className(), desc: #function) + repo.removeSessionDelegate(delegate: self) + repo.removeChatDelegate(delegate: self) + repo.removeTeamDelegate(delegate: self) + NIMSDK.shared().userManager.remove(self) + NotificationCenter.default.removeObserver(self) + } + func atMessageChange() { NELog.infoLog(className(), desc: "atMessageChange") delegate?.reloadTableView() } - public func fetchServerSessions(option: NIMFetchServerSessionOption, - _ completion: @escaping (NSError?, [ConversationListModel]?) - -> Void) { + open func fetchServerSessions(option: NIMFetchServerSessionOption, + _ completion: @escaping (NSError?, [ConversationListModel]?) + -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function) weak var weakSelf = self repo.getSessionList { error, conversaitonList in @@ -95,11 +104,21 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, NELog.infoLog(ModuleName, desc: "conversationListArray count : \(weakSelf?.conversationListArray?.count ?? 0)") completion(error, weakSelf?.conversationListArray) + + // 拉取好友信息 + ChatUserCache.removeAllUserInfo() + ContactRepo.shared.getFriendList(true, local: false) { friends, error in + if let friends = friends { + friends.forEach { user in + ChatUserCache.updateUserInfo(user) + } + } + } } } } - public func deleteRecentSession(recentSession: NIMRecentSession) { + open func deleteRecentSession(recentSession: NIMRecentSession) { NELog.infoLog( ModuleName + " " + className, desc: #function + ", sessionId:" + (recentSession.session?.sessionId ?? "nil") @@ -113,14 +132,14 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } - public func stickTopInfoForSession(session: NIMSession) -> NIMStickTopSessionInfo? { + open func stickTopInfoForSession(session: NIMSession) -> NIMStickTopSessionInfo? { NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId:" + session.sessionId) return repo.getStickTopSessionInfo(session: session) } - public func addStickTopSession(session: NIMSession, - _ completion: @escaping (NSError?, NIMStickTopSessionInfo?) - -> Void) { + open func addStickTopSession(session: NIMSession, + _ completion: @escaping (NSError?, NIMStickTopSessionInfo?) + -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId:" + session.sessionId) let params = NIMAddStickTopSessionParams(session: session) repo.addStickTop(params: params) { error, stickTopSessionInfo in @@ -128,43 +147,35 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } - public func removeStickTopSession(params: NIMStickTopSessionInfo, - _ completion: @escaping (NSError?, NIMStickTopSessionInfo?) - -> Void) { + open func removeStickTopSession(params: NIMStickTopSessionInfo, + _ completion: @escaping (NSError?, NIMStickTopSessionInfo?) + -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", sessionId:" + params.session.sessionId) repo.removeStickTop(params: params) { error, stickTopSessionInfo in completion(error as NSError?, stickTopSessionInfo) } } - public func loadStickTopSessionInfos(_ completion: + open func loadStickTopSessionInfos(_ completion: @escaping (NSError?, [NIMSession: NIMStickTopSessionInfo]?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function) repo.getStickTopSessionList(completion) } - public func notifyForNewMsg(userId: String?) -> Bool { + open func notifyForNewMsg(userId: String?) -> Bool { NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId:" + (userId ?? "nil")) return repo.isNeedNotify(userId: userId) } - public func notifyStateForNewMsg(teamId: String?) -> NIMTeamNotifyState { + open func notifyStateForNewMsg(teamId: String?) -> NIMTeamNotifyState { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:" + (teamId ?? "nil")) return repo.isNeedNotifyForTeam(teamId: teamId) } - deinit { - NELog.infoLog(ModuleName + " " + className, desc: #function) - NIMSDK.shared().userManager.remove(self) - repo.removeSessionDelegate(delegate: self) - repo.removeTeamDelegate(delegate: self) - NotificationCenter.default.removeObserver(self) - } - // MARK: ======================== private method ============================== - public func sortRecentSession() { + open func sortRecentSession() { NELog.infoLog(ModuleName + " " + className, desc: #function) var tempArr = [NIMRecentSession]() var dic = [String: ConversationListModel]() @@ -229,7 +240,7 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, // MARK: ==================== NIMChatManagerDelegate ========================== - public func onRecvMessageReceipts(_ receipts: [NIMMessageReceipt]) { + open func onRecvMessageReceipts(_ receipts: [NIMMessageReceipt]) { receipts.forEach { receipt in if receipt.session?.sessionType == .P2P { if let listArr = conversationListArray { @@ -246,20 +257,27 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, // MARK: ==================== ConversationRepoDelegate ========================== - public func onNotifyAddStickTopSession(_ newInfo: NIMStickTopSessionInfo) { + open func onNotifyAddStickTopSession(_ newInfo: NIMStickTopSessionInfo) { NELog.infoLog(ModuleName + " " + className, desc: #function + ",onNotifyAddStickTopSession sessionId:" + newInfo.session.sessionId) stickTopInfos[newInfo.session] = newInfo + if repo.getRecentSession(newInfo.session) == nil { + repo.addRecentSession(newInfo.session) + } delegate?.reloadTableView() } - public func onNotifyRemoveStickTopSession(_ removedInfo: NIMStickTopSessionInfo) { + open func onNotifyRemoveStickTopSession(_ removedInfo: NIMStickTopSessionInfo) { NELog.infoLog(ModuleName + " " + className, desc: #function + ",onNotifyRemoveStickTopSession sessionId:" + removedInfo.session.sessionId) stickTopInfos[removedInfo.session] = nil delegate?.reloadTableView() } - public func onNotifySyncStickTopSessions(_ response: NIMSyncStickTopSessionResponse) { + open func onNotifySyncStickTopSessions(_ response: NIMSyncStickTopSessionResponse) { loadStickTopSessionInfos { [weak self] error, sessionInfos in + NELog.infoLog( + ModuleName + " " + (self?.className ?? "ConversationViewModel"), + desc: "CALLBACK loadStickTopSessionInfos " + (error?.localizedDescription ?? "no error") + ) if error != nil { if let infos = self?.repo.getStickTopInfos() { self?.stickTopInfos = infos @@ -272,25 +290,50 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } - public func didServerSessionUpdated(_ recentSession: NIMRecentSession?) {} + open func didServerSessionUpdated(_ recentSession: NIMRecentSession?) { + NELog.infoLog(ModuleName + " " + className, desc: #function + ",didServerSessionUpdated:" + (recentSession?.session?.sessionId ?? "")) + } // MARK: ====================NIMConversationManagerDelegate===================== - public func didAdd(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { + open func didAdd(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { guard let targetId = recentSession.session?.sessionId else { NELog.errorLog(ModuleName + " " + className, desc: "❌sessionId is nil") return } NELog.infoLog(ModuleName + " " + className, desc: #function + ", did add session targetId:" + targetId) - DispatchQueue.main.async {} + + // 解散、退出群聊 if let object = recentSession.lastMessage?.messageObject as? NIMNotificationObject, object.notificationType == .team { if let content = object.content as? NIMTeamNotificationContent { - if content.operationType == .dismiss || (content.operationType == .leave && content.sourceID == NIMSDK.shared().loginManager.currentAccount()) { + if content.operationType == .dismiss || + (content.operationType == .kick && + content.targetIDs?.contains(IMKitClient.instance.imAccid()) == true) || + (content.operationType == .leave && + IMKitClient.instance.isMySelf(content.sourceID)) { + // 群聊被解散 + // 被踢出群聊 + // 主动退出群聊 NELog.infoLog( ModuleName + " " + className, desc: #function + "didAdd team dismiss or leave noti" + (recentSession.session?.sessionId ?? "nil") ) repo.deleteLocalSession(recentSession: recentSession) + + // 移除置顶 + if let session = recentSession.session { + if let param = stickTopInfos[session] { + removeStickTopSession(params: param) { error, _ in + if let err = error { + NELog.errorLog( + ModuleName + " ConversationViewModel", + desc: "CALLBACK removeStickTopSession failed,error = \(err)" + ) + } + } + } + stickTopInfos.removeValue(forKey: session) + } return } } @@ -310,6 +353,7 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, cacheAddSessionDic[sid] = listModel } listModel.recentSession = recentSession + if recentSession.session?.sessionType == .P2P { repo.fetchUserInfo(accountList: [targetId]) { users, error in if error == nil { @@ -324,21 +368,28 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } else if recentSession.session?.sessionType == .team { + if !repo.isMyTeam(teamId: targetId) { + // 自己不在群内,不新增该群聊会话 + return + } + repo.getTeamInfo(teamId: targetId) { error, teamInfo in listModel.teamInfo = teamInfo if let model = weakSelf?.sessionIsExist(listModel) { model.teamInfo = teamInfo weakSelf?.delegate?.didAddRecentSession() } else { - // 会话列表新增一项 - weakSelf?.conversationListArray?.append(listModel) - weakSelf?.delegate?.didAddRecentSession() + if listModel.teamInfo != nil { + // 会话列表新增一项 + weakSelf?.conversationListArray?.append(listModel) + weakSelf?.delegate?.didAddRecentSession() + } } } } } - public func didUpdate(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { + open func didUpdate(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { guard let targetId = recentSession.session?.sessionId else { NELog.errorLog(ModuleName + " " + className, desc: "❌sessionId is nil") return @@ -357,12 +408,34 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, if let object = recentSession.lastMessage?.messageObject as? NIMNotificationObject, object.notificationType == .team { if let content = object.content as? NIMTeamNotificationContent { - if content.operationType == .dismiss || (content.operationType == .leave && content.sourceID == NIMSDK.shared().loginManager.currentAccount()) { + if content.operationType == .dismiss || + (content.operationType == .kick && + content.targetIDs?.contains(IMKitClient.instance.imAccid()) == true) || + (content.operationType == .leave && + IMKitClient.instance.isMySelf(content.sourceID)) { + // 群聊被解散 + // 被踢出群聊 + // 主动退出群聊 NELog.infoLog( ModuleName + " " + className, desc: #function + "didUpdate team dismiss or leave noti: \(targetId)" ) repo.deleteLocalSession(recentSession: recentSession) + + // 移除置顶 + if let session = recentSession.session { + if let param = stickTopInfos[session] { + removeStickTopSession(params: param) { error, _ in + if let err = error { + NELog.errorLog( + ModuleName + " ConversationViewModel", + desc: "CALLBACK removeStickTopSession failed,error = \(err)" + ) + } + } + } + stickTopInfos.removeValue(forKey: session) + } return } } @@ -397,13 +470,16 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } weakSelf?.delegate?.reloadTableView() - break + return } } + + // 会话列表中没有该回话则添加 + didAdd(recentSession, totalUnreadCount: totalUnreadCount) } } - public func didRemove(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { + open func didRemove(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { guard let targetId = recentSession.session?.sessionId else { NELog.errorLog(ModuleName + " " + className, desc: "❌sessionId is nil") return @@ -439,15 +515,38 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, delegate?.reloadTableView() } + // 收到多端登录单向删除通知,手动更新会话最后一条消息 + open func onRecvMessagesDeleted(_ messages: [NIMMessage], exts: [String: String]?) { + for message in messages { + guard let session = message.session else { return } + + for listModel in conversationListArray ?? [] { + if session.sessionId == listModel.recentSession?.session?.sessionId { + NELog.infoLog(ModuleName + " " + className, desc: #function + "onRecvMessagesDeleted sessionid: \(session.sessionId) message text: \(message.text ?? "")") + + // 手动查询最后一条消息 + let param = NIMGetMessagesDynamicallyParam() + param.session = session + param.limit = 1 + ChatRepo.shared.getMessagesDynamically(param) { [weak self] _, _, messages in + listModel.recentSession?.lastMessage = messages?.first + self?.delegate?.reloadTableView() + } + break + } + } + } + } + // MARK: ========================NIMUserManagerDelegate========================= - public func onFriendChanged(_ user: NIMUser) { + open func onFriendChanged(_ user: NIMUser) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", userId:" + (user.userId ?? "nil")) if let listArr = conversationListArray { for (i, listModel) in listArr.enumerated() { if listModel.recentSession?.session?.sessionType == .P2P { if listModel.userInfo?.userId == user.userId { - listModel.userInfo = User(user: user) + listModel.userInfo = NEKitUser(user: user) delegate?.didUpdateRecentSession(index: i) break } @@ -458,7 +557,7 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, // MARK: =========================NIMTeamManagerDelegate======================== - public func onTeamUpdated(_ team: NIMTeam) { + open func onTeamUpdated(_ team: NIMTeam) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:" + (team.teamId ?? "nil")) guard let conversationArr = conversationListArray else { return @@ -472,7 +571,7 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } - public func onTeamAdded(_ team: NIMTeam) { + open func onTeamAdded(_ team: NIMTeam) { NELog.infoLog(ModuleName + " " + className, desc: #function + "onTeamAdded, teamId:" + (team.teamId ?? "nil")) guard let tid = team.teamId else { return @@ -481,16 +580,15 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, delegate?.didAddRecentSession() } - public func onTeamRemoved(_ team: NIMTeam) { + open func onTeamRemoved(_ team: NIMTeam) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:" + (team.teamId ?? "nil")) // 做删除会话操作(自己退出群聊会触发) guard let conversationArr = conversationListArray else { return } - // Fix sdk bug - DispatchQueue.main.asyncAfter(deadline: .now() + 2) { - for (_, listModel) in conversationArr.enumerated() { + DispatchQueue.main.async { + for listModel in conversationArr { if let teamInfo = listModel.teamInfo, teamInfo.teamId == team.teamId { if let recentSession = listModel.recentSession { self.deleteRecentSession(recentSession: recentSession) @@ -501,7 +599,7 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, } } - public func onTeamMemberChanged(_ team: NIMTeam) { + open func onTeamMemberChanged(_ team: NIMTeam) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:" + (team.teamId ?? "nil")) guard let conversationArr = conversationListArray else { return @@ -527,7 +625,7 @@ public class ConversationViewModel: NSObject, ConversationRepoDelegate, return nil } - public func onMuteListChanged() { + open func onMuteListChanged() { delegate?.reloadTableView() } } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunConversationController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunConversationController.swift index 3124592c..968b50f9 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunConversationController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunConversationController.swift @@ -79,7 +79,7 @@ open class FunConversationController: NEBaseConversationController { searchView.heightAnchor.constraint(equalToConstant: 36), ]) - popListController = FunPopListViewController() + popListView = FunPopListView() tableView.rowHeight = 72 tableView.backgroundColor = .funConversationBackgroundColor diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunPopListViewController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunPopListView.swift similarity index 70% rename from NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunPopListViewController.swift rename to NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunPopListView.swift index 05daba7f..81c091bd 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunPopListViewController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/FunUI/Controller/FunPopListView.swift @@ -8,7 +8,7 @@ import NECommonKit import UIKit @objcMembers -open class FunPopListViewController: NEBasePopListViewController { +open class FunPopListView: NEBasePopListView { public var triangleView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false @@ -20,17 +20,17 @@ open class FunPopListViewController: NEBasePopListViewController { override func setupUI() { super.setupUI() NSLayoutConstraint.activate([ - shadowView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), - shadowView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -8), + shadowView.topAnchor.constraint(equalTo: topAnchor, constant: topConstant), + shadowView.rightAnchor.constraint(equalTo: rightAnchor, constant: -8), ]) popView.backgroundColor = UIColor.funConversationPopViewBg - view.insertSubview(triangleView, aboveSubview: shadowView) + insertSubview(triangleView, aboveSubview: shadowView) NSLayoutConstraint.activate([ triangleView.widthAnchor.constraint(equalToConstant: 11), triangleView.heightAnchor.constraint(equalToConstant: 11), - triangleView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -25), + triangleView.rightAnchor.constraint(equalTo: rightAnchor, constant: -25), triangleView.topAnchor.constraint(equalTo: popView.topAnchor, constant: -5), ]) } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Manager/NEAtMessageManager.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Manager/NEAtMessageManager.swift index 99a6d4be..a592f4dd 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Manager/NEAtMessageManager.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Manager/NEAtMessageManager.swift @@ -10,20 +10,20 @@ public let yxAitMsg = "yxAitMsg" public let AtMessageChangeNoti = "at_message_change_noti" @objcMembers -public class AtMessageModel: NSObject { +open class AtMessageModel: NSObject { public var messageId: String? public var messageTime: NSNumber? } @objcMembers -public class AtMEMessageRecord: NSObject { +open class AtMEMessageRecord: NSObject { public var atMessages = [String: NSNumber]() public var lastTime: NSNumber? public var isRead = false } @objcMembers -public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManagerDelegate { +open class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManagerDelegate { public static var instance: NEAtMessageManager? private let workQueue = DispatchQueue(label: "AtMessageWorkQueue") private let lock = NSLock() @@ -45,7 +45,7 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag NEAtMessageManager.instance = NEAtMessageManager() } - public func onLogin(_ step: NIMLoginStep) { + open func onLogin(_ step: NIMLoginStep) { if step == .loginOK { NELog.infoLog(className(), desc: "login ok") currentAccid = NIMSDK.shared().loginManager.currentAccount() @@ -66,7 +66,7 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag } } - public func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) { + open func onRecvRevokeMessageNotification(_ notification: NIMRevokeMessageNotification) { guard let msg = notification.message else { return } @@ -86,7 +86,7 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag lock.unlock() } - public func isAtCurrentUser(sessionId: String) -> Bool { + open func isAtCurrentUser(sessionId: String) -> Bool { let dic = getMessageDic() NELog.infoLog(className(), desc: "session id : \(sessionId)") NELog.infoLog(className(), desc: "dic : \(dic)") @@ -96,7 +96,7 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag return false } - public func clearAtRecord(_ sessionId: String) { + open func clearAtRecord(_ sessionId: String) { weak var weakSelf = self workQueue.async { guard let dic = weakSelf?.getMessageDic() else { @@ -111,7 +111,7 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag } } - public func filterAtMessage(messages: [NIMMessage]) { + open func filterAtMessage(messages: [NIMMessage]) { NELog.infoLog(className(), desc: "at manager filterAtMessage : \(messages.count)") weak var weakSelf = self workQueue.async { @@ -124,14 +124,14 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag } } - public func removeRevokeAtMessage(messages: [NIMMessage]) { + open func removeRevokeAtMessage(messages: [NIMMessage]) { weak var weakSelf = self workQueue.async { weakSelf?.removeRevokeAtMessageInWorkqueue(messages: messages) } } - public func startFilterRoamingMessagesTask() { + open func startFilterRoamingMessagesTask() { weak var weakSelf = self workQueue.async { weakSelf?.startFilterRoamingMessagesTaskInWorkqueue() @@ -347,7 +347,7 @@ public class NEAtMessageManager: NSObject, NIMChatManagerDelegate, NIMLoginManag } } - public func onRecvMessages(_ messages: [NIMMessage]) { + open func onRecvMessages(_ messages: [NIMMessage]) { filterAtMessage(messages: messages) } } diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/ConversationController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/ConversationController.swift index 7fa791db..889f9713 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/ConversationController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/ConversationController.swift @@ -56,7 +56,7 @@ open class ConversationController: NEBaseConversationController { override open func setupSubviews() { super.setupSubviews() - popListController = PopListViewController() + popListView = PopListView() tableView.rowHeight = 62 tableView.backgroundColor = .white diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/PopListViewController.swift b/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/PopListView.swift similarity index 61% rename from NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/PopListViewController.swift rename to NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/PopListView.swift index 6e3e326f..8bb0d252 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/PopListViewController.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/NormalUI/Controller/PopListView.swift @@ -8,12 +8,12 @@ import NECommonKit import UIKit @objcMembers -open class PopListViewController: NEBasePopListViewController { +open class PopListView: NEBasePopListView { override func setupUI() { super.setupUI() NSLayoutConstraint.activate([ - shadowView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant - 10), - shadowView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20), + shadowView.topAnchor.constraint(equalTo: topAnchor, constant: topConstant - 10), + shadowView.rightAnchor.constraint(equalTo: rightAnchor, constant: -20), ]) popView.backgroundColor = NEConstant.hexRGB(0xFFFFFF) diff --git a/NEConversationUIKit/NEConversationUIKit/Classes/Util/NEMessageUtil.swift b/NEConversationUIKit/NEConversationUIKit/Classes/Util/NEMessageUtil.swift index a8727ada..847b40ef 100644 --- a/NEConversationUIKit/NEConversationUIKit/Classes/Util/NEMessageUtil.swift +++ b/NEConversationUIKit/NEConversationUIKit/Classes/Util/NEMessageUtil.swift @@ -5,17 +5,19 @@ import Foundation import NIMSDK -public class NEMessageUtil { +open class NEMessageUtil { /// last message /// - Parameter message: message /// - Returns: result - public class func messageContent(message: NIMMessage) -> String { + open class func messageContent(message: NIMMessage) -> String { var text = "" switch message.messageType { case .text: if let messageText = message.text { text = messageText } + case .tip: + return localizable("tip") case .audio: text = localizable("voice") case .image: @@ -28,10 +30,8 @@ public class NEMessageUtil { text = localizable("notification") case .file: text = localizable("file") - case .tip: - if let messageText = message.text { - text = messageText - } + case .custom: + text = contentOfCustomMessage(message: message) case .rtcCallRecord: let record = message.messageObject as? NIMRtcCallRecordObject text = (record?.callType == .audio) ? localizable("internet_phone") : @@ -42,4 +42,22 @@ public class NEMessageUtil { return text } + + /// 返回自定义消息的外显文案 + static func contentOfCustomMessage(message: NIMMessage?) -> String { + if message?.messageType == .custom, + let object = message?.messageObject as? NIMCustomObject, + let custom = object.attachment as? NECustomAttachment { + if custom.customType == customMultiForwardType { + return localizable("chat_history") + } + if custom.customType == customRichTextType { + if let data = NECustomAttachment.dataOfCustomMessage(message: message), + let title = data["title"] as? String { + return title + } + } + } + return localizable("unknown") + } } diff --git a/NEMapKit/NEMapKit.podspec b/NEMapKit/NEMapKit.podspec index a6315e08..021417ed 100644 --- a/NEMapKit/NEMapKit.podspec +++ b/NEMapKit/NEMapKit.podspec @@ -8,7 +8,7 @@ Pod::Spec.new do |s| s.name = 'NEMapKit' - s.version = '9.6.5' + s.version = '9.7.0' s.summary = 'Netease XKit' # This description is used to generate tags and improve search results. diff --git a/NERtcCallUIKit/NERtcCallUIKit.podspec b/NERtcCallUIKit/NERtcCallUIKit.podspec index 72278cec..3bef760f 100644 --- a/NERtcCallUIKit/NERtcCallUIKit.podspec +++ b/NERtcCallUIKit/NERtcCallUIKit.podspec @@ -17,45 +17,11 @@ Pod::Spec.new do |s| s.source = { :http => "" } s.source_files = 'NERtcCallUIKit/Classes/**/*' s.resource = 'NERtcCallUIKit/Assets/**/*' - - s.subspec 'NOS' do |nos| - nos.dependency 'NERtcCallKit/NOS','2.2.0' - nos.dependency 'SDWebImage' - nos.dependency 'NECoreKit','9.6.5' - nos.dependency 'NECommonKit' - nos.dependency 'NECommonUIKit' - nos.dependency 'NERtcSDK' - end - - s.subspec 'NOS_Special' do |nos| - nos.dependency 'NERtcCallKit/NOS_Special', "2.2.0" - nos.dependency 'SDWebImage' - nos.dependency 'NECoreKit','9.6.5' - nos.dependency 'NECommonKit' - nos.dependency 'NECommonUIKit' - nos.dependency 'NERtcSDK' - - end - - s.subspec 'FCS' do |fcs| - fcs.dependency 'NERtcCallKit/FCS','2.2.0' - fcs.dependency 'SDWebImage' - fcs.dependency 'NECoreKit','9.6.5' - fcs.dependency 'NECommonKit' - fcs.dependency 'NECommonUIKit' - fcs.dependency 'NERtcSDK' - - end - - s.subspec 'FCS_Special' do |fcs| - fcs.dependency 'NERtcCallKit/FCS_Special', "2.2.0" - fcs.dependency 'SDWebImage' - fcs.dependency 'NECoreKit','9.6.5' - fcs.dependency 'NECommonKit' - fcs.dependency 'NECommonUIKit' - fcs.dependency 'NERtcSDK' - - end - s.default_subspecs = 'NOS' + s.dependency 'NERtcCallKit/NOS_Special','2.2.0' + s.dependency 'SDWebImage' + s.dependency 'NECoreKit' + s.dependency 'NECommonKit' + s.dependency 'NECommonUIKit' + s.dependency 'NERtcSDK' end diff --git a/NETeamUIKit/NETeamUIKit.podspec b/NETeamUIKit/NETeamUIKit.podspec index 8dfe0b70..c0f5c3d1 100644 --- a/NETeamUIKit/NETeamUIKit.podspec +++ b/NETeamUIKit/NETeamUIKit.podspec @@ -8,7 +8,7 @@ Pod::Spec.new do |s| s.name = 'NETeamUIKit' - s.version = '9.6.5' + s.version = '9.7.0' s.summary = 'Netease XKit' # This description is used to generate tags and improve search results. diff --git a/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/Contents.json b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/Contents.json new file mode 100644 index 00000000..ea2e4827 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "clicked_we@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "clicked_we@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/clicked_we@2x.png b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/clicked_we@2x.png new file mode 100644 index 00000000..f69ac913 Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/clicked_we@2x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/clicked_we@3x.png b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/clicked_we@3x.png new file mode 100644 index 00000000..75777604 Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_select.imageset/clicked_we@3x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/Contents.json b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/Contents.json new file mode 100644 index 00000000..3331ca37 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "fun_user_empty@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "fun_user_empty@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/fun_user_empty@2x.png b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/fun_user_empty@2x.png new file mode 100644 index 00000000..54211c5a Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/fun_user_empty@2x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/fun_user_empty@3x.png b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/fun_user_empty@3x.png new file mode 100644 index 00000000..37ff7f70 Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/FunTeamUIKit.xcassets/fun_user_empty.imageset/fun_user_empty@3x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Contents.json b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Contents.json new file mode 100644 index 00000000..5c4d3b18 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Frame@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Frame@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Frame@2x.png b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Frame@2x.png new file mode 100644 index 00000000..510d989f Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Frame@2x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Frame@3x.png b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Frame@3x.png new file mode 100644 index 00000000..a4c9a4c5 Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/search.imageset/Frame@3x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/Contents.json b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/Contents.json new file mode 100644 index 00000000..c5aa7629 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "unselect@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "unslect@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/unselect@2x.png b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/unselect@2x.png new file mode 100644 index 00000000..2d699bb8 Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/unselect@2x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/unslect@3x.png b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/unslect@3x.png new file mode 100644 index 00000000..08d6c8fe Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/NEBaseTeamUIKit.xcassets/common/unselect.imageset/unslect@3x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/Contents.json b/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/Contents.json new file mode 100644 index 00000000..c2fd49ca --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "select@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "select@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/select@2x.png b/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/select@2x.png new file mode 100644 index 00000000..c405145b Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/select@2x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/select@3x.png b/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/select@3x.png new file mode 100644 index 00000000..8566dac8 Binary files /dev/null and b/NETeamUIKit/NETeamUIKit/Assets/NormalTeamUIKit.xcassets/select.imageset/select@3x.png differ diff --git a/NETeamUIKit/NETeamUIKit/Assets/en.lproj/Localizable.strings b/NETeamUIKit/NETeamUIKit/Assets/en.lproj/Localizable.strings index eb3b7786..62b596f1 100644 --- a/NETeamUIKit/NETeamUIKit/Assets/en.lproj/Localizable.strings +++ b/NETeamUIKit/NETeamUIKit/Assets/en.lproj/Localizable.strings @@ -10,14 +10,14 @@ "team_no_speak"="Mute"; "invite_permission"="Invite Permission"; "modify_team_info_permission"="Group info Permission"; -"agree"="是否需要被邀请者同意";//后期能力删除 +"agree"="Does the invitee need to consent?";//后期能力删除 "setting"="Setting"; "group_memmber"="Group Member"; "discuss_mebmer"="Temp Group Member"; "dismiss_team"="Disband Group"; "leave_team"="Leave Group"; "leave_discuss"="Leave Temp Group"; -"team_header"=" Group Avator"; +"team_header"=" Group Avatar"; "team_name"="Group Name"; "team_intr"="Group Info"; "default_icon"="Select Default icon"; @@ -44,7 +44,7 @@ "quit_discuss_chat"="Wether to leave Temp Group"; "cancel"="cancel"; "remind"="tip"; -"discuss_avatar"="Temp Group Avator"; +"discuss_avatar"="Temp Group Avatar"; "discuss_name"="Temp Group Name"; "discuss_intro"="Temp Group Introduce"; "invite_has_send"="Invitation sent"; @@ -52,3 +52,36 @@ // error toast "space_not_support"="All Spaces are not supported"; "team_not_exist"="team not exist"; + +"manage_team"="Manage Group"; +"confirm_delete_text"="Sure to Remove '%@'"; +"question_mark"="?"; + +"who_edit_team_info"="Edit group info permission"; +"who_edit_user_info"="Add member permission"; +"who_at_all"="@all permission"; +"who_mark"="Pin permission"; +"who_user_join_noti"="Group notification recipients"; +"manage_manger"="Manager management"; +"team_manager"="Manager"; +"transfer_owner"="Transfer group admin"; +"add_manager"="Add manager"; +"group_manager"="Group manager"; +"team_member_select"="Select member"; +"search_member"="Search member"; +"member_select_sure"="Sure"; +"member_empty_tip"="Select member"; +"team_tip_noti_at_manager"="Only admin and manager can @all"; +"team_tip_noti_at_all"="Everyone can @all"; +"team_owner_and_manager"="Admin and manager"; +"select_limit_tip"="Exceeding the %d person limit"; +"remove_manager_title"="Whether to remove"; +"remove_manager_tip"="No permission after remove"; +"max_managers_tip"="10 limit manager"; +"network_error"="Network is not available, please check"; +"no_permission_tip"="No permission"; +"no_manager_member"="No manager"; +"remove_member_tip"="This member will leave group after remove"; +"member_select_no_member"="No member"; +"remove_failed"="remove failed"; +"failed_operation"="操作失败"; diff --git a/NETeamUIKit/NETeamUIKit/Assets/zh-Hans.lproj/Localizable.strings b/NETeamUIKit/NETeamUIKit/Assets/zh-Hans.lproj/Localizable.strings index 1390f5af..58405ed7 100644 --- a/NETeamUIKit/NETeamUIKit/Assets/zh-Hans.lproj/Localizable.strings +++ b/NETeamUIKit/NETeamUIKit/Assets/zh-Hans.lproj/Localizable.strings @@ -52,3 +52,36 @@ // error toast "space_not_support"="不支持全空格"; "team_not_exist"="群组不存在"; + +"manage_team"="群管理"; +"who_edit_team_info"="谁可以编辑群信息"; +"who_edit_user_info"="谁可以添加群成员"; +"who_at_all"="谁可以@所有人"; +"who_mark"="谁可以标记"; +"who_user_join_noti"="谁可以收到用户进群通知"; +"manage_manger"="管理管理员"; +"team_manager"="管理员"; +"transfer_owner"="转让群主"; +"add_manager"="添加管理员"; +"group_manager"="群管理员"; +"team_member_select"="人员选择"; +"search_member"="搜索成员"; +"member_select_sure"="确定"; +"member_empty_tip"="请选择成员"; +"team_member_remove"="移除"; +"confirm_delete_text"="确认要移除“%@”"; +"question_mark"="吗?"; +"team_tip_noti_at_manager"="@所有人权限更新为群主和管理员"; +"team_tip_noti_at_all"="@所有人权限更新为所有人"; +"team_owner_and_manager"="群主和管理员"; +"select_limit_tip"="超出%d人限制"; +"remove_manager_title"="是否移除"; +"remove_manager_tip"="移除后该成员将无管理权限"; +"max_managers_tip"="最多只能设置10个管理员"; +"network_error"="当前网络不可用,请检查你的网络设置"; +"no_permission_tip"="您暂无操作权限"; +"no_manager_member"="暂无群管理人员"; +"remove_member_tip"="移除后该成员将离开当前群聊"; +"member_select_no_member"="暂无成员"; +"remove_failed"="移除失败"; +"failed_operation"="操作失败"; diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamArrowSettingCell.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamArrowSettingCell.swift index 1a5ab805..32986031 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamArrowSettingCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamArrowSettingCell.swift @@ -15,7 +15,7 @@ open class FunTeamArrowSettingCell: NEBaseTeamArrowSettingCell { super.init(coder: coder) } - override public func setupUI() { + override open func setupUI() { super.setupUI() contentView.updateLayoutConstraint(firstItem: dividerLine, seconedItem: contentView, attribute: .left, constant: 16) contentView.updateLayoutConstraint(firstItem: dividerLine, seconedItem: contentView, attribute: .right, constant: 0) diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamManagerMemberCell.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamManagerMemberCell.swift new file mode 100644 index 00000000..9a0380d6 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamManagerMemberCell.swift @@ -0,0 +1,32 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +class FunTeamManagerMemberCell: FunTeamMemberCell { +// lazy var removeLabel: UILabel = { +// let label = UILabel() +// label.translatesAutoresizingMaskIntoConstraints = false +// label.text = localizable("team_member_remove") +// label.textColor = .funTeamRemoveLabelColor +// label.font = UIFont.systemFont(ofSize: 14.0) +// return label +// }() + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + + override func setupUI() { + super.setupUI() + ownerLabel.isHidden = true + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberCell.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberCell.swift index 557fce04..ae063e2b 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberCell.swift @@ -24,29 +24,51 @@ open class FunTeamMemberCell: NEBaseTeamMemberCell { headerView.layer.cornerRadius = 4.0 contentView.addSubview(ownerLabel) + ownerWidth = ownerLabel.widthAnchor.constraint(equalToConstant: 48.0) NSLayoutConstraint.activate([ - ownerLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20), + ownerLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -55), ownerLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), ownerLabel.heightAnchor.constraint(equalToConstant: 25.0), - ownerLabel.widthAnchor.constraint(equalToConstant: 48.0), + ownerWidth!, ]) contentView.addSubview(nameLabel) NSLayoutConstraint.activate([ nameLabel.leftAnchor.constraint(equalTo: headerView.rightAnchor, constant: 14.0), nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - nameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -70), + nameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -115), ]) - ownerLabel.textColor = UIColor.funTeamMemberOwnerFlagColor - ownerLabel.backgroundColor = UIColor.funTeamMemberOwnerFlagColor.withAlphaComponent(0.1) - ownerLabel.layer.borderColor = UIColor.funTeamMemberOwnerFlagColor.cgColor + setOwnerStyle() contentView.addSubview(dividerLine) NSLayoutConstraint.activate([ dividerLine.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 20), - dividerLine.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20), + dividerLine.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0), dividerLine.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), dividerLine.heightAnchor.constraint(equalToConstant: 1), ]) + + contentView.addSubview(removeLabel) + removeLabel.textColor = .funTeamRemoveLabelColor + NSLayoutConstraint.activate([ + removeLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + removeLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), + ]) + + setupRemoveButton() + } + + func setOwnerStyle() { + ownerLabel.textColor = UIColor.funTeamMemberOwnerFlagColor + ownerLabel.backgroundColor = UIColor.funTeamMemberOwnerFlagColor.withAlphaComponent(0.1) + ownerLabel.layer.borderColor = UIColor.funTeamMemberOwnerFlagColor.cgColor + ownerWidth?.constant = 48 + } + + func setManagerStyle() { + ownerLabel.textColor = UIColor.funTeamMangerLabelTextColor + ownerLabel.backgroundColor = UIColor.funTeamManagerLabelBorderColor.withAlphaComponent(0.1) + ownerLabel.layer.borderColor = UIColor.funTeamManagerLabelBorderColor.cgColor + ownerWidth?.constant = 60 } } diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberSelectCell.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberSelectCell.swift new file mode 100644 index 00000000..8feaad39 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamMemberSelectCell.swift @@ -0,0 +1,47 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +class FunTeamMemberSelectCell: NEBaseTeamMemberSelectCell { + public var dividerLine: UIView = { + let view = UIView() + view.translatesAutoresizingMaskIntoConstraints = false + view.backgroundColor = .funTeamLineBorderColor + return view + }() + + override func setupUI() { + super.setupUI() + addSubview(dividerLine) + headerView.layer.cornerRadius = 4.0 + checkImageView.highlightedImage = coreLoader.loadImage("fun_select") + NSLayoutConstraint.activate([ + checkImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + checkImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), + checkImageView.widthAnchor.constraint(equalToConstant: 22), + checkImageView.heightAnchor.constraint(equalToConstant: 22), + ]) + + NSLayoutConstraint.activate([ + headerView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + headerView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 54), + headerView.widthAnchor.constraint(equalToConstant: 40), + headerView.heightAnchor.constraint(equalToConstant: 40), + ]) + + NSLayoutConstraint.activate([ + nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + nameLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 105), + nameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16), + ]) + + NSLayoutConstraint.activate([ + dividerLine.leftAnchor.constraint(equalTo: headerView.leftAnchor), + dividerLine.rightAnchor.constraint(equalTo: contentView.rightAnchor), + dividerLine.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), + dividerLine.heightAnchor.constraint(equalToConstant: 1), + ]) + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamSettingLabelArrowCell.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamSettingLabelArrowCell.swift new file mode 100644 index 00000000..35ca529b --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Cell/FunTeamSettingLabelArrowCell.swift @@ -0,0 +1,32 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +open class FunTeamSettingLabelArrowCell: FunTeamArrowSettingCell { + let arrowLabel: UILabel = { + let q = UILabel() + q.translatesAutoresizingMaskIntoConstraints = false + q.textColor = .ne_lightText + q.font = UIFont.systemFont(ofSize: 16) + q.textAlignment = .right + return q + }() + + override open func setupUI() { + super.setupUI() + contentView.addSubview(arrowLabel) + NSLayoutConstraint.activate([ + arrowLabel.centerYAnchor.constraint(equalTo: arrow.centerYAnchor), + arrowLabel.rightAnchor.constraint(equalTo: arrow.leftAnchor, constant: -4), + ]) + } + + override open func configure(_ anyModel: Any) { + super.configure(anyModel) + if let model = anyModel as? SettingCellLabelArrowModel { + arrowLabel.text = model.arrowLabelText + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamManageController.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamManageController.swift new file mode 100644 index 00000000..0ad8eec9 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamManageController.swift @@ -0,0 +1,67 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class FunTeamManageController: NEBaseTeamManageController { + override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + cellClassDic = [ + SettingCellType.SettingArrowCell.rawValue: FunTeamSettingLabelArrowCell.self, + SettingCellType.SettingSwitchCell.rawValue: FunTeamSettingSwitchCell.self, + SettingCellType.SettingSelectCell.rawValue: FunTeamSettingSelectCell.self, + ] + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .ne_lightBackgroundColor + navigationController?.navigationBar.backgroundColor = .ne_lightBackgroundColor + navigationView.backgroundColor = .ne_lightBackgroundColor + } + + override open func reloadSectionData() { + viewmodel.sectionData.forEach { setionModel in + setionModel.cellModels.forEach { cellModel in + cellModel.cornerType = .none + if cellModel.rowHeight > 70 { + cellModel.rowHeight = 78 + } else { + cellModel.rowHeight = 56 + } + } + } + } + + override open func getFooterView() -> UIView? { + let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 64.0)) + let button = UIButton() + button.translatesAutoresizingMaskIntoConstraints = false + footer.addSubview(button) + button.backgroundColor = .white + button.clipsToBounds = true + button.setTitleColor(NEConstant.hexRGB(0xE6605C), for: .normal) + button.titleLabel?.font = NEConstant.defaultTextFont(16.0) + button.setTitle(localizable("transfer_owner"), for: .normal) + button.addTarget(self, action: #selector(transferOwner), for: .touchUpInside) + NSLayoutConstraint.activate([ + button.leftAnchor.constraint(equalTo: footer.leftAnchor, constant: 0), + button.rightAnchor.constraint(equalTo: footer.rightAnchor, constant: 0), + button.topAnchor.constraint(equalTo: footer.topAnchor, constant: 12), + button.heightAnchor.constraint(equalToConstant: 56), + ]) + return footer + } + + override open func didManagerClick() { + let controller = FunTeamManagerListController() + controller.teamId = viewmodel.teamInfoModel?.team?.teamId + navigationController?.pushViewController(controller, animated: true) + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamManagerListController.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamManagerListController.swift new file mode 100644 index 00000000..62c25c82 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamManagerListController.swift @@ -0,0 +1,94 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonUIKit +import UIKit + +@objcMembers +open class FunTeamManagerListController: NEBaseTeamManagerListController { + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + // key 值 为 tableview section 对应的值 + cellClassDic = [0: FunTeamArrowSettingCell.self, 1: FunTeamManagerMemberCell.self] + } + + lazy var emptyView: NEEmptyDataView = { + let view = NEEmptyDataView(imageName: "fun_user_empty", content: localizable("no_manager_member"), frame: CGRect.zero) + view.translatesAutoresizingMaskIntoConstraints = false + view.isHidden = true + return view + }() + + public required init?(coder: NSCoder) { + super.init(coder: coder) + } + + override open func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + view.addSubview(emptyView) + NSLayoutConstraint.activate([ + emptyView.centerXAnchor.constraint(equalTo: view.centerXAnchor), + emptyView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -100), + emptyView.widthAnchor.constraint(equalToConstant: 122), + emptyView.heightAnchor.constraint(equalToConstant: 91), + ]) + sortAndReloadData() + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ + + override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + if indexPath.section == 0 { + let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.section)", for: indexPath) as! FunTeamArrowSettingCell + cell.titleLabel.text = localizable("add_manager") + return cell + } + let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.section)", for: indexPath) as! FunTeamManagerMemberCell + cell.delegate = self + cell.index = indexPath.row + cell.configure(viewmodel.managers[indexPath.row]) + if let type = viewmodel.currentMember?.type, type == .manager { + cell.removeBtn.isHidden = true + cell.removeLabel.isHidden = true + } + return cell + } + + override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + if indexPath.section == 0 { + return 46 + } else if indexPath.section == 1 { + return 64 + } + return 0 + } + + override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if indexPath.section == 0 { + let selectController = FunTeamMemberSelectController() + selectController.teamId = teamId + selectController.selectMemberBlock = { [weak self] datas in + self?.didAddManagers(datas) + } + navigationController?.pushViewController(selectController, animated: true) + } else if indexPath.section == 1 { + super.tableView(tableView, didSelectRowAt: indexPath) + } + } + + override open func sortAndReloadData() { + super.sortAndReloadData() + emptyView.isHidden = viewmodel.managers.count > 0 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMemberSelectController.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMemberSelectController.swift new file mode 100644 index 00000000..02a31097 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMemberSelectController.swift @@ -0,0 +1,45 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class FunTeamMemberSelectController: NEBaseTeamMemberSelectController { + override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + cellClassDic[0] = FunTeamMemberSelectCell.self + } + + public required init?(coder: NSCoder) { + super.init(coder: coder) + } + + override open func viewDidLoad() { + super.viewDidLoad() + navigationView.moreButton.setTitleColor(.funTeamThemeColor, for: .normal) + // Do any additional setup after loading the view. + emptyView.setEmptyImage(image: coreLoader.loadImage("fun_user_empty")) + } + + override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.section)", for: indexPath) as! FunTeamMemberSelectCell + let member = viewmodel.showDatas[indexPath.row] + cell.configureMember(member) + return cell + } + + override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + 64.0 + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMembersController.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMembersController.swift index 9723510b..1976eeaa 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMembersController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamMembersController.swift @@ -4,6 +4,8 @@ import NECommonKit import UIKit + +@objcMembers open class FunTeamMembersController: NEBaseTeamMembersController { let searchGrayBackView: UIView = { let view = UIView() @@ -36,7 +38,29 @@ open class FunTeamMembersController: NEBaseTeamMembersController { ) as? FunTeamMemberCell { if let model = getRealModel(indexPath.row) { cell.configure(model) - cell.ownerLabel.isHidden = !isOwner(model.nimUser?.userId) + var isShowRemove = false + if isOwner(model.nimUser?.userId) { + cell.ownerLabel.isHidden = false + cell.ownerLabel.text = localizable("team_owner") + cell.setOwnerStyle() + } else if model.teamMember?.type == .manager { + cell.ownerLabel.isHidden = false + cell.ownerLabel.text = localizable("team_manager") + cell.setManagerStyle() + if isOwner(IMKitClient.instance.imAccid()) { + isShowRemove = true + } + } else { + if isOwner(IMKitClient.instance.imAccid()) || viewmodel.currentMember?.type == .manager { + isShowRemove = true + } + cell.ownerLabel.isHidden = true + } + cell.index = indexPath.row + cell.delegate = self + cell.configure(model) + cell.removeBtn.isHidden = !isShowRemove + cell.removeLabel.isHidden = !isShowRemove } if isLastRow(indexPath.row) { cell.dividerLine.isHidden = true @@ -58,7 +82,7 @@ open class FunTeamMembersController: NEBaseTeamMembersController { return true } } - if let originDatas = datas, originDatas.count - 1 == index { + if viewmodel.datas.count - 1 == index { return true } return false diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamSettingViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamSettingViewController.swift index 8a2ec325..f9fe667e 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamSettingViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/Controller/FunTeamSettingViewController.swift @@ -68,7 +68,7 @@ open class FunTeamSettingViewController: NEBaseTeamSettingViewController { teamHeader.widthAnchor.constraint(equalToConstant: 50), teamHeader.heightAnchor.constraint(equalToConstant: 50), ]) - if let url = viewmodel.teamInfoModel?.team?.avatarUrl { + if let url = viewmodel.teamInfoModel?.team?.avatarUrl, !url.isEmpty { print("icon url : ", url) teamHeader.sd_setImage(with: URL(string: url), completed: nil) } else { @@ -164,7 +164,7 @@ open class FunTeamSettingViewController: NEBaseTeamSettingViewController { addBtn.addTarget(self, action: #selector(addUser), for: .touchUpInside) if viewmodel.isNormalTeam() == false, viewmodel.isOwner() == false, - let inviteMode = viewmodel.teamInfoModel?.team?.inviteMode, inviteMode == .manager { + let inviteMode = viewmodel.teamInfoModel?.team?.inviteMode, let member = viewmodel.memberInTeam, inviteMode == .manager, member.type != .manager { addBtnWidth?.constant = 0 addBtn.isHidden = true } @@ -229,8 +229,22 @@ open class FunTeamSettingViewController: NEBaseTeamSettingViewController { override open func checkoutAddShowOrHide() { if viewmodel.isNormalTeam() == false, viewmodel.isOwner() == false, let inviteMode = viewmodel.teamInfoModel?.team?.inviteMode, inviteMode == .manager { - return + if let member = viewmodel.memberInTeam, member.type == .manager { + addBtn.isHidden = false + addBtnWidth?.constant = 36.0 + addBtnLeftMargin?.constant = 16 + checkMemberCountLimit() + } else { + addBtn.isHidden = true + addBtnWidth?.constant = 0 + addBtnLeftMargin?.constant = 0 + } + } else { + checkMemberCountLimit() } + } + + func checkMemberCountLimit() { if viewmodel.teamInfoModel?.team?.level == viewmodel.teamInfoModel?.team?.memberNumber { addBtn.isHidden = true addBtnWidth?.constant = 0 @@ -296,6 +310,13 @@ open class FunTeamSettingViewController: NEBaseTeamSettingViewController { ) } + override open func didClickTeamManage() { + let manageTeam = FunTeamManageController() + manageTeam.managerUsers = getManaterUsers() + manageTeam.viewmodel.teamInfoModel = viewmodel.teamInfoModel + navigationController?.pushViewController(manageTeam, animated: true) + } + override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell( diff --git a/NETeamUIKit/NETeamUIKit/Classes/FunUI/FunTeamUIColor.swift b/NETeamUIKit/NETeamUIKit/Classes/FunUI/FunTeamUIColor.swift index 365403d1..21e9376a 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/FunUI/FunTeamUIColor.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/FunUI/FunTeamUIColor.swift @@ -15,4 +15,9 @@ extension UIColor { static let funTeamBackgroundColor = UIColor(hexString: "#EDEDED") static let funTeamLineBorderColor = UIColor(hexString: "#E5E5E5") static let funTeamHistoryCellTitleTextColor = UIColor(hexString: "#737373") + static let funTeamRemoveLabelColor = UIColor(hexString: "#505D75") + + static let funTeamMangerLabelTextColor = UIColor(hexString: "#EA8339") + static let funTeamMangerLabelBackColor = UIColor(hexString: "#F2C46B", 0.1) + static let funTeamManagerLabelBorderColor = UIColor(hexString: "#F2C46B") } diff --git a/NETeamUIKit/NETeamUIKit/Classes/NEBaseTeamRouter.swift b/NETeamUIKit/NETeamUIKit/Classes/NEBaseTeamRouter.swift index 112c400e..60f68364 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/NEBaseTeamRouter.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/NEBaseTeamRouter.swift @@ -3,12 +3,13 @@ // found in the LICENSE file. import Foundation +import NECommonKit import NECoreIMKit import NECoreKit import NIMSDK @objcMembers -public class TeamRouter: NSObject { +open class TeamRouter: NSObject { public static let repo = TeamRepo.shared public static var iconUrls = ["https://s.netease.im/safe/ABg8YjWQWvcqO6sAAAAAAAAAAAA?_im_url=1", "https://s.netease.im/safe/ABg8YjmQWvcqO6sAAAAAAAABAAA?_im_url=1", @@ -42,6 +43,12 @@ public class TeamRouter: NSObject { option.beInviteMode = .noAuth option.updateInfoMode = .all option.updateClientCustomMode = .all + var disucssFlag = [String: Any]() + disucssFlag[discussTeamKey] = true + let jsonString = NECommonUtil.getJSONStringFromDictionary(disucssFlag) + if jsonString.count > 0 { + option.clientCustomInfo = jsonString + } repo.createAdvanceTeam(accids, option) { error, teamid, failedIds in var result = [String: Any]() @@ -52,19 +59,6 @@ public class TeamRouter: NSObject { result["code"] = 0 result["msg"] = "ok" result["teamId"] = teamid - repo.sendCreateAdavanceNoti( - teamid ?? "", - localizable("create_senior_team_noti") - ) { error in - print("send noti message : ", error as Any) - } - if let tid = teamid { - repo.updateTeamCustomInfo(discussTeamKey, tid) { error in - if let err = error { - print(#function + "error: \(err.localizedDescription)") - } - } - } } Router.shared.use(TeamCreateDiscussResult, parameters: result, closure: nil) } diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamManagerMemberCell.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamManagerMemberCell.swift new file mode 100644 index 00000000..2aac954a --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamManagerMemberCell.swift @@ -0,0 +1,13 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +class TeamManagerMemberCell: TeamMemberCell { + override func setupUI() { + super.setupUI() + ownerLabel.isHidden = true + nameLabelRightMargin?.constant = -65 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberCell.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberCell.swift index 0736b0c4..e1d10a91 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberCell.swift @@ -5,4 +5,28 @@ import UIKit @objcMembers -open class TeamMemberCell: NEBaseTeamMemberCell {} +open class TeamMemberCell: NEBaseTeamMemberCell { + override open func setupUI() { + super.setupUI() + contentView.addSubview(removeLabel) + NSLayoutConstraint.activate([ + removeLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + removeLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20), + removeLabel.heightAnchor.constraint(equalToConstant: 22), + removeLabel.widthAnchor.constraint(equalToConstant: 40), + ]) + removeLabel.textColor = .ne_redText + removeLabel.clipsToBounds = true + removeLabel.layer.cornerRadius = 4.0 + removeLabel.layer.borderColor = UIColor.ne_redColor.cgColor + removeLabel.layer.borderWidth = 1.0 + removeLabel.font = UIFont.systemFont(ofSize: 12.0) + + ownerLabel.backgroundColor = .normalTeamOwnerBgColor + ownerLabel.textColor = .normalTeamOwnerColor + ownerLabel.layer.borderColor = UIColor.normalTeamOwnerBorderColor.cgColor + ownerLabel.layer.cornerRadius = 11.0 + + setupRemoveButton() + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberSelectCell.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberSelectCell.swift new file mode 100644 index 00000000..f07479ee --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamMemberSelectCell.swift @@ -0,0 +1,33 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class TeamMemberSelectCell: NEBaseTeamMemberSelectCell { + override open func setupUI() { + super.setupUI() + headerView.layer.cornerRadius = 18 + checkImageView.highlightedImage = coreLoader.loadImage("select") + NSLayoutConstraint.activate([ + checkImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + checkImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 18), + checkImageView.widthAnchor.constraint(equalToConstant: 18), + checkImageView.heightAnchor.constraint(equalToConstant: 18), + ]) + + NSLayoutConstraint.activate([ + headerView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + headerView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 52), + headerView.widthAnchor.constraint(equalToConstant: 36), + headerView.heightAnchor.constraint(equalToConstant: 36), + ]) + + NSLayoutConstraint.activate([ + nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + nameLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 102), + nameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -18), + ]) + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamSettingLabelArrowCell.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamSettingLabelArrowCell.swift new file mode 100644 index 00000000..f4a52175 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Cell/TeamSettingLabelArrowCell.swift @@ -0,0 +1,33 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class TeamSettingLabelArrowCell: TeamArrowSettingCell { + let arrowLabel: UILabel = { + let q = UILabel() + q.translatesAutoresizingMaskIntoConstraints = false + q.textColor = .ne_lightText + q.font = UIFont.systemFont(ofSize: 16) + q.textAlignment = .right + return q + }() + + override open func setupUI() { + super.setupUI() + contentView.addSubview(arrowLabel) + NSLayoutConstraint.activate([ + arrowLabel.centerYAnchor.constraint(equalTo: arrow.centerYAnchor), + arrowLabel.rightAnchor.constraint(equalTo: arrow.leftAnchor, constant: -4), + ]) + } + + override open func configure(_ anyModel: Any) { + super.configure(anyModel) + if let model = anyModel as? SettingCellLabelArrowModel { + arrowLabel.text = model.arrowLabelText + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamManageController.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamManageController.swift new file mode 100644 index 00000000..9685464b --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamManageController.swift @@ -0,0 +1,55 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NIMSDK +import UIKit + +@objcMembers +open class TeamManageController: NEBaseTeamManageController { + override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + navigationView.backgroundColor = .ne_lightBackgroundColor + navigationController?.navigationBar.backgroundColor = .ne_lightBackgroundColor + cellClassDic = [ + SettingCellType.SettingArrowCell.rawValue: TeamSettingLabelArrowCell.self, + SettingCellType.SettingSwitchCell.rawValue: TeamSettingSwitchCell.self, + SettingCellType.SettingSelectCell.rawValue: TeamSettingSelectCell.self, + ] + } + + public required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override open func viewDidLoad() { + super.viewDidLoad() + } + + override open func getFooterView() -> UIView? { + let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 64.0)) + let button = UIButton() + button.translatesAutoresizingMaskIntoConstraints = false + footer.addSubview(button) + button.backgroundColor = .white + button.clipsToBounds = true + button.setTitleColor(NEConstant.hexRGB(0xE6605C), for: .normal) + button.titleLabel?.font = NEConstant.defaultTextFont(16.0) + button.setTitle(localizable("transfer_owner"), for: .normal) + button.addTarget(self, action: #selector(transferOwner), for: .touchUpInside) + button.layer.cornerRadius = 8.0 + NSLayoutConstraint.activate([ + button.leftAnchor.constraint(equalTo: footer.leftAnchor, constant: 20), + button.rightAnchor.constraint(equalTo: footer.rightAnchor, constant: -20), + button.topAnchor.constraint(equalTo: footer.topAnchor, constant: 12), + button.heightAnchor.constraint(equalToConstant: 40), + ]) + return footer + } + + override open func didManagerClick() { + let controller = TeamManagerListController() + controller.teamId = viewmodel.teamInfoModel?.team?.teamId + navigationController?.pushViewController(controller, animated: true) + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamManagerListController.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamManagerListController.swift new file mode 100644 index 00000000..7f367af2 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamManagerListController.swift @@ -0,0 +1,95 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonUIKit +import UIKit + +@objcMembers +open class TeamManagerListController: NEBaseTeamManagerListController { + override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + // key 值 为 tableview section 对应的值 + cellClassDic = [0: TeamArrowSettingCell.self, 1: TeamManagerMemberCell.self] + } + + public lazy var emptyView: NEEmptyDataView = { + let view = NEEmptyDataView(imageName: "user_empty", content: localizable("no_manager_member"), frame: CGRect.zero) + view.translatesAutoresizingMaskIntoConstraints = false + view.isHidden = true + return view + }() + + public required init?(coder: NSCoder) { + super.init(coder: coder) + } + + override open func viewDidLoad() { + super.viewDidLoad() + navigationView.backgroundColor = .white + + // Do any additional setup after loading the view. + view.addSubview(emptyView) + NSLayoutConstraint.activate([ + emptyView.centerXAnchor.constraint(equalTo: view.centerXAnchor), + emptyView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -100), + emptyView.widthAnchor.constraint(equalToConstant: 122), + emptyView.heightAnchor.constraint(equalToConstant: 91), + ]) + sortAndReloadData() + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ + + override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + if indexPath.section == 0 { + let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.section)", for: indexPath) as! TeamArrowSettingCell + cell.titleLabel.text = localizable("add_manager") + return cell + } + let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.section)", for: indexPath) as! TeamManagerMemberCell + cell.delegate = self + cell.index = indexPath.row + cell.configure(viewmodel.managers[indexPath.row]) + if let type = viewmodel.currentMember?.type, type == .manager { + cell.removeBtn.isHidden = true + cell.removeLabel.isHidden = true + } + return cell + } + + override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + if indexPath.section == 0 { + return 46 + } else if indexPath.section == 1 { + return 52 + } + return 0 + } + + override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if indexPath.section == 0 { + let selectController = TeamMemberSelectController() + selectController.teamId = teamId + selectController.selectMemberBlock = { [weak self] datas in + self?.didAddManagers(datas) + } + navigationController?.pushViewController(selectController, animated: true) + } else if indexPath.section == 1 { + super.tableView(tableView, didSelectRowAt: indexPath) + } + } + + override open func sortAndReloadData() { + super.sortAndReloadData() + emptyView.isHidden = viewmodel.managers.count > 0 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMemberSelectController.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMemberSelectController.swift new file mode 100644 index 00000000..0333e5a6 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMemberSelectController.swift @@ -0,0 +1,34 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +@objcMembers +open class TeamMemberSelectController: NEBaseTeamMemberSelectController { + override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + cellClassDic[0] = TeamMemberSelectCell.self + } + + public required init?(coder: NSCoder) { + super.init(coder: coder) + } + + override open func viewDidLoad() { + super.viewDidLoad() + navigationView.backgroundColor = .white + navigationView.moreButton.setTitleColor(.normalTeamBlueColor, for: .normal) + } + + override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "\(indexPath.section)", for: indexPath) as! TeamMemberSelectCell + let member = viewmodel.showDatas[indexPath.row] + cell.configureMember(member) + return cell + } + + override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + 52.0 + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMembersController.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMembersController.swift index dd7540b2..0e5c509e 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMembersController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamMembersController.swift @@ -20,8 +20,29 @@ open class TeamMembersController: NEBaseTeamMembersController { for: indexPath ) as? TeamMemberCell { if let model = getRealModel(indexPath.row) { + var isShowRemove = false + if isOwner(model.nimUser?.userId) { + cell.ownerLabel.isHidden = false + cell.ownerLabel.text = localizable("team_owner") + cell.ownerWidth?.constant = 40 + } else if model.teamMember?.type == .manager { + cell.ownerLabel.isHidden = false + cell.ownerLabel.text = localizable("team_manager") + cell.ownerWidth?.constant = 52 + if isOwner(IMKitClient.instance.imAccid()) { + isShowRemove = true + } + } else { + if isOwner(IMKitClient.instance.imAccid()) || viewmodel.currentMember?.type == .manager { + isShowRemove = true + } + cell.ownerLabel.isHidden = true + } + cell.index = indexPath.row + cell.delegate = self cell.configure(model) - cell.ownerLabel.isHidden = !isOwner(model.nimUser?.userId) + cell.removeBtn.isHidden = !isShowRemove + cell.removeLabel.isHidden = !isShowRemove } return cell } diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamSettingViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamSettingViewController.swift index d07b4f68..e60ab70d 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamSettingViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/Controller/TeamSettingViewController.swift @@ -55,7 +55,7 @@ open class TeamSettingViewController: NEBaseTeamSettingViewController { teamHeader.widthAnchor.constraint(equalToConstant: 42), teamHeader.heightAnchor.constraint(equalToConstant: 42), ]) - if let url = viewmodel.teamInfoModel?.team?.avatarUrl { + if let url = viewmodel.teamInfoModel?.team?.avatarUrl, !url.isEmpty { print("icon url : ", url) teamHeader.sd_setImage(with: URL(string: url), completed: nil) } else { @@ -152,7 +152,7 @@ open class TeamSettingViewController: NEBaseTeamSettingViewController { addBtn.addTarget(self, action: #selector(addUser), for: .touchUpInside) if viewmodel.isNormalTeam() == false, viewmodel.isOwner() == false, - let inviteMode = viewmodel.teamInfoModel?.team?.inviteMode, inviteMode == .manager { + let inviteMode = viewmodel.teamInfoModel?.team?.inviteMode, let member = viewmodel.memberInTeam, inviteMode == .manager, member.type != .manager { addBtnWidth?.constant = 0 addBtn.isHidden = true } @@ -176,8 +176,22 @@ open class TeamSettingViewController: NEBaseTeamSettingViewController { override open func checkoutAddShowOrHide() { if viewmodel.isNormalTeam() == false, viewmodel.isOwner() == false, let inviteMode = viewmodel.teamInfoModel?.team?.inviteMode, inviteMode == .manager { - return + if let member = viewmodel.memberInTeam, member.type == .manager { + addBtn.isHidden = false + addBtnWidth?.constant = 36.0 + addBtnLeftMargin?.constant = 16 + checkMemberCountLimit() + } else { + addBtn.isHidden = true + addBtnWidth?.constant = 0 + addBtnLeftMargin?.constant = 0 + } + } else { + checkMemberCountLimit() } + } + + func checkMemberCountLimit() { if viewmodel.teamInfoModel?.team?.level == viewmodel.teamInfoModel?.team?.memberNumber { addBtn.isHidden = true addBtnWidth?.constant = 0 @@ -257,6 +271,13 @@ open class TeamSettingViewController: NEBaseTeamSettingViewController { ) } + override open func didClickTeamManage() { + let manageTeam = TeamManageController() + manageTeam.managerUsers = getManaterUsers() + manageTeam.viewmodel.teamInfoModel = viewmodel.teamInfoModel + navigationController?.pushViewController(manageTeam, animated: true) + } + override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell( @@ -264,6 +285,9 @@ open class TeamSettingViewController: NEBaseTeamSettingViewController { for: indexPath ) as? TeamUserCell { if let user = viewmodel.teamInfoModel?.users[indexPath.row] { + if let userId = user.nimUser?.userId, let nimUser = ChatUserCache.getUserInfo(userId) { + user.nimUser = nimUser + } cell.user = user } return cell diff --git a/NETeamUIKit/NETeamUIKit/Classes/NormalUI/NormalTeamUIColor.swift b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/NormalTeamUIColor.swift new file mode 100644 index 00000000..cd8d8691 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/NormalUI/NormalTeamUIColor.swift @@ -0,0 +1,12 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import Foundation + +extension UIColor { + static let normalTeamBlueColor = UIColor(hexString: "#337EFF") + static let normalTeamOwnerColor = UIColor(hexString: "#656A72") + static let normalTeamOwnerBgColor = UIColor(hexString: "#F7F7F7") + static let normalTeamOwnerBorderColor = UIColor(hexString: "#D6D8DB") +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/NESelectTeamMember.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/NESelectTeamMember.swift new file mode 100644 index 00000000..8a25f8c0 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/NESelectTeamMember.swift @@ -0,0 +1,12 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import UIKit + +@objcMembers +open class NESelectTeamMember: NSObject { + var isSelected: Bool = false + var member: TeamMemberInfoModel? +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellLabelArrowModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellLabelArrowModel.swift new file mode 100644 index 00000000..41a7a442 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellLabelArrowModel.swift @@ -0,0 +1,9 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import UIKit + +open class SettingCellLabelArrowModel: SettingCellModel { + var arrowLabelText = "" +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellModel.swift index b901d018..a458cb26 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellModel.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingCellModel.swift @@ -17,7 +17,7 @@ public enum SettingCellType: Int { } @objcMembers -public class SettingCellModel: NSObject { +open class SettingCellModel: NSObject { public typealias SwitchChangeCompletion = (Bool) -> Void public typealias CellClick = () -> Void public var cellName: String? diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingSectionModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingSectionModel.swift index 87eb5d52..608f1dff 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingSectionModel.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/Model/SettingSectionModel.swift @@ -6,7 +6,7 @@ import Foundation @objcMembers -public class SettingSectionModel: NSObject { +open class SettingSectionModel: NSObject { public var cellModels = [SettingCellModel]() override public init() {} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamHistoryMessageController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamHistoryMessageController.swift index 49214611..22af08ea 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamHistoryMessageController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamHistoryMessageController.swift @@ -105,24 +105,17 @@ open class NEBaseTeamHistoryMessageController: NEBaseViewController, UITextField // MARK: private method func searchTextFieldChange(textfield: SearchTextField) { - if textfield.text?.count == 0 { + guard let searchText = textfield.text else { + return + } + if searchText.count <= 0 { viewmodel.searchResultInfos?.removeAll() emptyView.isHidden = true tableView.reloadData() - } - } - - // MARK: UITextFieldDelegate - - open func textFieldShouldReturn(_ textField: UITextField) -> Bool { - guard let searchText = textField.text else { - return false - } - if searchText.count <= 0 { - return false + return } guard let session = teamSession else { - return false + return } weak var weakSelf = self searchStr = searchText @@ -147,8 +140,6 @@ open class NEBaseTeamHistoryMessageController: NEBaseViewController, UITextField ) } } - - return true } // MARK: UITableViewDelegate, UITableViewDataSource diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamManageController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamManageController.swift new file mode 100644 index 00000000..be2a7f90 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamManageController.swift @@ -0,0 +1,386 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NECoreIMKit +import NIMSDK +import UIKit + +@objcMembers +open class NEBaseTeamManageController: NEBaseViewController, UITableViewDelegate, UITableViewDataSource, TeamManageViewModelDelegate { + public let viewmodel = TeamManageViewModel() + + public var managerUsers = [TeamMemberInfoModel]() + + public var cellClassDic = [Int: NEBaseTeamSettingCell.Type]() + + public lazy var contentTable: UITableView = { + let table = UITableView() + table.translatesAutoresizingMaskIntoConstraints = false + table.backgroundColor = .clear + table.dataSource = self + table.delegate = self + table.separatorColor = .clear + table.separatorStyle = .none + table.sectionHeaderHeight = 12.0 + table + .tableFooterView = + UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 12)) + if #available(iOS 15.0, *) { + table.sectionHeaderTopPadding = 0.0 + } + return table + }() + + override open func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + title = localizable("manage_team") + viewmodel.managerUsers = managerUsers + viewmodel.delegate = self + view.backgroundColor = .ne_lightBackgroundColor + view.addSubview(contentTable) + + NSLayoutConstraint.activate([ + contentTable.leftAnchor.constraint(equalTo: view.leftAnchor), + contentTable.rightAnchor.constraint(equalTo: view.rightAnchor), + contentTable.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), + contentTable.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + cellClassDic.forEach { (key: Int, value: NEBaseTeamSettingCell.Type) in + contentTable.register(value, forCellReuseIdentifier: "\(key)") + } + if let tid = viewmodel.teamInfoModel?.team?.teamId { + viewmodel.getTeamInfo(tid) { [weak self] error in + self?.reloadSectionData() + self?.contentTable.reloadData() + } + } + } + + open func reloadSectionData() {} + + // MARK: UITableViewDataSource, UITableViewDelegate + + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + if viewmodel.sectionData.count > section { + let model = viewmodel.sectionData[section] + return model.cellModels.count + } + return 0 + } + + open func numberOfSections(in tableView: UITableView) -> Int { + viewmodel.sectionData.count + } + + open func tableView(_ tableView: UITableView, + cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let model = viewmodel.sectionData[indexPath.section].cellModels[indexPath.row] + if let cell = tableView.dequeueReusableCell( + withIdentifier: "\(model.type)", + for: indexPath + ) as? NEBaseTeamSettingCell { + cell.configure(model) + return cell + } + return UITableViewCell() + } + + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + let model = viewmodel.sectionData[indexPath.section].cellModels[indexPath.row] + if let block = model.cellClick { + block() + } + } + + open func tableView(_ tableView: UITableView, + heightForRowAt indexPath: IndexPath) -> CGFloat { + let model = viewmodel.sectionData[indexPath.section].cellModels[indexPath.row] + return model.rowHeight + } + + open func tableView(_ tableView: UITableView, + heightForHeaderInSection section: Int) -> CGFloat { + if viewmodel.sectionData.count > section { + let model = viewmodel.sectionData[section] + if model.cellModels.count > 0 { + return 12.0 + } + } + return 0 + } + + open func tableView(_ tableView: UITableView, + viewForHeaderInSection section: Int) -> UIView? { + let header = UIView() + header.backgroundColor = .ne_lightBackgroundColor + return header + } + + open func tableView(_ tableView: UITableView, + heightForFooterInSection section: Int) -> CGFloat { + if section == viewmodel.sectionData.count - 1 { + return 12.0 + } + return 0 + } + + open func getFooterView() -> UIView? { + nil + } + + open func transferOwner() {} + + func updateTeamInfoAllAction(_ model: SettingCellModel) { + weak var weakSelf = self + view.makeToastActivity(.center) + viewmodel.repo + .updateTeamInfoPrivilege(.all, viewmodel.teamInfoModel?.team?.teamId ?? "") { error in + NELog.infoLog( + ModuleName + " " + self.className(), + desc: "CALLBACK updateTeamInfoPrivilege " + (error?.localizedDescription ?? "no error") + ) + weakSelf?.view.hideToastActivity() + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } + } else { + weakSelf?.viewmodel.teamInfoModel?.team?.updateInfoMode = .all + model.subTitle = localizable("team_all") + weakSelf?.contentTable.reloadData() + } + } + } + + open func didUpdateTeamInfoClick(_ model: SettingCellModel) { + weak var weakSelf = self + + let actionSheetController = UIAlertController( + title: nil, + message: nil, + preferredStyle: .actionSheet + ) + + let cancelActionButton = UIAlertAction(title: localizable("cancel"), style: .cancel) { _ in + print("Cancel") + } + cancelActionButton.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + actionSheetController.addAction(cancelActionButton) + + let all = UIAlertAction(title: localizable("team_all"), style: .default) { _ in + weakSelf?.updateTeamInfoAllAction(model) + } + all.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + all.accessibilityIdentifier = "id.teamAllMember" + actionSheetController.addAction(all) + + let manager = UIAlertAction(title: localizable("team_owner_and_manager"), style: .default) { _ in + weakSelf?.updateTeamInfoOwnerAction(model) + } + manager.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + manager.accessibilityIdentifier = "id.teamOwner" + actionSheetController.addAction(manager) + + actionSheetController.fixIpadAction() + + navigationController?.present(actionSheetController, animated: true, completion: nil) + } + + func updateTeamInfoOwnerAction(_ model: SettingCellModel) { + weak var weakSelf = self + view.makeToastActivity(.center) + viewmodel.repo + .updateTeamInfoPrivilege(.manager, viewmodel.teamInfoModel?.team?.teamId ?? "") { error in + NELog.infoLog( + ModuleName + " " + self.className(), + desc: "CALLBACK updateTeamInfoPrivilege " + (error?.localizedDescription ?? "no error") + ) + weakSelf?.view.hideToastActivity() + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } + } else { + weakSelf?.viewmodel.teamInfoModel?.team?.updateInfoMode = .manager + model.subTitle = localizable("team_owner_and_manager") + weakSelf?.contentTable.reloadData() + } + } + } + + func updateInviteModeOwnerAction(_ model: SettingCellModel) { + weak var weakSelf = self + view.makeToastActivity(.center) + viewmodel.repo.updateInviteMode(.manager, viewmodel.teamInfoModel?.team?.teamId ?? "") { error in + NELog.infoLog( + ModuleName + " " + self.className(), + desc: "CALLBACK updateInviteMode " + (error?.localizedDescription ?? "no error") + ) + weakSelf?.view.hideToastActivity() + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } + } else { + weakSelf?.viewmodel.teamInfoModel?.team?.inviteMode = .manager + model.subTitle = localizable("team_owner_and_manager") + weakSelf?.contentTable.reloadData() + } + } + } + + func updateInviteModeAllAction(_ model: SettingCellModel) { + weak var weakSelf = self + view.makeToastActivity(.center) + viewmodel.repo.updateInviteMode(.all, viewmodel.teamInfoModel?.team?.teamId ?? "") { error in + NELog.infoLog( + ModuleName + " " + self.className(), + desc: "CALLBACK updateInviteMode " + (error?.localizedDescription ?? "no error") + ) + weakSelf?.view.hideToastActivity() + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } + } else { + weakSelf?.viewmodel.teamInfoModel?.team?.inviteMode = .all + model.subTitle = localizable("team_all") + weakSelf?.contentTable.reloadData() + } + } + } + + open func didChangeInviteModeClick(_ model: SettingCellModel) { + weak var weakSelf = self + + let actionSheetController = UIAlertController( + title: nil, + message: nil, + preferredStyle: .actionSheet + ) + + let cancelActionButton = UIAlertAction(title: localizable("cancel"), style: .cancel) { _ in + print("Cancel") + } + cancelActionButton.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + actionSheetController.addAction(cancelActionButton) + + let allActionButton = UIAlertAction(title: localizable("team_all"), style: .default) { _ in + weakSelf?.updateInviteModeAllAction(model) + } + + allActionButton.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + allActionButton.accessibilityIdentifier = "id.teamAllMember" + actionSheetController.addAction(allActionButton) + + let ownerActionButton = UIAlertAction(title: localizable("team_owner_and_manager"), style: .default) { _ in + weakSelf?.updateInviteModeOwnerAction(model) + } + ownerActionButton.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + ownerActionButton.accessibilityIdentifier = "id.teamOwner" + actionSheetController.addAction(ownerActionButton) + + actionSheetController.fixIpadAction() + navigationController?.present(actionSheetController, animated: true, completion: nil) + } + + open func didAtPermissionClick(_ model: SettingCellModel) { + weak var weakSelf = self + + let actionSheetController = UIAlertController( + title: nil, + message: nil, + preferredStyle: .actionSheet + ) + + let cancelActionButton = UIAlertAction(title: localizable("cancel"), style: .cancel) { _ in + print("Cancel") + } + cancelActionButton.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + actionSheetController.addAction(cancelActionButton) + + let all = UIAlertAction(title: localizable("team_all"), style: .default) { _ in + weakSelf?.viewmodel.updateTeamAtPermission(false) { error in + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } + } else { + weakSelf?.viewmodel.sendTipNoti(false) { error in + } + model.subTitle = localizable("team_all") + weakSelf?.contentTable.reloadData() + } + } + } + all.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + all.accessibilityIdentifier = "id.teamAllMember" + actionSheetController.addAction(all) + actionSheetController.fixIpadAction() + + let manager = UIAlertAction(title: localizable("team_owner_and_manager"), style: .default) { _ in + weakSelf?.viewmodel.updateTeamAtPermission(true) { error in + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } + } else { + weakSelf?.viewmodel.sendTipNoti(true) { error in + } + model.subTitle = localizable("team_owner_and_manager") + weakSelf?.contentTable.reloadData() + } + } + } + manager.setValue(UIColor.ne_darkText, forKey: "_titleTextColor") + manager.accessibilityIdentifier = "id.teamOwner" + actionSheetController.addAction(manager) + + navigationController?.present(actionSheetController, animated: true, completion: nil) + } + + open func didManagerClick() {} + + open func didRefreshData() { + reloadSectionData() + contentTable.reloadData() + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamManagerListController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamManagerListController.swift new file mode 100644 index 00000000..b804e0d6 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamManagerListController.swift @@ -0,0 +1,173 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NECommonUIKit +import UIKit + +@objcMembers +open class NEBaseTeamManagerListController: NEBaseViewController, UITableViewDelegate, UITableViewDataSource, TeamMemberCellDelegate, TeamManagerListViewModelDelegate { + public var teamId: String? + + let viewmodel = TeamManagerListViewModel() + + public lazy var contentTable: UITableView = { + let table = UITableView() + table.translatesAutoresizingMaskIntoConstraints = false + table.backgroundColor = .clear + table.dataSource = self + table.delegate = self + table.separatorColor = .clear + table.separatorStyle = .none + table.keyboardDismissMode = .onDrag + table.sectionHeaderHeight = 12.0 + table + .tableFooterView = + UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 12)) + if #available(iOS 15.0, *) { + table.sectionHeaderTopPadding = 0.0 + } + return table + }() + + public var cellClassDic = [Int: UITableViewCell.Type]() // key 值为 table section 值 + + override open func viewDidLoad() { + super.viewDidLoad() + + title = localizable("group_manager") + + viewmodel.teamId = teamId + + viewmodel.delegate = self + + if let tid = teamId { + viewmodel.getCurrentMember(tid) + viewmodel.getManagerDatas(tid) { [weak self] error in + if let err = error { + self?.view.makeToast(err.localizedDescription) + } else { + self?.sortAndReloadData() + } + } + } + view.addSubview(contentTable) + NSLayoutConstraint.activate([ + contentTable.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0), + contentTable.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0), + contentTable.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant), + contentTable.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0), + ]) + + cellClassDic.forEach { (key: Int, value: UITableViewCell.Type) in + contentTable.register(value, forCellReuseIdentifier: "\(key)") + } + } + + open func numberOfSections(in tableView: UITableView) -> Int { + 2 + } + + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + if section == 0 { + return 1 + } + return viewmodel.managers.count + } + + open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + UITableViewCell() + } + + open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + 0 + } + + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + if indexPath.section == 1 { + let model = viewmodel.managers[indexPath.row] + if let user = model.nimUser { + if IMKitClient.instance.isMySelf(user.userId) { + Router.shared.use( + MeSettingRouter, + parameters: ["nav": navigationController as Any], + closure: nil + ) + } else { + if let uid = user.userId { + Router.shared.use( + ContactUserInfoPageRouter, + parameters: ["nav": navigationController as Any, "uid": uid], + closure: nil + ) + } + } + } + } + } + + open func didAddManagers(_ managers: [TeamMemberInfoModel]) { + if let tid = teamId { + var uids = [String]() + managers.forEach { member in + if let uid = member.nimUser?.userId { + uids.append(uid) + } + } + viewmodel.addTeamManager(tid, uids) { [weak self] error in + if let err = error { + self?.view.makeToast(err.localizedDescription) + } else { + self?.viewmodel.managers.insert(contentsOf: managers, at: 0) + self?.sortAndReloadData() + } + } + } + } + + func didClickRemoveButton(_ model: TeamMemberInfoModel?, _ index: Int) { + print("did click remove button") + weak var weakSelf = self + // let content = String(format: localizable("confirm_delete_text"), model?.atNameInTeam() ?? "") + localizable("question_mark") + showAlert(title: localizable("remove_manager_title"), message: localizable("remove_manager_tip")) { + if let tid = weakSelf?.teamId, let uid = model?.nimUser?.userId { + weakSelf?.viewmodel.removeTeamManager(tid, [uid]) { error in + if let err = error { + weakSelf?.view.makeToast(err.localizedDescription) + } else { + if weakSelf?.viewmodel.managers.count ?? 0 > index { + weakSelf?.viewmodel.managers.remove(at: index) + weakSelf?.sortAndReloadData() + } + } + } + } + } + } + + open func getFilters() -> Set { + var filters = Set() + viewmodel.managers.forEach { model in + if let uid = model.nimUser?.userId { + filters.insert(uid) + } + } + return filters + } + + open func sortAndReloadData() { + // 数据源根据时间排序 + viewmodel.managers.sort { model1, model2 -> Bool in + if let time1 = model1.teamMember?.createTime, let time2 = model2.teamMember?.createTime { + return time2 > time1 + } + return false + } + contentTable.reloadData() + } + + open func didNeedReloadData() { + sortAndReloadData() + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMemberSelectController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMemberSelectController.swift new file mode 100644 index 00000000..86d629ae --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMemberSelectController.swift @@ -0,0 +1,266 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonKit +import UIKit + +public typealias NESelectTeamMemberBlock = ([TeamMemberInfoModel]) -> Void + +@objcMembers +open class NEBaseTeamMemberSelectController: NEBaseViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, TeamMemberSelectViewModelDelegate { + public var selectMemberBlock: NESelectTeamMemberBlock? + + let viewmodel = TeamMemberSelectViewModel() + + var teamId: String? + + public var cellClassDic = [Int: UITableViewCell.Type]() // key 值为 table section 值 + + public let searchInput = UITextField() + + public var selectCountLimit = 10 + + public lazy var contentTable: UITableView = { + let table = UITableView() + table.translatesAutoresizingMaskIntoConstraints = false + table.backgroundColor = .clear + table.dataSource = self + table.delegate = self + table.separatorColor = .clear + table.separatorStyle = .none + table.sectionHeaderHeight = 12.0 + table.keyboardDismissMode = .onDrag + table + .tableFooterView = + UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 12)) + if #available(iOS 15.0, *) { + table.sectionHeaderTopPadding = 0.0 + } + return table + }() + + public lazy var emptyView: NEEmptyDataView = { + let view = NEEmptyDataView( + imageName: "user_empty", + content: localizable("member_select_no_member"), + frame: CGRect.zero + ) + view.translatesAutoresizingMaskIntoConstraints = false + view.isHidden = true + return view + + }() + + override open func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + viewmodel.delegate = self + setupUI() + if let tid = teamId { + viewmodel.getTeamInfo(tid) { [weak self] error in + if let err = error { + self?.view.makeToast(err.localizedDescription) + } else { + self?.contentTable.reloadData() + } + } + } + } + + open func setupUI() { + title = localizable("team_member_select") + view.backgroundColor = .white + view.addSubview(contentTable) + + let searchBack = UIView() + view.addSubview(searchBack) + searchBack.backgroundColor = UIColor(hexString: "F2F4F5") + searchBack.translatesAutoresizingMaskIntoConstraints = false + searchBack.clipsToBounds = true + searchBack.layer.cornerRadius = 4.0 + NSLayoutConstraint.activate([ + searchBack.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20), + searchBack.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20), + searchBack.topAnchor.constraint(equalTo: view.topAnchor, constant: 13 + topConstant), + searchBack.heightAnchor.constraint(equalToConstant: 32), + ]) + + let searchImage = UIImageView() + searchBack.addSubview(searchImage) + searchImage.image = coreLoader.loadImage("search") + searchImage.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + searchImage.centerYAnchor.constraint(equalTo: searchBack.centerYAnchor), + searchImage.leftAnchor.constraint(equalTo: searchBack.leftAnchor, constant: 18), + searchImage.widthAnchor.constraint(equalToConstant: 13), + searchImage.heightAnchor.constraint(equalToConstant: 13), + ]) + + searchBack.addSubview(searchInput) + searchInput.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + searchInput.leftAnchor.constraint(equalTo: searchImage.rightAnchor, constant: 5), + searchInput.rightAnchor.constraint(equalTo: searchBack.rightAnchor, constant: -18), + searchInput.topAnchor.constraint(equalTo: searchBack.topAnchor), + searchInput.bottomAnchor.constraint(equalTo: searchBack.bottomAnchor), + ]) + searchInput.textColor = UIColor(hexString: "333333") + searchInput.placeholder = localizable("search_member") + searchInput.font = UIFont.systemFont(ofSize: 14.0) + searchInput.returnKeyType = .search + searchInput.delegate = self + searchInput.clearButtonMode = .always + if let clearButton = searchInput.value(forKey: "_clearButton") as? UIButton { + clearButton.accessibilityIdentifier = "id.clear" + } + searchInput.accessibilityIdentifier = "id.addFriendAccount" + +// NotificationCenter.default.addObserver( +// self, +// selector: #selector(textFieldChange), +// name: UITextField.textDidChangeNotification, +// object: nil +// ) + + NSLayoutConstraint.activate([ + contentTable.leftAnchor.constraint(equalTo: view.leftAnchor), + contentTable.rightAnchor.constraint(equalTo: view.rightAnchor), + contentTable.topAnchor.constraint(equalTo: searchBack.bottomAnchor), + contentTable.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + cellClassDic.forEach { (key: Int, value: UITableViewCell.Type) in + contentTable.register(value, forCellReuseIdentifier: "\(key)") + } + + view.addSubview(emptyView) + NSLayoutConstraint.activate([ + emptyView.centerXAnchor.constraint(equalTo: view.centerXAnchor), + emptyView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -100), + emptyView.widthAnchor.constraint(equalToConstant: 122), + emptyView.heightAnchor.constraint(equalToConstant: 91), + ]) + + navigationView.moreButton.isHidden = false + navigationView.moreButton.setImage(nil, for: .normal) + navigationView.moreButton.addTarget(self, action: #selector(didClickSure), for: .touchUpInside) + didChangeSelectMember() + } + + open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + if viewmodel.showDatas.count <= 0 { + emptyView.isHidden = false + } else { + emptyView.isHidden = true + } + return viewmodel.showDatas.count + } + + open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + UITableViewCell() + } + + open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + let model = viewmodel.showDatas[indexPath.row] + guard let cell = tableView.cellForRow(at: indexPath) as? NEBaseTeamMemberSelectCell else { + return + } + if let member = model.member, let accid = member.teamMember?.userId { + if viewmodel.selectDic[accid] != nil { + viewmodel.selectDic[accid] = nil + model.isSelected = false + cell.checkImageView.isHighlighted = false + } else { + if viewmodel.selectDic.count >= selectCountLimit { + let toastString = String(format: localizable("select_limit_tip"), selectCountLimit) + view.makeToast(toastString) + return + } + viewmodel.selectDic[accid] = member + model.isSelected = true + cell.checkImageView.isHighlighted = true + } + didChangeSelectMember() + } + } + + open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + 0 + } + + open func textFieldShouldReturn(_ textField: UITextField) -> Bool { + guard let text = textField.text else { + return false + } + if text.count <= 0 { + return false + } + return true + } + + open func textFieldShouldClear(_ textField: UITextField) -> Bool { + viewmodel.showDatas = viewmodel.datas + contentTable.reloadData() + return true + } + + open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + let finalString = (textField.text! as NSString).replacingCharacters(in: range, with: string) + if string.count <= 0 { + if finalString.count <= 0 { + viewmodel.showDatas = viewmodel.datas + contentTable.reloadData() + } else { + viewmodel.showDatas = viewmodel.searchAllData(finalString) + contentTable.reloadData() + } + } else { + viewmodel.showDatas = viewmodel.searchAllData(finalString) + contentTable.reloadData() + } + return true + } + + func didChangeSelectMember() { + if viewmodel.selectDic.count > 0 { + let title = localizable("member_select_sure") + "(\(viewmodel.selectDic.count))" + navigationView.moreButton.setTitle(title, for: .normal) + } else { + navigationView.moreButton.setTitle(localizable("member_select_sure"), for: .normal) + } + } + + open func didNeedRefresh() { + contentTable.reloadData() + didChangeSelectMember() + } + + open func didClickSure() { + print("sure click") + + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + view.makeToast(localizable("network_error")) + return + } + + if viewmodel.selectDic.count + viewmodel.managerSet.count > selectCountLimit { + view.makeToast(localizable("max_managers_tip")) + return + } + + if viewmodel.selectDic.count <= 0 { + view.makeToast(localizable("member_empty_tip")) + return + } + + var retArray = [TeamMemberInfoModel]() + viewmodel.selectDic.forEach { (key: String, value: TeamMemberInfoModel) in + retArray.append(value) + } + if let block = selectMemberBlock { + block(retArray) + } + navigationController?.popViewController(animated: true) + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMembersController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMembersController.swift index 109bc7d9..48862110 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMembersController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/NEBaseTeamMembersController.swift @@ -3,15 +3,22 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. +import NEChatKit +import NECommonUIKit +import NECoreIMKit import NECoreKit import UIKit @objcMembers open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegate, - UITableViewDataSource { + UITableViewDataSource, TeamMemberCellDelegate, TeamMembersViewModelDelegate { public var teamId: String? - public var datas: [TeamMemberInfoModel]? + public var memberDatas: [TeamMemberInfoModel]? { + didSet { + viewmodel.setShowDatas(memberDatas) + } + } public var ownerId: String? @@ -21,6 +28,8 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat public let back = UIView() + let viewmodel = TeamMembersViewModel() + public lazy var searchTextField: UITextField = { let field = UITextField() field.translatesAutoresizingMaskIntoConstraints = false @@ -71,31 +80,30 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat fatalError("init(coder:) has not been implemented") } - override open func viewWillAppear(_ animated: Bool) { - TeamRepo.shared.fetchTeamInfo(teamId ?? "") { [weak self] error, teamModel in - if let err = error as? NSError { - if err.code == 803 || err.code == 1 { - self?.showToast(localizable("team_not_exist")) - } else { - self?.showToast(err.localizedDescription) - } - } else { - self?.datas = teamModel?.users - self?.contentTable.reloadData() - } - } - } - override open func viewDidLoad() { super.viewDidLoad() + addObserver() + viewmodel.delegate = self let team = TeamProvider.shared.getTeam(teamId: teamId ?? "") ownerId = team?.owner if team?.isDisscuss() == false { isSenior = true } + if let tid = team?.teamId { + viewmodel.getMemberInfo(tid) + } setupUI() + + TeamRepo.shared.fetchTeamInfo(teamId ?? "") { [weak self] error, teamModel in + if error != nil { + self?.emptyView.isHidden = false + } else { + self?.viewmodel.setShowDatas(teamModel?.users) + self?.didNeedRefreshUI() + } + } } open func setupUI() { @@ -149,28 +157,21 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat NSLayoutConstraint.activate([ emptyView.leftAnchor.constraint(equalTo: contentTable.leftAnchor), emptyView.rightAnchor.constraint(equalTo: contentTable.rightAnchor), - emptyView.topAnchor.constraint(equalTo: contentTable.topAnchor), + emptyView.topAnchor.constraint(equalTo: contentTable.topAnchor, constant: 50), emptyView.bottomAnchor.constraint(equalTo: contentTable.bottomAnchor), ]) + } + func addObserver() { NotificationCenter.default.addObserver( self, selector: #selector(textChange), name: UITextField.textDidChangeNotification, object: nil ) + NotificationCenter.default.addObserver(self, selector: #selector(didNeedRefreshUI), name: NENotificationName.updateFriendInfo, object: nil) } - /* - // MARK: - Navigation - - // In a storyboard-based application, you will often want to do a little preparation before navigation - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - // Get the new view controller using segue.destination. - // Pass the selected object to the new view controller. - } - */ - func isOwner(_ userId: String?) -> Bool { if isSenior == false { return false @@ -184,7 +185,7 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat func textChange() { searchDatas.removeAll() if let text = searchTextField.text, text.count > 0 { - datas?.forEach { model in + viewmodel.datas.forEach { model in if let uid = model.nimUser?.userId, uid.contains(text) { searchDatas.append(model) } else if let nick = model.nimUser?.userInfo?.nickName, nick.contains(text) { @@ -199,14 +200,14 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat } else { emptyView.isHidden = true } - contentTable.reloadData() + didNeedRefreshUI() } func getRealModel(_ index: Int) -> TeamMemberInfoModel? { if let text = searchTextField.text, text.count > 0 { return searchDatas[index] } - return datas?[index] + return viewmodel.datas[index] } deinit { @@ -219,7 +220,7 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat if let text = searchTextField.text, text.count > 0 { return searchDatas.count } - return datas?.count ?? 0 + return viewmodel.datas.count } open func tableView(_ tableView: UITableView, @@ -261,4 +262,45 @@ open class NEBaseTeamMembersController: NEBaseViewController, UITableViewDelegat } } } + + func didClickRemoveButton(_ model: TeamMemberInfoModel?, _ index: Int) { + print("did click remove button") + weak var weakSelf = self + + // 注释掉的暂时留存,后续可能更改提示语 let content = String(format: localizable("confirm_delete_text"), model?.atNameInTeam() ?? "") + localizable("question_mark") + + showAlert(title: localizable("remove_manager_title"), message: localizable("remove_member_tip")) { + if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false { + weakSelf?.view.makeToast(commonLocalizable("network_error")) + return + } + + if let tid = weakSelf?.teamId, let uid = model?.nimUser?.userId { + weakSelf?.viewmodel.removeTeamMember(tid, [uid]) { error in + if let err = error { + if err.code == noPermissionCode { + weakSelf?.view.makeToast(localizable("no_permission_tip")) + } else { + weakSelf?.view.makeToast(localizable("remove_failed")) + } + } else { + if let text = weakSelf?.searchTextField.text, text.count > 0 { + weakSelf?.searchDatas.remove(at: index) + weakSelf?.viewmodel.removeModel(model) + weakSelf?.didNeedRefreshUI() + } else { + weakSelf?.viewmodel.removeModel(model) + weakSelf?.didNeedRefreshUI() + } + } + } + } + } + } + + // 查找移除数据在 data 中的位置 + + func didNeedRefreshUI() { + contentTable.reloadData() + } } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseHistoryMessageCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseHistoryMessageCell.swift index 89f9416d..d6a5097c 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseHistoryMessageCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseHistoryMessageCell.swift @@ -10,17 +10,6 @@ open class NEBaseHistoryMessageCell: UITableViewCell { public var searchText: String? public var rangeTextColor = UIColor.ne_blueText - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubviews() @@ -44,21 +33,20 @@ open class NEBaseHistoryMessageCell: UITableViewCell { guard let searchStr = searchText else { return } - if let range = resultText.findAllIndex(searchStr).first { - let attributedStr = NSMutableAttributedString(string: resultText) - // range必须要加,参数分别表示从索引几开始取几个字符 - attributedStr.addAttribute( - .foregroundColor, - value: rangeTextColor, - range: range - ) - subTitle.attributedText = attributedStr - } + let attributedStr = NSMutableAttributedString(string: resultText) + // range 表示从索引几开始取几个字符 + let range = attributedStr.mutableString.range(of: searchStr) + attributedStr.addAttribute( + .foregroundColor, + value: rangeTextColor, + range: range + ) + subTitle.attributedText = attributedStr title.text = message?.name timeLabel.text = message?.time - if let imageName = message?.avatar { + if let imageName = message?.avatar, !imageName.isEmpty { headImge.setTitle("") headImge.sd_setImage(with: URL(string: imageName), completed: nil) } else { diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamArrowSettingCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamArrowSettingCell.swift index 78ed7443..1a036a8f 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamArrowSettingCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamArrowSettingCell.swift @@ -17,7 +17,7 @@ open class NEBaseTeamArrowSettingCell: NEBaseTeamSettingCell { super.init(coder: coder) } - override public func configure(_ anyModel: Any) { + override open func configure(_ anyModel: Any) { super.configure(anyModel) } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamAvatarViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamAvatarViewController.swift index cd3fb504..2a93848c 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamAvatarViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamAvatarViewController.swift @@ -21,6 +21,8 @@ open class NEBaseTeamAvatarViewController: NEBaseViewController, UICollectionVie public let tag = UILabel() public var iconUrls = TeamRouter.iconUrls + public var viewmodel = TeamAvatarViewModel() + public lazy var headerView: NEUserHeaderView = { let header = NEUserHeaderView(frame: .zero) header.translatesAutoresizingMaskIntoConstraints = false @@ -51,6 +53,7 @@ open class NEBaseTeamAvatarViewController: NEBaseViewController, UICollectionVie override open func viewDidLoad() { super.viewDidLoad() + viewmodel.getCurrentUserTeamMember(team?.teamId) setupUI() } @@ -74,7 +77,7 @@ open class NEBaseTeamAvatarViewController: NEBaseViewController, UICollectionVie headerView.heightAnchor.constraint(equalToConstant: 80.0), headerView.widthAnchor.constraint(equalToConstant: 80.0), ]) - if let url = team?.avatarUrl { + if let url = team?.avatarUrl, !url.isEmpty { headerView.sd_setImage(with: URL(string: url), completed: nil) headerUrl = url } @@ -127,6 +130,9 @@ open class NEBaseTeamAvatarViewController: NEBaseViewController, UICollectionVie if let mode = team?.updateInfoMode, mode == .all { return true } + if let member = viewmodel.currentTeamMember, member.type == .manager { + return true + } return false } @@ -147,10 +153,10 @@ open class NEBaseTeamAvatarViewController: NEBaseViewController, UICollectionVie NELog.infoLog(ModuleName + " " + self.className(), desc: #function + "CALLBACK " + (error?.localizedDescription ?? "no error")) weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { + if err.code == noNetworkCode { weakSelf?.showToast(commonLocalizable("network_error")) } else { - weakSelf?.showToast(err.localizedDescription) + weakSelf?.showToast(localizable("failed_operation")) } } else { weakSelf?.team?.avatarUrl = weakSelf?.headerUrl diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamInfoViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamInfoViewController.swift index 2b552fe5..f7f8ee64 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamInfoViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamInfoViewController.swift @@ -42,11 +42,11 @@ open class NEBaseTeamInfoViewController: NEBaseViewController, UITableViewDelega } else { title = localizable("group_info") } - viewmodel.getData(team) } override open func viewDidLoad() { super.viewDidLoad() + viewmodel.getData(team) setupUI() } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamIntroduceViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamIntroduceViewController.swift index 619cc68d..eafa4c6e 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamIntroduceViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamIntroduceViewController.swift @@ -9,15 +9,13 @@ import UIKit @objcMembers open class NEBaseTeamIntroduceViewController: NEBaseViewController, UITextViewDelegate { -// typealias SaveCompletion = () -> Void -// -// var block: SaveCompletion? - public var team: NIMTeam? public let textLimit = 100 public let repo = TeamRepo.shared public let backView = UIView() + public let viewmodel = TeamIntroduceViewModel() + public lazy var textView: UITextView = { let text = UITextView() text.translatesAutoresizingMaskIntoConstraints = false @@ -50,6 +48,7 @@ open class NEBaseTeamIntroduceViewController: NEBaseViewController, UITextViewDe override open func viewDidLoad() { super.viewDidLoad() + viewmodel.getCurrentUserTeamMember(team?.teamId) setupUI() } @@ -93,6 +92,9 @@ open class NEBaseTeamIntroduceViewController: NEBaseViewController, UITextViewDe if let mode = team?.updateInfoMode, mode == .all { return true } + if let member = viewmodel.currentTeamMember, member.type == .manager { + return true + } return false } @@ -113,8 +115,12 @@ open class NEBaseTeamIntroduceViewController: NEBaseViewController, UITextViewDe desc: "CALLBACK updateTeamIntroduce " + (error?.localizedDescription ?? "no error") ) weakSelf?.view.hideToastActivity() - if let err = error { - weakSelf?.showToast(err.localizedDescription) + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } } else { weakSelf?.team?.intro = text weakSelf?.navigationController?.popViewController(animated: true) diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberCell.swift index 733b2d03..59cbf140 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberCell.swift @@ -6,8 +6,22 @@ import NECommonUIKit import UIKit +protocol TeamMemberCellDelegate: NSObject { + func didClickRemoveButton(_ model: TeamMemberInfoModel?, _ index: Int) +} + @objcMembers open class NEBaseTeamMemberCell: UITableViewCell { + var currentModel: TeamMemberInfoModel? + + weak var delegate: TeamMemberCellDelegate? + + public var ownerWidth: NSLayoutConstraint? + + public var nameLabelRightMargin: NSLayoutConstraint? + + var index = 0 + lazy var headerView: NEUserHeaderView = { let header = NEUserHeaderView(frame: .zero) header.titleLabel.font = NEConstant.defaultTextFont(14) @@ -15,7 +29,6 @@ open class NEBaseTeamMemberCell: UITableViewCell { header.layer.cornerRadius = 21 header.clipsToBounds = true header.translatesAutoresizingMaskIntoConstraints = false - header.accessibilityIdentifier = "id.avatar" return header }() @@ -44,16 +57,20 @@ open class NEBaseTeamMemberCell: UITableViewCell { return label }() - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) + lazy var removeLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.text = localizable("team_member_remove") + label.font = UIFont.systemFont(ofSize: 14.0) + label.textAlignment = .center + return label + }() - // Configure the view for the selected state - } + lazy var removeBtn: UIButton = { + let button = UIButton() + button.translatesAutoresizingMaskIntoConstraints = false + return button + }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) @@ -74,25 +91,30 @@ open class NEBaseTeamMemberCell: UITableViewCell { headerView.heightAnchor.constraint(equalToConstant: 42), ]) - contentView.addSubview(ownerLabel) - NSLayoutConstraint.activate([ - ownerLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20), - ownerLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - ownerLabel.heightAnchor.constraint(equalToConstant: 25.0), - ownerLabel.widthAnchor.constraint(equalToConstant: 48.0), - ]) - + nameLabelRightMargin = nameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -116) contentView.addSubview(nameLabel) NSLayoutConstraint.activate([ nameLabel.leftAnchor.constraint(equalTo: headerView.rightAnchor, constant: 14.0), nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), - nameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -70), + nameLabelRightMargin!, + ]) + + ownerWidth = ownerLabel.widthAnchor.constraint(equalToConstant: 48.0) + contentView.addSubview(ownerLabel) + NSLayoutConstraint.activate([ + ownerLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -70), + ownerLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), + ownerLabel.heightAnchor.constraint(equalToConstant: 22.0), + ownerWidth!, ]) } func configure(_ model: TeamMemberInfoModel) { -// ownerLabel.isHidden = !isOwner(model.nimUser?.userId) - if let url = model.nimUser?.userInfo?.avatarUrl { + if let userId = model.nimUser?.userId, let user = ChatUserCache.getUserInfo(userId) { + model.nimUser = user + } + currentModel = model + if let url = model.nimUser?.userInfo?.avatarUrl, !url.isEmpty { headerView.sd_setImage(with: URL(string: url), completed: nil) headerView.setTitle("") } else { @@ -102,4 +124,19 @@ open class NEBaseTeamMemberCell: UITableViewCell { } nameLabel.text = model.atNameInTeam() } + + func setupRemoveButton() { + contentView.addSubview(removeBtn) + NSLayoutConstraint.activate([ + removeBtn.topAnchor.constraint(equalTo: contentView.topAnchor), + removeBtn.rightAnchor.constraint(equalTo: contentView.rightAnchor), + removeBtn.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), + removeBtn.widthAnchor.constraint(equalToConstant: 100), + ]) + removeBtn.addTarget(self, action: #selector(didClickRemove), for: .touchUpInside) + } + + func didClickRemove() { + delegate?.didClickRemoveButton(currentModel, index) + } } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberSelectCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberSelectCell.swift new file mode 100644 index 00000000..b473143d --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamMemberSelectCell.swift @@ -0,0 +1,66 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NECommonUIKit +import UIKit + +@objcMembers +open class NEBaseTeamMemberSelectCell: UITableViewCell { + // check box image + public lazy var checkImageView: UIImageView = { + let imageView = UIImageView() + imageView.translatesAutoresizingMaskIntoConstraints = false + imageView.contentMode = .scaleAspectFit + imageView.image = coreLoader.loadImage("unselect") + return imageView + }() + + lazy var headerView: NEUserHeaderView = { + let header = NEUserHeaderView(frame: .zero) + header.titleLabel.font = NEConstant.defaultTextFont(14) + header.titleLabel.textColor = UIColor.white + header.clipsToBounds = true + header.translatesAutoresizingMaskIntoConstraints = false + header.accessibilityIdentifier = "id.avatar" + return header + }() + + lazy var nameLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.font = NEConstant.defaultTextFont(16.0) + label.textColor = .ne_darkText + label.accessibilityIdentifier = "id.userName" + return label + }() + + override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + selectionStyle = .none + setupUI() + } + + public required init?(coder: NSCoder) { + super.init(coder: coder) + } + + open func setupUI() { + contentView.addSubview(headerView) + contentView.addSubview(nameLabel) + contentView.addSubview(checkImageView) + } + + open func configureMember(_ model: NESelectTeamMember?) { + checkImageView.isHighlighted = model?.isSelected ?? false + if let url = model?.member?.nimUser?.userInfo?.avatarUrl, !url.isEmpty { + headerView.sd_setImage(with: URL(string: url), completed: nil) + headerView.setTitle("") + } else { + headerView.image = nil + headerView.setTitle(model?.member?.showNickInTeam() ?? "") + headerView.backgroundColor = UIColor.colorWithString(string: model?.member?.nimUser?.userId) + } + nameLabel.text = model?.member?.atNameInTeam() + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamNameViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamNameViewController.swift index 62ae95f7..237e5d71 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamNameViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamNameViewController.swift @@ -10,7 +10,6 @@ import UIKit @objcMembers open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegate { public var team: NIMTeam? -// var user: NIMUser? public var type = ChangeType.TeamName public var teamMember: NIMTeamMember? public var repo = TeamRepo.shared @@ -18,6 +17,8 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat public let backView = UIView() + let viewModel = TeamNameViewModel() + public lazy var countLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false @@ -49,6 +50,7 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat override open func viewDidLoad() { super.viewDidLoad() + viewModel.getCurrentUserTeamMember(team?.teamId) setupUI() } @@ -117,6 +119,9 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat if let mode = team?.updateInfoMode, mode == .all { return true } + if let member = viewModel.currentTeamMember, member.type == .manager { + return true + } return false } @@ -136,7 +141,7 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat open func saveName() { guard let tid = team?.teamId else { - showToast(localizable("team_not_exist")) + showToast(localizable("failed_operation")) return } @@ -163,7 +168,7 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat repo.updateTeamName(tid, n) { error in weakSelf?.view.hideToastActivity() if let err = error { - weakSelf?.showToast(err.localizedDescription) + weakSelf?.showToast(localizable("failed_operation")) } else { weakSelf?.team?.teamName = n weakSelf?.navigationController?.popViewController(animated: true) @@ -176,7 +181,7 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat weakSelf?.view.hideToastActivity() if let err = error { - weakSelf?.showToast(err.localizedDescription) + weakSelf?.showToast(localizable("failed_operation")) } else { weakSelf?.navigationController?.popViewController(animated: true) } @@ -204,7 +209,7 @@ open class NEBaseTeamNameViewController: NEBaseViewController, UITextViewDelegat // MARK: UITextViewDelegate - public func textViewDidChange(_ textView: UITextView) { + open func textViewDidChange(_ textView: UITextView) { if let _ = textView.markedTextRange { return } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingCell.swift index 623a13cf..ec8fcff6 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingCell.swift @@ -46,18 +46,7 @@ open class NEBaseTeamSettingCell: CornerCell { super.init(coder: coder) } - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - - public func configure(_ anyModel: Any) { + open func configure(_ anyModel: Any) { if let m = anyModel as? SettingCellModel { model = m cornerType = m.cornerType diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingHeaderCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingHeaderCell.swift index 698da2d7..4668b0fd 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingHeaderCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingHeaderCell.swift @@ -12,7 +12,6 @@ open class NEBaseTeamSettingHeaderCell: NEBaseTeamSettingCell { let header = NEUserHeaderView(frame: .zero) header.translatesAutoresizingMaskIntoConstraints = false header.clipsToBounds = true - header.accessibilityIdentifier = "id.avatar" return header }() @@ -27,9 +26,9 @@ open class NEBaseTeamSettingHeaderCell: NEBaseTeamSettingCell { setupUI() } - override public func configure(_ anyModel: Any) { + override open func configure(_ anyModel: Any) { super.configure(anyModel) - if let url = model?.headerUrl { + if let url = model?.headerUrl, !url.isEmpty { headerView.sd_setImage(with: URL(string: url), completed: nil) headerView.setTitle("") } else { diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSelectCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSelectCell.swift index a09f5922..a35e0c9d 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSelectCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSelectCell.swift @@ -26,7 +26,7 @@ open class NEBaseTeamSettingSelectCell: NEBaseTeamSettingCell { super.init(coder: coder) } - override public func configure(_ anyModel: Any) { + override open func configure(_ anyModel: Any) { super.configure(anyModel) subTitleLabel.text = model?.subTitle } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSwitchCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSwitchCell.swift index 8adf331b..a0a677c0 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSwitchCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingSwitchCell.swift @@ -24,7 +24,7 @@ open class NEBaseTeamSettingSwitchCell: NEBaseTeamSettingCell { super.init(coder: coder) } - override public func configure(_ anyModel: Any) { + override open func configure(_ anyModel: Any) { super.configure(anyModel) if let open = model?.switchOpen { tSwitch.isOn = open @@ -37,7 +37,7 @@ open class NEBaseTeamSettingSwitchCell: NEBaseTeamSettingCell { tSwitch.addTarget(self, action: #selector(switchChange(_:)), for: .touchUpInside) } - public func switchChange(_ s: UISwitch) { + open func switchChange(_ s: UISwitch) { if let block = model?.swichChange { block(s.isOn) } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingViewController.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingViewController.swift index 193d82d5..75b580fc 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingViewController.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamSettingViewController.swift @@ -51,7 +51,6 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.titleLabel.font = NEConstant.defaultTextFont(16.0) - imageView.accessibilityIdentifier = "id.avatar" return imageView }() @@ -97,7 +96,7 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let model = viewmodel.teamInfoModel { - if let url = model.team?.avatarUrl { + if let url = model.team?.avatarUrl, !url.isEmpty { teamHeader.sd_setImage(with: URL(string: url)) } if let name = model.team?.teamName { @@ -118,8 +117,12 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ModuleName + " " + self.className, desc: "CALLBACK getTeamInfo " + (error?.localizedDescription ?? "no error") ) - if let err = error { - weakSelf?.showToast(err.localizedDescription) + if let err = error as? NSError { + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else { + weakSelf?.showToast(localizable("team_not_exist")) + } } else { if let type = weakSelf?.viewmodel.teamInfoModel?.team?.type { if type == .normal { @@ -133,21 +136,30 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi } } } + if let type = weakSelf?.teamSettingType { + weakSelf?.viewmodel.teamSettingType = type + } weakSelf?.reloadSectionData() weakSelf?.contentTable.tableHeaderView = weakSelf?.getHeaderView() weakSelf?.contentTable.tableFooterView = weakSelf?.getFooterView() weakSelf?.contentTable.reloadData() - weakSelf?.userinfoCollection.reloadData() + weakSelf?.didRefreshUserinfoCollection() weakSelf?.checkoutAddShowOrHide() } } } // Do any additional setup after loading the view. setupUI() + + NotificationCenter.default.addObserver(self, selector: #selector(didRefreshUserinfoCollection), name: NENotificationName.updateFriendInfo, object: nil) } open func reloadSectionData() {} + open func didRefreshUserinfoCollection() { + userinfoCollection.reloadData() + } + open func setupUI() { view.backgroundColor = .ne_lightBackgroundColor view.addSubview(contentTable) @@ -241,13 +253,9 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi viewmodel.transferTeamOwner { error in weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(commonLocalizable("network_error")) - } else { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.didError(err) } else { - weakSelf?.navigationController?.popViewController(animated: true) + NotificationCenter.default.post(name: NotificationName.popGroupChatVC, object: nil) } } return @@ -372,20 +380,26 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi func didAddUserAndRefreshUI(_ accids: [String], _ tid: String) { weak var weakSelf = self view.makeToastActivity(.center) - viewmodel.repo.inviteUser(accids, tid, nil, nil) { error, members in + viewmodel.inviterUsers(accids, tid) { error, members in if let err = error { weakSelf?.view.hideToastActivity() - weakSelf?.showToast(err.localizedDescription) + if err.code == noNetworkCode { + weakSelf?.showToast(commonLocalizable("network_error")) + } else if err.code == noPermissionCode { + weakSelf?.showToast(localizable("no_permission_tip")) + } else { + weakSelf?.showToast(localizable("failed_operation")) + } } else { print("add users success : ", members as Any) if let ms = members, let model = weakSelf?.viewmodel.teamInfoModel { weakSelf?.viewmodel.repo.splitGroupMember(ms, model) { error, team in weakSelf?.view.hideToastActivity() - if let e = error { - weakSelf?.showToast(e.localizedDescription) + if let err = error as? NSError { + weakSelf?.didError(err) } else { weakSelf?.refreshMemberCount() - weakSelf?.userinfoCollection.reloadData() + weakSelf?.didRefreshUserinfoCollection() weakSelf?.checkoutAddShowOrHide() } } @@ -405,8 +419,8 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi desc: "CALLBACK inviteUser " + (error?.localizedDescription ?? "no error") ) weakSelf?.view.hideToastActivity() - if let err = error { - weakSelf?.showToast(err.localizedDescription) + if let err = error as? NSError { + weakSelf?.didError(err) } else { weakSelf?.showToast(localizable("invite_has_send")) } @@ -424,29 +438,22 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ) weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(commonLocalizable("network_error")) - } else { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.didError(err) } else { - weakSelf?.navigationController?.popViewController(animated: true) + NotificationCenter.default.post(name: NotificationName.popGroupChatVC, object: nil) } } } } func refreshMemberCount() { - if let count = viewmodel.teamInfoModel?.users.count { + if let count = viewmodel.teamInfoModel?.team?.memberNumber { memberCountLabel.text = "\(count)" } } func leaveTeam() { if let tid = teamId { - // 需要先于 SDK 回调进行通知 - NotificationCenter.default.post(name: NotificationName.leaveTeamBySelf, object: true) - view.makeToastActivity(.center) viewmodel.quitTeam(tid) { [weak self] error in NELog.infoLog( @@ -455,27 +462,18 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ) self?.view.hideToastActivity() if let err = error as? NSError { - // 退出群聊失败则需要重置通知 - NotificationCenter.default.post(name: NotificationName.leaveTeamBySelf, object: false) - if err.code == 803 { - self?.navigationController?.popViewController(animated: true) - } else if err.code == 408 { - self?.showToast(commonLocalizable("network_error")) - } else { - self?.showToast(err.localizedDescription) - } + self?.didError(err) } else { - // 会话列表中移除该群聊 - let session = NIMSession(tid, type: .team) - if let stickInfo = self?.viewmodel.getTopSessionInfo(session) { - self?.viewmodel.removeStickTop(params: stickInfo) { err, _ in - NELog.infoLog( - ModuleName + " " + (self?.className ?? "TeamSettingViewController"), - desc: "CALLBACK removeStickTop " + (error?.localizedDescription ?? "no error") - ) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { + self?.viewmodel.getTeamInfo(tid) { _ in + if self?.viewmodel.teamInfoModel?.team?.memberNumber == 1, + self?.viewmodel.isOwner() == true { + self?.dismissTeam() + } else { + NotificationCenter.default.post(name: NotificationName.popGroupChatVC, object: nil) + } } } - self?.navigationController?.popViewController(animated: true) } } } @@ -489,20 +487,22 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi } func didError(_ error: NSError) { - if error.code == 408 { + if error.code == noNetworkCode { showToast(commonLocalizable("network_error")) } else { - showToast(error.localizedDescription) + showToast(localizable("failed_operation")) } } func didNeedRefreshUI() { contentTable.reloadData() refreshMemberCount() - userinfoCollection.reloadData() + didRefreshUserinfoCollection() checkoutAddShowOrHide() } + open func didClickTeamManage() {} + open func checkoutAddShowOrHide() {} func updateInviteModeOwnerAction(_ model: SettingCellModel) { @@ -515,11 +515,7 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ) weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(commonLocalizable("network_error")) - } else { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.didError(err) } else { weakSelf?.viewmodel.teamInfoModel?.team?.inviteMode = .manager model.subTitle = localizable("team_owner") @@ -538,11 +534,7 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ) weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(commonLocalizable("network_error")) - } else { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.didError(err) } else { weakSelf?.viewmodel.teamInfoModel?.team?.inviteMode = .all model.subTitle = localizable("team_all") @@ -595,11 +587,7 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ) weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(commonLocalizable("network_error")) - } else { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.didError(err) } else { weakSelf?.viewmodel.teamInfoModel?.team?.updateInfoMode = .manager model.subTitle = localizable("team_owner") @@ -619,11 +607,7 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi ) weakSelf?.view.hideToastActivity() if let err = error as? NSError { - if err.code == 408 { - weakSelf?.showToast(commonLocalizable("network_error")) - } else { - weakSelf?.showToast(err.localizedDescription) - } + weakSelf?.didError(err) } else { weakSelf?.viewmodel.teamInfoModel?.team?.updateInfoMode = .all model.subTitle = localizable("team_all") @@ -667,4 +651,14 @@ open class NEBaseTeamSettingViewController: NEBaseViewController, UICollectionVi open func didClickChangeNick() {} open func didClickHistoryMessage() {} + + open func getManaterUsers() -> [TeamMemberInfoModel] { + var members = [TeamMemberInfoModel]() + viewmodel.teamInfoModel?.users.forEach { model in + if model.teamMember?.type == .manager { + members.append(model) + } + } + return members + } } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamUserCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamUserCell.swift index f1855812..15bbe475 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamUserCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/NEBaseTeamUserCell.swift @@ -16,7 +16,10 @@ open class NEBaseTeamUserCell: UICollectionViewCell { if let name = user?.showNickInTeam() { userHeader.setTitle(name) } - if let url = user?.nimUser?.userInfo?.avatarUrl { + if let userId = user?.nimUser?.userId, let nimUser = ChatUserCache.getUserInfo(userId) { + user?.nimUser = nimUser + } + if let url = user?.nimUser?.userInfo?.avatarUrl, !url.isEmpty { userHeader.sd_setImage(with: URL(string: url), completed: nil) userHeader.setTitle("") } else if let id = user?.nimUser?.userId { @@ -31,7 +34,6 @@ open class NEBaseTeamUserCell: UICollectionViewCell { header.translatesAutoresizingMaskIntoConstraints = false header.titleLabel.font = NEConstant.defaultTextFont(11.0) header.clipsToBounds = true - header.accessibilityIdentifier = "id.avatar" return header }() diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingRightCustomCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingRightCustomCell.swift index 289a9d22..22af44a5 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingRightCustomCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingRightCustomCell.swift @@ -7,18 +7,7 @@ import UIKit @objcMembers open class TeamSettingRightCustomCell: TeamSettingSubtitleCell { - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - - override public func configure(_ anyModel: Any) { + override open func configure(_ anyModel: Any) { super.configure(anyModel) if let icon = model?.rightCustomViewIcon, icon.count > 0 { customRightView.isHidden = false @@ -54,7 +43,7 @@ open class TeamSettingRightCustomCell: TeamSettingSubtitleCell { return btn }() - public func customRightViewClick() { + open func customRightViewClick() { if let block = model?.customViewClick { block() } diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingSubtitleCell.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingSubtitleCell.swift index c041c1d4..115bd1b5 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingSubtitleCell.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/View/TeamSettingSubtitleCell.swift @@ -9,17 +9,6 @@ import UIKit open class TeamSettingSubtitleCell: NEBaseTeamSettingCell { public var titleWidthAnchor: NSLayoutConstraint? - override public func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override public func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none @@ -56,7 +45,7 @@ open class TeamSettingSubtitleCell: NEBaseTeamSettingCell { ]) } - override public func configure(_ anyModel: Any) { + override open func configure(_ anyModel: Any) { super.configure(anyModel) if let m = anyModel as? SettingCellModel { titleWidthAnchor?.constant = m.titleWidth diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamAvatarViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamAvatarViewModel.swift new file mode 100644 index 00000000..2073ab57 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamAvatarViewModel.swift @@ -0,0 +1,20 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK +import UIKit + +@objcMembers +open class TeamAvatarViewModel: NSObject { + let repo = ChatRepo.shared + var currentTeamMember: NIMTeamMember? + + func getCurrentUserTeamMember(_ teamId: String?) { + if let tid = teamId { + let currentUserAccid = IMKitClient.instance.imAccid() + currentTeamMember = repo.getTeamMemberList(userId: currentUserAccid, teamId: tid) + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamInfoViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamInfoViewModel.swift index 9c03c911..d3c5a532 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamInfoViewModel.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamInfoViewModel.swift @@ -7,7 +7,7 @@ import NECoreIMKit import NIMSDK @objcMembers -public class TeamInfoViewModel: NSObject { +open class TeamInfoViewModel: NSObject { var cellDatas = [SettingCellModel]() func getData(_ team: NIMTeam?) { diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamIntroduceViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamIntroduceViewModel.swift new file mode 100644 index 00000000..381db61d --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamIntroduceViewModel.swift @@ -0,0 +1,21 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK +import UIKit + +@objc +@objcMembers +open class TeamIntroduceViewModel: NSObject { + let repo = ChatRepo.shared + var currentTeamMember: NIMTeamMember? + + func getCurrentUserTeamMember(_ teamId: String?) { + if let tid = teamId { + let currentUserAccid = IMKitClient.instance.imAccid() + currentTeamMember = repo.getTeamMemberList(userId: currentUserAccid, teamId: tid) + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamManageViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamManageViewModel.swift new file mode 100644 index 00000000..ba330f3b --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamManageViewModel.swift @@ -0,0 +1,230 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NECommonKit +import NIMSDK +import UIKit + +public protocol TeamManageViewModelDelegate: NSObjectProtocol { + func didChangeInviteModeClick(_ model: SettingCellModel) + func didUpdateTeamInfoClick(_ model: SettingCellModel) + func didAtPermissionClick(_ model: SettingCellModel) + func didManagerClick() + func didRefreshData() +} + +@objc +@objcMembers +open class TeamManageViewModel: NSObject, NIMTeamManagerDelegate { + let repo = TeamRepo.shared + + let chatRepo = ChatRepo.shared + + public var teamInfoModel: TeamInfoModel? + + var sectionData = [SettingSectionModel]() + + public var managerUsers = [TeamMemberInfoModel]() + + var isRequestData = false + + weak var delegate: TeamManageViewModelDelegate? + + override public init() { + super.init() + NIMSDK.shared().teamManager.add(self) + } + + open func getSectionData() { + sectionData.removeAll() + if teamInfoModel?.team?.owner == IMKitClient.instance.imAccid() { + sectionData.append(getTopSection()) + } + sectionData.append(getMidSection()) + } + + open func getTeamInfo(_ tid: String, _ completion: @escaping (Error?) -> Void) { + if isRequestData == true { + return + } + weak var weakSelf = self + isRequestData = true + repo.fetchTeamInfo(tid) { error, teamInfo in + weakSelf?.isRequestData = false + if error == nil { + weakSelf?.managerUsers.removeAll() + } + teamInfo?.users.forEach { model in + if model.teamMember?.type == .manager { + weakSelf?.managerUsers.append(model) + } + } + weakSelf?.teamInfoModel = teamInfo + weakSelf?.getSectionData() + completion(error) + } + } + + open func getTopSection() -> SettingSectionModel { + NELog.infoLog(ModuleName + " " + className(), desc: #function) + weak var weakSelf = self + let model = SettingSectionModel() + let manager = SettingCellLabelArrowModel() + manager.cellName = localizable("manage_manger") + manager.type = SettingCellType.SettingArrowCell.rawValue + manager.rowHeight = 56 + manager.arrowLabelText = "\(managerUsers.count)" + model.cellModels.append(contentsOf: [manager]) + model.setCornerType() + manager.cellClick = { + weakSelf?.delegate?.didManagerClick() + } + return model + } + + open func getMidSection() -> SettingSectionModel { + NELog.infoLog(ModuleName + " " + className(), desc: #function) + weak var weakSelf = self + let model = SettingSectionModel() + + let editTeam = SettingCellModel() + editTeam.cellName = localizable("who_edit_team_info") + editTeam.type = SettingCellType.SettingSelectCell.rawValue + editTeam.rowHeight = 73 + + if let updateMode = teamInfoModel?.team?.updateInfoMode, updateMode == .all { + editTeam.subTitle = localizable("team_all") + } else { + editTeam.subTitle = localizable("team_owner_and_manager") + } + + editTeam.cellClick = { + weakSelf?.delegate?.didUpdateTeamInfoClick(editTeam) + } + + let invitePermission = SettingCellModel() + invitePermission.cellName = localizable("who_edit_user_info") + invitePermission.type = SettingCellType.SettingSelectCell.rawValue + invitePermission.rowHeight = 73 + if let inviteMode = teamInfoModel?.team?.inviteMode, inviteMode == .all { + invitePermission.subTitle = localizable("team_all") + } else { + invitePermission.subTitle = localizable("team_owner_and_manager") + } + + invitePermission.cellClick = { + weakSelf?.delegate?.didChangeInviteModeClick(invitePermission) + } + + let atAll = SettingCellModel() + atAll.cellName = localizable("who_at_all") + atAll.type = SettingCellType.SettingSelectCell.rawValue + atAll.rowHeight = 73 + atAll.subTitle = localizable("team_owner_and_manager") + atAll.subTitle = getTeamAtPermissionValue() + + atAll.cellClick = { + weakSelf?.delegate?.didAtPermissionClick(atAll) + } + + model.cellModels.append(contentsOf: [editTeam, invitePermission, atAll]) + model.setCornerType() + + return model + } + + open func updateTeamAtPermission(_ isManager: Bool, _ completion: @escaping (Error?) -> Void) { + let value = isManager == true ? allowAtManagerValue : allowAtAllValue + guard let tid = teamInfoModel?.team?.teamId else { + return + } + let latestTeam = repo.getTeam(tid) + if let custom = latestTeam?.clientCustomInfo { + if var dic = NECommonUtil.getDictionaryFromJSONString(custom) as? [String: Any] { + dic[keyAllowAtAll] = value + let info = NECommonUtil.getJSONStringFromDictionary(dic) + repo.updateTeamCustomInfo(info, tid) { error in + completion(error) + } + } + } else { + var dic = [String: Any]() + dic[keyAllowAtAll] = value + let info = NECommonUtil.getJSONStringFromDictionary(dic) + repo.updateTeamCustomInfo(info, tid) { error in + completion(error) + } + } + } + + func getTeamAtPermissionValue() -> String { + if let custom = teamInfoModel?.team?.clientCustomInfo { + if let dic = NECommonUtil.getDictionaryFromJSONString(custom) as? [String: Any] { + if let value = dic[keyAllowAtAll] as? String { + if value == allowAtManagerValue { + return localizable("team_owner_and_manager") + } + } + } + } + return localizable("team_all") + } + + open func onTeamMemberChanged(_ team: NIMTeam) { + updateTeamInfo(team) + } + + open func onTeamUpdated(_ team: NIMTeam) { + updateTeamInfo(team) + } + + func sendTipNoti(_ isManagerPermission: Bool, _ completion: @escaping (Error?) -> Void) { + guard let teamId = teamInfoModel?.team?.teamId else { + return + } + let session = NIMSession(teamId, type: .team) + let tipContent = isManagerPermission ? localizable("team_tip_noti_at_manager") : localizable("team_tip_noti_at_all") + let tipMessage = NIMMessage() + let object = NIMTipObject(attach: nil, callbackExt: nil) + tipMessage.messageObject = object + tipMessage.text = tipContent + let setting = NIMMessageSetting() + setting.shouldBeCounted = false + setting.apnsEnabled = false + tipMessage.setting = setting + chatRepo.sendMessage(message: tipMessage, session: session) { error in + completion(error) + } + } + + private func updateTeamInfo(_ team: NIMTeam) { + guard let tid = teamInfoModel?.team?.teamId else { + return + } + + if isRequestData == true { + return + } + isRequestData = true + repo.fetchTeamInfo(tid) { [weak self] error, info in + if error == nil, info != nil { + self?.teamInfoModel = info + self?.managerUsers.removeAll() + info?.users.forEach { userInfo in + if userInfo.teamMember?.type == .manager { + self?.managerUsers.append(userInfo) + } + } + + self?.sectionData.removeAll() + self?.getSectionData() + self?.delegate?.didRefreshData() + + print("onTeamMemberChanged managers count : ", self?.managerUsers.count as Any) + } + self?.isRequestData = false + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamManagerListViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamManagerListViewModel.swift new file mode 100644 index 00000000..d768b721 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamManagerListViewModel.swift @@ -0,0 +1,90 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK +import UIKit + +public protocol TeamManagerListViewModelDelegate: NSObject { + func didNeedReloadData() +} + +open class TeamManagerListViewModel: NSObject, NIMTeamManagerDelegate { + let repo = TeamRepo.shared + + public var currentMember: NIMTeamMember? + + public var managers = [TeamMemberInfoModel]() + + weak var delegate: TeamManagerListViewModelDelegate? + + public var teamId: String? + + override public init() { + super.init() + NIMSDK.shared().teamManager.add(self) + NotificationCenter.default.addObserver(self, selector: #selector(refreshData), name: NENotificationName.updateFriendInfo, object: nil) + } + + deinit { + NIMSDK.shared().teamManager.remove(self) + } + + open func getManagerDatas(_ tid: String, _ completion: @escaping (Error?) -> Void) { + repo.fetchTeamInfo(tid) { [weak self] error, teamInfo in + if error == nil { + self?.managers.removeAll() + teamInfo?.users.forEach { model in + if model.teamMember?.type == .manager { + self?.managers.append(model) + } + } + completion(nil) + } else { + completion(error) + } + } + } + + open func addTeamManager(_ teamId: String, _ uids: [String], _ completion: @escaping (Error?) -> Void) { + repo.addTeamManagers(teamId, uids) { error in + completion(error) + } + } + + open func removeTeamManager(_ teamId: String, _ uids: [String], _ completion: @escaping (Error?) -> Void) { + repo.removeTeamManagers(teamId, uids) { error in + completion(error) + } + } + + open func getCurrentMember(_ teamId: String) { + currentMember = repo.getMemberInfo(IMKitClient.instance.imAccid(), teamId) + } + + @objc func refreshData() { + guard let tid = teamId else { + return + } + getManagerDatas(tid) { [weak self] error in + if error == nil { + self?.delegate?.didNeedReloadData() + } + } + } + + public func onTeamMemberChanged(_ team: NIMTeam) { + guard let tid = teamId else { + return + } + if tid != team.teamId { + return + } + getManagerDatas(tid) { [weak self] error in + if error != nil { + self?.delegate?.didNeedReloadData() + } + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamMemberSelectViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamMemberSelectViewModel.swift new file mode 100644 index 00000000..7b863baa --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamMemberSelectViewModel.swift @@ -0,0 +1,135 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NECoreIMKit +import NIMSDK +import UIKit + +public protocol TeamMemberSelectViewModelDelegate: NSObject { + func didNeedRefresh() +} + +class TeamMemberSelectViewModel: NSObject, NIMTeamManagerDelegate { + let repo = TeamRepo.shared + + var datas = [NESelectTeamMember]() + + var showDatas = [NESelectTeamMember]() + + var teamInfoModel: TeamInfoModel? + + weak var delegate: TeamMemberSelectViewModelDelegate? + + var selectDic = [String: TeamMemberInfoModel]() // key 值为用户 id + + var isRequest = false + + var managerSet = Set() + + override init() { + super.init() + NIMSDK.shared().teamManager.add(self) + } + + deinit { + NIMSDK.shared().teamManager.remove(self) + } + + func getTeamInfo(_ teamId: String, _ completion: @escaping (Error?) -> Void) { + if isRequest == true { + return + } + weak var weakSelf = self + isRequest = true + repo.fetchTeamInfo(teamId) { error, teamInfo in + weakSelf?.isRequest = false + if error == nil { + weakSelf?.datas.removeAll() + weakSelf?.showDatas.removeAll() + } + weakSelf?.teamInfoModel = teamInfo + weakSelf?.getData() + completion(error) + } + } + + func getData() { + var temFilters = Set() + selectDic.forEach { (key: String, value: TeamMemberInfoModel) in + temFilters.insert(key) + } + managerSet.removeAll() + + teamInfoModel?.users.forEach { [weak self] userModel in + if let uid = userModel.nimUser?.userId { + temFilters.remove(uid) + if uid == IMKitClient.instance.imAccid() { + return + } + if uid == self?.teamInfoModel?.team?.owner { + return + } + if userModel.teamMember?.type == .manager { + self?.managerSet.insert(uid) + self?.selectDic.removeValue(forKey: uid) + return + } + } + let selectMember = NESelectTeamMember() + selectMember.member = userModel + self?.datas.append(selectMember) + self?.showDatas.append(selectMember) + } + temFilters.forEach { uid in + selectDic.removeValue(forKey: uid) + } + datas.forEach { member in + if let accid = member.member?.nimUser?.userId { + if selectDic.contains(where: { (key: String, value: TeamMemberInfoModel) in + key == accid + }) { + member.isSelected = true + } + } + } + } + + func searchAllData(_ searchText: String) -> [NESelectTeamMember] { + let result = datas.filter { findContainStr(searchText, $0) } + return result + } + + func searchShowData(_ searchText: String) -> [NESelectTeamMember] { + let result = showDatas.filter { findContainStr(searchText, $0) } + return result + } + + func findContainStr(_ text: String, _ selectModel: NESelectTeamMember) -> Bool { + if let uid = selectModel.member?.nimUser?.userId, uid.contains(text) { + return true + } else if let nick = selectModel.member?.nimUser?.userInfo?.nickName, nick.contains(text) { + return true + } else if let alias = selectModel.member?.nimUser?.alias, alias.contains(text) { + return true + } else if let tNick = selectModel.member?.teamMember?.nickname, tNick.contains(text) { + return true + } + return false + } + + func onTeamMemberChanged(_ team: NIMTeam) { + guard let tid = teamInfoModel?.team?.teamId else { + return + } + if tid != team.teamId { + return + } + getTeamInfo(tid) { [weak self] error in + if error == nil { + self?.delegate?.didNeedRefresh() + } + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamMembersViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamMembersViewModel.swift new file mode 100644 index 00000000..055f439f --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamMembersViewModel.swift @@ -0,0 +1,82 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK +import UIKit + +protocol TeamMembersViewModelDelegate: NSObject { + func didNeedRefreshUI() +} + +class TeamMembersViewModel: NSObject { + weak var delegate: TeamMembersViewModelDelegate? + + var datas = [TeamMemberInfoModel]() + + let repo = TeamRepo.shared + public var currentMember: NIMTeamMember? + + func getMemberInfo(_ teamId: String) { + currentMember = repo.getMemberInfo(IMKitClient.instance.imAccid(), teamId) + } + + func removeTeamMember(_ teamdId: String, _ uids: [String], _ completion: @escaping (NSError?) -> Void) { + repo.removeMembers(teamdId, uids) { error in + completion(error as NSError?) + } + } + + func setShowDatas(_ memberDatas: [TeamMemberInfoModel]?) { + var owner: TeamMemberInfoModel? + var managers = [TeamMemberInfoModel]() + var normalMembers = [TeamMemberInfoModel]() + + memberDatas?.forEach { model in + if model.teamMember?.type == .owner { + owner = model + } else if model.teamMember?.type == .manager { + managers.append(model) + } else { + normalMembers.append(model) + } + } + + datas.removeAll() + if let findOwner = owner { + datas.append(findOwner) + } + // managers 根据 时间排序 排序 + managers.sort { model1, model2 in + if let time1 = model1.teamMember?.createTime, let time2 = model2.teamMember?.createTime { + return time2 > time1 + } + return false + } + // normalMembers 根据 时间排序 排序 + normalMembers.sort { model1, model2 in + if let time1 = model1.teamMember?.createTime, let time2 = model2.teamMember?.createTime { + return time2 > time1 + } + return false + } + datas.append(contentsOf: managers) + datas.append(contentsOf: normalMembers) + delegate?.didNeedRefreshUI() + } + + func removeModel(_ model: TeamMemberInfoModel?) { + guard let rmModel = model else { + return + } + datas.removeAll(where: { model in + if let rmUid = rmModel.nimUser?.userId, let uid = model.nimUser?.userId { + if rmUid == uid { + return true + } + } + return false + }) + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamNameViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamNameViewModel.swift new file mode 100644 index 00000000..bf92a566 --- /dev/null +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamNameViewModel.swift @@ -0,0 +1,21 @@ +//// Copyright (c) 2022 NetEase, Inc. All rights reserved. +// Use of this source code is governed by a MIT license that can be +// found in the LICENSE file. + +import NEChatKit +import NIMSDK +import UIKit + +@objc +@objcMembers +open class TeamNameViewModel: NSObject { + let repo = ChatRepo.shared + var currentTeamMember: NIMTeamMember? + + func getCurrentUserTeamMember(_ teamId: String?) { + if let tid = teamId { + let currentUserAccid = IMKitClient.instance.imAccid() + currentTeamMember = repo.getTeamMemberList(userId: currentUserAccid, teamId: tid) + } + } +} diff --git a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamSettingViewModel.swift b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamSettingViewModel.swift index 9f850d6d..7ecec906 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamSettingViewModel.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/Setting/ViewModel/TeamSettingViewModel.swift @@ -15,10 +15,11 @@ protocol TeamSettingViewModelDelegate: NSObjectProtocol { func didNeedRefreshUI() func didError(_ error: NSError) func didClickMark() + func didClickTeamManage() } @objcMembers -public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { +open class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { public var sectionData = [SettingSectionModel]() public var searchResultInfos: [HistoryMessageModel]? @@ -33,6 +34,8 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { private let className = "TeamSettingViewModel" + public var teamSettingType: TeamSettingType = .Discuss + override public init() { super.init() NIMSDK.shared().teamManager.add(self) @@ -52,7 +55,6 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { return } sectionData.append(getThreeSection()) - sectionData.append(getFourSection()) } } @@ -110,7 +112,7 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { } } } else { -// weakSelf?.repo.updateNoti(.none, tid) + // weakSelf?.repo.updateNoti(.none, tid) weakSelf?.repo.setTeamNotify(.none, tid) { error in if let err = error as? NSError { weakSelf?.delegate?.didNeedRefreshUI() @@ -137,9 +139,14 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { if let tid = weakSelf?.teamInfoModel?.team?.teamId { let session = NIMSession(tid, type: .team) if isOpen { + // 不存在最近会话的置顶,先创建最近会话 + if weakSelf?.getRecenterSession() == nil { + NELog.infoLog(weakSelf?.className() ?? "", desc: #function + "addRecentetSession") + weakSelf?.addRecentetSession() + } let params = NIMAddStickTopSessionParams(session: session) weakSelf?.repo.addStickTop(params: params) { error, info in - print("add stick : ", error as Any) + NELog.infoLog(weakSelf?.className() ?? "", desc: #function + "addStickTop error : \(error?.localizedDescription ?? "") ") if let err = error { weakSelf?.delegate?.didNeedRefreshUI() weakSelf?.delegate?.didError(err) @@ -150,7 +157,7 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { } else { if let info = weakSelf?.repo.getTopSessionInfo(session) { weakSelf?.repo.removeStickTop(params: info) { error, info in - print("remote stick : ", error as Any) + NELog.infoLog(weakSelf?.className() ?? "", desc: #function + "removeStickTop error : \(error?.localizedDescription ?? "") ") if let err = error { weakSelf?.delegate?.didNeedRefreshUI() weakSelf?.delegate?.didError(err) @@ -163,12 +170,21 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { } } - model.cellModels.append(contentsOf: [ - mark, // 标记 - history, // 历史记录 - remind, // 开启消息提醒 - setTop, // 聊天置顶 - ]) + let nick = SettingCellModel() + nick.cellName = localizable("team_nick") + nick.type = SettingCellType.SettingArrowCell.rawValue + nick.cellClick = { + weakSelf?.delegate?.didClickChangeNick() + } + + model.cellModels.append(mark) + model.cellModels.append(history) + model.cellModels.append(remind) + model.cellModels.append(setTop) + if isNormalTeam() == false { + model.cellModels.append(nick) + } + model.setCornerType() return model } @@ -177,14 +193,7 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { private func getThreeSection() -> SettingSectionModel { NELog.infoLog(ModuleName + " " + className, desc: #function) let model = SettingSectionModel() - weak var weakSelf = self - let nick = SettingCellModel() - nick.cellName = localizable("team_nick") - nick.type = SettingCellType.SettingArrowCell.rawValue - nick.cellClick = { - weakSelf?.delegate?.didClickChangeNick() - } let forbiddenWords = SettingCellModel() forbiddenWords.cellName = localizable("team_no_speak") @@ -208,10 +217,21 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { } } - model.cellModels.append(nick) + // 群管理 + let teamManager = SettingCellModel() + teamManager.cellName = localizable("manage_team") + teamManager.type = SettingCellType.SettingArrowCell.rawValue + teamManager.cellClick = { + weakSelf?.delegate?.didClickTeamManage() + } + if isOwner() { model.cellModels.append(forbiddenWords) } + + if isOwner() || isManager() { + model.cellModels.append(teamManager) + } model.setCornerType() return model } @@ -249,45 +269,6 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { modifyPermission.cellClick = { weakSelf?.delegate?.didUpdateTeamInfoClick(modifyPermission) } - // 产品策略调整,暂时移除该功能 - /* - let agreePermission = SettingCellModel() - agreePermission.cellName = localizable("agree") - agreePermission.type = SettingCellType.SettingSwitchCell.rawValue - if let inviteMode = teamInfoModel?.team?.beInviteMode, inviteMode == .needAuth { - agreePermission.switchOpen = true - } - agreePermission.swichChange = { isOpen in - if let tid = weakSelf?.teamInfoModel?.team?.teamId { - if isOpen == true { - weakSelf?.repo.updateBeInviteMode(.needAuth, tid) { error in - print("join mode : ", error as Any) - if let err = error { - agreePermission.switchOpen = false - weakSelf?.delegate?.didNeedRefreshUI() - weakSelf?.delegate?.didError(err) - } else { - weakSelf?.teamInfoModel?.team?.joinMode = .needAuth - agreePermission.switchOpen = true - } - } - - } else { - weakSelf?.repo.updateBeInviteMode(.noAuth, tid) { error in - print("join mode : ", error as Any) - if let err = error { - agreePermission.switchOpen = true - weakSelf?.delegate?.didNeedRefreshUI() - weakSelf?.delegate?.didError(err) - } else { - weakSelf?.teamInfoModel?.team?.joinMode = .noAuth - agreePermission.switchOpen = false - } - } - } - } - } - */ if isOwner() { model.cellModels.append(contentsOf: [invitePermission, modifyPermission]) @@ -302,12 +283,6 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { weak var weakSelf = self repo.fetchTeamInfo(teamId) { error, teamInfo in weakSelf?.teamInfoModel = teamInfo - print("get team info user: ", teamInfo?.users as Any) - teamInfo?.users.forEach { member in - print("team meber accid : ", member.nimUser?.userId as Any) - } - print("get team info team: ", teamInfo?.team as Any) - print("get team info error: ", error as Any) if error == nil { weakSelf?.getData() weakSelf?.getCurrentMember(IMKitClient.instance.imAccid(), teamId) @@ -321,19 +296,19 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { repo.dismissTeam(teamId, completion) } - public func quitTeam(_ teamId: String, _ completion: @escaping (Error?) -> Void) { + open func quitTeam(_ teamId: String, _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:\(teamId)") repo.quitTeam(teamId, completion) } - public func getTopSessionInfo(_ session: NIMSession) -> NIMStickTopSessionInfo { + open func getTopSessionInfo(_ session: NIMSession) -> NIMStickTopSessionInfo { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:\(session.sessionId)") return repo.getTopSessionInfo(session) } - public func removeStickTop(params: NIMStickTopSessionInfo, - _ completion: @escaping (NSError?, NIMStickTopSessionInfo?) - -> Void) { + open func removeStickTop(params: NIMStickTopSessionInfo, + _ completion: @escaping (NSError?, NIMStickTopSessionInfo?) + -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", teamId:\(params.session.sessionId)") repo.removeStickTop(params: params, completion) } @@ -349,6 +324,7 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { func isOwner() -> Bool { NELog.infoLog(ModuleName + " " + className, desc: #function) + if let accid = teamInfoModel?.team?.owner { if IMKitClient.instance.isMySelf(accid) { return true @@ -357,9 +333,21 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { return false } + func isManager() -> Bool { + if let tid = teamInfoModel?.team?.teamId, let currentTeamMebmer = repo.getMemberInfo(IMKitClient.instance.imAccid(), tid) { + if currentTeamMebmer.type == .manager { + return true + } + } + return false + } + private func sampleMemberId(arr: [TeamMemberInfoModel], owner: String) -> String? { var index = arc4random_uniform(UInt32(arr.count)) while arr[Int(index)].teamMember?.userId == owner { + if arr.count == 1 { + return owner + } index = arc4random_uniform(UInt32(arr.count)) } return arr[Int(index)].teamMember?.userId @@ -384,33 +372,41 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { userId = sampleOwnerId } + if userId == NIMSDK.shared().loginManager.currentAccount() { + dismissTeam(teamId, completion) + return + } + NIMSDK.shared().teamManager.transferManager(withTeam: teamId, newOwnerId: userId, isLeave: true) { error in completion(error) } } - public func updateInfoMode(_ mode: NIMTeamUpdateInfoMode, _ teamId: String, - _ completion: @escaping (Error?) -> Void) { + open func updateInfoMode(_ mode: NIMTeamUpdateInfoMode, _ teamId: String, + _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", mode:\(mode.rawValue)") repo.updateTeamInfoPrivilege(mode, teamId, completion) } - public func updateInviteMode(_ mode: NIMTeamInviteMode, _ teamId: String, - _ completion: @escaping (Error?) -> Void) { + open func updateInviteMode(_ mode: NIMTeamInviteMode, _ teamId: String, + _ completion: @escaping (Error?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", mode:\(mode.rawValue)") repo.updateInviteMode(mode, teamId, completion) } - public func isNormalTeam() -> Bool { + open func isNormalTeam() -> Bool { NELog.infoLog(ModuleName + " " + className, desc: #function) if let type = teamInfoModel?.team?.type, type == .normal { return true } + if teamInfoModel?.team?.clientCustomInfo?.contains(discussTeamKey) == true { + return true + } return false } - public func searchMessages(_ session: NIMSession, option: NIMMessageSearchOption, - _ completion: @escaping (NSError?, [HistoryMessageModel]?) -> Void) { + open func searchMessages(_ session: NIMSession, option: NIMMessageSearchOption, + _ completion: @escaping (NSError?, [HistoryMessageModel]?) -> Void) { NELog.infoLog(ModuleName + " " + className, desc: #function + ", session:\(session.sessionId)") weak var weakSelf = self repo.searchMessages(session, option: option) { error, messages in @@ -423,9 +419,8 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { } } - public func onTeamMemberRemoved(_ team: NIMTeam, withMembers memberIDs: [String]?) { + open func onTeamMemberRemoved(_ team: NIMTeam, withMembers memberIDs: [String]?) { if let accids = memberIDs { - weak var weakSelf = self accids.forEach { accid in if let users = teamInfoModel?.users { for (i, m) in users.enumerated() { @@ -439,9 +434,41 @@ public class TeamSettingViewModel: NSObject, NIMTeamManagerDelegate { } } - public func onTeamMemberChanged(_ team: NIMTeam) {} + public func onTeamMemberChanged(_ team: NIMTeam) { + if let tid = teamInfoModel?.team?.teamId, tid != team.teamId { + return + } + teamInfoModel?.team = team + getCurrentMember(IMKitClient.instance.imAccid(), teamInfoModel?.team?.teamId) + getData() + delegate?.didNeedRefreshUI() + } - public func onTeamUpdated(_ team: NIMTeam) { + open func onTeamUpdated(_ team: NIMTeam) { + if let teamId = teamInfoModel?.team?.teamId, teamId != team.teamId { + return + } teamInfoModel?.team = team } + + open func inviterUsers(_ accids: [String], _ tid: String, _ completion: @escaping (NSError?, [NIMTeamMember]?) -> Void) { + repo.inviteUser(accids, tid, nil, nil) { error, members in + completion(error as NSError?, members) + } + } + + public func addRecentetSession() { + if let tid = teamInfoModel?.team?.teamId { + let currentSession = NIMSession(tid, type: .team) + repo.addRecentSession(currentSession) + } + } + + public func getRecenterSession() -> NIMRecentSession? { + if let tid = teamInfoModel?.team?.teamId { + let currentSession = NIMSession(tid, type: .team) + return repo.getRecentSession(currentSession) + } + return nil + } } diff --git a/NETeamUIKit/NETeamUIKit/Classes/TeamConstant.swift b/NETeamUIKit/NETeamUIKit/Classes/TeamConstant.swift index 0ca9ea84..04f5cdb1 100644 --- a/NETeamUIKit/NETeamUIKit/Classes/TeamConstant.swift +++ b/NETeamUIKit/NETeamUIKit/Classes/TeamConstant.swift @@ -21,4 +21,5 @@ public var inviteNumberLimit: Int = 200 enum NotificationName { static let leaveTeamBySelf = Notification.Name(rawValue: "team.leaveTeamBySelf") + static let popGroupChatVC = Notification.Name(rawValue: "team.popGroupChatVC") } diff --git a/Podfile b/Podfile index 15c129a7..30148591 100644 --- a/Podfile +++ b/Podfile @@ -10,37 +10,37 @@ target 'app' do pod 'YXLogin', '1.0.0' #可选UI库 - pod 'NEContactUIKit', '9.6.5' - pod 'NEConversationUIKit', '9.6.5' - pod 'NEChatUIKit', '9.6.5' - pod 'NETeamUIKit', '9.6.5' + pod 'NEContactUIKit', '9.7.0' + pod 'NEConversationUIKit', '9.7.0' + pod 'NEChatUIKit', '9.7.0' + pod 'NETeamUIKit', '9.7.0' #可选Kit库(和UIKit对应) - pod 'NEChatKit', '9.6.5' + pod 'NEChatKit', '9.7.0' #基础kit库 - pod 'NIMSDK_LITE','9.14.0' - pod 'NECommonUIKit', '9.6.5' - pod 'NECommonKit', '9.6.4' - pod 'NECoreIMKit', '9.6.5' - pod 'NECoreKit', '9.6.5' + pod 'NECommonUIKit', '9.6.6' + pod 'NECommonKit', '9.6.6' + pod 'NECoreIMKit', '9.6.7' + pod 'NECoreKit', '9.6.6' #扩展库 - pod 'NEMapKit', '9.6.5' +# pod 'NEMapKit', '9.7.0' #呼叫组件,音视频通话能力,需要开通 音视频2.0,可选,聊天一面会根据依赖初始化自动显示音视频通话入口 + pod 'NIMSDK_LITE','9.14.2' pod 'NERtcCallKit/NOS_Special', '2.2.0' pod 'NERtcCallUIKit/NOS_Special', '2.2.0' pod 'NERtcSDK', '5.5.2' # # 如果需要查看UI部分源码请注释掉以上在线依赖,打开下面的本地依赖 - # pod 'NEContactUIKit', :path => 'NEContactUIKit/NEContactUIKit.podspec' - # pod 'NEConversationUIKit', :path => 'NEConversationUIKit/NEConversationUIKit.podspec' - # pod 'NETeamUIKit', :path => 'NETeamUIKit/NETeamUIKit.podspec' - # pod 'NEChatUIKit', :path => 'NEChatUIKit/NEChatUIKit.podspec' - # pod 'NEMapKit', :path => 'NEMapKit/NEMapKit.podspec' - # pod 'NERtcCallUIKit', :path => 'NERtcCallUIKit/NERtcCallUIKit.podspec' +# pod 'NEContactUIKit', :path => 'NEContactUIKit/NEContactUIKit.podspec' +# pod 'NEConversationUIKit', :path => 'NEConversationUIKit/NEConversationUIKit.podspec' +# pod 'NETeamUIKit', :path => 'NETeamUIKit/NETeamUIKit.podspec' +# pod 'NEChatUIKit', :path => 'NEChatUIKit/NEChatUIKit.podspec' +# pod 'NEMapKit', :path => 'NEMapKit/NEMapKit.podspec' +# pod 'NERtcCallUIKit', :path => 'NERtcCallUIKit/NERtcCallUIKit.podspec' end @@ -50,7 +50,7 @@ post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES' - config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0' + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0' end end end diff --git a/app/Custom/CustomAttachment.swift b/app/Custom/CustomAttachment.swift index 602ed073..58cdac24 100644 --- a/app/Custom/CustomAttachment.swift +++ b/app/Custom/CustomAttachment.swift @@ -1,4 +1,3 @@ - // Copyright (c) 2022 NetEase, Inc. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. @@ -6,21 +5,19 @@ import NEChatUIKit import NIMSDK import UIKit -public class CustomAttachment: NSObject, NIMCustomAttachment, NECustomAttachmentProtocol { - public var customType: Int = 0 - - public var cellHeight: CGFloat = 0 - - public var type = 0 - +public class CustomAttachment: NECustomAttachment { public var goodsName = "name" public var goodsURL = "url" - public func encode() -> String { - let info = ["goodsName": goodsName, "goodsURL": goodsURL, "type": type] as [String: Any] + override public func encode() -> String { + // 自定义序列化方法之前必须调用父类的序列化方法 + let neContent = super.encode() + var info: [String: Any] = getDictionaryFromJSONString(neContent) as? [String: Any] ?? [:] + info["goodsName"] = goodsName + info["goodsURL"] = goodsURL - let jsonData = try? JSONSerialization.data(withJSONObject: info, options: .prettyPrinted) + let jsonData = try? JSONSerialization.data(withJSONObject: info, options: []) var content = "" if let data = jsonData { content = String(data: data, encoding: .utf8) ?? "" @@ -29,41 +26,18 @@ public class CustomAttachment: NSObject, NIMCustomAttachment, NECustomAttachment } } -public class CustomAttachmentDecoder: NSObject, NIMCustomAttachmentCoding { - public func decodeAttachment(_ content: String?) -> NIMCustomAttachment? { - var attachment: NIMCustomAttachment? - let data = content?.data(using: .utf8) - guard let dataInfo = data else { - return attachment +public class CustomAttachmentDecoder: NECustomAttachmentDecoder { + override public func decodeCustomMessage(info: [String: Any]) -> CustomAttachment { + // 自定义反序列化方法之前必须调用父类的反序列化方法 + let neCustomAttachment = super.decodeCustomMessage(info: info) + let customAttachment = CustomAttachment(customType: neCustomAttachment.customType, + cellHeight: neCustomAttachment.cellHeight, + data: neCustomAttachment.data) + if customAttachment.customType == 20 { + customAttachment.cellHeight = 50 } - - let infoDict = try? JSONSerialization.jsonObject( - with: dataInfo, - options: .mutableContainers - ) - let infoResult = infoDict as? [String: Any] - let type = infoResult?["type"] as? Int - - switch type { - case 0: - attachment = - decodeCustomMessage(info: infoDict as? [String: Any] ?? [String(): String()]) - default: - print("test") - } - - return attachment - } - - func decodeCustomMessage(info: [String: Any]) -> CustomAttachment { - let customAttachment = CustomAttachment() customAttachment.goodsName = info["goodsName"] as? String ?? "" customAttachment.goodsURL = info["goodsURL"] as? String ?? "" - if let type = info["type"] as? Int { - customAttachment.type = type - } - customAttachment.customType = 20 - customAttachment.cellHeight = 50 return customAttachment } diff --git a/app/Custom/CustomChatCell.swift b/app/Custom/CustomChatCell.swift index e21c5024..0625c66f 100644 --- a/app/Custom/CustomChatCell.swift +++ b/app/Custom/CustomChatCell.swift @@ -36,7 +36,7 @@ class CustomChatCell: NEChatBaseCell { testLabel.textColor = UIColor.black } - override func setModel(_ model: MessageContentModel) { + override func setModel(_ model: MessageContentModel, _ isSend: Bool) { print("this is custom message") testLabel.text = "this is custom message" } diff --git a/app/Custom/CustomContactTableViewCell.swift b/app/Custom/CustomContactTableViewCell.swift index cb95f899..e93c4a63 100644 --- a/app/Custom/CustomContactTableViewCell.swift +++ b/app/Custom/CustomContactTableViewCell.swift @@ -29,6 +29,7 @@ public class CustomContactTableViewCell: ContactTableViewCell { fatalError("init(coder:) has not been implemented") } + // 根据数据模型设置 cell 内容 override public func setModel(_ model: ContactInfo) { super.setModel(model) onlineView.isHidden = false diff --git a/app/Custom/CustomContactsViewController.swift b/app/Custom/CustomContactsViewController.swift index ca603bb1..2d0dbad6 100644 --- a/app/Custom/CustomContactsViewController.swift +++ b/app/Custom/CustomContactsViewController.swift @@ -144,6 +144,7 @@ public class CustomContactsViewController: ContactsViewController, NEBaseContact bodyBottomViewHeight = 0 } + // 父类加载完数据后会调用此方法,可在此对数据进行二次处理 public func onDataLoaded() { viewModel.contacts[1].contacts.forEach { info in info.contactCellType = ContactCellType.ContactCutom.rawValue diff --git a/app/Custom/CustomConversationController.swift b/app/Custom/CustomConversationController.swift index bb2867bf..8a302134 100644 --- a/app/Custom/CustomConversationController.swift +++ b/app/Custom/CustomConversationController.swift @@ -117,9 +117,9 @@ open class CustomConversationController: ConversationController, NEBaseConversat } /// 会话列表点击事件 - NEKitConversationConfig.shared.ui.itemClick = { model, indexPath in - self.showToast((model?.userInfo?.showName(true) ?? model?.teamInfo?.getShowName()) ?? "会话列表点击事件") - } +// NEKitConversationConfig.shared.ui.itemClick = { model, indexPath in +// self.showToast((model?.userInfo?.showName(true) ?? model?.teamInfo?.getShowName()) ?? "会话列表点击事件") +// } /* 布局自定义 @@ -148,6 +148,14 @@ open class CustomConversationController: ConversationController, NEBaseConversat // 实现协议(重写tabbar点击事件) navigationView.delegate = self + // 自定义会话列表标题、图标、间距 + navigationView.brandBtn.setTitle("消息", for: .normal) + navigationView.brandBtn.setImage(nil, for: .normal) + navigationView.brandBtn.layoutButtonImage(style: .left, space: 0) + + // 自定义添加按钮图标 + navigationView.addBtn.setImage(UIImage.ne_imageNamed(name: "noNeed_notify"), for: .normal) + // 顶部bodyTopView中添加自定义view(需要设置bodyTopView的高度) customTopView.btn.setTitle("通过重写方式添加", for: .normal) bodyTopView.addSubview(customTopView) diff --git a/app/Custom/CustomConversationListCell.swift b/app/Custom/CustomConversationListCell.swift index afa64a91..de8d11e9 100644 --- a/app/Custom/CustomConversationListCell.swift +++ b/app/Custom/CustomConversationListCell.swift @@ -7,6 +7,7 @@ import NEConversationUIKit import UIKit open class CustomConversationListCell: ConversationListCell { + // 新增 UI 元素,用于展示在线状态 private lazy var onlineView: UIImageView = { let notify = UIImageView() notify.translatesAutoresizingMaskIntoConstraints = false @@ -16,6 +17,8 @@ open class CustomConversationListCell: ConversationListCell { override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) + + // 头像右下角 contentView.addSubview(onlineView) NSLayoutConstraint.activate([ onlineView.rightAnchor.constraint(equalTo: headImge.rightAnchor), @@ -29,8 +32,9 @@ open class CustomConversationListCell: ConversationListCell { fatalError("init(coder:) has not been implemented") } + // 此方法用于数据和 UI 的绑定,可在此处在数据展示前对数据进行处理 override open func configData(sessionModel: ConversationListModel?) { super.configData(sessionModel: sessionModel) -// subTitle.text = "[自定义类型文案]" +// subTitle.text = "[自定义类型文案]" } } diff --git a/app/Custom/CustomP2PChatViewController.swift b/app/Custom/CustomP2PChatViewController.swift index 0e4c435b..91302645 100644 --- a/app/Custom/CustomP2PChatViewController.swift +++ b/app/Custom/CustomP2PChatViewController.swift @@ -6,9 +6,10 @@ import NEChatUIKit import NIMSDK import UIKit class CustomP2PChatViewController: P2PChatViewController { + let customMessageType = 20 override func viewDidLoad() { - // 自定义消息以及外部扩展 覆盖cell UI 样式示例 -// customMessage() + // 自定义消息cell绑定需要放在 super.viewDidLoad() 之前 + NEChatUIKitClient.instance.regsiterCustomCell(["\(customMessageType)": CustomChatCell.self]) // 通过配置项实现自定义 customByConfig() @@ -17,6 +18,9 @@ class CustomP2PChatViewController: P2PChatViewController { // customByOverread() super.viewDidLoad() + + // 自定义消息以及外部扩展 覆盖cell UI 样式示例 + customMessage() } /// 通过配置项实现 UI 自定义 @@ -200,7 +204,6 @@ class CustomP2PChatViewController: P2PChatViewController { func customMessage() { // 注册自定义消息的解析器 NIMCustomObject.registerCustomDecoder(CustomAttachmentDecoder()) - NEChatUIKitClient.instance.regsiterCustomCell(["20": CustomChatCell.self]) // 测试自定义消息发送按钮 let testBtn = UIButton() @@ -269,9 +272,8 @@ class CustomP2PChatViewController: P2PChatViewController { } @objc func sendCustomButton() { - let attachment = CustomAttachment() - attachment.customType = 20 - attachment.cellHeight = 50 + let data = ["type": customMessageType] + let attachment = CustomAttachment(customType: customMessageType, cellHeight: 50, data: data) let message = NIMMessage() let object = NIMCustomObject() object.attachment = attachment diff --git a/app/Main/AppDelegate.swift b/app/Main/AppDelegate.swift index c0389c49..8668a71b 100644 --- a/app/Main/AppDelegate.swift +++ b/app/Main/AppDelegate.swift @@ -33,12 +33,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD func setupInit(){ - // init + // 初始化NIMSDK let option = NIMSDKOption() option.appKey = AppKey.appKey option.apnsCername = AppKey.pushCerName IMKitClient.instance.setupCoreKitIM(option) + // 登录IM之前先初始化 @ 消息监听mananger + NEAtMessageManager.setupInstance() + let account = "<#account#>" let token = "<#token#>" @@ -173,7 +176,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD return } let anchor = param["anchor"] as? NIMMessage - var p2pChatVC = P2PChatViewController(session: session, anchor: anchor) + let p2pChatVC = P2PChatViewController(session: session, anchor: anchor) + for (i, vc) in (nav?.viewControllers ?? []).enumerated() { if vc.isKind(of: ChatViewController.self) { nav?.viewControllers[i] = p2pChatVC @@ -181,6 +185,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD return } } + + if let remove = param["removeUserVC"] as? Bool, remove { + nav?.viewControllers.removeLast() + } + nav?.pushViewController(p2pChatVC, animated: true) } } else { @@ -191,7 +200,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD return } let anchor = param["anchor"] as? NIMMessage - var p2pChatVC = FunP2PChatViewController(session: session, anchor: anchor) + let p2pChatVC = FunP2PChatViewController(session: session, anchor: anchor) + for (i, vc) in (nav?.viewControllers ?? []).enumerated() { if vc.isKind(of: ChatViewController.self) { nav?.viewControllers[i] = p2pChatVC @@ -199,6 +209,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD return } } + + if let remove = param["removeUserVC"] as? Bool, remove { + nav?.viewControllers.removeLast() + } + nav?.pushViewController(p2pChatVC, animated: true) } } diff --git a/app/Mine/Controller/MeViewController.swift b/app/Mine/Controller/MeViewController.swift index 65bea16f..24e36faa 100644 --- a/app/Mine/Controller/MeViewController.swift +++ b/app/Mine/Controller/MeViewController.swift @@ -10,7 +10,7 @@ import NIMSDK import UIKit import YXLogin -class MeViewController: UIViewController { +class MeViewController: UIViewController, UIGestureRecognizerDelegate { private let mineData = [ [NSLocalizedString("setting", comment: ""): "mine_setting"], [NSLocalizedString("about_yunxin", comment: ""): "about_yunxin"], @@ -22,7 +22,6 @@ class MeViewController: UIViewController { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white - view.accessibilityIdentifier = "id.avatar" return view }() @@ -61,6 +60,13 @@ class MeViewController: UIViewController { navigationController?.setNavigationBarHidden(true, animated: false) updateUserInfo() super.viewWillAppear(animated) + if navigationController?.viewControllers.count ?? 0 > 0 { + if let root = navigationController?.viewControllers[0] as? UIViewController { + if root.isKind(of: MeViewController.self) { + navigationController?.interactivePopGestureRecognizer?.delegate = self + } + } + } } func setupSubviews() { @@ -233,4 +239,14 @@ extension MeViewController: UITableViewDelegate, UITableViewDataSource { navigationController?.pushViewController(ctrl, animated: true) } else if indexPath.row == 2 {} } + + public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if let navigationController = navigationController, + navigationController.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)), + gestureRecognizer == navigationController.interactivePopGestureRecognizer, + navigationController.visibleViewController == navigationController.viewControllers.first { + return false + } + return true + } } diff --git a/app/Mine/Controller/NELoginViewController.swift b/app/Mine/Controller/NELoginViewController.swift index 9dd4ae8a..4b298a55 100644 --- a/app/Mine/Controller/NELoginViewController.swift +++ b/app/Mine/Controller/NELoginViewController.swift @@ -3,11 +3,11 @@ // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. -import UIKit +import NEChatUIKit import NECommonKit -import YXLogin import NECoreIMKit -import NEChatUIKit +import UIKit +import YXLogin public class NELoginViewController: UIViewController { // 登录成功 @@ -156,6 +156,7 @@ public class NELoginViewController: UIViewController { label.text = NSLocalizedString("appName", comment: "") label.font = UIFont.systemFont(ofSize: 24.0) label.textColor = UIColor(hexString: "333333") + label.accessibilityIdentifier = "id.appYunxin" return label }() @@ -168,6 +169,7 @@ public class NELoginViewController: UIViewController { btn.titleLabel?.font = UIFont.systemFont(ofSize: 15.0) btn.setTitle(NSLocalizedString("register_login", comment: ""), for: .normal) btn.addTarget(self, action: #selector(loginBtnClick), for: .touchUpInside) + btn.accessibilityIdentifier = "id.loginButton" return btn }() @@ -178,7 +180,7 @@ public class NELoginViewController: UIViewController { btn.titleLabel?.font = UIFont.systemFont(ofSize: 12.0) btn.setTitle(NSLocalizedString("email_login", comment: ""), for: .normal) btn.addTarget(self, action: #selector(emailLoginBtnClick), for: .touchUpInside) - + btn.accessibilityIdentifier = "id.emailLogin" return btn }() @@ -196,7 +198,7 @@ public class NELoginViewController: UIViewController { btn.titleLabel?.font = UIFont.systemFont(ofSize: 12.0) btn.setTitle(NSLocalizedString("node_select", comment: ""), for: .normal) btn.addTarget(self, action: #selector(nodeBtnClick), for: .touchUpInside) - + btn.accessibilityIdentifier = "id.serverConfig" return btn }() } diff --git a/app/Mine/Controller/PersonInfoViewController.swift b/app/Mine/Controller/PersonInfoViewController.swift index 8e79511a..62cb08d9 100644 --- a/app/Mine/Controller/PersonInfoViewController.swift +++ b/app/Mine/Controller/PersonInfoViewController.swift @@ -110,7 +110,7 @@ class PersonInfoViewController: NEBaseViewController, NIMUserManagerDelegate, if let t = time { weakSelf?.viewModel.updateBirthday(birthDay: t) { error in if error != nil { - if error?.code == 408 { + if error?.code == noNetworkCode { weakSelf?.showToast(commonLocalizable("network_error")) } else { weakSelf?.showToast(NSLocalizedString("setting_birthday_failure", comment: "")) @@ -240,7 +240,7 @@ class PersonInfoViewController: NEBaseViewController, NIMUserManagerDelegate, sex = value == 0 ? .male : .female weakSelf?.viewModel.updateSex(sex: sex) { error in if error != nil { - if error?.code == 408 { + if error?.code == noNetworkCode { weakSelf?.showToast(commonLocalizable("network_error")) } else { weakSelf?.showToast(NSLocalizedString("change_gender_failure", comment: "")) diff --git a/app/Mine/ViewModel/PersonInfoViewModel.swift b/app/Mine/ViewModel/PersonInfoViewModel.swift index c213c7ab..8a7e54c9 100644 --- a/app/Mine/ViewModel/PersonInfoViewModel.swift +++ b/app/Mine/ViewModel/PersonInfoViewModel.swift @@ -24,7 +24,7 @@ public class PersonInfoViewModel: NSObject { public let friendProvider = FriendProvider.shared public let userProvider = UserInfoProvider.shared - private var userInfo: User? + private var userInfo: NEKitUser? weak var delegate: PersonInfoViewModelDelegate? func getData() {