SecondTabViewController.swift 71 KB

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