SecondTabViewController.swift 49 KB

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