SecondTabViewController.swift 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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 {
  12. var isChooser: ((String, String) -> ())?
  13. var isAdmin: Bool = false
  14. var chats: [Chat] = []
  15. var contacts: [User] = []
  16. var groups: [Group] = []
  17. var cancelSearchButton = UIBarButtonItem()
  18. var menuItem = UIBarButtonItem()
  19. var voiceItem = UIBarButtonItem()
  20. var childrenMenu = [UIAction]()
  21. var groupMap: [String:Int] = [:]
  22. var isAllowSpeech = false
  23. var alertController = UIAlertController()
  24. lazy var searchController: UISearchController = {
  25. var searchController = UISearchController(searchResultsController: nil)
  26. searchController.delegate = self
  27. searchController.searchResultsUpdater = self
  28. searchController.searchBar.autocapitalizationType = .none
  29. searchController.searchBar.delegate = self
  30. searchController.searchBar.barTintColor = .secondaryColor
  31. searchController.searchBar.searchTextField.backgroundColor = .secondaryColor
  32. searchController.obscuresBackgroundDuringPresentation = false
  33. searchController.searchBar.placeholder = "Search chats & messages".localized()
  34. return searchController
  35. }()
  36. lazy var segment: UISegmentedControl = {
  37. var segment = UISegmentedControl(items: ["Chats".localized(), "Groups".localized()])
  38. segment.sizeToFit()
  39. segment.selectedSegmentIndex = 0
  40. segment.addTarget(self, action: #selector(segmentChanged(sender:)), for: .valueChanged)
  41. return segment
  42. }()
  43. var fillteredData: [Any] = []
  44. var isSearchBarEmpty: Bool {
  45. return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  46. }
  47. var isFilltering: Bool {
  48. return !isSearchBarEmpty
  49. }
  50. @IBOutlet var tableView: UITableView!
  51. var speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "id"))
  52. var recognitionRequest : SFSpeechAudioBufferRecognitionRequest?
  53. var recognitionTask : SFSpeechRecognitionTask?
  54. let audioEngine = AVAudioEngine()
  55. func filterContentForSearchText(_ searchText: String) {
  56. switch segment.selectedSegmentIndex {
  57. case 1:
  58. fillteredData = self.groups.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  59. default:
  60. fillteredData = self.chats.filter { $0.name.lowercased().contains(searchText.lowercased()) || $0.messageText.lowercased().contains(searchText.lowercased()) }
  61. }
  62. tableView.reloadData()
  63. }
  64. override func viewDidLoad() {
  65. super.viewDidLoad()
  66. let me = UserDefaults.standard.string(forKey: "me")!
  67. Database.shared.database?.inTransaction({ fmdb, rollback in
  68. 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() {
  69. isAdmin = cursor.string(forColumnIndex: 3) == "23" || cursor.string(forColumnIndex: 3) == "24"
  70. cursor.close()
  71. }
  72. })
  73. var childrenMenu : [UIAction] = []
  74. if(isAdmin){
  75. childrenMenu.append(UIAction(title: "Broadcast Message", image: UIImage(systemName: "envelope.open"), handler: {[weak self](_) in
  76. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  77. self?.navigationController?.present(controller, animated: true, completion: nil)
  78. }))
  79. }
  80. menuItem = UIBarButtonItem(image: UIImage(systemName: "square.and.pencil"), style: .plain, target: self, action: #selector(startConversation))
  81. voiceItem = UIBarButtonItem(image: UIImage(systemName: "mic.fill"), style: .plain, target: self, action: #selector(recordAudio))
  82. tabBarController?.navigationItem.leftBarButtonItem = voiceItem
  83. tabBarController?.navigationItem.rightBarButtonItem = menuItem
  84. tabBarController?.navigationItem.searchController = searchController
  85. definesPresentationContext = true
  86. NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: "onMessageChat"), object: nil)
  87. NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: "onReceiveChat"), object: nil)
  88. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
  89. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil)
  90. tableView.tableHeaderView = segment
  91. tableView.tableFooterView = UIView()
  92. if PrefsUtil.getCpaasMode() == PrefsUtil.CPAAS_MODE_DOCKED {
  93. tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
  94. }
  95. pullBuddy()
  96. let cpaasMode = PrefsUtil.getCpaasMode()
  97. let isBurger = cpaasMode == PrefsUtil.CPAAS_MODE_BURGER
  98. navigationController?.setNavigationBarHidden(!isBurger, animated: false)
  99. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(collapseDocked))
  100. tapGesture.cancelsTouchesInView = false
  101. tapGesture.delegate = self
  102. self.view.addGestureRecognizer(tapGesture)
  103. }
  104. @objc func collapseDocked() {
  105. if ViewController.isExpandButton {
  106. ViewController.expandButton()
  107. }
  108. }
  109. @objc func startConversation(){
  110. let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
  111. navigationController.modalPresentationStyle = .fullScreen
  112. navigationController.navigationBar.tintColor = .white
  113. navigationController.navigationBar.barTintColor = .mainColor
  114. navigationController.navigationBar.isTranslucent = false
  115. let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
  116. navigationController.navigationBar.titleTextAttributes = textAttributes
  117. navigationController.view.backgroundColor = .mainColor
  118. self.navigationController?.present(navigationController, animated: true, completion: nil)
  119. }
  120. @objc func recordAudio(){
  121. if !isAllowSpeech {
  122. setupSpeech()
  123. } else {
  124. runVoice()
  125. }
  126. }
  127. func setupSpeech() {
  128. self.speechRecognizer?.delegate = self
  129. SFSpeechRecognizer.requestAuthorization { (authStatus) in
  130. var isButtonEnabled = false
  131. switch authStatus {
  132. case .authorized:
  133. isButtonEnabled = true
  134. case .denied:
  135. isButtonEnabled = false
  136. print("User denied access to speech recognition")
  137. case .restricted:
  138. isButtonEnabled = false
  139. print("Speech recognition restricted on this device")
  140. case .notDetermined:
  141. isButtonEnabled = false
  142. print("Speech recognition not yet authorized")
  143. @unknown default:
  144. isButtonEnabled = false
  145. }
  146. OperationQueue.main.addOperation() {
  147. self.isAllowSpeech = isButtonEnabled
  148. if isButtonEnabled {
  149. UserDefaults.standard.set(isButtonEnabled, forKey: "allowSpeech")
  150. self.runVoice()
  151. }
  152. }
  153. }
  154. }
  155. func startRecording() {
  156. // Clear all previous session data and cancel task
  157. if recognitionTask != nil {
  158. recognitionTask?.cancel()
  159. recognitionTask = nil
  160. }
  161. // Create instance of audio session to record voice
  162. let audioSession = AVAudioSession.sharedInstance()
  163. do {
  164. try audioSession.setCategory(AVAudioSession.Category.record, mode: AVAudioSession.Mode.measurement, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
  165. try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
  166. } catch {
  167. print("audioSession properties weren't set because of an error.")
  168. }
  169. self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
  170. let inputNode = audioEngine.inputNode
  171. guard let recognitionRequest = recognitionRequest else {
  172. fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
  173. }
  174. recognitionRequest.shouldReportPartialResults = true
  175. self.recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
  176. var isFinal = false
  177. if result != nil {
  178. self.alertController.dismiss(animated: true)
  179. self.audioEngine.stop()
  180. self.recognitionRequest?.endAudio()
  181. isFinal = (result?.isFinal)!
  182. }
  183. if error != nil || isFinal {
  184. if error == nil {
  185. self.searchController.searchBar.searchTextField.text = result!.bestTranscription.formattedString
  186. self.updateSearchResults(for: self.searchController)
  187. } else {
  188. self.audioEngine.stop()
  189. self.recognitionRequest?.endAudio()
  190. }
  191. self.voiceItem.image = UIImage(systemName: "mic.fill")
  192. inputNode.removeTap(onBus: 0)
  193. self.recognitionRequest = nil
  194. self.recognitionTask = nil
  195. }
  196. })
  197. let recordingFormat = inputNode.outputFormat(forBus: 0)
  198. inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
  199. self.recognitionRequest?.append(buffer)
  200. }
  201. self.audioEngine.prepare()
  202. do {
  203. try self.audioEngine.start()
  204. } catch {
  205. print("audioEngine couldn't start because of an error.")
  206. }
  207. }
  208. func runVoice() {
  209. if !audioEngine.isRunning {
  210. self.voiceItem.image = UIImage(systemName: "mic")
  211. alertController = UIAlertController(title: "Start Recording".localized(), message: "Say something, I'm listening!".localized(), preferredStyle: .alert)
  212. self.present(alertController, animated: true)
  213. self.startRecording()
  214. }
  215. }
  216. override func viewDidAppear(_ animated: Bool) {
  217. self.navigationController?.navigationBar.topItem?.title = "Chats".localized() + " & " + "Groups".localized()
  218. DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
  219. var viewController = UIApplication.shared.windows.first!.rootViewController
  220. if !(viewController is ViewController) {
  221. viewController = self.parent
  222. }
  223. if ViewController.middleButton.isHidden {
  224. ViewController.isExpandButton = false
  225. if let viewController = viewController as? ViewController {
  226. if viewController.tabBar.isHidden {
  227. viewController.tabBar.isHidden = false
  228. ViewController.middleButton.isHidden = false
  229. }
  230. }
  231. } else if PrefsUtil.getCpaasMode() != PrefsUtil.CPAAS_MODE_DOCKED {
  232. DispatchQueue.main.async {
  233. if let viewController = viewController as? ViewController {
  234. if viewController.tabBar.isHidden {
  235. viewController.tabBar.isHidden = false
  236. }
  237. }
  238. }
  239. }
  240. })
  241. }
  242. override func viewWillAppear(_ animated: Bool) {
  243. // tabBarController?.navigationItem.leftBarButtonItem = cancelSearchButton
  244. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
  245. navigationController?.navigationBar.backgroundColor = .clear
  246. navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
  247. navigationController?.navigationBar.shadowImage = UIImage()
  248. navigationController?.navigationBar.isTranslucent = true
  249. navigationController?.setNavigationBarHidden(false, animated: false)
  250. navigationController?.navigationBar.tintColor = .black
  251. tabBarController?.navigationItem.leftBarButtonItem = voiceItem
  252. tabBarController?.navigationItem.searchController = searchController
  253. tabBarController?.navigationItem.rightBarButtonItem = menuItem
  254. let lang = UserDefaults.standard.string(forKey: "i18n_language")
  255. speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: lang ?? "en"))
  256. backgroundImage.backgroundColor = .white
  257. DispatchQueue.global().async {
  258. if let listBg = PrefsUtil.getBackground() {
  259. if listBg.isEmpty {
  260. return
  261. }
  262. var bgChoosen = ""
  263. let arrayBg = listBg.split(separator: ",")
  264. bgChoosen = String(arrayBg[Int.random(in: 0..<arrayBg.count)])
  265. ViewController.getDataImageFromUrl(from: URL(string: PrefsUtil.getURLBase() + "/dashboardv2/uploads/background/" + bgChoosen)!) { data, response, error in
  266. guard let data = data, error == nil else { return }
  267. // always update the UI from the main thread
  268. DispatchQueue.main.async() { [self] in
  269. backgroundImage.image = UIImage(data: data)!
  270. }
  271. }
  272. }
  273. }
  274. if segment.numberOfSegments == 2 {
  275. segment.setTitle("Chats".localized(), forSegmentAt: 0)
  276. segment.setTitle("Groups".localized(), forSegmentAt: 1)
  277. }
  278. if segment.selectedSegmentIndex == 0 {
  279. searchController.searchBar.placeholder = "Search chats & messages".localized()
  280. } else {
  281. searchController.searchBar.placeholder = "Search groups name".localized()
  282. }
  283. removeAllData()
  284. getData()
  285. }
  286. func removeAllData() {
  287. groups.removeAll()
  288. groupMap.removeAll()
  289. chats.removeAll()
  290. tableView.reloadData()
  291. }
  292. override func viewWillDisappear(_ animated: Bool) {
  293. tabBarController?.navigationItem.leftBarButtonItem = nil
  294. tabBarController?.navigationItem.searchController = nil
  295. tabBarController?.navigationItem.rightBarButtonItem = nil
  296. if ViewController.isExpandButton {
  297. ViewController.expandButton()
  298. }
  299. }
  300. @objc func onReload(notification: NSNotification) {
  301. let data:[AnyHashable : Any] = notification.userInfo!
  302. if data["member"] as? String == UserDefaults.standard.string(forKey: "me")! {
  303. DispatchQueue.main.async {
  304. self.getData()
  305. }
  306. } else if data["state"] as? Int == 99 {
  307. DispatchQueue.main.async {
  308. self.getData()
  309. }
  310. }
  311. }
  312. @objc func onReceiveMessage(notification: NSNotification) {
  313. self.getChats {
  314. DispatchQueue.main.async {
  315. self.tableView.reloadData()
  316. }
  317. }
  318. }
  319. @objc func segmentChanged(sender: Any) {
  320. switch segment.selectedSegmentIndex {
  321. case 1:
  322. searchController.searchBar.placeholder = "Search groups name".localized()
  323. default:
  324. searchController.searchBar.placeholder = "Search chats & messages".localized()
  325. }
  326. filterContentForSearchText(searchController.searchBar.text!)
  327. }
  328. // MARK: - Data source
  329. func getData() {
  330. getChats {
  331. self.getContacts {
  332. self.getGroups { g1 in
  333. self.groupMap.removeAll()
  334. self.groups.removeAll()
  335. self.groups.append(contentsOf: g1)
  336. DispatchQueue.main.async {
  337. self.tableView.reloadData()
  338. }
  339. DispatchQueue.global().async {
  340. self.getOpenGroups(listGroups: g1, completion: { g in
  341. DispatchQueue.main.async {
  342. for og in g {
  343. if self.groups.first(where: { $0.id == og.id }) == nil {
  344. self.groups.append(og)
  345. }
  346. }
  347. DispatchQueue.main.async {
  348. self.tableView.reloadData()
  349. }
  350. }
  351. })
  352. }
  353. }
  354. }
  355. }
  356. }
  357. func getChats(completion: @escaping ()->()) {
  358. DispatchQueue.global().async {
  359. self.chats.removeAll()
  360. self.chats.append(contentsOf: Chat.getData())
  361. completion()
  362. }
  363. }
  364. private func getContacts(completion: @escaping ()->()) {
  365. DispatchQueue.global().async {
  366. self.contacts.removeAll()
  367. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  368. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_pin, first_name, last_name, image_id, official_account, user_type FROM BUDDY where f_pin <> '\(UserDefaults.standard.string(forKey: "me")!)' order by 5 desc, 2 collate nocase asc") {
  369. while cursorData.next() {
  370. let user = User(pin: cursorData.string(forColumnIndex: 0) ?? "",
  371. firstName: cursorData.string(forColumnIndex: 1) ?? "",
  372. lastName: cursorData.string(forColumnIndex: 2) ?? "",
  373. thumb: cursorData.string(forColumnIndex: 3) ?? "",
  374. userType: cursorData.string(forColumnIndex: 5) ?? "")
  375. if (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces) == "USR\(user.pin)" {
  376. continue
  377. }
  378. user.official = cursorData.string(forColumnIndex: 4) ?? ""
  379. self.contacts.append(user)
  380. }
  381. cursorData.close()
  382. }
  383. completion()
  384. })
  385. }
  386. }
  387. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  388. var data: [Group] = []
  389. 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 from GROUPZ g where "
  390. if id.isEmpty {
  391. query += "g.parent = '\(parent)'"
  392. } else {
  393. query += "g.group_id = '\(id)'"
  394. }
  395. query += "order by 10 desc"
  396. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  397. while cursor.next() {
  398. let group = Group(
  399. id: cursor.string(forColumnIndex: 0) ?? "",
  400. name: cursor.string(forColumnIndex: 1) ?? "",
  401. profile: cursor.string(forColumnIndex: 2) ?? "",
  402. quote: cursor.string(forColumnIndex: 3) ?? "",
  403. by: cursor.string(forColumnIndex: 4) ?? "",
  404. date: cursor.string(forColumnIndex: 5) ?? "",
  405. parent: cursor.string(forColumnIndex: 6) ?? "",
  406. chatId: "",
  407. groupType: cursor.string(forColumnIndex: 7) ?? "",
  408. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  409. official: cursor.string(forColumnIndex: 9) ?? "",
  410. isEducation: cursor.string(forColumnIndex: 10) ?? "",
  411. level: cursor.string(forColumnIndex: 11) ?? "")
  412. if group.chatId.isEmpty {
  413. 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")
  414. group.childs.append(lounge)
  415. }
  416. if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  417. while topicCursor.next() {
  418. let topic = Group(id: group.id,
  419. name: topicCursor.string(forColumnIndex: 1) ?? "",
  420. profile: topicCursor.string(forColumnIndex: 2) ?? "",
  421. quote: group.quote,
  422. by: group.by,
  423. date: group.date,
  424. parent: group.id,
  425. chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  426. groupType: group.groupType,
  427. isOpen: group.isOpen,
  428. official: group.official,
  429. isEducation: group.isEducation,
  430. level: group.level != "-1" ? group.level : "2")
  431. group.childs.append(topic)
  432. }
  433. topicCursor.close()
  434. }
  435. if !group.id.isEmpty {
  436. // if group.official == "1" {
  437. // let idMe = UserDefaults.standard.string(forKey: "me") as String?
  438. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  439. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  440. // cursorUser.close()
  441. // }
  442. // } else if group.official != "1"{
  443. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  444. // }
  445. group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  446. // group.childs = group.childs.sorted(by: { $0.name < $1.name })
  447. // let dataLounge = group.childs.filter({$0.name == "Lounge".localized()})
  448. // group.childs = group.childs.filter({ $0.name != "Lounge".localized() })
  449. // group.childs.insert(contentsOf: dataLounge, at: 0)
  450. }
  451. data.append(group)
  452. }
  453. cursor.close()
  454. }
  455. return data
  456. }
  457. private func getOpenGroups(listGroups: [Group], completion: @escaping ([Group]) -> ()) {
  458. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getOpenGroups(p_account: "1,2,3,5,6,7", offset: "0", search: "")) {
  459. var dataGroups: [Group] = []
  460. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  461. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  462. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [[String: Any?]] {
  463. for dataJson in json {
  464. let group = Group(
  465. id: dataJson[CoreMessage_TMessageKey.GROUP_ID] as? String ?? "",
  466. name: dataJson[CoreMessage_TMessageKey.GROUP_NAME] as? String ?? "",
  467. profile: dataJson[CoreMessage_TMessageKey.THUMB_ID] as? String ?? "",
  468. quote: dataJson[CoreMessage_TMessageKey.QUOTE] as? String ?? "",
  469. by: dataJson[CoreMessage_TMessageKey.BLOCK] as? String ?? "",
  470. date: "",
  471. parent: "",
  472. chatId: "",
  473. groupType: "NOTJOINED",
  474. isOpen: dataJson[CoreMessage_TMessageKey.IS_OPEN] as? String ?? "",
  475. official: "0",
  476. isEducation: "")
  477. dataGroups.append(group)
  478. }
  479. }
  480. } else {
  481. DispatchQueue.main.async {
  482. self.groups.removeAll()
  483. self.groups.append(contentsOf: listGroups)
  484. self.tableView.reloadData()
  485. }
  486. }
  487. completion(dataGroups)
  488. }
  489. }
  490. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  491. DispatchQueue.global().async {
  492. Database.shared.database?.inTransaction({ fmdb, rollback in
  493. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  494. })
  495. }
  496. }
  497. private func pullBuddy() {
  498. if let me = UserDefaults.standard.string(forKey: "me") {
  499. DispatchQueue.global().async {
  500. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  501. }
  502. }
  503. }
  504. private func joinOpenGroup(groupId: String, flagMember: String = "0", completion: @escaping (Bool) -> ()) {
  505. DispatchQueue.global().async {
  506. var result: Bool = false
  507. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  508. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddGroupMember(p_group_id: groupId, p_member_pin: idMe!, p_position: "0")), response.isOk() {
  509. result = true
  510. }
  511. completion(result)
  512. }
  513. }
  514. @IBOutlet weak var backgroundImage: UIImageView!
  515. /*
  516. // MARK: - Navigation
  517. // In a storyboard-based application, you will often want to do a little preparation before navigation
  518. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  519. // Get the new view controller using segue.destination.
  520. // Pass the selected object to the new view controller.
  521. }
  522. */
  523. }
  524. // MARK: - Table view data source
  525. extension SecondTabViewController: UITableViewDelegate, UITableViewDataSource {
  526. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  527. switch segment.selectedSegmentIndex {
  528. case 0:
  529. let data: Chat
  530. if isFilltering {
  531. data = fillteredData[indexPath.row] as! Chat
  532. } else {
  533. data = chats[indexPath.row]
  534. }
  535. if let chooser = isChooser {
  536. if data.pin == "-999"{
  537. return
  538. }
  539. chooser(data.messageScope, data.pin)
  540. dismiss(animated: true, completion: nil)
  541. return
  542. }
  543. if data.messageScope == "3" {
  544. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  545. editorPersonalVC.hidesBottomBarWhenPushed = true
  546. editorPersonalVC.unique_l_pin = data.pin
  547. navigationController?.show(editorPersonalVC, sender: nil)
  548. } else {
  549. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  550. editorGroupVC.hidesBottomBarWhenPushed = true
  551. editorGroupVC.unique_l_pin = data.pin
  552. navigationController?.show(editorGroupVC, sender: nil)
  553. }
  554. case 1:
  555. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  556. default:
  557. let data = contacts[indexPath.row]
  558. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  559. editorPersonalVC.hidesBottomBarWhenPushed = true
  560. editorPersonalVC.unique_l_pin = data.pin
  561. navigationController?.show(editorPersonalVC, sender: nil)
  562. }
  563. }
  564. func expandCollapseGroup(tableView: UITableView, indexPath: IndexPath) {
  565. let group: Group
  566. if isFilltering {
  567. if indexPath.row == 0 {
  568. group = fillteredData[indexPath.section] as! Group
  569. } else {
  570. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  571. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  572. } else {
  573. return
  574. }
  575. }
  576. } else {
  577. if indexPath.row == 0 {
  578. group = groups[indexPath.section]
  579. } else {
  580. group = groups[indexPath.section].childs[indexPath.row - 1]
  581. }
  582. }
  583. group.isSelected = !group.isSelected
  584. if !group.isSelected{
  585. var sects = 0
  586. var sect = indexPath.section
  587. var id = group.id
  588. if let _ = groupMap[id] {
  589. var loooop = true
  590. repeat {
  591. let c = sect + 1
  592. if isFilltering {
  593. if let o = self.fillteredData[c] as? Group {
  594. if o.parent == id {
  595. sects = sects + 1
  596. sect = c
  597. id = o.id
  598. (self.fillteredData[c] as! Group).isSelected = false
  599. self.groupMap.removeValue(forKey: (self.fillteredData[c] as! Group).id)
  600. }
  601. else {
  602. loooop = false
  603. }
  604. }
  605. }
  606. else {
  607. if c < self.groups.count && self.groups[c].parent == id {
  608. sects = sects + 1
  609. sect = c
  610. id = self.groups[c].id
  611. self.groups[c].isSelected = false
  612. self.groupMap.removeValue(forKey: self.groups[c].id)
  613. }
  614. else {
  615. loooop = false
  616. }
  617. }
  618. } while(loooop)
  619. }
  620. for i in stride(from: sects, to: 0, by: -1){
  621. if isFilltering {
  622. self.fillteredData.remove(at: indexPath.section + i)
  623. }
  624. else {
  625. self.groups.remove(at: indexPath.section + i)
  626. }
  627. }
  628. groupMap.removeValue(forKey: group.id)
  629. }
  630. if group.groupType == "NOTJOINED" {
  631. let alert = UIAlertController(title: "Do you want to join this group?".localized(), message: "Groups : \(group.name)\nMembers: \(group.by)".localized(), preferredStyle: .alert)
  632. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  633. alert.addAction(UIAlertAction(title: "Join".localized(), style: .default, handler: {(_) in
  634. self.joinOpenGroup(groupId: group.id, completion: { result in
  635. if result {
  636. DispatchQueue.main.async {
  637. self.groupMap.removeAll()
  638. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  639. editorGroupVC.hidesBottomBarWhenPushed = true
  640. editorGroupVC.unique_l_pin = group.id
  641. self.navigationController?.show(editorGroupVC, sender: nil)
  642. }
  643. }
  644. })
  645. }))
  646. self.present(alert, animated: true, completion: nil)
  647. return
  648. }
  649. if group.childs.count == 0 {
  650. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  651. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  652. 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() {
  653. let groupId = group.chatId.isEmpty ? group.id : group.chatId
  654. if let chooser = isChooser {
  655. chooser("4", groupId)
  656. dismiss(animated: true, completion: nil)
  657. return
  658. }
  659. self.groupMap.removeAll()
  660. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  661. editorGroupVC.hidesBottomBarWhenPushed = true
  662. editorGroupVC.unique_l_pin = groupId
  663. navigationController?.show(editorGroupVC, sender: nil)
  664. cursorMember.close()
  665. } else {
  666. var viewController = UIApplication.shared.windows.first!.rootViewController
  667. if !(viewController is ViewController) {
  668. viewController = self.parent
  669. }
  670. if let viewController = viewController as? ViewController {
  671. viewController.view.makeToast("You are not a member of this group".localized(), duration: 0.5)
  672. }
  673. }
  674. })
  675. } else {
  676. if indexPath.row == 0 {
  677. tableView.reloadData()
  678. } else {
  679. getGroups(id: group.id) { g in
  680. DispatchQueue.main.async {
  681. print("index path section: \(indexPath.section)")
  682. print("index path row: \(indexPath.row)")
  683. // print("index path item: \(indexPath.item)")
  684. if self.isFilltering {
  685. // self.fillteredData.remove(at: indexPath.section)
  686. if self.fillteredData[indexPath.section] is Group {
  687. self.groupMap[(self.fillteredData[indexPath.section] as! Group).id] = 1
  688. self.fillteredData.insert(contentsOf: g, at: indexPath.section + 1)
  689. }
  690. } else {
  691. // self.groups.remove(at: indexPath.section)
  692. self.groupMap[self.groups[indexPath.section].id] = 1
  693. self.groups.insert(contentsOf: g, at: indexPath.section + 1)
  694. }
  695. print("groupMap: \(self.groupMap)")
  696. tableView.reloadData()
  697. self.expandCollapseGroup(tableView: tableView, indexPath: IndexPath(row: 0, section: indexPath.section + 1))
  698. }
  699. }
  700. }
  701. }
  702. }
  703. func numberOfSections(in tableView: UITableView) -> Int {
  704. if isFilltering {
  705. if segment.selectedSegmentIndex == 1 {
  706. return fillteredData.count
  707. }
  708. return 1
  709. } else {
  710. if segment.selectedSegmentIndex == 1 {
  711. return groups.count
  712. }
  713. return 1
  714. }
  715. }
  716. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  717. var value = 0
  718. if isFilltering {
  719. if segment.selectedSegmentIndex == 1, let groups = fillteredData as? [Group] {
  720. let group = groups[section]
  721. if group.isSelected {
  722. if let _ = groupMap[group.id] {
  723. value = 1
  724. }
  725. else {
  726. value = group.childs.count + 1
  727. }
  728. } else {
  729. value = 1
  730. }
  731. } else {
  732. value = fillteredData.count
  733. }
  734. return value
  735. }
  736. switch segment.selectedSegmentIndex {
  737. case 0:
  738. value = chats.count
  739. case 1:
  740. let group = groups[section]
  741. if group.isSelected {
  742. if let _ = groupMap[group.id] {
  743. value = 1
  744. }
  745. else {
  746. value = group.childs.count + 1
  747. }
  748. } else {
  749. value = 1
  750. }
  751. default:
  752. value = chats.count
  753. }
  754. return value
  755. }
  756. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  757. var cell: UITableViewCell!
  758. switch segment.selectedSegmentIndex {
  759. case 0:
  760. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierChat", for: indexPath)
  761. cell.separatorInset.left = 60.0
  762. let content = cell.contentView
  763. if content.subviews.count > 0 {
  764. content.subviews.forEach { $0.removeFromSuperview() }
  765. }
  766. if chats.count == 0 {
  767. return cell
  768. }
  769. let data: Chat
  770. if isFilltering {
  771. data = fillteredData[indexPath.row] as! Chat
  772. } else {
  773. data = chats[indexPath.row]
  774. }
  775. let imageView = UIImageView()
  776. content.addSubview(imageView)
  777. imageView.translatesAutoresizingMaskIntoConstraints = false
  778. NSLayoutConstraint.activate([
  779. imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 10.0),
  780. imageView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  781. imageView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -25.0),
  782. imageView.widthAnchor.constraint(equalToConstant: 40.0),
  783. imageView.heightAnchor.constraint(equalToConstant: 40.0)
  784. ])
  785. if data.profile.isEmpty && data.pin != "-999" {
  786. if data.messageScope == "3" {
  787. imageView.image = UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  788. } else {
  789. imageView.image = UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  790. }
  791. } else {
  792. if PrefsUtil.getIconDock() != nil {
  793. let dataImage = try? Data(contentsOf: URL(string: PrefsUtil.getUrlDock()!)!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
  794. if dataImage != nil {
  795. getImage(name: data.profile, placeholderImage: UIImage(data: dataImage!), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  796. imageView.image = image
  797. })
  798. }
  799. } else {
  800. getImage(name: data.profile, placeholderImage: UIImage(named: data.pin == "-999" ? "pb_button" : "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  801. imageView.image = image
  802. })
  803. }
  804. }
  805. let titleView = UILabel()
  806. content.addSubview(titleView)
  807. titleView.translatesAutoresizingMaskIntoConstraints = false
  808. NSLayoutConstraint.activate([
  809. titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  810. titleView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  811. titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  812. ])
  813. titleView.text = data.name
  814. titleView.font = UIFont.systemFont(ofSize: 14, weight: .medium)
  815. let messageView = UILabel()
  816. content.addSubview(messageView)
  817. messageView.translatesAutoresizingMaskIntoConstraints = false
  818. NSLayoutConstraint.activate([
  819. messageView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  820. messageView.topAnchor.constraint(equalTo: titleView.bottomAnchor, constant: 5.0),
  821. messageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  822. ])
  823. messageView.textColor = .gray
  824. let text = Utils.previewMessageText(chat: data)
  825. let idMe = UserDefaults.standard.string(forKey: "me") as String?
  826. if let attributeText = text as? NSAttributedString {
  827. if data.fpin == idMe {
  828. let stringMessage = NSMutableAttributedString(string: "")
  829. let imageStatus = NSTextAttachment()
  830. let status = getRealStatus(messageId: data.messageId)
  831. if (status == "1" || status == "2" ) {
  832. imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  833. } else if (status == "3") {
  834. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  835. } else if (status == "8") {
  836. imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  837. } else {
  838. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  839. }
  840. imageStatus.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
  841. let imageStatusString = NSAttributedString(attachment: imageStatus)
  842. stringMessage.append(imageStatusString)
  843. stringMessage.append(NSAttributedString(string: " "))
  844. stringMessage.append(attributeText)
  845. messageView.attributedText = stringMessage
  846. } else {
  847. messageView.attributedText = attributeText
  848. }
  849. } else if let stringText = text as? String {
  850. if data.fpin == idMe {
  851. let stringMessage = NSMutableAttributedString(string: "")
  852. let imageStatus = NSTextAttachment()
  853. let status = getRealStatus(messageId: data.messageId)
  854. if (status == "1" || status == "2" ) {
  855. imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  856. } else if (status == "3") {
  857. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  858. } else if (status == "8") {
  859. imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  860. } else {
  861. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  862. }
  863. imageStatus.bounds = CGRect(x: 0, y: 0, width: 15, height: 15)
  864. let imageStatusString = NSAttributedString(attachment: imageStatus)
  865. stringMessage.append(imageStatusString)
  866. stringMessage.append(NSAttributedString(string: " "))
  867. stringMessage.append(NSAttributedString(string: stringText))
  868. messageView.attributedText = stringMessage
  869. } else {
  870. messageView.text = stringText
  871. }
  872. }
  873. messageView.numberOfLines = 2
  874. if data.counter != "0" {
  875. let viewCounter = UIView()
  876. content.addSubview(viewCounter)
  877. viewCounter.translatesAutoresizingMaskIntoConstraints = false
  878. NSLayoutConstraint.activate([
  879. viewCounter.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  880. viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
  881. viewCounter.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
  882. viewCounter.heightAnchor.constraint(equalToConstant: 20)
  883. ])
  884. viewCounter.backgroundColor = .systemRed
  885. viewCounter.layer.cornerRadius = 10
  886. viewCounter.clipsToBounds = true
  887. viewCounter.layer.borderWidth = 0.5
  888. viewCounter.layer.borderColor = UIColor.secondaryColor.cgColor
  889. let labelCounter = UILabel()
  890. viewCounter.addSubview(labelCounter)
  891. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  892. NSLayoutConstraint.activate([
  893. labelCounter.centerYAnchor.constraint(equalTo: viewCounter.centerYAnchor),
  894. labelCounter.leadingAnchor.constraint(equalTo: viewCounter.leadingAnchor, constant: 2),
  895. labelCounter.trailingAnchor.constraint(equalTo: viewCounter.trailingAnchor, constant: -2),
  896. ])
  897. labelCounter.font = UIFont.systemFont(ofSize: 11)
  898. if Int(data.counter)! > 99 {
  899. labelCounter.text = "99+"
  900. } else {
  901. labelCounter.text = data.counter
  902. }
  903. labelCounter.textColor = .secondaryColor
  904. labelCounter.textAlignment = .center
  905. }
  906. case 1:
  907. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  908. var content = cell.defaultContentConfiguration()
  909. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  910. let group: Group
  911. if isFilltering {
  912. if indexPath.row == 0 {
  913. print("DATA GROUP1 \((fillteredData[indexPath.section] as! Group).name)")
  914. group = fillteredData[indexPath.section] as! Group
  915. } else {
  916. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  917. print("DATA GROUP2 \((fillteredData[indexPath.section] as! Group).name)")
  918. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  919. } else {
  920. return cell
  921. }
  922. }
  923. } else {
  924. if indexPath.row == 0 {
  925. group = groups[indexPath.section]
  926. } else {
  927. group = groups[indexPath.section].childs[indexPath.row - 1]
  928. }
  929. }
  930. if group.official == "1" && group.parent == "" {
  931. 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)
  932. }
  933. else if group.isOpen == "1" && group.parent == "" {
  934. if self.traitCollection.userInterfaceStyle == .dark {
  935. content.attributedText = self.set(image: UIImage(systemName: "globe")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4)
  936. } else {
  937. content.attributedText = self.set(image: UIImage(systemName: "globe")!, with: " \(group.name)", size: 15, y: -4)
  938. }
  939. } else if group.parent == "" {
  940. if self.traitCollection.userInterfaceStyle == .dark {
  941. content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4)
  942. } else {
  943. content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!, with: " \(group.name)", size: 15, y: -4)
  944. }
  945. } else {
  946. content.text = group.name
  947. }
  948. if group.childs.count > 0 {
  949. let iconName = (group.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  950. let imageView = UIImageView(image: UIImage(systemName: iconName))
  951. imageView.tintColor = .black
  952. cell.accessoryView = imageView
  953. }
  954. else {
  955. cell.accessoryView = nil
  956. cell.accessoryType = .none
  957. }
  958. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  959. 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
  960. content.image = image
  961. }
  962. cell.contentConfiguration = content
  963. if !group.level.isEmpty {
  964. if group.level != "-1" && Int(group.level)! < 7 {
  965. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * Int(group.level)!), bottom: 0.0, right: 0)
  966. } else if Int(group.level)! > 6 {
  967. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * (Int(group.level)! - 6)), bottom: 0.0, right: 0)
  968. }
  969. }
  970. default:
  971. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  972. var content = cell.defaultContentConfiguration()
  973. content.text = ""
  974. cell.contentConfiguration = content
  975. }
  976. cell.backgroundColor = .clear
  977. return cell
  978. }
  979. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  980. return 75.0
  981. }
  982. private func getRealStatus(messageId: String) -> String {
  983. var status = "1"
  984. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  985. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
  986. var listStatus: [Int] = []
  987. while cursorStatus.next() {
  988. listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
  989. }
  990. cursorStatus.close()
  991. status = "\(listStatus.min() ?? 2)"
  992. }
  993. })
  994. return status
  995. }
  996. }
  997. extension SecondTabViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  998. func updateSearchResults(for searchController: UISearchController) {
  999. filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
  1000. }
  1001. func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
  1002. recordAudio()
  1003. }
  1004. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat) -> NSAttributedString {
  1005. let attachment = NSTextAttachment()
  1006. attachment.image = image
  1007. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  1008. let attachmentStr = NSAttributedString(attachment: attachment)
  1009. let mutableAttributedString = NSMutableAttributedString()
  1010. mutableAttributedString.append(attachmentStr)
  1011. let textString = NSAttributedString(string: text)
  1012. mutableAttributedString.append(textString)
  1013. return mutableAttributedString
  1014. }
  1015. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  1016. searchBar.showsCancelButton = true
  1017. let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
  1018. cBtn.setTitle("Cancel".localized(), for: .normal)
  1019. }
  1020. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  1021. searchBar.showsCancelButton = false
  1022. }
  1023. }
  1024. extension SecondTabViewController: SFSpeechRecognizerDelegate {
  1025. func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
  1026. if available {
  1027. self.isAllowSpeech = true
  1028. } else {
  1029. self.isAllowSpeech = false
  1030. }
  1031. }
  1032. }