12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451 |
- //
- // SecondTabViewController.swift
- // AppBuilder
- //
- // Created by Kevin Maulana on 30/03/22.
- //
- import UIKit
- import FMDB
- import NexilisLite
- import Speech
- class SecondTabViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate {
-
- var isChooser: ((String, String) -> ())?
-
- var isAdmin: Bool = false
-
- var chats: [Chat] = []
-
- var groups: [Group] = []
-
- var cancelSearchButton = UIBarButtonItem()
- var menuItem = UIBarButtonItem()
- var menuBroadcast = UIBarButtonItem()
- var voiceItem = UIBarButtonItem()
-
- var childrenMenu = [UIAction]()
-
- var groupMap: [String:Int] = [:]
-
- var isAllowSpeech = false
- var alertController = LibAlertController()
-
- var noData = false
-
- let textViewSearch = UITextField()
- let imageVoiceSb = UIImageView()
- let imageNewChatSb = UIImageView()
-
- override var preferredStatusBarStyle: UIStatusBarStyle {
- return self.traitCollection.userInterfaceStyle == .dark ? .default : .lightContent // Change this to .default for black text color
- }
- lazy var searchController: UISearchController = {
- var searchController = UISearchController(searchResultsController: nil)
- searchController.delegate = self
- searchController.searchResultsUpdater = self
- searchController.searchBar.autocapitalizationType = .none
- searchController.searchBar.delegate = self
- // searchController.searchBar.setMagnifyingGlassColorTo(color: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
- // searchController.searchBar.updateHeight(height: 30, radius: 15, borderColor: UIColor.clear.cgColor)
- searchController.searchBar.setImage(UIImage(), for: .search, state: .normal)
- searchController.searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
- searchController.searchBar.setCustomBackgroundImage(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
- searchController.obscuresBackgroundDuringPresentation = false
- searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search...".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])
- return searchController
- }()
-
- lazy var segment: UISegmentedControl = {
- var segment = UISegmentedControl(items: ["Chats".localized(), "Forums".localized()])
- segment.sizeToFit()
- segment.selectedSegmentIndex = 0
- segment.addTarget(self, action: #selector(segmentChanged(sender:)), for: .valueChanged)
- segment.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12.0)], for: .normal)
- return segment
- }()
-
- var fillteredData: [Any] = []
-
- var isSearchBarEmpty: Bool {
- return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
- }
-
- var isFiltering: Bool {
- return !textViewSearch.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
- // return !isSearchBarEmpty
- }
- @IBOutlet var tableView: UITableView!
-
- var speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "id"))
- var recognitionRequest : SFSpeechAudioBufferRecognitionRequest?
- var recognitionTask : SFSpeechRecognitionTask?
- let audioEngine = AVAudioEngine()
-
- func filterContentForSearchText(_ searchText: String) {
- if !searchText.isEmpty {
- switch segment.selectedSegmentIndex {
- case 1:
- fillteredData = self.groups.filter { $0.name.lowercased().contains(searchText.lowercased()) }
- default:
- fillteredData = self.chats.filter { $0.name.lowercased().contains(searchText.lowercased()) || $0.messageText.lowercased().contains(searchText.lowercased()) }
- }
- }
- tableView.reloadData()
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
- let me = User.getMyPin()!
- Database.shared.database?.inTransaction({ fmdb, rollback in
- 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() {
- isAdmin = cursor.string(forColumnIndex: 3) == "23" || cursor.string(forColumnIndex: 3) == "24"
- cursor.close()
- }
- })
-
- // var childrenMenu : [UIAction] = []
- //
- // if(isAdmin){
- // childrenMenu.append(UIAction(title: "Broadcast Message".localized(), image: UIImage(systemName: "envelope.open"), handler: {[weak self](_) in
- // let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
- // self?.navigationController?.present(controller, animated: true, completion: nil)
- // }))
- // }
-
- // let startConvIcon = resizeImage(image: self.traitCollection.userInterfaceStyle == .dark ? UIImage(systemName: "square.and.pencil")!.withTintColor(.white) : UIImage(systemName: "square.and.pencil")!, targetSize: CGSize(width: 25, height: 25))
- // let viewStartConv = UIButton(frame: CGRect(x: 0, y: 0, width: startConvIcon.size.width, height: startConvIcon.size.height))
- // viewStartConv.setImage(startConvIcon, for: .normal)
- // viewStartConv.addTarget(self, action: #selector(startConversation), for: .touchUpInside)
- // let brodcastIcon = resizeImage(image: self.traitCollection.userInterfaceStyle == .dark ? UIImage(named: "ic_broadcast")!.withTintColor(.white) : UIImage(named: "ic_broadcast")!, targetSize: CGSize(width: 25, height: 25))
- // let viewbrodcast = UIButton(frame: CGRect(x: 0, y: 0, width: brodcastIcon.size.width, height: brodcastIcon.size.height))
- // viewbrodcast.setImage(brodcastIcon, for: .normal)
- // viewbrodcast.addTarget(self, action: #selector(openBroadcast), for: .touchUpInside)
- //
- // menuItem = UIBarButtonItem(customView: viewStartConv)
- // menuBroadcast = UIBarButtonItem(customView: viewbrodcast)
-
- // menuItem = UIBarButtonItem(image: UIImage(systemName: "square.and.pencil"), style: .plain, target: self, action: #selector(startConversation))
- // menuBroadcast = UIBarButtonItem(image: UIImage(systemName: "info.bubble"), style: .plain, target: self, action: #selector(openBroadcast))
- // voiceItem = UIBarButtonItem(image: UIImage(systemName: "mic.fill"), style: .plain, target: self, action: #selector(recordAudio))
-
- definesPresentationContext = true
-
- NotificationCenter.default.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
-
-
-
- tableView.tableHeaderView = segment
- tableView.tableFooterView = UIView()
-
- if PrefsUtil.getCpaasMode() == PrefsUtil.CPAAS_MODE_DOCKED {
- tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
- }
-
- pullBuddy()
- navigationController?.setNavigationBarHidden(true, animated: false)
-
- let tapGesture = UITapGestureRecognizer(target: self, action: #selector(collapseDocked))
- tapGesture.cancelsTouchesInView = false
- tapGesture.delegate = self
- self.view.addGestureRecognizer(tapGesture)
- }
-
- @objc func collapseDocked() {
- if ViewController.isExpandButton {
- ViewController.expandButton()
- }
- if textViewSearch.isFirstResponder {
- textViewSearch.resignFirstResponder()
- }
- }
-
- @objc func openBroadcast() {
- let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
- controller.modalPresentationStyle = .fullScreen
- self.navigationController?.present(controller, animated: true, completion: nil)
- }
-
- @objc func startConversation(){
- let navigationController = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "contactChatNav") as! UINavigationController
- navigationController.view.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
- Utils.addBackground(view: navigationController.view)
- navigationController.modalPresentationStyle = .fullScreen
- navigationController.navigationBar.tintColor = .white
- navigationController.navigationBar.barTintColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
- navigationController.navigationBar.isTranslucent = false
- let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
- UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
- let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
- navigationController.navigationBar.titleTextAttributes = textAttributes
- navigationController.navigationBar.overrideUserInterfaceStyle = .dark
- navigationController.navigationBar.barStyle = .black
- self.navigationController?.present(navigationController, animated: true, completion: nil)
- }
-
- @objc func recordAudio(){
- if !isAllowSpeech {
- setupSpeech()
- } else {
- runVoice()
- }
- }
-
- func setupSpeech() {
- self.speechRecognizer?.delegate = self
- SFSpeechRecognizer.requestAuthorization { (authStatus) in
- var isButtonEnabled = false
- switch authStatus {
- case .authorized:
- isButtonEnabled = true
- case .denied:
- isButtonEnabled = false
- //print("User denied access to speech recognition")
- case .restricted:
- isButtonEnabled = false
- //print("Speech recognition restricted on this device")
- case .notDetermined:
- isButtonEnabled = false
- //print("Speech recognition not yet authorized")
- @unknown default:
- isButtonEnabled = false
- }
- OperationQueue.main.addOperation() {
- self.isAllowSpeech = isButtonEnabled
- if isButtonEnabled {
- SecureUserDefaults.shared.set(isButtonEnabled, forKey: "allowSpeech")
- self.runVoice()
- }
- }
- }
- }
-
- func startRecording() {
- // Clear all previous session data and cancel task
- if recognitionTask != nil {
- recognitionTask?.cancel()
- recognitionTask = nil
- }
- // Create instance of audio session to record voice
- let audioSession = AVAudioSession.sharedInstance()
- do {
- try audioSession.setCategory(AVAudioSession.Category.record, mode: AVAudioSession.Mode.measurement, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
- try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
- } catch {
- //print("audioSession properties weren't set because of an error.")
- }
- self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
- let inputNode = audioEngine.inputNode
- guard let recognitionRequest = recognitionRequest else {
- fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
- }
- recognitionRequest.shouldReportPartialResults = true
- self.recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
- var isFinal = false
- if result != nil {
- self.alertController.dismiss(animated: true)
- self.audioEngine.stop()
- self.recognitionRequest?.endAudio()
- isFinal = (result?.isFinal)!
- }
- if error != nil || isFinal {
- if error == nil {
- let textRes = result!.bestTranscription.formattedString
- self.textViewSearch.text = textRes
- self.filterContentForSearchText(textRes)
- // self.searchController.searchBar.searchTextField.text = result!.bestTranscription.formattedString
- // self.updateSearchResults(for: self.searchController)
- } else {
- self.audioEngine.stop()
- self.recognitionRequest?.endAudio()
- }
- self.voiceItem.image = UIImage(systemName: "mic.fill")
- inputNode.removeTap(onBus: 0)
- self.recognitionRequest = nil
- self.recognitionTask = nil
- }
- })
- let recordingFormat = inputNode.outputFormat(forBus: 0)
- inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
- self.recognitionRequest?.append(buffer)
- }
- self.audioEngine.prepare()
- do {
- try self.audioEngine.start()
- } catch {
- //print("audioEngine couldn't start because of an error.")
- }
- }
-
- func runVoice() {
- if !audioEngine.isRunning {
- self.voiceItem.image = UIImage(systemName: "mic")
- alertController = LibAlertController(title: "Start Recording".localized(), message: "Say something, I'm listening!".localized(), preferredStyle: .alert)
- self.present(alertController, animated: true)
- self.startRecording()
- }
- }
-
- override func viewDidAppear(_ animated: Bool) {
- self.navigationController?.navigationBar.topItem?.title = "Chats".localized() + " & " + "Forums".localized()
- self.navigationController?.navigationBar.setNeedsLayout()
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
- var viewController = UIApplication.shared.windows.first!.rootViewController
- if !(viewController is ViewController) {
- viewController = self.parent
- }
- if ViewController.middleButton.isHidden {
- ViewController.isExpandButton = false
- if let viewController = viewController as? ViewController {
- if viewController.tabBar.isHidden {
- viewController.tabBar.isHidden = false
- ViewController.alwaysHideButton = false
- ViewController.middleButton.isHidden = false
- }
- }
- } else if PrefsUtil.getCpaasMode() != PrefsUtil.CPAAS_MODE_DOCKED {
- DispatchQueue.main.async {
- if let viewController = viewController as? ViewController {
- if viewController.tabBar.isHidden {
- ViewController.alwaysHideButton = false
- viewController.tabBar.isHidden = false
- }
- }
- }
- }
- })
- getData()
- DispatchQueue.global().async {
- self.getOpenGroups(listGroups: self.groups, completion: { g in
- DispatchQueue.main.async {
- for og in g {
- if self.groups.first(where: { $0.id == og.id }) == nil {
- self.groups.append(og)
- }
- }
- self.groups.sort { (a, b) -> Bool in
- if Int(a.official) == 1 {
- return true
- } else if Int(b.official) == 1 {
- return false
- } else {
- return Int(a.official) ?? 0 > Int(b.official) ?? 0
- }
- }
- DispatchQueue.main.async {
- self.tableView.reloadData()
- }
- }
- })
- }
- }
-
- override func viewWillAppear(_ animated: Bool) {
- // tabBarController?.navigationItem.leftBarButtonItem = cancelSearchButton
- let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
- UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
- let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16)]
- let navBarAppearance = UINavigationBarAppearance()
- navBarAppearance.configureWithTransparentBackground()
- navBarAppearance.titleTextAttributes = attributes
- navigationController?.navigationBar.standardAppearance = navBarAppearance
- navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
- navigationController?.navigationBar.backgroundColor = .clear
- navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
- navigationController?.navigationBar.shadowImage = UIImage()
- navigationController?.navigationBar.isTranslucent = true
- navigationController?.setNavigationBarHidden(false, animated: false)
- navigationController?.navigationBar.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
- navigationController?.navigationBar.overrideUserInterfaceStyle = self.traitCollection.userInterfaceStyle == .dark ? .dark : .light
- navigationController?.navigationBar.barStyle = .default
- // tabBarController?.navigationItem.leftBarButtonItem = voiceItem
- // let myData = User.getData(pin: User.getMyPin())
- // if User.isOfficial(official_account: myData?.official ?? "") || User.isOfficialRegular(official_account: myData?.official ?? "") || User.isInternal(userType: myData?.userType ?? "") {
- // let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
- // fixedSpace.width = 15.0
- // tabBarController?.navigationItem.rightBarButtonItems = [menuBroadcast, fixedSpace, menuItem]
- // } else {
- // tabBarController?.navigationItem.rightBarButtonItem = menuItem
- // }
- // tabBarController?.navigationItem.searchController = searchController
- let customView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))
- customView.isUserInteractionEnabled = true
-
- let imageViewSearch = UIImageView(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
- imageViewSearch.contentMode = .scaleToFill
- customView.addSubview(imageViewSearch)
- imageViewSearch.anchor(top: customView.topAnchor, left: customView.leftAnchor, bottom: customView.bottomAnchor, right: customView.rightAnchor, height: 35)
- imageViewSearch.isUserInteractionEnabled = true
-
- let imageSetting = UIImageView(image: UIImage(named: "nx_setting_sb", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
- imageSetting.contentMode = .scaleToFill
- imageViewSearch.addSubview(imageSetting)
- imageSetting.anchor(right: customView.rightAnchor, paddingRight: 18, centerY: customView.centerYAnchor, width: 20, height: 20)
- imageSetting.isUserInteractionEnabled = true
- imageSetting.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(settingTapped)))
-
- imageVoiceSb.image = UIImage(named: "nx_mic", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!
- imageVoiceSb.contentMode = .scaleAspectFit
- imageViewSearch.addSubview(imageVoiceSb)
- imageVoiceSb.anchor(top: imageViewSearch.topAnchor, right: imageSetting.leftAnchor, paddingTop: 5, paddingRight: 15, width: 20, height: 20)
- imageVoiceSb.isUserInteractionEnabled = true
- imageVoiceSb.isHidden = true
- imageVoiceSb.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(recordAudio)))
-
- imageNewChatSb.image = UIImage(systemName: "square.and.pencil")!
- imageNewChatSb.tintColor = .nxColor
- imageNewChatSb.contentMode = .scaleAspectFit
- imageViewSearch.addSubview(imageNewChatSb)
- imageNewChatSb.anchor(top: imageViewSearch.topAnchor, right: imageVoiceSb.leftAnchor, paddingTop: 5, paddingRight: 15, width: 20, height: 20)
- imageNewChatSb.isUserInteractionEnabled = true
- imageNewChatSb.isHidden = true
- imageNewChatSb.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startConversation)))
-
- textViewSearch.placeholder = "Search...".localized()
- textViewSearch.isUserInteractionEnabled = true
- imageViewSearch.addSubview(textViewSearch)
- textViewSearch.font = .systemFont(ofSize: 11)
- textViewSearch.anchor(top: imageViewSearch.topAnchor, left: imageViewSearch.leftAnchor, bottom: imageViewSearch.bottomAnchor, right: imageViewSearch.rightAnchor, paddingTop: 5, paddingLeft: 20, paddingBottom: 5, paddingRight: 120)
- textViewSearch.delegate = self
-
- tabBarController?.navigationItem.titleView = customView
- let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
- speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: lang ?? "en"))
- backgroundImage.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
- DispatchQueue.global().async {
- DispatchQueue.main.async {
- let listBg = PrefsUtil.getBackgroundLight().isEmpty && PrefsUtil.getBackgroundDark().isEmpty ? PrefsUtil.getBackground() :
- self.traitCollection.userInterfaceStyle == .dark ? PrefsUtil.getBackgroundDark() : PrefsUtil.getBackgroundLight()
- if listBg.isEmpty {
- return
- }
- var bgChoosen = ""
- let arrayBg = listBg.split(separator: ",")
- bgChoosen = String(arrayBg[Int.random(in: 0..<arrayBg.count)])
- let urlString = PrefsUtil.getURLBase() + "get_file_from_path?img=" + bgChoosen
- if let cachedImage = ImageCache.shared.image(forKey: urlString) {
- DispatchQueue.main.async() { [self] in
- backgroundImage.image = cachedImage
- }
- return
- }
- Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
- guard let data = data, error == nil else { return }
- // always update the UI from the main thread
- DispatchQueue.main.async() { [self] in
- if UIImage(data: data) != nil {
- backgroundImage.image = UIImage(data: data)!
- ImageCache.shared.save(image: UIImage(data: data)!, forKey: urlString)
- }
- }
- }
- }
- }
- if segment.numberOfSegments == 2 {
- segment.setTitle("Chats".localized(), forSegmentAt: 0)
- segment.setTitle("Forums".localized(), forSegmentAt: 1)
- }
- if segment.selectedSegmentIndex == 0 {
- Utils.inTabChats = true
- // searchController.searchBar.placeholder = "Search chats & messages".localized()
- // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search chats & messages".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
- } else {
- // searchController.searchBar.placeholder = "Search groups name".localized()
- // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search groups name".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
- }
- // removeAllData()
- // getData()
- }
-
- // func removeAllData() {
- // groups.removeAll()
- // groupMap.removeAll()
- // chats.removeAll()
- // tableView.reloadData()
- // }
-
- func textFieldDidChangeSelection(_ textField: UITextField) {
- if textField == textViewSearch {
- let textSerch = textField.text ?? ""
- filterContentForSearchText(textSerch)
- }
- }
-
- override func viewWillDisappear(_ animated: Bool) {
- tabBarController?.navigationItem.leftBarButtonItem = nil
- tabBarController?.navigationItem.searchController = nil
- tabBarController?.navigationItem.rightBarButtonItem = nil
- tabBarController?.navigationItem.rightBarButtonItems = nil
- tabBarController?.navigationItem.titleView = nil
- Utils.inTabChats = false
- if ViewController.isExpandButton {
- ViewController.expandButton()
- }
- }
-
- @objc func settingTapped() {
- imageVoiceSb.isHidden = !imageVoiceSb.isHidden
- imageNewChatSb.isHidden = !imageNewChatSb.isHidden
- }
-
- @objc func onReloadTab(notification: NSNotification) {
- DispatchQueue.main.async {
- self.getData()
- }
- }
-
- @objc func onReload(notification: NSNotification) {
- let data:[AnyHashable : Any] = notification.userInfo!
- if data["member"] as? String == User.getMyPin()! {
- DispatchQueue.main.async {
- self.getData()
- }
- } else if data["state"] as? Int == 99 {
- DispatchQueue.main.async {
- self.getData()
- }
- }
- }
-
- @objc func onReceiveMessage(notification: NSNotification) {
- DispatchQueue.main.async { [self] in
- let data:[AnyHashable : Any] = notification.userInfo!
- if let dataMessage = data["message"] as? TMessage {
- let chatData = dataMessage.mBodies
- if chatData[CoreMessage_TMessageKey.IS_CALL_CENTER] == nil || chatData[CoreMessage_TMessageKey.IS_CALL_CENTER] == "0" {
- var indexChat: Int?
- if chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "3" && chatData[CoreMessage_TMessageKey.F_PIN] != User.getMyPin() {
- indexChat = chats.firstIndex(where: { $0.fpin == chatData[CoreMessage_TMessageKey.F_PIN] })
- } else if chatData[CoreMessage_TMessageKey.MESSAGE_SCOPE_ID] == "4" && chatData[CoreMessage_TMessageKey.F_PIN] != User.getMyPin() {
- indexChat = chats.firstIndex(where: { (chatData[CoreMessage_TMessageKey.CHAT_ID] ?? "").isEmpty ? $0.pin == chatData[CoreMessage_TMessageKey.L_PIN] : $0.pin == chatData[CoreMessage_TMessageKey.CHAT_ID] })
- }
- let newChat = Chat.getData(messageId: chatData[CoreMessage_TMessageKey.MESSAGE_ID] ?? "")
- if newChat.count > 0 {
- if indexChat != nil {
- chats.remove(at: indexChat!)
- chats.insert(newChat[0], at: 0)
- let indexPathToMove = IndexPath(row: indexChat!, section: 0)
- let indexPathNewPosition = IndexPath(row: 0, section: 0)
- tableView.performBatchUpdates({
- tableView.moveRow(at: indexPathToMove, to: indexPathNewPosition)
- }, completion: nil)
- tableView.beginUpdates()
- tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
- tableView.endUpdates()
- } else {
- chats.insert(newChat[0], at: 0)
- tableView.reloadData()
- }
- }
- }
- }
- }
- }
-
- @objc func onStatusChat(notification: NSNotification) {
- DispatchQueue.main.async { [self] in
- let data:[AnyHashable : Any] = notification.userInfo!
- if let dataMessage = data["message"] as? TMessage {
- var idMessage = dataMessage.getBody(key: CoreMessage_TMessageKey.MESSAGE_ID)
- if idMessage.contains(",") {
- let listString = dataMessage.getBody(key: CoreMessage_TMessageKey.MESSAGE_ID).components(separatedBy: ",")
- idMessage = listString[listString.count - 1]
- }
- let indexChat = chats.firstIndex(where: { $0.messageId == idMessage })
- if indexChat != nil {
- if dataMessage.getBody(key: CoreMessage_TMessageKey.DELETE_MESSAGE_FLAG) == "1" {
- chats[indexChat!].lock = "1"
- }
- tableView.beginUpdates()
- tableView.reloadRows(at: [IndexPath(row: indexChat!, section: 0)], with: .none)
- tableView.endUpdates()
- }
- }
- }
- }
-
- @objc func segmentChanged(sender: Any) {
- switch segment.selectedSegmentIndex {
- case 1:
- Utils.inTabChats = false
- // searchController.searchBar.placeholder = "Search groups name".localized()
- // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search groups name".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
- default:
- Utils.inTabChats = true
- // searchController.searchBar.placeholder = "Search chats & messages".localized()
- // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search chats & messages".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
- }
- // filterContentForSearchText(searchController.searchBar.text!)
- filterContentForSearchText(self.textViewSearch.text ?? "")
- }
-
- // MARK: - Data source
-
- func getData() {
- getChats {
- self.getGroups { g1 in
- self.groupMap.removeAll()
- self.groups = g1
- self.groups.sort { (a, b) -> Bool in
- if Int(a.official) == 1 {
- return true
- } else if Int(b.official) == 1 {
- return false
- } else {
- return Int(a.official) ?? 0 > Int(b.official) ?? 0
- }
- }
- DispatchQueue.main.async {
- self.tableView.reloadData()
- }
- }
- }
- }
-
- func getChats(completion: @escaping ()->()) {
- DispatchQueue.global().async {
- self.chats = Chat.getData()
- completion()
- }
- }
-
- private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
- var data: [Group] = []
- var query = "select g.group_id, g.f_name, g.image_id, g.quote, g.created_by, g.created_date, g.parent, g.group_type, g.is_open, g.official, g.is_education, g.level, g.chat_modifier from GROUPZ g where "
- if id.isEmpty {
- query += "g.parent = '\(parent)'"
- } else {
- query += "g.group_id = '\(id)'"
- }
- query += "order by 12 asc, 13 asc, 2 asc"
- if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
- while cursor.next() {
- let group = Group(
- id: cursor.string(forColumnIndex: 0) ?? "",
- name: cursor.string(forColumnIndex: 1) ?? "",
- profile: cursor.string(forColumnIndex: 2) ?? "",
- quote: cursor.string(forColumnIndex: 3) ?? "",
- by: cursor.string(forColumnIndex: 4) ?? "",
- date: cursor.string(forColumnIndex: 5) ?? "",
- parent: cursor.string(forColumnIndex: 6) ?? "",
- chatId: "",
- groupType: cursor.string(forColumnIndex: 7) ?? "",
- isOpen: cursor.string(forColumnIndex: 8) ?? "",
- official: cursor.string(forColumnIndex: 9) ?? "",
- isEducation: cursor.string(forColumnIndex: 10) ?? "",
- level: cursor.string(forColumnIndex: 11) ?? "")
-
- if group.chatId.isEmpty {
- 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")
- group.childs.append(lounge)
- }
-
- if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
- while topicCursor.next() {
- let topic = Group(id: group.id,
- name: topicCursor.string(forColumnIndex: 1) ?? "",
- profile: topicCursor.string(forColumnIndex: 2) ?? "",
- quote: group.quote,
- by: group.by,
- date: group.date,
- parent: group.id,
- chatId: topicCursor.string(forColumnIndex: 0) ?? "",
- groupType: group.groupType,
- isOpen: group.isOpen,
- official: group.official,
- isEducation: group.isEducation,
- level: group.level != "-1" ? group.level : "2")
- group.childs.append(topic)
- }
- topicCursor.close()
- }
-
- if !group.id.isEmpty {
- // if group.official == "1" {
- // let idMe = User.getMyPin() as String?
- // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
- // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
- // cursorUser.close()
- // }
- // } else if group.official != "1"{
- // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
- // }
- group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
- // group.childs = group.childs.sorted(by: { $0.name < $1.name })
- // let dataLounge = group.childs.filter({$0.name == "Lounge".localized()})
- // group.childs = group.childs.filter({ $0.name != "Lounge".localized() })
- // group.childs.insert(contentsOf: dataLounge, at: 0)
- }
- data.append(group)
- }
- cursor.close()
- }
- return data
- }
-
- private func getOpenGroups(listGroups: [Group], completion: @escaping ([Group]) -> ()) {
- if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getOpenGroups(p_account: "1,2,3,6,5,7", offset: "0", search: "")) {
- var dataGroups: [Group] = []
- if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
- let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
- if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [[String: Any?]] {
- for dataJson in json {
- let group = Group(
- id: dataJson[CoreMessage_TMessageKey.GROUP_ID] as? String ?? "",
- name: dataJson[CoreMessage_TMessageKey.GROUP_NAME] as? String ?? "",
- profile: dataJson[CoreMessage_TMessageKey.THUMB_ID] as? String ?? "",
- quote: dataJson[CoreMessage_TMessageKey.QUOTE] as? String ?? "",
- by: dataJson[CoreMessage_TMessageKey.BLOCK] as? String ?? "",
- date: "",
- parent: "",
- chatId: "",
- groupType: "NOTJOINED",
- isOpen: dataJson[CoreMessage_TMessageKey.IS_OPEN] as? String ?? "",
- official: "0",
- isEducation: "")
- dataGroups.append(group)
- }
- }
- }
- completion(dataGroups)
- }
- }
-
- private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
- DispatchQueue.global().async {
- Database.shared.database?.inTransaction({ fmdb, rollback in
- completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
- })
- }
- }
-
- private func pullBuddy() {
- if let me = User.getMyPin() {
- DispatchQueue.global().async {
- let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
- }
- }
- }
-
- private func joinOpenGroup(groupId: String, flagMember: String = "0", completion: @escaping (Bool) -> ()) {
- DispatchQueue.global().async {
- var result: Bool = false
- let idMe = User.getMyPin() as String?
- if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddGroupMember(p_group_id: groupId, p_member_pin: idMe!, p_position: "0")), response.isOk() {
- result = true
- }
- completion(result)
- }
- }
- @IBOutlet weak var backgroundImage: UIImageView!
-
- /*
- // MARK: - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- // Get the new view controller using segue.destination.
- // Pass the selected object to the new view controller.
- }
- */
- }
- // MARK: - Table view data source
- extension SecondTabViewController: UITableViewDelegate, UITableViewDataSource {
-
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- if noData {
- return
- }
- tableView.deselectRow(at: indexPath, animated: true)
- switch segment.selectedSegmentIndex {
- case 0:
- let data: Chat
- if isFiltering {
- data = fillteredData[indexPath.row] as! Chat
- } else {
- data = chats[indexPath.row]
- }
- if let chooser = isChooser {
- if data.pin == "-999"{
- return
- }
- chooser(data.messageScope, data.pin)
- dismiss(animated: true, completion: nil)
- return
- }
- if data.messageScope == "3" {
- let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
- editorPersonalVC.hidesBottomBarWhenPushed = true
- editorPersonalVC.unique_l_pin = data.pin
- navigationController?.show(editorPersonalVC, sender: nil)
- } else {
- let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
- editorGroupVC.hidesBottomBarWhenPushed = true
- editorGroupVC.unique_l_pin = data.pin
- navigationController?.show(editorGroupVC, sender: nil)
- }
- case 1:
- expandCollapseGroup(tableView: tableView, indexPath: indexPath)
- default:
- expandCollapseGroup(tableView: tableView, indexPath: indexPath)
- }
- }
-
- func expandCollapseGroup(tableView: UITableView, indexPath: IndexPath) {
- let group: Group
- if isFiltering {
- if indexPath.row == 0 {
- group = fillteredData[indexPath.section] as! Group
- } else {
- if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
- group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
- } else {
- return
- }
- }
- } else {
- if indexPath.row == 0 {
- group = groups[indexPath.section]
- } else {
- group = groups[indexPath.section].childs[indexPath.row - 1]
- }
- }
- if (checkOverrideAction(groupHolder: group)) {
- return;
- }
- group.isSelected = !group.isSelected
- if !group.isSelected{
- var sects = 0
- var sect = indexPath.section
- var id = group.id
- if let _ = groupMap[id] {
- var loooop = true
- repeat {
- let c = sect + 1
- if isFiltering {
- if let o = self.fillteredData[c] as? Group {
- if o.parent == id {
- sects = sects + 1
- sect = c
- id = o.id
- (self.fillteredData[c] as! Group).isSelected = false
- self.groupMap.removeValue(forKey: (self.fillteredData[c] as! Group).id)
- }
- else {
- loooop = false
- }
- }
- }
- else {
- if c < self.groups.count && self.groups[c].parent == id {
- sects = sects + 1
- sect = c
- id = self.groups[c].id
- self.groups[c].isSelected = false
- self.groupMap.removeValue(forKey: self.groups[c].id)
- }
- else {
- loooop = false
- }
- }
- } while(loooop)
- }
- for i in stride(from: sects, to: 0, by: -1){
- if isFiltering {
- self.fillteredData.remove(at: indexPath.section + i)
- }
- else {
- self.groups.remove(at: indexPath.section + i)
- }
- }
- groupMap.removeValue(forKey: group.id)
- }
- if group.groupType == "NOTJOINED" {
- let alert = LibAlertController(title: "Do you want to join this group?".localized(), message: "Groups : \(group.name)\nMembers: \(group.by)".localized(), preferredStyle: .alert)
- alert.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
- alert.addAction(UIAlertAction(title: "Join".localized(), style: .default, handler: {(_) in
- self.joinOpenGroup(groupId: group.id, completion: { result in
- if result {
- DispatchQueue.main.async {
- self.groupMap.removeAll()
- let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
- editorGroupVC.hidesBottomBarWhenPushed = true
- editorGroupVC.unique_l_pin = group.id
- self.navigationController?.show(editorGroupVC, sender: nil)
- }
- }
- })
- }))
- self.present(alert, animated: true, completion: nil)
- return
- }
- if group.childs.count == 0 {
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- let idMe = User.getMyPin() as String?
- 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() {
- let groupId = group.chatId.isEmpty ? group.id : group.chatId
- if let chooser = isChooser {
- chooser("4", groupId)
- dismiss(animated: true, completion: nil)
- return
- }
- self.groupMap.removeAll()
- let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
- editorGroupVC.hidesBottomBarWhenPushed = true
- editorGroupVC.unique_l_pin = groupId
- navigationController?.show(editorGroupVC, sender: nil)
- cursorMember.close()
- } else {
- var viewController = UIApplication.shared.windows.first!.rootViewController
- if !(viewController is ViewController) {
- viewController = self.parent
- }
- if let viewController = viewController as? ViewController {
- viewController.view.makeToast("You are not a member of this group".localized(), duration: 0.5)
- }
- }
- })
- } else {
- if indexPath.row == 0 {
- tableView.reloadData()
- } else {
- getGroups(id: group.id) { g in
- DispatchQueue.main.async {
- //print("index path section: \(indexPath.section)")
- //print("index path row: \(indexPath.row)")
- //print("index path item: \(indexPath.item)")
- if self.isFiltering {
- // self.fillteredData.remove(at: indexPath.section)
- if self.fillteredData[indexPath.section] is Group {
- self.groupMap[(self.fillteredData[indexPath.section] as! Group).id] = 1
- self.fillteredData.insert(contentsOf: g, at: indexPath.section + 1)
- }
- } else {
- // self.groups.remove(at: indexPath.section)
- self.groupMap[self.groups[indexPath.section].id] = 1
- self.groups.insert(contentsOf: g, at: indexPath.section + 1)
- }
- //print("groupMap: \(self.groupMap)")
- tableView.reloadData()
-
- self.expandCollapseGroup(tableView: tableView, indexPath: IndexPath(row: 0, section: indexPath.section + 1))
- }
- }
- }
- }
- }
-
- func checkOverrideAction(groupHolder: Group) -> Bool {
- if groupHolder.isLounge {
- return false
- }
- let groupId = groupHolder.chatId.isEmpty ? groupHolder.id : groupHolder.chatId
- switch (groupId){
- case "18d1c6cffb70215af7b49" //bpkh konsultasi
- , "18d1c6e37a20215af7b49"
- , "18d1c6f852d0215af7b49"
- , "18d1c6ff83a0215af7b49"
- , "18d1c705e970215af7b49"
- , "18d30db3bde0230d00c15" //ina konsultasi bot
- , "18d30e64ce30230d00c15"
- , "18d30e9b6d80230d00c15"
- , "18d30ee00610230d00c15"
- , "18d30f02f850230d00c15":
- APIS.openSmartChatbot();
- return true;
- case "18d30daa4540230d00c15" //ina cc
- , "18d30e59a950230d00c15"
- , "18d30e9292b0230d00c15"
- , "18d30ed8e250230d00c15"
- , "18d30efa66c0230d00c15"
- , "18d35b220540215af7b49" //bpkhcc
- , "18d35b2f5ee0215af7b49"
- , "18d35b356530215af7b49"
- , "18d35b411510215af7b49"
- , "18d35b46ae90215af7b49":
- APIS.openContactCenter();
- return true;
- case "18d1c6d9f330215af7b49": //bpkh haji
- Nexilis.openUrl(url: Utils.decrypt(str: "6]tov!l_opgn=hgz?ykmgv?yoro3kt?uo>yoro3kt??@yvzzn"))
- return true;
- case "18d1c6eefd40215af7b49": //bpkh bpjs
- Nexilis.openUrl(url: Utils.decrypt(str: "1>ojq`g@tkqc.cbu:tfhbq:tjmjyfo:pj/tjmjyfo::;tquui"))
- return true;
- case "18d30e711c20230d00c15": //ina bpjs
- Nexilis.openUrl(url: Utils.decrypt(str: "6]tov!l_ypvh=hgz?ykmgv?yoro3kt?sui>ykrgyomojrkyz??@yvzzn"))
- return true;
- case "18d30e47ae60230d00c15": //ina KTP, KK, SKL
- Nexilis.openUrl(url: Utils.decrypt(str: "1>ojq`g@qul.cbu:tfhbq:tjmjyfo:npd/tfmbtjhjemftu::;tquui"))
- return true;
- case "18d30eb2e910230d00c15": //SIM, SKKB, SKBN
- Nexilis.openUrl(url: Utils.decrypt(str: "4[rmt}j]qmw;fex=wiket=wmpm1ir=qsg<wipewmkmhpiwx==>wtxxl"))
- return true;
- case "18da1c0200f0215af7b49": //BPKH index BMI
- Nexilis.openUrl(url: Utils.decrypt(str: "4[rmt}j]mqf}1ihrm=mqf=wmpm1ir=sm<wmpm1ir==>wtxxl"))
- return true;
- default:
- break;
- }
- return false
- }
-
- func numberOfSections(in tableView: UITableView) -> Int {
- if isFiltering {
- if segment.selectedSegmentIndex == 1 {
- return fillteredData.count
- }
- return 1
- } else {
- if segment.selectedSegmentIndex == 1 {
- return groups.count
- }
- return 1
- }
- }
-
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- var value = 0
- if isFiltering {
- if segment.selectedSegmentIndex == 1, let groups = fillteredData as? [Group] {
- let group = groups[section]
- if group.isSelected {
- if let _ = groupMap[group.id] {
- value = 1
- }
- else {
- value = group.childs.count + 1
- }
- } else {
- value = 1
- }
- } else {
- value = fillteredData.count
- }
- if value == 0 {
- value = 1
- tableView.separatorStyle = .none
- } else {
- tableView.separatorStyle = .singleLine
- }
- return value
- }
- switch segment.selectedSegmentIndex {
- case 0:
- value = chats.count
- case 1:
- let group = groups[section]
- if group.isSelected {
- if let _ = groupMap[group.id] {
- value = 1
- }
- else {
- value = group.childs.count + 1
- }
- } else {
- value = 1
- }
- default:
- value = chats.count
- }
- if value == 0 {
- noData = true
- value = 1
- tableView.separatorStyle = .none
- } else {
- noData = false
- tableView.separatorStyle = .singleLine
- }
- return value
- }
-
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- var cell: UITableViewCell!
- switch segment.selectedSegmentIndex {
- case 0:
- cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierChat", for: indexPath)
- let content = cell.contentView
- if content.subviews.count > 0 {
- content.subviews.forEach { $0.removeFromSuperview() }
- }
- if noData || (isFiltering && fillteredData.count == 0) {
- let labelNochat = UILabel()
- labelNochat.text = isFiltering ? "No Result".localized() : "There are no conversations".localized()
- labelNochat.font = .systemFont(ofSize: 13)
- labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
- content.addSubview(labelNochat)
- labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
- cell.backgroundColor = .clear
- cell.selectionStyle = .none
- return cell
- }
- let data: Chat
- if isFiltering {
- data = fillteredData[indexPath.row] as! Chat
- } else {
- if chats.count == 0 {
- let labelNochat = UILabel()
- labelNochat.text = "There are no conversations".localized()
- labelNochat.font = .systemFont(ofSize: 13)
- labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
- content.addSubview(labelNochat)
- labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
- cell.backgroundColor = .clear
- cell.selectionStyle = .none
- return cell
- }
- data = chats[indexPath.row]
- }
- let imageView = UIImageView()
- content.addSubview(imageView)
- imageView.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 10.0),
- imageView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
- imageView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -10.0),
- imageView.widthAnchor.constraint(equalToConstant: 55.0),
- imageView.heightAnchor.constraint(equalToConstant: 55.0)
- ])
- if data.profile.isEmpty && data.pin != "-999" {
- if data.messageScope == "3" {
- imageView.image = UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
- } else {
- imageView.image = UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
- }
- } else {
- getImage(name: data.profile, placeholderImage: UIImage(named: data.pin == "-999" ? "pb_button" : data.messageScope == "3" ? "Profile---Purple" : "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
- imageView.image = image
- })
- }
- let titleView = UILabel()
- content.addSubview(titleView)
- titleView.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
- titleView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
- titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
- ])
- titleView.text = data.name
- titleView.font = UIFont.systemFont(ofSize: 14, weight: .medium)
-
- let messageView = UILabel()
- content.addSubview(messageView)
- messageView.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- messageView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
- messageView.topAnchor.constraint(equalTo: titleView.bottomAnchor, constant: 5.0),
- messageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
- ])
- messageView.textColor = .gray
- if data.messageText.contains("■") {
- data.messageText = data.messageText.components(separatedBy: "■")[0]
- data.messageText = data.messageText.trimmingCharacters(in: .whitespacesAndNewlines)
- }
- let text = Utils.previewMessageText(chat: data)
- let idMe = User.getMyPin() as String?
- if let attributeText = text as? NSMutableAttributedString {
- let stringMessage = NSMutableAttributedString(string: "")
- if data.fpin == idMe {
- if data.lock == "1" {
- if data.messageScope == "4" {
- stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
- }
- stringMessage.append(("🚫 _"+"You were deleted this message".localized()+"_").richText())
- } else {
- let imageStatus = NSTextAttachment()
- let status = getRealStatus(messageId: data.messageId)
- if status == "0" {
- imageStatus.image = UIImage(systemName: "xmark.circle")!.withTintColor(UIColor.red, renderingMode: .alwaysOriginal)
- } else if status == "1" {
- imageStatus.image = UIImage(systemName: "clock.arrow.circlepath")!.withTintColor(UIColor.lightGray, renderingMode: .alwaysOriginal)
- } else if status == "2" {
- imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
- } else if (status == "3") {
- imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
- } else if (status == "8") {
- imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
- } else {
- imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
- }
- imageStatus.bounds = CGRect(x: 0, y: -2, width: 15, height: 15)
- let imageStatusString = NSAttributedString(attachment: imageStatus)
- stringMessage.append(imageStatusString)
- stringMessage.append(NSAttributedString(string: " "))
- if data.messageScope == "4" {
- stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
- }
- stringMessage.append(attributeText)
- }
- } else {
- if data.messageScope == "4" {
- stringMessage.append(NSAttributedString(string: User.getData(pin: data.fpin)!.firstName + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
- }
- if data.lock == "1" {
- stringMessage.append(("🚫 _"+"This message was deleted".localized()+"_").richText())
- } else {
- stringMessage.append(attributeText)
- }
- }
- messageView.attributedText = stringMessage
- }
- messageView.numberOfLines = 2
-
- let timeView = UILabel()
- content.addSubview(timeView)
- timeView.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- timeView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
- timeView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20.0),
- ])
- timeView.textColor = .gray
- timeView.font = UIFont.systemFont(ofSize: 14)
-
- let date = Date(milliseconds: Int64(data.serverDate)!)
- let calendar = Calendar.current
-
- if (calendar.isDateInToday(date)) {
- let formatter = DateFormatter()
- formatter.dateFormat = "HH:mm"
- formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
- timeView.text = formatter.string(from: date as Date)
- } else {
- let startOfNow = calendar.startOfDay(for: Date())
- let startOfTimeStamp = calendar.startOfDay(for: date)
- let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
- let day = -(components.day!)
- if day == 1 {
- timeView.text = "Yesterday".localized()
- } else {
- if day < 7 {
- let formatter = DateFormatter()
- formatter.dateFormat = "EEEE"
- let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
- if lang == "id" {
- formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
- }
- timeView.text = formatter.string(from: date)
- } else {
- let formatter = DateFormatter()
- formatter.dateFormat = "M/dd/yy"
- formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
- let stringFormat = formatter.string(from: date as Date)
- timeView.text = stringFormat
- }
- }
- }
-
- if data.counter != "0" {
- timeView.textColor = .systemRed
- let viewCounter = UIView()
- content.addSubview(viewCounter)
- viewCounter.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- viewCounter.topAnchor.constraint(equalTo: timeView.bottomAnchor, constant: 5.0),
- viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
- viewCounter.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
- viewCounter.heightAnchor.constraint(equalToConstant: 20)
- ])
- viewCounter.backgroundColor = .systemRed
- viewCounter.layer.cornerRadius = 10
- viewCounter.clipsToBounds = true
- viewCounter.layer.borderWidth = 0.5
- viewCounter.layer.borderColor = UIColor.secondaryColor.cgColor
- let labelCounter = UILabel()
- viewCounter.addSubview(labelCounter)
- labelCounter.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- labelCounter.centerYAnchor.constraint(equalTo: viewCounter.centerYAnchor),
- labelCounter.leadingAnchor.constraint(equalTo: viewCounter.leadingAnchor, constant: 2),
- labelCounter.trailingAnchor.constraint(equalTo: viewCounter.trailingAnchor, constant: -2),
- ])
- labelCounter.font = UIFont.systemFont(ofSize: 11)
- if Int(data.counter)! > 99 {
- labelCounter.text = "99+"
- } else {
- labelCounter.text = data.counter
- }
- labelCounter.textColor = .secondaryColor
- labelCounter.textAlignment = .center
- }
- case 1:
- cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
- var content = cell.defaultContentConfiguration()
- content.textProperties.font = UIFont.systemFont(ofSize: 14)
- let group: Group
- if isFiltering {
- if indexPath.row == 0 {
- group = fillteredData[indexPath.section] as! Group
- } else {
- if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
- group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
- } else {
- return cell
- }
- }
- } else {
- if indexPath.row == 0 {
- if indexPath.section > (groups.count - 1) {
- return cell
- }
- group = groups[indexPath.section]
- } else {
- group = groups[indexPath.section].childs[indexPath.row - 1]
- }
- }
- if group.official == "1" && group.parent == "" {
- content.attributedText = self.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
- }
- else if group.isOpen == "1" && group.parent == "" {
- if self.traitCollection.userInterfaceStyle == .dark {
- content.attributedText = self.set(image: UIImage(systemName: "globe")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
- } else {
- content.attributedText = self.set(image: UIImage(systemName: "globe")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
- }
- } else if group.parent == "" {
- if self.traitCollection.userInterfaceStyle == .dark {
- content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
- } else {
- content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
- }
- } else {
- content.text = group.name
- }
- if group.childs.count > 0 {
- let iconName = (group.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
- let imageView = UIImageView(image: UIImage(systemName: iconName))
- imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
- cell.accessoryView = imageView
- }
- else {
- cell.accessoryView = nil
- cell.accessoryType = .none
- }
- content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
- 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
- content.image = image
- }
- cell.contentConfiguration = content
- if !group.level.isEmpty {
- if group.level != "-1" && Int(group.level)! < 7 {
- cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * Int(group.level)!), bottom: 0.0, right: 0)
- } else if Int(group.level)! > 6 {
- cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * (Int(group.level)! - 6)), bottom: 0.0, right: 0)
- }
- }
- default:
- cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
- var content = cell.defaultContentConfiguration()
- content.text = ""
- cell.contentConfiguration = content
- }
- cell.backgroundColor = .clear
- cell.separatorInset = UIEdgeInsets(top: 0, left: 60.0, bottom: 0, right: 0)
- return cell
- }
-
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- return 75.0
- }
-
- private func getRealStatus(messageId: String) -> String {
- var status = "1"
- Database.shared.database?.inTransaction({ (fmdb, rollback) in
- if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
- var listStatus: [Int] = []
- while cursorStatus.next() {
- listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
- }
- cursorStatus.close()
- status = "\(listStatus.min() ?? 2)"
- }
- })
- return status
- }
-
- }
- extension SecondTabViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
-
- func updateSearchResults(for searchController: UISearchController) {
- filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
- }
-
- func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
- recordAudio()
- }
-
- func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
- let attachment = NSTextAttachment()
- attachment.image = image
- attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
- let attachmentStr = NSAttributedString(attachment: attachment)
-
- let mutableAttributedString = NSMutableAttributedString()
- mutableAttributedString.append(attachmentStr)
-
- let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
- let textString = NSAttributedString(string: text, attributes: attributedStringColor)
- mutableAttributedString.append(textString)
-
-
- return mutableAttributedString
- }
-
- func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
- searchBar.showsCancelButton = true
- let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
- cBtn.setTitle("Cancel".localized(), for: .normal)
- }
-
- func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
- searchBar.showsCancelButton = false
- }
-
- }
- extension SecondTabViewController: SFSpeechRecognizerDelegate {
- func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
- if available {
- self.isAllowSpeech = true
- } else {
- self.isAllowSpeech = false
- }
- }
- }
|