SecondTabViewController.swift 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. //
  2. // SecondTabViewController.swift
  3. // AppBuilder
  4. //
  5. // Created by Kevin Maulana on 30/03/22.
  6. //
  7. import UIKit
  8. import FMDB
  9. import NexilisLite
  10. import Speech
  11. class SecondTabViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate {
  12. var isChooser: ((String, String) -> ())?
  13. var isAdmin: Bool = false
  14. var chats: [Chat] = []
  15. var groups: [Group] = []
  16. var cancelSearchButton = UIBarButtonItem()
  17. var menuItem = UIBarButtonItem()
  18. var menuBroadcast = UIBarButtonItem()
  19. var voiceItem = UIBarButtonItem()
  20. var childrenMenu = [UIAction]()
  21. var groupMap: [String:Int] = [:]
  22. var isAllowSpeech = false
  23. var alertController = LibAlertController()
  24. var noData = false
  25. let textViewSearch = UITextField()
  26. let imageVoiceSb = UIImageView()
  27. let imageNewChatSb = UIImageView()
  28. override var preferredStatusBarStyle: UIStatusBarStyle {
  29. return self.traitCollection.userInterfaceStyle == .dark ? .default : .lightContent // Change this to .default for black text color
  30. }
  31. lazy var searchController: UISearchController = {
  32. var searchController = UISearchController(searchResultsController: nil)
  33. searchController.delegate = self
  34. searchController.searchResultsUpdater = self
  35. searchController.searchBar.autocapitalizationType = .none
  36. searchController.searchBar.delegate = self
  37. // searchController.searchBar.setMagnifyingGlassColorTo(color: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  38. // searchController.searchBar.updateHeight(height: 30, radius: 15, borderColor: UIColor.clear.cgColor)
  39. searchController.searchBar.setImage(UIImage(), for: .search, state: .normal)
  40. searchController.searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
  41. searchController.searchBar.setCustomBackgroundImage(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
  42. searchController.obscuresBackgroundDuringPresentation = false
  43. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search...".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])
  44. return searchController
  45. }()
  46. lazy var segment: UISegmentedControl = {
  47. var segment = UISegmentedControl(items: ["Chats".localized(), "Forums".localized()])
  48. segment.sizeToFit()
  49. segment.selectedSegmentIndex = 0
  50. segment.addTarget(self, action: #selector(segmentChanged(sender:)), for: .valueChanged)
  51. segment.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12.0)], for: .normal)
  52. return segment
  53. }()
  54. var fillteredData: [Any] = []
  55. var isSearchBarEmpty: Bool {
  56. return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  57. }
  58. var isFiltering: Bool {
  59. return !textViewSearch.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  60. // return !isSearchBarEmpty
  61. }
  62. @IBOutlet var tableView: UITableView!
  63. var speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "id"))
  64. var recognitionRequest : SFSpeechAudioBufferRecognitionRequest?
  65. var recognitionTask : SFSpeechRecognitionTask?
  66. let audioEngine = AVAudioEngine()
  67. func filterContentForSearchText(_ searchText: String) {
  68. if !searchText.isEmpty {
  69. switch segment.selectedSegmentIndex {
  70. case 1:
  71. fillteredData = self.groups.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  72. default:
  73. fillteredData = self.chats.filter { $0.name.lowercased().contains(searchText.lowercased()) || $0.messageText.lowercased().contains(searchText.lowercased()) }
  74. }
  75. }
  76. tableView.reloadData()
  77. }
  78. override func viewDidLoad() {
  79. super.viewDidLoad()
  80. let me = User.getMyPin()!
  81. Database.shared.database?.inTransaction({ fmdb, rollback in
  82. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select FIRST_NAME, LAST_NAME, IMAGE_ID, USER_TYPE from BUDDY where F_PIN = '\(me)'"), cursor.next() {
  83. isAdmin = cursor.string(forColumnIndex: 3) == "23" || cursor.string(forColumnIndex: 3) == "24"
  84. cursor.close()
  85. }
  86. })
  87. // var childrenMenu : [UIAction] = []
  88. //
  89. // if(isAdmin){
  90. // childrenMenu.append(UIAction(title: "Broadcast Message".localized(), image: UIImage(systemName: "envelope.open"), handler: {[weak self](_) in
  91. // let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  92. // self?.navigationController?.present(controller, animated: true, completion: nil)
  93. // }))
  94. // }
  95. // let startConvIcon = resizeImage(image: self.traitCollection.userInterfaceStyle == .dark ? UIImage(systemName: "square.and.pencil")!.withTintColor(.white) : UIImage(systemName: "square.and.pencil")!, targetSize: CGSize(width: 25, height: 25))
  96. // let viewStartConv = UIButton(frame: CGRect(x: 0, y: 0, width: startConvIcon.size.width, height: startConvIcon.size.height))
  97. // viewStartConv.setImage(startConvIcon, for: .normal)
  98. // viewStartConv.addTarget(self, action: #selector(startConversation), for: .touchUpInside)
  99. // let brodcastIcon = resizeImage(image: self.traitCollection.userInterfaceStyle == .dark ? UIImage(named: "ic_broadcast")!.withTintColor(.white) : UIImage(named: "ic_broadcast")!, targetSize: CGSize(width: 25, height: 25))
  100. // let viewbrodcast = UIButton(frame: CGRect(x: 0, y: 0, width: brodcastIcon.size.width, height: brodcastIcon.size.height))
  101. // viewbrodcast.setImage(brodcastIcon, for: .normal)
  102. // viewbrodcast.addTarget(self, action: #selector(openBroadcast), for: .touchUpInside)
  103. //
  104. // menuItem = UIBarButtonItem(customView: viewStartConv)
  105. // menuBroadcast = UIBarButtonItem(customView: viewbrodcast)
  106. // menuItem = UIBarButtonItem(image: UIImage(systemName: "square.and.pencil"), style: .plain, target: self, action: #selector(startConversation))
  107. // menuBroadcast = UIBarButtonItem(image: UIImage(systemName: "info.bubble"), style: .plain, target: self, action: #selector(openBroadcast))
  108. // voiceItem = UIBarButtonItem(image: UIImage(systemName: "mic.fill"), style: .plain, target: self, action: #selector(recordAudio))
  109. definesPresentationContext = true
  110. NotificationCenter.default.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
  116. tableView.tableHeaderView = segment
  117. tableView.tableFooterView = UIView()
  118. if PrefsUtil.getCpaasMode() == PrefsUtil.CPAAS_MODE_DOCKED {
  119. tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
  120. }
  121. pullBuddy()
  122. navigationController?.setNavigationBarHidden(true, animated: false)
  123. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(collapseDocked))
  124. tapGesture.cancelsTouchesInView = false
  125. tapGesture.delegate = self
  126. self.view.addGestureRecognizer(tapGesture)
  127. }
  128. @objc func collapseDocked() {
  129. if ViewController.isExpandButton {
  130. ViewController.expandButton()
  131. }
  132. if textViewSearch.isFirstResponder {
  133. textViewSearch.resignFirstResponder()
  134. }
  135. }
  136. @objc func openBroadcast() {
  137. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  138. controller.modalPresentationStyle = .fullScreen
  139. self.navigationController?.present(controller, animated: true, completion: nil)
  140. }
  141. @objc func startConversation(){
  142. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  143. navigationController.view.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  144. Utils.addBackground(view: navigationController.view)
  145. navigationController.modalPresentationStyle = .fullScreen
  146. navigationController.navigationBar.tintColor = .white
  147. navigationController.navigationBar.barTintColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  148. navigationController.navigationBar.isTranslucent = false
  149. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  150. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  151. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  152. navigationController.navigationBar.titleTextAttributes = textAttributes
  153. navigationController.navigationBar.overrideUserInterfaceStyle = .dark
  154. navigationController.navigationBar.barStyle = .black
  155. self.navigationController?.present(navigationController, animated: true, completion: nil)
  156. }
  157. @objc func recordAudio(){
  158. if !isAllowSpeech {
  159. setupSpeech()
  160. } else {
  161. runVoice()
  162. }
  163. }
  164. func setupSpeech() {
  165. self.speechRecognizer?.delegate = self
  166. SFSpeechRecognizer.requestAuthorization { (authStatus) in
  167. var isButtonEnabled = false
  168. switch authStatus {
  169. case .authorized:
  170. isButtonEnabled = true
  171. case .denied:
  172. isButtonEnabled = false
  173. //print("User denied access to speech recognition")
  174. case .restricted:
  175. isButtonEnabled = false
  176. //print("Speech recognition restricted on this device")
  177. case .notDetermined:
  178. isButtonEnabled = false
  179. //print("Speech recognition not yet authorized")
  180. @unknown default:
  181. isButtonEnabled = false
  182. }
  183. OperationQueue.main.addOperation() {
  184. self.isAllowSpeech = isButtonEnabled
  185. if isButtonEnabled {
  186. SecureUserDefaults.shared.set(isButtonEnabled, forKey: "allowSpeech")
  187. self.runVoice()
  188. }
  189. }
  190. }
  191. }
  192. func startRecording() {
  193. // Clear all previous session data and cancel task
  194. if recognitionTask != nil {
  195. recognitionTask?.cancel()
  196. recognitionTask = nil
  197. }
  198. // Create instance of audio session to record voice
  199. let audioSession = AVAudioSession.sharedInstance()
  200. do {
  201. try audioSession.setCategory(AVAudioSession.Category.record, mode: AVAudioSession.Mode.measurement, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
  202. try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
  203. } catch {
  204. //print("audioSession properties weren't set because of an error.")
  205. }
  206. self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
  207. let inputNode = audioEngine.inputNode
  208. guard let recognitionRequest = recognitionRequest else {
  209. fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
  210. }
  211. recognitionRequest.shouldReportPartialResults = true
  212. self.recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
  213. var isFinal = false
  214. if result != nil {
  215. self.alertController.dismiss(animated: true)
  216. self.audioEngine.stop()
  217. self.recognitionRequest?.endAudio()
  218. isFinal = (result?.isFinal)!
  219. }
  220. if error != nil || isFinal {
  221. if error == nil {
  222. let textRes = result!.bestTranscription.formattedString
  223. self.textViewSearch.text = textRes
  224. self.filterContentForSearchText(textRes)
  225. // self.searchController.searchBar.searchTextField.text = result!.bestTranscription.formattedString
  226. // self.updateSearchResults(for: self.searchController)
  227. } else {
  228. self.audioEngine.stop()
  229. self.recognitionRequest?.endAudio()
  230. }
  231. self.voiceItem.image = UIImage(systemName: "mic.fill")
  232. inputNode.removeTap(onBus: 0)
  233. self.recognitionRequest = nil
  234. self.recognitionTask = nil
  235. }
  236. })
  237. let recordingFormat = inputNode.outputFormat(forBus: 0)
  238. inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
  239. self.recognitionRequest?.append(buffer)
  240. }
  241. self.audioEngine.prepare()
  242. do {
  243. try self.audioEngine.start()
  244. } catch {
  245. //print("audioEngine couldn't start because of an error.")
  246. }
  247. }
  248. func runVoice() {
  249. if !audioEngine.isRunning {
  250. self.voiceItem.image = UIImage(systemName: "mic")
  251. alertController = LibAlertController(title: "Start Recording".localized(), message: "Say something, I'm listening!".localized(), preferredStyle: .alert)
  252. self.present(alertController, animated: true)
  253. self.startRecording()
  254. }
  255. }
  256. override func viewDidAppear(_ animated: Bool) {
  257. self.navigationController?.navigationBar.topItem?.title = "Chats".localized() + " & " + "Forums".localized()
  258. self.navigationController?.navigationBar.setNeedsLayout()
  259. DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
  260. var viewController = UIApplication.shared.windows.first!.rootViewController
  261. if !(viewController is ViewController) {
  262. viewController = self.parent
  263. }
  264. if ViewController.middleButton.isHidden {
  265. ViewController.isExpandButton = false
  266. if let viewController = viewController as? ViewController {
  267. if viewController.tabBar.isHidden {
  268. viewController.tabBar.isHidden = false
  269. ViewController.alwaysHideButton = false
  270. ViewController.middleButton.isHidden = false
  271. }
  272. }
  273. } else if PrefsUtil.getCpaasMode() != PrefsUtil.CPAAS_MODE_DOCKED {
  274. DispatchQueue.main.async {
  275. if let viewController = viewController as? ViewController {
  276. if viewController.tabBar.isHidden {
  277. ViewController.alwaysHideButton = false
  278. viewController.tabBar.isHidden = false
  279. }
  280. }
  281. }
  282. }
  283. })
  284. getData()
  285. DispatchQueue.global().async {
  286. self.getOpenGroups(listGroups: self.groups, completion: { g in
  287. DispatchQueue.main.async {
  288. for og in g {
  289. if self.groups.first(where: { $0.id == og.id }) == nil {
  290. self.groups.append(og)
  291. }
  292. }
  293. self.groups.sort { (a, b) -> Bool in
  294. if Int(a.official) == 1 {
  295. return true
  296. } else if Int(b.official) == 1 {
  297. return false
  298. } else {
  299. return Int(a.official) ?? 0 > Int(b.official) ?? 0
  300. }
  301. }
  302. DispatchQueue.main.async {
  303. self.tableView.reloadData()
  304. }
  305. }
  306. })
  307. }
  308. }
  309. override func viewWillAppear(_ animated: Bool) {
  310. // tabBarController?.navigationItem.leftBarButtonItem = cancelSearchButton
  311. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  312. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  313. let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16)]
  314. let navBarAppearance = UINavigationBarAppearance()
  315. navBarAppearance.configureWithTransparentBackground()
  316. navBarAppearance.titleTextAttributes = attributes
  317. navigationController?.navigationBar.standardAppearance = navBarAppearance
  318. navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
  319. navigationController?.navigationBar.backgroundColor = .clear
  320. navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
  321. navigationController?.navigationBar.shadowImage = UIImage()
  322. navigationController?.navigationBar.isTranslucent = true
  323. navigationController?.setNavigationBarHidden(false, animated: false)
  324. navigationController?.navigationBar.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  325. navigationController?.navigationBar.overrideUserInterfaceStyle = self.traitCollection.userInterfaceStyle == .dark ? .dark : .light
  326. navigationController?.navigationBar.barStyle = .default
  327. // tabBarController?.navigationItem.leftBarButtonItem = voiceItem
  328. // let myData = User.getData(pin: User.getMyPin())
  329. // if User.isOfficial(official_account: myData?.official ?? "") || User.isOfficialRegular(official_account: myData?.official ?? "") || User.isInternal(userType: myData?.userType ?? "") {
  330. // let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  331. // fixedSpace.width = 15.0
  332. // tabBarController?.navigationItem.rightBarButtonItems = [menuBroadcast, fixedSpace, menuItem]
  333. // } else {
  334. // tabBarController?.navigationItem.rightBarButtonItem = menuItem
  335. // }
  336. // tabBarController?.navigationItem.searchController = searchController
  337. let customView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))
  338. customView.isUserInteractionEnabled = true
  339. let imageViewSearch = UIImageView(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
  340. imageViewSearch.contentMode = .scaleToFill
  341. customView.addSubview(imageViewSearch)
  342. imageViewSearch.anchor(top: customView.topAnchor, left: customView.leftAnchor, bottom: customView.bottomAnchor, right: customView.rightAnchor, height: 35)
  343. imageViewSearch.isUserInteractionEnabled = true
  344. let imageSetting = UIImageView(image: UIImage(named: "nx_setting_sb", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
  345. imageSetting.contentMode = .scaleToFill
  346. imageViewSearch.addSubview(imageSetting)
  347. imageSetting.anchor(right: customView.rightAnchor, paddingRight: 18, centerY: customView.centerYAnchor, width: 20, height: 20)
  348. imageSetting.isUserInteractionEnabled = true
  349. imageSetting.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(settingTapped)))
  350. imageVoiceSb.image = UIImage(named: "nx_mic", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!
  351. imageVoiceSb.contentMode = .scaleAspectFit
  352. imageViewSearch.addSubview(imageVoiceSb)
  353. imageVoiceSb.anchor(top: imageViewSearch.topAnchor, right: imageSetting.leftAnchor, paddingTop: 5, paddingRight: 15, width: 20, height: 20)
  354. imageVoiceSb.isUserInteractionEnabled = true
  355. imageVoiceSb.isHidden = true
  356. imageVoiceSb.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(recordAudio)))
  357. imageNewChatSb.image = UIImage(systemName: "square.and.pencil")!
  358. imageNewChatSb.tintColor = .nxColor
  359. imageNewChatSb.contentMode = .scaleAspectFit
  360. imageViewSearch.addSubview(imageNewChatSb)
  361. imageNewChatSb.anchor(top: imageViewSearch.topAnchor, right: imageVoiceSb.leftAnchor, paddingTop: 5, paddingRight: 15, width: 20, height: 20)
  362. imageNewChatSb.isUserInteractionEnabled = true
  363. imageNewChatSb.isHidden = true
  364. imageNewChatSb.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startConversation)))
  365. textViewSearch.placeholder = "Search...".localized()
  366. textViewSearch.isUserInteractionEnabled = true
  367. imageViewSearch.addSubview(textViewSearch)
  368. textViewSearch.font = .systemFont(ofSize: 11)
  369. textViewSearch.anchor(top: imageViewSearch.topAnchor, left: imageViewSearch.leftAnchor, bottom: imageViewSearch.bottomAnchor, right: imageViewSearch.rightAnchor, paddingTop: 5, paddingLeft: 20, paddingBottom: 5, paddingRight: 120)
  370. textViewSearch.delegate = self
  371. tabBarController?.navigationItem.titleView = customView
  372. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  373. speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: lang ?? "en"))
  374. backgroundImage.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  375. DispatchQueue.global().async {
  376. DispatchQueue.main.async {
  377. let listBg = PrefsUtil.getBackgroundLight().isEmpty && PrefsUtil.getBackgroundDark().isEmpty ? PrefsUtil.getBackground() :
  378. self.traitCollection.userInterfaceStyle == .dark ? PrefsUtil.getBackgroundDark() : PrefsUtil.getBackgroundLight()
  379. if listBg.isEmpty {
  380. return
  381. }
  382. var bgChoosen = ""
  383. let arrayBg = listBg.split(separator: ",")
  384. bgChoosen = String(arrayBg[Int.random(in: 0..<arrayBg.count)])
  385. let urlString = PrefsUtil.getURLBase() + "get_file_from_path?img=" + bgChoosen
  386. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  387. DispatchQueue.main.async() { [self] in
  388. backgroundImage.image = cachedImage
  389. }
  390. return
  391. }
  392. Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
  393. guard let data = data, error == nil else { return }
  394. // always update the UI from the main thread
  395. DispatchQueue.main.async() { [self] in
  396. if UIImage(data: data) != nil {
  397. backgroundImage.image = UIImage(data: data)!
  398. ImageCache.shared.save(image: UIImage(data: data)!, forKey: urlString)
  399. }
  400. }
  401. }
  402. }
  403. }
  404. if segment.numberOfSegments == 2 {
  405. segment.setTitle("Chats".localized(), forSegmentAt: 0)
  406. segment.setTitle("Forums".localized(), forSegmentAt: 1)
  407. }
  408. if segment.selectedSegmentIndex == 0 {
  409. Utils.inTabChats = true
  410. // searchController.searchBar.placeholder = "Search chats & messages".localized()
  411. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search chats & messages".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  412. } else {
  413. // searchController.searchBar.placeholder = "Search groups name".localized()
  414. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search groups name".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  415. }
  416. // removeAllData()
  417. // getData()
  418. }
  419. // func removeAllData() {
  420. // groups.removeAll()
  421. // groupMap.removeAll()
  422. // chats.removeAll()
  423. // tableView.reloadData()
  424. // }
  425. func textFieldDidChangeSelection(_ textField: UITextField) {
  426. if textField == textViewSearch {
  427. let textSerch = textField.text ?? ""
  428. filterContentForSearchText(textSerch)
  429. }
  430. }
  431. override func viewWillDisappear(_ animated: Bool) {
  432. tabBarController?.navigationItem.leftBarButtonItem = nil
  433. tabBarController?.navigationItem.searchController = nil
  434. tabBarController?.navigationItem.rightBarButtonItem = nil
  435. tabBarController?.navigationItem.rightBarButtonItems = nil
  436. tabBarController?.navigationItem.titleView = nil
  437. Utils.inTabChats = false
  438. if ViewController.isExpandButton {
  439. ViewController.expandButton()
  440. }
  441. }
  442. @objc func settingTapped() {
  443. imageVoiceSb.isHidden = !imageVoiceSb.isHidden
  444. imageNewChatSb.isHidden = !imageNewChatSb.isHidden
  445. }
  446. @objc func onReloadTab(notification: NSNotification) {
  447. DispatchQueue.main.async {
  448. self.getData()
  449. }
  450. }
  451. @objc func onReload(notification: NSNotification) {
  452. let data:[AnyHashable : Any] = notification.userInfo!
  453. if data["member"] as? String == User.getMyPin()! {
  454. DispatchQueue.main.async {
  455. self.getData()
  456. }
  457. } else if data["state"] as? Int == 99 {
  458. DispatchQueue.main.async {
  459. self.getData()
  460. }
  461. }
  462. }
  463. @objc func onReceiveMessage(notification: NSNotification) {
  464. DispatchQueue.main.async { [self] in
  465. let data:[AnyHashable : Any] = notification.userInfo!
  466. if let dataMessage = data["message"] as? TMessage {
  467. let chatData = dataMessage.mBodies
  468. if chatData[CoreMessage_TMessageKey.IS_CALL_CENTER] == nil || chatData[CoreMessage_TMessageKey.IS_CALL_CENTER] == "0" {
  469. var indexChat: Int?
  470. if chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "3" && chatData[CoreMessage_TMessageKey.F_PIN] != User.getMyPin() {
  471. indexChat = chats.firstIndex(where: { $0.fpin == chatData[CoreMessage_TMessageKey.F_PIN] })
  472. } else if chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "4" && chatData[CoreMessage_TMessageKey.F_PIN] != User.getMyPin() {
  473. indexChat = chats.firstIndex(where: { (chatData[CoreMessage_TMessageKey.CHAT_ID] ?? "").isEmpty ? $0.pin == chatData[CoreMessage_TMessageKey.L_PIN] : $0.pin == chatData[CoreMessage_TMessageKey.CHAT_ID] })
  474. }
  475. let newChat = Chat.getData(messageId: chatData[CoreMessage_TMessageKey.MESSAGE_ID] ?? "")
  476. if newChat.count > 0 {
  477. if indexChat != nil {
  478. chats.remove(at: indexChat!)
  479. chats.insert(newChat[0], at: 0)
  480. let indexPathToMove = IndexPath(row: indexChat!, section: 0)
  481. let indexPathNewPosition = IndexPath(row: 0, section: 0)
  482. tableView.performBatchUpdates({
  483. tableView.moveRow(at: indexPathToMove, to: indexPathNewPosition)
  484. }, completion: nil)
  485. tableView.beginUpdates()
  486. tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
  487. tableView.endUpdates()
  488. } else {
  489. chats.insert(newChat[0], at: 0)
  490. tableView.reloadData()
  491. }
  492. }
  493. }
  494. }
  495. }
  496. }
  497. @objc func onStatusChat(notification: NSNotification) {
  498. DispatchQueue.main.async { [self] in
  499. let data:[AnyHashable : Any] = notification.userInfo!
  500. if let dataMessage = data["message"] as? TMessage {
  501. var idMessage = dataMessage.getBody(key: CoreMessage_TMessageKey.MESSAGE_ID)
  502. if idMessage.contains(",") {
  503. let listString = dataMessage.getBody(key: CoreMessage_TMessageKey.MESSAGE_ID).components(separatedBy: ",")
  504. idMessage = listString[listString.count - 1]
  505. }
  506. let indexChat = chats.firstIndex(where: { $0.messageId == idMessage })
  507. if indexChat != nil {
  508. if dataMessage.getBody(key: CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG) == "1" {
  509. chats[indexChat!].lock = "1"
  510. }
  511. tableView.beginUpdates()
  512. tableView.reloadRows(at: [IndexPath(row: indexChat!, section: 0)], with: .none)
  513. tableView.endUpdates()
  514. }
  515. }
  516. }
  517. }
  518. @objc func segmentChanged(sender: Any) {
  519. switch segment.selectedSegmentIndex {
  520. case 1:
  521. Utils.inTabChats = false
  522. // searchController.searchBar.placeholder = "Search groups name".localized()
  523. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search groups name".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  524. default:
  525. Utils.inTabChats = true
  526. // searchController.searchBar.placeholder = "Search chats & messages".localized()
  527. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search chats & messages".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  528. }
  529. // filterContentForSearchText(searchController.searchBar.text!)
  530. filterContentForSearchText(self.textViewSearch.text ?? "")
  531. }
  532. // MARK: - Data source
  533. func getData() {
  534. getChats {
  535. self.getGroups { g1 in
  536. self.groupMap.removeAll()
  537. self.groups = g1
  538. self.groups.sort { (a, b) -> Bool in
  539. if Int(a.official) == 1 {
  540. return true
  541. } else if Int(b.official) == 1 {
  542. return false
  543. } else {
  544. return Int(a.official) ?? 0 > Int(b.official) ?? 0
  545. }
  546. }
  547. DispatchQueue.main.async {
  548. self.tableView.reloadData()
  549. }
  550. }
  551. }
  552. }
  553. func getChats(completion: @escaping ()->()) {
  554. DispatchQueue.global().async {
  555. self.chats = Chat.getData()
  556. completion()
  557. }
  558. }
  559. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  560. var data: [Group] = []
  561. var query = "select g.group_id, g.f_name, g.image_id, g.quote, g.created_by, g.created_date, g.parent, g.group_type, g.is_open, g.official, g.is_education, g.level, g.chat_modifier from GROUPZ g where "
  562. if id.isEmpty {
  563. query += "g.parent = '\(parent)'"
  564. } else {
  565. query += "g.group_id = '\(id)'"
  566. }
  567. query += "order by 12 asc, 13 asc, 2 asc"
  568. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  569. while cursor.next() {
  570. let group = Group(
  571. id: cursor.string(forColumnIndex: 0) ?? "",
  572. name: cursor.string(forColumnIndex: 1) ?? "",
  573. profile: cursor.string(forColumnIndex: 2) ?? "",
  574. quote: cursor.string(forColumnIndex: 3) ?? "",
  575. by: cursor.string(forColumnIndex: 4) ?? "",
  576. date: cursor.string(forColumnIndex: 5) ?? "",
  577. parent: cursor.string(forColumnIndex: 6) ?? "",
  578. chatId: "",
  579. groupType: cursor.string(forColumnIndex: 7) ?? "",
  580. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  581. official: cursor.string(forColumnIndex: 9) ?? "",
  582. isEducation: cursor.string(forColumnIndex: 10) ?? "",
  583. level: cursor.string(forColumnIndex: 11) ?? "")
  584. if group.chatId.isEmpty {
  585. let lounge = Group(id: group.id, name: "Lounge".localized(), profile: "", quote: group.quote, by: group.by, date: group.date, parent: group.id, chatId: group.chatId, groupType: group.groupType, isOpen: group.isOpen, official: group.official, isEducation: group.isEducation, isLounge: true, level: group.level != "-1" ? group.level : "2")
  586. group.childs.append(lounge)
  587. }
  588. if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  589. while topicCursor.next() {
  590. let topic = Group(id: group.id,
  591. name: topicCursor.string(forColumnIndex: 1) ?? "",
  592. profile: topicCursor.string(forColumnIndex: 2) ?? "",
  593. quote: group.quote,
  594. by: group.by,
  595. date: group.date,
  596. parent: group.id,
  597. chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  598. groupType: group.groupType,
  599. isOpen: group.isOpen,
  600. official: group.official,
  601. isEducation: group.isEducation,
  602. level: group.level != "-1" ? group.level : "2")
  603. group.childs.append(topic)
  604. }
  605. topicCursor.close()
  606. }
  607. if !group.id.isEmpty {
  608. // if group.official == "1" {
  609. // let idMe = User.getMyPin() as String?
  610. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  611. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  612. // cursorUser.close()
  613. // }
  614. // } else if group.official != "1"{
  615. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  616. // }
  617. group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  618. // group.childs = group.childs.sorted(by: { $0.name < $1.name })
  619. // let dataLounge = group.childs.filter({$0.name == "Lounge".localized()})
  620. // group.childs = group.childs.filter({ $0.name != "Lounge".localized() })
  621. // group.childs.insert(contentsOf: dataLounge, at: 0)
  622. }
  623. data.append(group)
  624. }
  625. cursor.close()
  626. }
  627. return data
  628. }
  629. private func getOpenGroups(listGroups: [Group], completion: @escaping ([Group]) -> ()) {
  630. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getOpenGroups(p_account: "1,2,3,6,5,7", offset: "0", search: "")) {
  631. var dataGroups: [Group] = []
  632. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  633. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  634. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [[String: Any?]] {
  635. for dataJson in json {
  636. let group = Group(
  637. id: dataJson[CoreMessage_TMessageKey.GROUP_ID] as? String ?? "",
  638. name: dataJson[CoreMessage_TMessageKey.GROUP_NAME] as? String ?? "",
  639. profile: dataJson[CoreMessage_TMessageKey.THUMB_ID] as? String ?? "",
  640. quote: dataJson[CoreMessage_TMessageKey.QUOTE] as? String ?? "",
  641. by: dataJson[CoreMessage_TMessageKey.BLOCK] as? String ?? "",
  642. date: "",
  643. parent: "",
  644. chatId: "",
  645. groupType: "NOTJOINED",
  646. isOpen: dataJson[CoreMessage_TMessageKey.IS_OPEN] as? String ?? "",
  647. official: "0",
  648. isEducation: "")
  649. dataGroups.append(group)
  650. }
  651. }
  652. }
  653. completion(dataGroups)
  654. }
  655. }
  656. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  657. DispatchQueue.global().async {
  658. Database.shared.database?.inTransaction({ fmdb, rollback in
  659. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  660. })
  661. }
  662. }
  663. private func pullBuddy() {
  664. if let me = User.getMyPin() {
  665. DispatchQueue.global().async {
  666. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  667. }
  668. }
  669. }
  670. private func joinOpenGroup(groupId: String, flagMember: String = "0", completion: @escaping (Bool) -> ()) {
  671. DispatchQueue.global().async {
  672. var result: Bool = false
  673. let idMe = User.getMyPin() as String?
  674. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddGroupMember(p_group_id: groupId, p_member_pin: idMe!, p_position: "0")), response.isOk() {
  675. result = true
  676. }
  677. completion(result)
  678. }
  679. }
  680. @IBOutlet weak var backgroundImage: UIImageView!
  681. /*
  682. // MARK: - Navigation
  683. // In a storyboard-based application, you will often want to do a little preparation before navigation
  684. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  685. // Get the new view controller using segue.destination.
  686. // Pass the selected object to the new view controller.
  687. }
  688. */
  689. }
  690. // MARK: - Table view data source
  691. extension SecondTabViewController: UITableViewDelegate, UITableViewDataSource {
  692. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  693. if noData {
  694. return
  695. }
  696. tableView.deselectRow(at: indexPath, animated: true)
  697. switch segment.selectedSegmentIndex {
  698. case 0:
  699. let data: Chat
  700. if isFiltering {
  701. data = fillteredData[indexPath.row] as! Chat
  702. } else {
  703. data = chats[indexPath.row]
  704. }
  705. if let chooser = isChooser {
  706. if data.pin == "-999"{
  707. return
  708. }
  709. chooser(data.messageScope, data.pin)
  710. dismiss(animated: true, completion: nil)
  711. return
  712. }
  713. if data.messageScope == "3" {
  714. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  715. editorPersonalVC.hidesBottomBarWhenPushed = true
  716. editorPersonalVC.unique_l_pin = data.pin
  717. navigationController?.show(editorPersonalVC, sender: nil)
  718. } else {
  719. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  720. editorGroupVC.hidesBottomBarWhenPushed = true
  721. editorGroupVC.unique_l_pin = data.pin
  722. navigationController?.show(editorGroupVC, sender: nil)
  723. }
  724. case 1:
  725. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  726. default:
  727. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  728. }
  729. }
  730. func expandCollapseGroup(tableView: UITableView, indexPath: IndexPath) {
  731. let group: Group
  732. if isFiltering {
  733. if indexPath.row == 0 {
  734. group = fillteredData[indexPath.section] as! Group
  735. } else {
  736. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  737. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  738. } else {
  739. return
  740. }
  741. }
  742. } else {
  743. if indexPath.row == 0 {
  744. group = groups[indexPath.section]
  745. } else {
  746. group = groups[indexPath.section].childs[indexPath.row - 1]
  747. }
  748. }
  749. if (checkOverrideAction(groupHolder: group)) {
  750. return;
  751. }
  752. group.isSelected = !group.isSelected
  753. if !group.isSelected{
  754. var sects = 0
  755. var sect = indexPath.section
  756. var id = group.id
  757. if let _ = groupMap[id] {
  758. var loooop = true
  759. repeat {
  760. let c = sect + 1
  761. if isFiltering {
  762. if let o = self.fillteredData[c] as? Group {
  763. if o.parent == id {
  764. sects = sects + 1
  765. sect = c
  766. id = o.id
  767. (self.fillteredData[c] as! Group).isSelected = false
  768. self.groupMap.removeValue(forKey: (self.fillteredData[c] as! Group).id)
  769. }
  770. else {
  771. loooop = false
  772. }
  773. }
  774. }
  775. else {
  776. if c < self.groups.count && self.groups[c].parent == id {
  777. sects = sects + 1
  778. sect = c
  779. id = self.groups[c].id
  780. self.groups[c].isSelected = false
  781. self.groupMap.removeValue(forKey: self.groups[c].id)
  782. }
  783. else {
  784. loooop = false
  785. }
  786. }
  787. } while(loooop)
  788. }
  789. for i in stride(from: sects, to: 0, by: -1){
  790. if isFiltering {
  791. self.fillteredData.remove(at: indexPath.section + i)
  792. }
  793. else {
  794. self.groups.remove(at: indexPath.section + i)
  795. }
  796. }
  797. groupMap.removeValue(forKey: group.id)
  798. }
  799. if group.groupType == "NOTJOINED" {
  800. let alert = LibAlertController(title: "Do you want to join this group?".localized(), message: "Groups : \(group.name)\nMembers: \(group.by)".localized(), preferredStyle: .alert)
  801. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  802. alert.addAction(UIAlertAction(title: "Join".localized(), style: .default, handler: {(_) in
  803. self.joinOpenGroup(groupId: group.id, completion: { result in
  804. if result {
  805. DispatchQueue.main.async {
  806. self.groupMap.removeAll()
  807. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  808. editorGroupVC.hidesBottomBarWhenPushed = true
  809. editorGroupVC.unique_l_pin = group.id
  810. self.navigationController?.show(editorGroupVC, sender: nil)
  811. }
  812. }
  813. })
  814. }))
  815. self.present(alert, animated: true, completion: nil)
  816. return
  817. }
  818. if group.childs.count == 0 {
  819. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  820. let idMe = User.getMyPin() as String?
  821. if let cursorMember = Database.shared.getRecords(fmdb: fmdb, query: "select f_pin from GROUPZ_MEMBER where group_id = '\(group.id)' and f_pin = '\(idMe!)'"), cursorMember.next() {
  822. let groupId = group.chatId.isEmpty ? group.id : group.chatId
  823. if let chooser = isChooser {
  824. chooser("4", groupId)
  825. dismiss(animated: true, completion: nil)
  826. return
  827. }
  828. self.groupMap.removeAll()
  829. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  830. editorGroupVC.hidesBottomBarWhenPushed = true
  831. editorGroupVC.unique_l_pin = groupId
  832. navigationController?.show(editorGroupVC, sender: nil)
  833. cursorMember.close()
  834. } else {
  835. var viewController = UIApplication.shared.windows.first!.rootViewController
  836. if !(viewController is ViewController) {
  837. viewController = self.parent
  838. }
  839. if let viewController = viewController as? ViewController {
  840. viewController.view.makeToast("You are not a member of this group".localized(), duration: 0.5)
  841. }
  842. }
  843. })
  844. } else {
  845. if indexPath.row == 0 {
  846. tableView.reloadData()
  847. } else {
  848. getGroups(id: group.id) { g in
  849. DispatchQueue.main.async {
  850. //print("index path section: \(indexPath.section)")
  851. //print("index path row: \(indexPath.row)")
  852. //print("index path item: \(indexPath.item)")
  853. if self.isFiltering {
  854. // self.fillteredData.remove(at: indexPath.section)
  855. if self.fillteredData[indexPath.section] is Group {
  856. self.groupMap[(self.fillteredData[indexPath.section] as! Group).id] = 1
  857. self.fillteredData.insert(contentsOf: g, at: indexPath.section + 1)
  858. }
  859. } else {
  860. // self.groups.remove(at: indexPath.section)
  861. self.groupMap[self.groups[indexPath.section].id] = 1
  862. self.groups.insert(contentsOf: g, at: indexPath.section + 1)
  863. }
  864. //print("groupMap: \(self.groupMap)")
  865. tableView.reloadData()
  866. self.expandCollapseGroup(tableView: tableView, indexPath: IndexPath(row: 0, section: indexPath.section + 1))
  867. }
  868. }
  869. }
  870. }
  871. }
  872. func checkOverrideAction(groupHolder: Group) -> Bool {
  873. if groupHolder.isLounge {
  874. return false
  875. }
  876. let groupId = groupHolder.chatId.isEmpty ? groupHolder.id : groupHolder.chatId
  877. switch (groupId){
  878. case "18d1c6cffb70215af7b49" //bpkh konsultasi
  879. , "18d1c6e37a20215af7b49"
  880. , "18d1c6f852d0215af7b49"
  881. , "18d1c6ff83a0215af7b49"
  882. , "18d1c705e970215af7b49"
  883. , "18d30db3bde0230d00c15" //ina konsultasi bot
  884. , "18d30e64ce30230d00c15"
  885. , "18d30e9b6d80230d00c15"
  886. , "18d30ee00610230d00c15"
  887. , "18d30f02f850230d00c15":
  888. APIS.openSmartChatbot();
  889. return true;
  890. case "18d30daa4540230d00c15" //ina cc
  891. , "18d30e59a950230d00c15"
  892. , "18d30e9292b0230d00c15"
  893. , "18d30ed8e250230d00c15"
  894. , "18d30efa66c0230d00c15"
  895. , "18d35b220540215af7b49" //bpkhcc
  896. , "18d35b2f5ee0215af7b49"
  897. , "18d35b356530215af7b49"
  898. , "18d35b411510215af7b49"
  899. , "18d35b46ae90215af7b49":
  900. APIS.openContactCenter();
  901. return true;
  902. case "18d1c6d9f330215af7b49": //bpkh haji
  903. Nexilis.openUrl(url: Utils.decrypt(str: "6]tov!l_opgn=hgz?ykmgv?yoro3kt?uo>yoro3kt??@yvzzn"))
  904. return true;
  905. case "18d1c6eefd40215af7b49": //bpkh bpjs
  906. Nexilis.openUrl(url: Utils.decrypt(str: "1>ojq`g@tkqc.cbu:tfhbq:tjmjyfo:pj/tjmjyfo::;tquui"))
  907. return true;
  908. case "18d30e711c20230d00c15": //ina bpjs
  909. Nexilis.openUrl(url: Utils.decrypt(str: "6]tov!l_ypvh=hgz?ykmgv?yoro3kt?sui>ykrgyomojrkyz??@yvzzn"))
  910. return true;
  911. case "18d30e47ae60230d00c15": //ina KTP, KK, SKL
  912. Nexilis.openUrl(url: Utils.decrypt(str: "1>ojq`g@qul.cbu:tfhbq:tjmjyfo:npd/tfmbtjhjemftu::;tquui"))
  913. return true;
  914. case "18d30eb2e910230d00c15": //SIM, SKKB, SKBN
  915. Nexilis.openUrl(url: Utils.decrypt(str: "4[rmt}j]qmw;fex=wiket=wmpm1ir=qsg<wipewmkmhpiwx==>wtxxl"))
  916. return true;
  917. case "18da1c0200f0215af7b49": //BPKH index BMI
  918. Nexilis.openUrl(url: Utils.decrypt(str: "4[rmt}j]mqf}1ihrm=mqf=wmpm1ir=sm<wmpm1ir==>wtxxl"))
  919. return true;
  920. default:
  921. break;
  922. }
  923. return false
  924. }
  925. func numberOfSections(in tableView: UITableView) -> Int {
  926. if isFiltering {
  927. if segment.selectedSegmentIndex == 1 {
  928. return fillteredData.count
  929. }
  930. return 1
  931. } else {
  932. if segment.selectedSegmentIndex == 1 {
  933. return groups.count
  934. }
  935. return 1
  936. }
  937. }
  938. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  939. var value = 0
  940. if isFiltering {
  941. if segment.selectedSegmentIndex == 1, let groups = fillteredData as? [Group] {
  942. let group = groups[section]
  943. if group.isSelected {
  944. if let _ = groupMap[group.id] {
  945. value = 1
  946. }
  947. else {
  948. value = group.childs.count + 1
  949. }
  950. } else {
  951. value = 1
  952. }
  953. } else {
  954. value = fillteredData.count
  955. }
  956. if value == 0 {
  957. value = 1
  958. tableView.separatorStyle = .none
  959. } else {
  960. tableView.separatorStyle = .singleLine
  961. }
  962. return value
  963. }
  964. switch segment.selectedSegmentIndex {
  965. case 0:
  966. value = chats.count
  967. case 1:
  968. let group = groups[section]
  969. if group.isSelected {
  970. if let _ = groupMap[group.id] {
  971. value = 1
  972. }
  973. else {
  974. value = group.childs.count + 1
  975. }
  976. } else {
  977. value = 1
  978. }
  979. default:
  980. value = chats.count
  981. }
  982. if value == 0 {
  983. noData = true
  984. value = 1
  985. tableView.separatorStyle = .none
  986. } else {
  987. noData = false
  988. tableView.separatorStyle = .singleLine
  989. }
  990. return value
  991. }
  992. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  993. var cell: UITableViewCell!
  994. switch segment.selectedSegmentIndex {
  995. case 0:
  996. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierChat", for: indexPath)
  997. let content = cell.contentView
  998. if content.subviews.count > 0 {
  999. content.subviews.forEach { $0.removeFromSuperview() }
  1000. }
  1001. if noData || (isFiltering && fillteredData.count == 0) {
  1002. let labelNochat = UILabel()
  1003. labelNochat.text = isFiltering ? "No Result".localized() : "There are no conversations".localized()
  1004. labelNochat.font = .systemFont(ofSize: 13)
  1005. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1006. content.addSubview(labelNochat)
  1007. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  1008. cell.backgroundColor = .clear
  1009. cell.selectionStyle = .none
  1010. return cell
  1011. }
  1012. let data: Chat
  1013. if isFiltering {
  1014. data = fillteredData[indexPath.row] as! Chat
  1015. } else {
  1016. if chats.count == 0 {
  1017. let labelNochat = UILabel()
  1018. labelNochat.text = "There are no conversations".localized()
  1019. labelNochat.font = .systemFont(ofSize: 13)
  1020. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1021. content.addSubview(labelNochat)
  1022. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  1023. cell.backgroundColor = .clear
  1024. cell.selectionStyle = .none
  1025. return cell
  1026. }
  1027. data = chats[indexPath.row]
  1028. }
  1029. let imageView = UIImageView()
  1030. content.addSubview(imageView)
  1031. imageView.translatesAutoresizingMaskIntoConstraints = false
  1032. NSLayoutConstraint.activate([
  1033. imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 10.0),
  1034. imageView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  1035. imageView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -10.0),
  1036. imageView.widthAnchor.constraint(equalToConstant: 55.0),
  1037. imageView.heightAnchor.constraint(equalToConstant: 55.0)
  1038. ])
  1039. if data.profile.isEmpty && data.pin != "-999" {
  1040. if data.messageScope == "3" {
  1041. imageView.image = UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1042. } else {
  1043. imageView.image = UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1044. }
  1045. } else {
  1046. getImage(name: data.profile, placeholderImage: UIImage(named: data.pin == "-999" ? "pb_button" : data.messageScope == "3" ? "Profile---Purple" : "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  1047. imageView.image = image
  1048. })
  1049. }
  1050. let titleView = UILabel()
  1051. content.addSubview(titleView)
  1052. titleView.translatesAutoresizingMaskIntoConstraints = false
  1053. NSLayoutConstraint.activate([
  1054. titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  1055. titleView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  1056. titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  1057. ])
  1058. titleView.text = data.name
  1059. titleView.font = UIFont.systemFont(ofSize: 14, weight: .medium)
  1060. let messageView = UILabel()
  1061. content.addSubview(messageView)
  1062. messageView.translatesAutoresizingMaskIntoConstraints = false
  1063. NSLayoutConstraint.activate([
  1064. messageView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  1065. messageView.topAnchor.constraint(equalTo: titleView.bottomAnchor, constant: 5.0),
  1066. messageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  1067. ])
  1068. messageView.textColor = .gray
  1069. if data.messageText.contains("■") {
  1070. data.messageText = data.messageText.components(separatedBy: "■")[0]
  1071. data.messageText = data.messageText.trimmingCharacters(in: .whitespacesAndNewlines)
  1072. }
  1073. let text = Utils.previewMessageText(chat: data)
  1074. let idMe = User.getMyPin() as String?
  1075. if let attributeText = text as? NSMutableAttributedString {
  1076. let stringMessage = NSMutableAttributedString(string: "")
  1077. if data.fpin == idMe {
  1078. if data.lock == "1" {
  1079. if data.messageScope == "4" {
  1080. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
  1081. }
  1082. stringMessage.append(("🚫 _"+"You were deleted this message".localized()+"_").richText())
  1083. } else {
  1084. let imageStatus = NSTextAttachment()
  1085. let status = getRealStatus(messageId: data.messageId)
  1086. if status == "0" {
  1087. imageStatus.image = UIImage(systemName: "xmark.circle")!.withTintColor(UIColor.red, renderingMode: .alwaysOriginal)
  1088. } else if status == "1" {
  1089. imageStatus.image = UIImage(systemName: "clock.arrow.circlepath")!.withTintColor(UIColor.lightGray, renderingMode: .alwaysOriginal)
  1090. } else if status == "2" {
  1091. imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1092. } else if (status == "3") {
  1093. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1094. } else if (status == "8") {
  1095. imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1096. } else {
  1097. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  1098. }
  1099. imageStatus.bounds = CGRect(x: 0, y: -2, width: 15, height: 15)
  1100. let imageStatusString = NSAttributedString(attachment: imageStatus)
  1101. stringMessage.append(imageStatusString)
  1102. stringMessage.append(NSAttributedString(string: " "))
  1103. if data.messageScope == "4" {
  1104. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
  1105. }
  1106. stringMessage.append(attributeText)
  1107. }
  1108. } else {
  1109. if data.messageScope == "4" {
  1110. stringMessage.append(NSAttributedString(string: User.getData(pin: data.fpin)!.firstName + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
  1111. }
  1112. if data.lock == "1" {
  1113. stringMessage.append(("🚫 _"+"This message was deleted".localized()+"_").richText())
  1114. } else {
  1115. stringMessage.append(attributeText)
  1116. }
  1117. }
  1118. messageView.attributedText = stringMessage
  1119. }
  1120. messageView.numberOfLines = 2
  1121. let timeView = UILabel()
  1122. content.addSubview(timeView)
  1123. timeView.translatesAutoresizingMaskIntoConstraints = false
  1124. NSLayoutConstraint.activate([
  1125. timeView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  1126. timeView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20.0),
  1127. ])
  1128. timeView.textColor = .gray
  1129. timeView.font = UIFont.systemFont(ofSize: 14)
  1130. let date = Date(milliseconds: Int64(data.serverDate)!)
  1131. let calendar = Calendar.current
  1132. if (calendar.isDateInToday(date)) {
  1133. let formatter = DateFormatter()
  1134. formatter.dateFormat = "HH:mm"
  1135. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1136. timeView.text = formatter.string(from: date as Date)
  1137. } else {
  1138. let startOfNow = calendar.startOfDay(for: Date())
  1139. let startOfTimeStamp = calendar.startOfDay(for: date)
  1140. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  1141. let day = -(components.day!)
  1142. if day == 1 {
  1143. timeView.text = "Yesterday".localized()
  1144. } else {
  1145. if day < 7 {
  1146. let formatter = DateFormatter()
  1147. formatter.dateFormat = "EEEE"
  1148. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  1149. if lang == "id" {
  1150. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1151. }
  1152. timeView.text = formatter.string(from: date)
  1153. } else {
  1154. let formatter = DateFormatter()
  1155. formatter.dateFormat = "M/dd/yy"
  1156. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1157. let stringFormat = formatter.string(from: date as Date)
  1158. timeView.text = stringFormat
  1159. }
  1160. }
  1161. }
  1162. if data.counter != "0" {
  1163. timeView.textColor = .systemRed
  1164. let viewCounter = UIView()
  1165. content.addSubview(viewCounter)
  1166. viewCounter.translatesAutoresizingMaskIntoConstraints = false
  1167. NSLayoutConstraint.activate([
  1168. viewCounter.topAnchor.constraint(equalTo: timeView.bottomAnchor, constant: 5.0),
  1169. viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
  1170. viewCounter.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
  1171. viewCounter.heightAnchor.constraint(equalToConstant: 20)
  1172. ])
  1173. viewCounter.backgroundColor = .systemRed
  1174. viewCounter.layer.cornerRadius = 10
  1175. viewCounter.clipsToBounds = true
  1176. viewCounter.layer.borderWidth = 0.5
  1177. viewCounter.layer.borderColor = UIColor.secondaryColor.cgColor
  1178. let labelCounter = UILabel()
  1179. viewCounter.addSubview(labelCounter)
  1180. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  1181. NSLayoutConstraint.activate([
  1182. labelCounter.centerYAnchor.constraint(equalTo: viewCounter.centerYAnchor),
  1183. labelCounter.leadingAnchor.constraint(equalTo: viewCounter.leadingAnchor, constant: 2),
  1184. labelCounter.trailingAnchor.constraint(equalTo: viewCounter.trailingAnchor, constant: -2),
  1185. ])
  1186. labelCounter.font = UIFont.systemFont(ofSize: 11)
  1187. if Int(data.counter)! > 99 {
  1188. labelCounter.text = "99+"
  1189. } else {
  1190. labelCounter.text = data.counter
  1191. }
  1192. labelCounter.textColor = .secondaryColor
  1193. labelCounter.textAlignment = .center
  1194. }
  1195. case 1:
  1196. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  1197. var content = cell.defaultContentConfiguration()
  1198. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  1199. let group: Group
  1200. if isFiltering {
  1201. if indexPath.row == 0 {
  1202. group = fillteredData[indexPath.section] as! Group
  1203. } else {
  1204. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  1205. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  1206. } else {
  1207. return cell
  1208. }
  1209. }
  1210. } else {
  1211. if indexPath.row == 0 {
  1212. if indexPath.section > (groups.count - 1) {
  1213. return cell
  1214. }
  1215. group = groups[indexPath.section]
  1216. } else {
  1217. group = groups[indexPath.section].childs[indexPath.row - 1]
  1218. }
  1219. }
  1220. if group.official == "1" && group.parent == "" {
  1221. content.attributedText = self.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1222. }
  1223. else if group.isOpen == "1" && group.parent == "" {
  1224. if self.traitCollection.userInterfaceStyle == .dark {
  1225. content.attributedText = self.set(image: UIImage(systemName: "globe")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1226. } else {
  1227. content.attributedText = self.set(image: UIImage(systemName: "globe")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1228. }
  1229. } else if group.parent == "" {
  1230. if self.traitCollection.userInterfaceStyle == .dark {
  1231. content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1232. } else {
  1233. content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1234. }
  1235. } else {
  1236. content.text = group.name
  1237. }
  1238. if group.childs.count > 0 {
  1239. let iconName = (group.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  1240. let imageView = UIImageView(image: UIImage(systemName: iconName))
  1241. imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1242. cell.accessoryView = imageView
  1243. }
  1244. else {
  1245. cell.accessoryView = nil
  1246. cell.accessoryType = .none
  1247. }
  1248. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  1249. getImage(name: group.profile, placeholderImage: UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath) { result, isDownloaded, image in
  1250. content.image = image
  1251. }
  1252. cell.contentConfiguration = content
  1253. if !group.level.isEmpty {
  1254. if group.level != "-1" && Int(group.level)! < 7 {
  1255. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * Int(group.level)!), bottom: 0.0, right: 0)
  1256. } else if Int(group.level)! > 6 {
  1257. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * (Int(group.level)! - 6)), bottom: 0.0, right: 0)
  1258. }
  1259. }
  1260. default:
  1261. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  1262. var content = cell.defaultContentConfiguration()
  1263. content.text = ""
  1264. cell.contentConfiguration = content
  1265. }
  1266. cell.backgroundColor = .clear
  1267. cell.separatorInset = UIEdgeInsets(top: 0, left: 60.0, bottom: 0, right: 0)
  1268. return cell
  1269. }
  1270. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  1271. return 75.0
  1272. }
  1273. private func getRealStatus(messageId: String) -> String {
  1274. var status = "1"
  1275. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1276. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
  1277. var listStatus: [Int] = []
  1278. while cursorStatus.next() {
  1279. listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
  1280. }
  1281. cursorStatus.close()
  1282. status = "\(listStatus.min() ?? 2)"
  1283. }
  1284. })
  1285. return status
  1286. }
  1287. }
  1288. extension SecondTabViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  1289. func updateSearchResults(for searchController: UISearchController) {
  1290. filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
  1291. }
  1292. func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
  1293. recordAudio()
  1294. }
  1295. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
  1296. let attachment = NSTextAttachment()
  1297. attachment.image = image
  1298. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  1299. let attachmentStr = NSAttributedString(attachment: attachment)
  1300. let mutableAttributedString = NSMutableAttributedString()
  1301. mutableAttributedString.append(attachmentStr)
  1302. let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
  1303. let textString = NSAttributedString(string: text, attributes: attributedStringColor)
  1304. mutableAttributedString.append(textString)
  1305. return mutableAttributedString
  1306. }
  1307. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  1308. searchBar.showsCancelButton = true
  1309. let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
  1310. cBtn.setTitle("Cancel".localized(), for: .normal)
  1311. }
  1312. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  1313. searchBar.showsCancelButton = false
  1314. }
  1315. }
  1316. extension SecondTabViewController: SFSpeechRecognizerDelegate {
  1317. func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
  1318. if available {
  1319. self.isAllowSpeech = true
  1320. } else {
  1321. self.isAllowSpeech = false
  1322. }
  1323. }
  1324. }