SecondTabViewController.swift 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411
  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. import QuickLook
  12. import SDWebImage
  13. class SecondTabViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, QLPreviewControllerDataSource {
  14. var isChooser: ((String, String) -> ())?
  15. var isAdmin: Bool = false
  16. var chats: [Chat] = []
  17. var chatGroupMaps: [String: [Chat]] = [:]
  18. var groups: [Group] = []
  19. var cancelSearchButton = UIBarButtonItem()
  20. var menuItem = UIBarButtonItem()
  21. var menuBroadcast = UIBarButtonItem()
  22. var voiceItem = UIBarButtonItem()
  23. var childrenMenu = [UIAction]()
  24. var groupMap: [String:Int] = [:]
  25. var isAllowSpeech = false
  26. var alertController = LibAlertController()
  27. var noData = false
  28. var loadingData = true
  29. var waitingLoading = false
  30. let textViewSearch = UITextField()
  31. let buttonImageVoiceSb = UIButton(type: .custom)
  32. let imageNewChatSb = UIImageView()
  33. let buttonImageClearSearch = UIButton(type: .custom)
  34. @IBOutlet weak var viewToolbar: UIView!
  35. @IBOutlet weak var heightToolbar: NSLayoutConstraint!
  36. var viewCategorySearch: UIScrollView!
  37. var leftTVSearch: NSLayoutConstraint!
  38. var viewCatInTV: UIView!
  39. var imageViewSearch: UIImageView!
  40. var gridImage: UICollectionView!
  41. var previewItem: NSURL?
  42. var audioPlayer: AVAudioPlayer?
  43. let UNREAD_TAG = 10
  44. let PHOTOS_TAG = 11
  45. let DOCUMENTS_TAG = 12
  46. let LINKS_TAG = 13
  47. let VIDEOS_TAG = 14
  48. let GIFS_TAG = 15
  49. let AUDIOS_TAG = 16
  50. var selectedTag = 0
  51. // override var preferredStatusBarStyle: UIStatusBarStyle {
  52. // return self.traitCollection.userInterfaceStyle == .dark ? .default : .lightContent // Change this to .default for black text color
  53. // }
  54. lazy var searchController: UISearchController = {
  55. var searchController = UISearchController(searchResultsController: nil)
  56. searchController.delegate = self
  57. searchController.searchResultsUpdater = self
  58. searchController.searchBar.autocapitalizationType = .none
  59. searchController.searchBar.delegate = self
  60. // searchController.searchBar.setMagnifyingGlassColorTo(color: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  61. // searchController.searchBar.updateHeight(height: 30, radius: 15, borderColor: UIColor.clear.cgColor)
  62. searchController.searchBar.setImage(UIImage(), for: .search, state: .normal)
  63. searchController.searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
  64. 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)!)
  65. searchController.obscuresBackgroundDuringPresentation = false
  66. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search...".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)])
  67. return searchController
  68. }()
  69. lazy var segment: UISegmentedControl = {
  70. var segment = UISegmentedControl(items: ["Chats".localized(), "Forums".localized()])
  71. segment.sizeToFit()
  72. segment.selectedSegmentIndex = 0
  73. segment.addTarget(self, action: #selector(segmentChanged(sender:)), for: .valueChanged)
  74. segment.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12.0)], for: .normal)
  75. return segment
  76. }()
  77. var fillteredData: [Any] = []
  78. var isSearchBarEmpty: Bool {
  79. return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  80. }
  81. var isFiltering: Bool {
  82. return !textViewSearch.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  83. // return !isSearchBarEmpty
  84. }
  85. @IBOutlet var tableView: UITableView!
  86. var speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "id"))
  87. var recognitionRequest : SFSpeechAudioBufferRecognitionRequest?
  88. var recognitionTask : SFSpeechRecognitionTask?
  89. let audioEngine = AVAudioEngine()
  90. func filterContentForSearchText(_ searchText: String) {
  91. if !searchText.isEmpty {
  92. switch segment.selectedSegmentIndex {
  93. case 1:
  94. fillteredData = self.groups.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  95. default:
  96. if selectedTag == 0 {
  97. var group_id: String?
  98. if let filterGroupKey = self.chatGroupMaps.first(where: { $0.value.contains { $0.name.lowercased().contains(searchText.lowercased()) || $0.groupName.lowercased().contains(searchText.lowercased()) || $0.messageText.lowercased().contains(searchText.lowercased()) } } ) {
  99. group_id = filterGroupKey.key
  100. }
  101. let deepCopyChats = self.chats.map{ $0.copy() }
  102. fillteredData = deepCopyChats.filter { $0.name.lowercased().contains(searchText.lowercased()) || $0.messageText.lowercased().contains(searchText.lowercased()) || $0.groupId == group_id }
  103. } else {
  104. switch(selectedTag) {
  105. case UNREAD_TAG :
  106. let deepCopyChats = self.chats.map{ $0.copy() }
  107. fillteredData = deepCopyChats.filter { $0.counter != "0" }
  108. break
  109. case PHOTOS_TAG, VIDEOS_TAG, GIFS_TAG :
  110. fillteredData = Chat.getData(isImage: selectedTag == PHOTOS_TAG, isVideo: selectedTag == VIDEOS_TAG, isGIF: selectedTag == GIFS_TAG)
  111. if fillteredData.count > 0 {
  112. if gridImage != nil && gridImage.isDescendant(of: self.view) {
  113. gridImage.removeFromSuperview()
  114. }
  115. let width = self.view.frame.width / 3 - 2
  116. var cellSize = CGSize(width:width, height:width)
  117. if selectedTag == GIFS_TAG {
  118. cellSize = CGSize(width:self.view.frame.width / 2 - 2, height:self.view.frame.width / 2 - 62)
  119. }
  120. let layout = UICollectionViewFlowLayout()
  121. layout.scrollDirection = .vertical
  122. layout.itemSize = cellSize
  123. layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
  124. layout.minimumLineSpacing = 1.0
  125. layout.minimumInteritemSpacing = 1.0
  126. gridImage = UICollectionView(frame: .zero, collectionViewLayout: layout)
  127. self.view.addSubview(gridImage)
  128. gridImage.anchor(top: tableView.topAnchor, left: tableView.leftAnchor, bottom: tableView.bottomAnchor, right: tableView.rightAnchor)
  129. gridImage.backgroundColor = .clear
  130. gridImage.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "gridCell")
  131. gridImage.delegate = self
  132. gridImage.dataSource = self
  133. tableView.isHidden = true
  134. }
  135. break
  136. case DOCUMENTS_TAG :
  137. fillteredData = Chat.getData(isDoc: true)
  138. break
  139. case LINKS_TAG :
  140. fillteredData = Chat.getData(isLink: true)
  141. break
  142. case AUDIOS_TAG :
  143. fillteredData = Chat.getData(isAudio: true)
  144. break
  145. default:
  146. break
  147. }
  148. }
  149. }
  150. }
  151. tableView.reloadData()
  152. }
  153. override func viewDidLoad() {
  154. super.viewDidLoad()
  155. let me = User.getMyPin()!
  156. Database.shared.database?.inTransaction({ fmdb, rollback in
  157. 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() {
  158. isAdmin = cursor.string(forColumnIndex: 3) == "23" || cursor.string(forColumnIndex: 3) == "24"
  159. cursor.close()
  160. }
  161. })
  162. // var childrenMenu : [UIAction] = []
  163. //
  164. // if(isAdmin){
  165. // childrenMenu.append(UIAction(title: "Broadcast Message".localized(), image: UIImage(systemName: "envelope.open"), handler: {[weak self](_) in
  166. // let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  167. // self?.navigationController?.present(controller, animated: true, completion: nil)
  168. // }))
  169. // }
  170. // 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))
  171. // let viewStartConv = UIButton(frame: CGRect(x: 0, y: 0, width: startConvIcon.size.width, height: startConvIcon.size.height))
  172. // viewStartConv.setImage(startConvIcon, for: .normal)
  173. // viewStartConv.addTarget(self, action: #selector(startConversation), for: .touchUpInside)
  174. // let brodcastIcon = resizeImage(image: self.traitCollection.userInterfaceStyle == .dark ? UIImage(named: "ic_broadcast")!.withTintColor(.white) : UIImage(named: "ic_broadcast")!, targetSize: CGSize(width: 25, height: 25))
  175. // let viewbrodcast = UIButton(frame: CGRect(x: 0, y: 0, width: brodcastIcon.size.width, height: brodcastIcon.size.height))
  176. // viewbrodcast.setImage(brodcastIcon, for: .normal)
  177. // viewbrodcast.addTarget(self, action: #selector(openBroadcast), for: .touchUpInside)
  178. //
  179. // menuItem = UIBarButtonItem(customView: viewStartConv)
  180. // menuBroadcast = UIBarButtonItem(customView: viewbrodcast)
  181. // menuItem = UIBarButtonItem(image: UIImage(systemName: "square.and.pencil"), style: .plain, target: self, action: #selector(startConversation))
  182. // menuBroadcast = UIBarButtonItem(image: UIImage(systemName: "info.bubble"), style: .plain, target: self, action: #selector(openBroadcast))
  183. // voiceItem = UIBarButtonItem(image: UIImage(systemName: "mic.fill"), style: .plain, target: self, action: #selector(recordAudio))
  184. definesPresentationContext = true
  185. NotificationCenter.default.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil)
  186. NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil)
  187. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
  188. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil)
  189. NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil)
  190. NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
  191. imageViewSearch = UIImageView(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
  192. imageViewSearch.contentMode = .scaleToFill
  193. viewToolbar.addSubview(imageViewSearch)
  194. imageViewSearch.anchor(top: viewToolbar.topAnchor, left: viewToolbar.leftAnchor, right: viewToolbar.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingRight: 10, height: 35)
  195. imageViewSearch.isUserInteractionEnabled = true
  196. viewCategorySearch = UIScrollView()
  197. viewCategorySearch.showsHorizontalScrollIndicator = false
  198. viewToolbar.addSubview(viewCategorySearch)
  199. viewCategorySearch.anchor(top: imageViewSearch.bottomAnchor, left: viewToolbar.leftAnchor, right: viewToolbar.rightAnchor, paddingLeft: 10, paddingRight: 10, height: 40)
  200. viewCategorySearch.isHidden = true
  201. let groupViewCat = UIStackView()
  202. viewCategorySearch.addSubview(groupViewCat)
  203. groupViewCat.anchor(left: viewCategorySearch.leftAnchor, right: viewCategorySearch.rightAnchor, centerY: viewCategorySearch.centerYAnchor, height: 30)
  204. groupViewCat.axis = .horizontal
  205. groupViewCat.spacing = 10
  206. for i in 0..<7 {
  207. var widthView: CGFloat = 105
  208. var iconCat = UIImage(systemName: "bubble.right")
  209. var textCat = "Unread".localized()
  210. var tag = UNREAD_TAG
  211. if i == 1 {
  212. widthView = 100
  213. iconCat = UIImage(systemName: "photo")
  214. textCat = "Photos".localized()
  215. tag = PHOTOS_TAG
  216. } else if i == 2 {
  217. widthView = 130
  218. iconCat = UIImage(systemName: "doc")
  219. textCat = "Documents".localized()
  220. tag = DOCUMENTS_TAG
  221. } else if i == 3 {
  222. widthView = 80
  223. iconCat = UIImage(systemName: "link")
  224. textCat = "Links".localized()
  225. tag = LINKS_TAG
  226. } else if i == 4 {
  227. widthView = 100
  228. iconCat = UIImage(systemName: "video")
  229. textCat = "Videos".localized()
  230. tag = VIDEOS_TAG
  231. } else if i == 5 {
  232. widthView = 80
  233. iconCat = UIImage(systemName: "photo.on.rectangle")
  234. textCat = "GIFs".localized()
  235. tag = GIFS_TAG
  236. } else if i == 6 {
  237. widthView = 80
  238. iconCat = UIImage(systemName: "music.note")
  239. textCat = "Audio".localized()
  240. tag = AUDIOS_TAG
  241. }
  242. let viewCat = UIView(frame: CGRect(x: 0, y: 0, width: widthView, height: 30))
  243. groupViewCat.addArrangedSubview(viewCat)
  244. viewCat.anchor(width: widthView, height: 30)
  245. viewCat.layer.cornerRadius = 15
  246. viewCat.layer.borderColor = UIColor.gray.cgColor
  247. viewCat.layer.borderWidth = 0.5
  248. viewCat.backgroundColor = .white
  249. viewCat.isUserInteractionEnabled = true
  250. viewCat.tag = tag
  251. viewCat.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTapCategory(_:))))
  252. let imageIcon = UIImageView()
  253. imageIcon.image = iconCat
  254. imageIcon.tintColor = .black
  255. viewCat.addSubview(imageIcon)
  256. imageIcon.anchor(left: viewCat.leftAnchor, paddingLeft: 10, centerY: viewCat.centerYAnchor)
  257. let imageText = UILabel()
  258. imageText.text = textCat
  259. viewCat.addSubview(imageText)
  260. imageText.anchor(left: imageIcon.rightAnchor, paddingLeft: 5, centerY: viewCat.centerYAnchor)
  261. imageText.font = .systemFont(ofSize: 15)
  262. }
  263. let buttonImageSetting = UIButton(type: .custom)
  264. let imageSetting = UIImage(named: "nx_setting_sb", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!
  265. buttonImageSetting.backgroundColor = .clear
  266. buttonImageSetting.setImage(imageSetting, for: .normal)
  267. imageViewSearch.addSubview(buttonImageSetting)
  268. buttonImageSetting.anchor(right: imageViewSearch.rightAnchor, paddingRight: 15, centerY: imageViewSearch.centerYAnchor, width: 20, height: 20)
  269. buttonImageSetting.addTarget(self, action: #selector(settingTapped), for: .touchUpInside)
  270. let imageVoiceSb = UIImage(named: "nx_mic", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!
  271. buttonImageVoiceSb.setImage(imageVoiceSb, for: .normal)
  272. buttonImageVoiceSb.imageView?.contentMode = .scaleAspectFit
  273. imageViewSearch.addSubview(buttonImageVoiceSb)
  274. buttonImageVoiceSb.anchor(right: buttonImageSetting.leftAnchor, paddingRight: 10, centerY: imageViewSearch.centerYAnchor, width: 20, height: 20)
  275. buttonImageVoiceSb.isHidden = true
  276. buttonImageVoiceSb.addTarget(self, action: #selector(recordAudio), for: .touchUpInside)
  277. let imageClearSearch = UIImage(systemName: "xmark")
  278. buttonImageClearSearch.setImage(imageClearSearch, for: .normal)
  279. buttonImageClearSearch.imageView?.contentMode = .scaleAspectFit
  280. buttonImageClearSearch.tintColor = .gray
  281. imageViewSearch.addSubview(buttonImageClearSearch)
  282. buttonImageClearSearch.anchor(right: buttonImageVoiceSb.leftAnchor, paddingRight: 5, centerY: imageViewSearch.centerYAnchor, width: 20, height: 20)
  283. buttonImageClearSearch.isHidden = true
  284. buttonImageClearSearch.addTarget(self, action: #selector(clearSearch), for: .touchUpInside)
  285. textViewSearch.placeholder = "Search...".localized()
  286. textViewSearch.isUserInteractionEnabled = true
  287. imageViewSearch.addSubview(textViewSearch)
  288. textViewSearch.font = .systemFont(ofSize: 11)
  289. textViewSearch.anchor(top: imageViewSearch.topAnchor, bottom: imageViewSearch.bottomAnchor, right: imageViewSearch.rightAnchor, paddingTop: 5, paddingBottom: 5, paddingRight: 90)
  290. leftTVSearch = textViewSearch.leftAnchor.constraint(equalTo: imageViewSearch.leftAnchor, constant: 20.0)
  291. NSLayoutConstraint.activate([
  292. leftTVSearch
  293. ])
  294. textViewSearch.delegate = self
  295. tableView.tableHeaderView = segment
  296. tableView.tableFooterView = UIView()
  297. if PrefsUtil.getCpaasMode() == PrefsUtil.CPAAS_MODE_DOCKED {
  298. tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
  299. }
  300. pullBuddy()
  301. navigationController?.setNavigationBarHidden(true, animated: false)
  302. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(collapseDocked))
  303. tapGesture.cancelsTouchesInView = false
  304. tapGesture.delegate = self
  305. self.view.addGestureRecognizer(tapGesture)
  306. }
  307. @objc func collapseDocked() {
  308. if ViewController.isExpandButton {
  309. ViewController.expandButton()
  310. }
  311. if textViewSearch.isFirstResponder {
  312. textViewSearch.resignFirstResponder()
  313. }
  314. }
  315. @objc func openBroadcast() {
  316. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  317. controller.modalPresentationStyle = .fullScreen
  318. self.navigationController?.present(controller, animated: true, completion: nil)
  319. }
  320. @objc func startConversation(){
  321. APIS.openChat()
  322. }
  323. @objc func recordAudio(){
  324. if !isAllowSpeech {
  325. setupSpeech()
  326. } else {
  327. runVoice()
  328. }
  329. }
  330. @objc func clearSearch(){
  331. selectedTag = 0
  332. if gridImage != nil && gridImage.isDescendant(of: self.view) {
  333. gridImage.removeFromSuperview()
  334. tableView.isHidden = false
  335. }
  336. textViewSearch.text = ""
  337. buttonImageClearSearch.isHidden = true
  338. if !textViewSearch.isFirstResponder {
  339. viewCategorySearch.isHidden = true
  340. buttonImageVoiceSb.isHidden = true
  341. heightToolbar.constant = 45
  342. filterContentForSearchText("")
  343. } else if heightToolbar.constant == 45 {
  344. viewCategorySearch.isHidden = false
  345. heightToolbar.constant = 85
  346. }
  347. if leftTVSearch.constant != 20 {
  348. viewCatInTV.removeFromSuperview()
  349. leftTVSearch.constant = 20
  350. }
  351. }
  352. func setupSpeech() {
  353. self.speechRecognizer?.delegate = self
  354. SFSpeechRecognizer.requestAuthorization { (authStatus) in
  355. var isButtonEnabled = false
  356. switch authStatus {
  357. case .authorized:
  358. isButtonEnabled = true
  359. case .denied:
  360. isButtonEnabled = false
  361. //print("User denied access to speech recognition")
  362. case .restricted:
  363. isButtonEnabled = false
  364. //print("Speech recognition restricted on this device")
  365. case .notDetermined:
  366. isButtonEnabled = false
  367. //print("Speech recognition not yet authorized")
  368. @unknown default:
  369. isButtonEnabled = false
  370. }
  371. OperationQueue.main.addOperation() {
  372. self.isAllowSpeech = isButtonEnabled
  373. if isButtonEnabled {
  374. SecureUserDefaults.shared.set(isButtonEnabled, forKey: "allowSpeech")
  375. self.runVoice()
  376. }
  377. }
  378. }
  379. }
  380. func startRecording() {
  381. // Clear all previous session data and cancel task
  382. if recognitionTask != nil {
  383. recognitionTask?.cancel()
  384. recognitionTask = nil
  385. }
  386. // Create instance of audio session to record voice
  387. let audioSession = AVAudioSession.sharedInstance()
  388. do {
  389. try audioSession.setCategory(AVAudioSession.Category.record, mode: AVAudioSession.Mode.measurement, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
  390. try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
  391. } catch {
  392. //print("audioSession properties weren't set because of an error.")
  393. }
  394. self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
  395. let inputNode = audioEngine.inputNode
  396. guard let recognitionRequest = recognitionRequest else {
  397. fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
  398. }
  399. recognitionRequest.shouldReportPartialResults = true
  400. self.recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
  401. var isFinal = false
  402. if result != nil {
  403. self.alertController.dismiss(animated: true)
  404. self.audioEngine.stop()
  405. self.recognitionRequest?.endAudio()
  406. isFinal = (result?.isFinal)!
  407. }
  408. if error != nil || isFinal {
  409. if error == nil {
  410. let textRes = result!.bestTranscription.formattedString
  411. self.textViewSearch.text = textRes
  412. self.filterContentForSearchText(textRes)
  413. // self.searchController.searchBar.searchTextField.text = result!.bestTranscription.formattedString
  414. // self.updateSearchResults(for: self.searchController)
  415. } else {
  416. self.audioEngine.stop()
  417. self.recognitionRequest?.endAudio()
  418. }
  419. self.voiceItem.image = UIImage(systemName: "mic.fill")
  420. inputNode.removeTap(onBus: 0)
  421. self.recognitionRequest = nil
  422. self.recognitionTask = nil
  423. }
  424. })
  425. let recordingFormat = inputNode.outputFormat(forBus: 0)
  426. inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
  427. self.recognitionRequest?.append(buffer)
  428. }
  429. self.audioEngine.prepare()
  430. do {
  431. try self.audioEngine.start()
  432. } catch {
  433. //print("audioEngine couldn't start because of an error.")
  434. }
  435. }
  436. func runVoice() {
  437. if !audioEngine.isRunning {
  438. self.voiceItem.image = UIImage(systemName: "mic")
  439. alertController = LibAlertController(title: "Start Recording".localized(), message: "Say something, I'm listening!".localized(), preferredStyle: .alert)
  440. self.present(alertController, animated: true)
  441. self.startRecording()
  442. }
  443. }
  444. override func viewDidAppear(_ animated: Bool) {
  445. // self.navigationController?.navigationBar.topItem?.title = "Chats".localized() + " & " + "Forums".localized()
  446. // self.navigationController?.navigationBar.setNeedsLayout()
  447. DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
  448. var viewController = UIApplication.shared.windows.first!.rootViewController
  449. if !(viewController is ViewController) {
  450. viewController = self.parent
  451. }
  452. if ViewController.middleButton.isHidden {
  453. ViewController.isExpandButton = false
  454. if let viewController = viewController as? ViewController {
  455. if viewController.tabBar.isHidden {
  456. viewController.tabBar.isHidden = false
  457. ViewController.alwaysHideButton = false
  458. ViewController.middleButton.isHidden = false
  459. }
  460. }
  461. } else if PrefsUtil.getCpaasMode() != PrefsUtil.CPAAS_MODE_DOCKED {
  462. DispatchQueue.main.async {
  463. if let viewController = viewController as? ViewController {
  464. if viewController.tabBar.isHidden {
  465. ViewController.alwaysHideButton = false
  466. viewController.tabBar.isHidden = false
  467. }
  468. }
  469. }
  470. }
  471. })
  472. getData()
  473. APIS.setDataForShareExtension()
  474. }
  475. override func viewWillAppear(_ animated: Bool) {
  476. // tabBarController?.navigationItem.leftBarButtonItem = cancelSearchButton
  477. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  478. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  479. let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16)]
  480. let navBarAppearance = UINavigationBarAppearance()
  481. navBarAppearance.configureWithTransparentBackground()
  482. navBarAppearance.titleTextAttributes = attributes
  483. navigationController?.navigationBar.standardAppearance = navBarAppearance
  484. navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
  485. navigationController?.navigationBar.backgroundColor = .clear
  486. navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
  487. navigationController?.navigationBar.shadowImage = UIImage()
  488. navigationController?.navigationBar.isTranslucent = true
  489. navigationController?.setNavigationBarHidden(true, animated: false)
  490. navigationController?.navigationBar.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  491. navigationController?.navigationBar.overrideUserInterfaceStyle = self.traitCollection.userInterfaceStyle == .dark ? .dark : .light
  492. navigationController?.navigationBar.barStyle = .default
  493. // tabBarController?.navigationItem.leftBarButtonItem = voiceItem
  494. // let myData = User.getData(pin: User.getMyPin())
  495. // if User.isOfficial(official_account: myData?.official ?? "") || User.isOfficialRegular(official_account: myData?.official ?? "") || User.isInternal(userType: myData?.userType ?? "") {
  496. // let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
  497. // fixedSpace.width = 15.0
  498. // tabBarController?.navigationItem.rightBarButtonItems = [menuBroadcast, fixedSpace, menuItem]
  499. // } else {
  500. // tabBarController?.navigationItem.rightBarButtonItem = menuItem
  501. // }
  502. // tabBarController?.navigationItem.searchController = searchController
  503. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  504. speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: lang ?? "en"))
  505. backgroundImage.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  506. DispatchQueue.global().async {
  507. DispatchQueue.main.async {
  508. let listBg = PrefsUtil.getBackgroundLight().isEmpty && PrefsUtil.getBackgroundDark().isEmpty ? PrefsUtil.getBackground() :
  509. self.traitCollection.userInterfaceStyle == .dark ? PrefsUtil.getBackgroundDark() : PrefsUtil.getBackgroundLight()
  510. if listBg.isEmpty {
  511. return
  512. }
  513. var bgChoosen = ""
  514. let arrayBg = listBg.split(separator: ",")
  515. bgChoosen = String(arrayBg[Int.random(in: 0..<arrayBg.count)])
  516. let urlString = PrefsUtil.getURLBase() + "get_file_from_path?img=" + bgChoosen
  517. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  518. DispatchQueue.main.async() { [self] in
  519. backgroundImage.image = cachedImage
  520. }
  521. return
  522. }
  523. Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
  524. guard let data = data, error == nil else { return }
  525. // always update the UI from the main thread
  526. DispatchQueue.main.async() { [self] in
  527. if UIImage(data: data) != nil {
  528. backgroundImage.image = UIImage(data: data)!
  529. ImageCache.shared.save(image: UIImage(data: data)!, forKey: urlString)
  530. }
  531. }
  532. }
  533. }
  534. }
  535. if segment.numberOfSegments == 2 {
  536. segment.setTitle("Chats".localized(), forSegmentAt: 0)
  537. segment.setTitle("Forums".localized(), forSegmentAt: 1)
  538. }
  539. if segment.selectedSegmentIndex == 0 {
  540. Utils.inTabChats = true
  541. }
  542. }
  543. func textFieldDidChangeSelection(_ textField: UITextField) {
  544. if textField == textViewSearch {
  545. var textSerch = textField.text ?? ""
  546. textSerch = textSerch.trimmingCharacters(in: .whitespacesAndNewlines)
  547. if !textSerch.isEmpty && buttonImageClearSearch.isHidden {
  548. buttonImageClearSearch.isHidden = false
  549. } else if textSerch.isEmpty && !buttonImageClearSearch.isHidden {
  550. buttonImageClearSearch.isHidden = true
  551. }
  552. if textField.text?.count == 1 && leftTVSearch.constant != 20 {
  553. selectedTag = 0
  554. if gridImage != nil && gridImage.isDescendant(of: self.view) {
  555. gridImage.removeFromSuperview()
  556. tableView.isHidden = false
  557. }
  558. textField.text = ""
  559. viewCatInTV.removeFromSuperview()
  560. leftTVSearch.constant = 20
  561. }
  562. filterContentForSearchText(textSerch)
  563. }
  564. if viewCatInTV != nil && viewCatInTV.isDescendant(of: imageViewSearch) {
  565. viewCategorySearch.isHidden = true
  566. heightToolbar.constant = 45
  567. } else if (viewCatInTV == nil || !viewCatInTV.isDescendant(of: imageViewSearch)) && segment.selectedSegmentIndex == 0 {
  568. viewCategorySearch.isHidden = false
  569. heightToolbar.constant = 85
  570. }
  571. }
  572. func textFieldDidBeginEditing(_ textField: UITextField) {
  573. if textField == textViewSearch {
  574. if segment.selectedSegmentIndex == 0 && (viewCatInTV == nil || !viewCatInTV.isDescendant(of: imageViewSearch)) {
  575. heightToolbar.constant = 85
  576. viewCategorySearch.isHidden = false
  577. buttonImageVoiceSb.isHidden = false
  578. }
  579. }
  580. }
  581. func textFieldDidEndEditing(_ textField: UITextField) {
  582. if textField == textViewSearch {
  583. if let text = textField.text {
  584. if text.isEmpty {
  585. viewCategorySearch.isHidden = true
  586. buttonImageVoiceSb.isHidden = true
  587. heightToolbar.constant = 45
  588. }
  589. }
  590. }
  591. }
  592. override func viewWillDisappear(_ animated: Bool) {
  593. tabBarController?.navigationItem.leftBarButtonItem = nil
  594. tabBarController?.navigationItem.searchController = nil
  595. tabBarController?.navigationItem.rightBarButtonItem = nil
  596. tabBarController?.navigationItem.rightBarButtonItems = nil
  597. tabBarController?.navigationItem.titleView = nil
  598. Utils.inTabChats = false
  599. if ViewController.isExpandButton {
  600. ViewController.expandButton()
  601. }
  602. }
  603. @objc func settingTapped() {
  604. // imageVoiceSb.isHidden = !imageVoiceSb.isHidden
  605. // imageNewChatSb.isHidden = !imageNewChatSb.isHidden
  606. startConversation()
  607. }
  608. @objc func onTapCategory(_ sender: UITapGestureRecognizer) {
  609. if let tappedView = sender.view {
  610. if viewCatInTV != nil && viewCatInTV.isDescendant(of: imageViewSearch) {
  611. viewCatInTV.removeFromSuperview()
  612. }
  613. var width1: CGFloat = 67
  614. var width2: CGFloat = 80
  615. viewCatInTV = UIView()
  616. imageViewSearch.addSubview(viewCatInTV)
  617. var iconCat = UIImage(systemName: "bubble.right")
  618. var textCat = "Unread".localized()
  619. selectedTag = tappedView.tag
  620. if tappedView.tag == PHOTOS_TAG {
  621. iconCat = UIImage(systemName: "photo")
  622. textCat = "Photos".localized()
  623. } else if tappedView.tag == DOCUMENTS_TAG {
  624. iconCat = UIImage(systemName: "doc")
  625. textCat = "Documents".localized()
  626. width1 = 97
  627. width2 = 110
  628. } else if tappedView.tag == LINKS_TAG {
  629. iconCat = UIImage(systemName: "link")
  630. textCat = "Links".localized()
  631. width1 = 57
  632. width2 = 70
  633. } else if tappedView.tag == VIDEOS_TAG {
  634. iconCat = UIImage(systemName: "video")
  635. textCat = "Videos".localized()
  636. } else if tappedView.tag == GIFS_TAG {
  637. iconCat = UIImage(systemName: "photo.on.rectangle")
  638. textCat = "GIFs".localized()
  639. width1 = 52
  640. width2 = 65
  641. } else if tappedView.tag == AUDIOS_TAG {
  642. iconCat = UIImage(systemName: "music.note")
  643. textCat = "Audio".localized()
  644. width1 = 62
  645. width2 = 75
  646. }
  647. viewCatInTV.frame = CGRect(x: 0, y: 0, width: width1, height: 30)
  648. viewCatInTV.anchor(left: imageViewSearch.leftAnchor, paddingLeft: 20, centerY: imageViewSearch.centerYAnchor, width: width1, height: 25)
  649. viewCatInTV.backgroundColor = .white
  650. viewCatInTV.layer.cornerRadius = 8
  651. viewCatInTV.clipsToBounds = true
  652. viewCatInTV.backgroundColor = .black
  653. textViewSearch.text = "~ "
  654. leftTVSearch.constant = width2
  655. let imageIcon = UIImageView()
  656. imageIcon.image = iconCat
  657. imageIcon.tintColor = .white
  658. viewCatInTV.addSubview(imageIcon)
  659. imageIcon.anchor(left: viewCatInTV.leftAnchor, paddingLeft: 5, centerY: viewCatInTV.centerYAnchor, width: 12, height: 12)
  660. let imageText = UILabel()
  661. imageText.text = textCat
  662. viewCatInTV.addSubview(imageText)
  663. imageText.textColor = .white
  664. imageText.anchor(left: imageIcon.rightAnchor, paddingLeft: 3, centerY: viewCatInTV.centerYAnchor, height: 12)
  665. imageText.font = .systemFont(ofSize: 12)
  666. }
  667. }
  668. private func reloadAllData() {
  669. DispatchQueue.global().async { [self] in
  670. if waitingLoading {
  671. return
  672. }
  673. waitingLoading = true
  674. while loadingData {
  675. Thread.sleep(forTimeInterval: 0.5)
  676. }
  677. waitingLoading = false
  678. getData()
  679. }
  680. }
  681. @objc func onReloadTab(notification: NSNotification) {
  682. reloadAllData()
  683. }
  684. @objc func onReload(notification: NSNotification) {
  685. let data:[AnyHashable : Any] = notification.userInfo!
  686. if data["member"] as? String == User.getMyPin()! {
  687. reloadAllData()
  688. } else if data["state"] as? Int == 99 {
  689. reloadAllData()
  690. }
  691. }
  692. @objc func onReceiveMessage(notification: NSNotification) {
  693. reloadAllData()
  694. }
  695. @objc func onStatusChat(notification: NSNotification) {
  696. reloadAllData()
  697. }
  698. @objc func segmentChanged(sender: Any) {
  699. switch segment.selectedSegmentIndex {
  700. case 1:
  701. Utils.inTabChats = false
  702. // searchController.searchBar.placeholder = "Search groups name".localized()
  703. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search groups name".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  704. DispatchQueue.global().async {
  705. self.getOpenGroups(listGroups: self.groups, completion: { g in
  706. DispatchQueue.main.async {
  707. for og in g {
  708. if self.groups.first(where: { $0.id == og.id }) == nil {
  709. self.groups.append(og)
  710. }
  711. }
  712. self.groups.sort { (a, b) -> Bool in
  713. if Int(a.official) == 1 {
  714. return true
  715. } else if Int(b.official) == 1 {
  716. return false
  717. } else {
  718. return Int(a.official) ?? 0 > Int(b.official) ?? 0
  719. }
  720. }
  721. DispatchQueue.main.async {
  722. self.tableView.reloadData()
  723. }
  724. }
  725. })
  726. }
  727. default:
  728. Utils.inTabChats = true
  729. // searchController.searchBar.placeholder = "Search chats & messages".localized()
  730. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search chats & messages".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  731. }
  732. // filterContentForSearchText(searchController.searchBar.text!)
  733. filterContentForSearchText(self.textViewSearch.text ?? "")
  734. }
  735. // MARK: - Data source
  736. func getData() {
  737. getChats {
  738. self.getGroups { g1 in
  739. self.groupMap.removeAll()
  740. self.groups = g1
  741. self.groups.sort { (a, b) -> Bool in
  742. if Int(a.official) == 1 {
  743. return true
  744. } else if Int(b.official) == 1 {
  745. return false
  746. } else {
  747. return Int(a.official) ?? 0 > Int(b.official) ?? 0
  748. }
  749. }
  750. DispatchQueue.main.async {
  751. self.tableView.reloadData()
  752. self.loadingData = false
  753. }
  754. }
  755. }
  756. }
  757. func getChats(completion: @escaping ()->()) {
  758. DispatchQueue.global().async {
  759. self.chatGroupMaps.removeAll()
  760. let previousChat = self.chats
  761. let allChats = Chat.getData()
  762. var tempChats: [Chat] = []
  763. for singleChat in allChats {
  764. if !singleChat.groupId.isEmpty {
  765. let chatParentInPreviousChats = previousChat.first(where: { $0.isParent && $0.groupId == singleChat.groupId })
  766. if self.chatGroupMaps[singleChat.groupId] != nil {
  767. self.chatGroupMaps[singleChat.groupId]!.insert(singleChat, at: 0)
  768. if let parentChat = tempChats.first(where: { $0.groupId == singleChat.groupId && $0.isParent }) {
  769. let counterParent = parentChat.counter
  770. parentChat.counter = "\(Int(counterParent)! + Int(singleChat.counter)!)"
  771. }
  772. if let parentExist = chatParentInPreviousChats, parentExist.isSelected {
  773. if let indexParent = tempChats.firstIndex(where: { $0.isParent && $0.groupId == singleChat.groupId }){
  774. tempChats.insert(singleChat, at: indexParent + self.chatGroupMaps[singleChat.groupId]!.count)
  775. }
  776. }
  777. } else {
  778. self.chatGroupMaps[singleChat.groupId] = [singleChat]
  779. let parentChat = Chat(profile: singleChat.profile, groupName: singleChat.groupName, counter: singleChat.counter, groupId: singleChat.groupId)
  780. parentChat.isParent = true
  781. if let parentExist = chatParentInPreviousChats, parentExist.isSelected {
  782. parentChat.isSelected = true
  783. tempChats.append(parentChat)
  784. tempChats.append(singleChat)
  785. } else {
  786. tempChats.append(parentChat)
  787. }
  788. }
  789. } else {
  790. tempChats.append(singleChat)
  791. }
  792. }
  793. self.chats = tempChats
  794. completion()
  795. }
  796. }
  797. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  798. var data: [Group] = []
  799. 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 "
  800. if id.isEmpty {
  801. query += "g.parent = '\(parent)'"
  802. } else {
  803. query += "g.group_id = '\(id)'"
  804. }
  805. query += "order by 12 asc, 13 asc, 2 asc"
  806. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  807. while cursor.next() {
  808. let group = Group(
  809. id: cursor.string(forColumnIndex: 0) ?? "",
  810. name: cursor.string(forColumnIndex: 1) ?? "",
  811. profile: cursor.string(forColumnIndex: 2) ?? "",
  812. quote: cursor.string(forColumnIndex: 3) ?? "",
  813. by: cursor.string(forColumnIndex: 4) ?? "",
  814. date: cursor.string(forColumnIndex: 5) ?? "",
  815. parent: cursor.string(forColumnIndex: 6) ?? "",
  816. chatId: "",
  817. groupType: cursor.string(forColumnIndex: 7) ?? "",
  818. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  819. official: cursor.string(forColumnIndex: 9) ?? "",
  820. isEducation: cursor.string(forColumnIndex: 10) ?? "",
  821. level: cursor.string(forColumnIndex: 11) ?? "")
  822. if group.chatId.isEmpty {
  823. 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")
  824. group.childs.append(lounge)
  825. }
  826. if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  827. while topicCursor.next() {
  828. let topic = Group(id: group.id,
  829. name: topicCursor.string(forColumnIndex: 1) ?? "",
  830. profile: topicCursor.string(forColumnIndex: 2) ?? "",
  831. quote: group.quote,
  832. by: group.by,
  833. date: group.date,
  834. parent: group.id,
  835. chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  836. groupType: group.groupType,
  837. isOpen: group.isOpen,
  838. official: group.official,
  839. isEducation: group.isEducation,
  840. level: group.level != "-1" ? group.level : "2")
  841. group.childs.append(topic)
  842. }
  843. topicCursor.close()
  844. }
  845. if !group.id.isEmpty {
  846. // if group.official == "1" {
  847. // let idMe = User.getMyPin() as String?
  848. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  849. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  850. // cursorUser.close()
  851. // }
  852. // } else if group.official != "1"{
  853. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  854. // }
  855. group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  856. // group.childs = group.childs.sorted(by: { $0.name < $1.name })
  857. // let dataLounge = group.childs.filter({$0.name == "Lounge".localized()})
  858. // group.childs = group.childs.filter({ $0.name != "Lounge".localized() })
  859. // group.childs.insert(contentsOf: dataLounge, at: 0)
  860. }
  861. data.append(group)
  862. }
  863. cursor.close()
  864. }
  865. return data
  866. }
  867. private func getOpenGroups(listGroups: [Group], completion: @escaping ([Group]) -> ()) {
  868. while Nexilis.isProcessWriteSync {
  869. Thread.sleep(forTimeInterval: 0.5)
  870. }
  871. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getOpenGroups(p_account: "1,2,3,6,5,7", offset: "0", search: "")) {
  872. var dataGroups: [Group] = []
  873. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  874. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  875. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [[String: Any?]] {
  876. for dataJson in json {
  877. let group = Group(
  878. id: dataJson[CoreMessage_TMessageKey.GROUP_ID] as? String ?? "",
  879. name: dataJson[CoreMessage_TMessageKey.GROUP_NAME] as? String ?? "",
  880. profile: dataJson[CoreMessage_TMessageKey.THUMB_ID] as? String ?? "",
  881. quote: dataJson[CoreMessage_TMessageKey.QUOTE] as? String ?? "",
  882. by: dataJson[CoreMessage_TMessageKey.BLOCK] as? String ?? "",
  883. date: "",
  884. parent: "",
  885. chatId: "",
  886. groupType: "NOTJOINED",
  887. isOpen: dataJson[CoreMessage_TMessageKey.IS_OPEN] as? String ?? "",
  888. official: "0",
  889. isEducation: "")
  890. dataGroups.append(group)
  891. }
  892. }
  893. }
  894. completion(dataGroups)
  895. }
  896. }
  897. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  898. DispatchQueue.global().async {
  899. Database.shared.database?.inTransaction({ fmdb, rollback in
  900. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  901. })
  902. }
  903. }
  904. private func pullBuddy() {
  905. if let me = User.getMyPin() {
  906. DispatchQueue.global().async {
  907. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  908. }
  909. }
  910. }
  911. private func joinOpenGroup(groupId: String, flagMember: String = "0", completion: @escaping (Bool) -> ()) {
  912. DispatchQueue.global().async {
  913. var result: Bool = false
  914. let idMe = User.getMyPin() as String?
  915. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddGroupMember(p_group_id: groupId, p_member_pin: idMe!, p_position: "0")), response.isOk() {
  916. result = true
  917. }
  918. completion(result)
  919. }
  920. }
  921. @IBOutlet weak var backgroundImage: UIImageView!
  922. /*
  923. // MARK: - Navigation
  924. // In a storyboard-based application, you will often want to do a little preparation before navigation
  925. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  926. // Get the new view controller using segue.destination.
  927. // Pass the selected object to the new view controller.
  928. }
  929. */
  930. }
  931. // MARK: - Table view data source
  932. extension SecondTabViewController: UITableViewDelegate, UITableViewDataSource {
  933. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  934. if noData || (isFiltering && fillteredData.count == 0) {
  935. return
  936. }
  937. tableView.deselectRow(at: indexPath, animated: true)
  938. switch segment.selectedSegmentIndex {
  939. case 0:
  940. let data: Chat
  941. if isFiltering {
  942. data = fillteredData[indexPath.row] as! Chat
  943. } else {
  944. data = chats[indexPath.row]
  945. }
  946. if data.isParent {
  947. expandCollapseChats(tableView: tableView, indexPath: indexPath)
  948. return
  949. }
  950. if let chooser = isChooser {
  951. if data.pin == "-999"{
  952. return
  953. }
  954. chooser(data.messageScope, data.pin)
  955. dismiss(animated: true, completion: nil)
  956. return
  957. }
  958. if data.pin == "-997" {
  959. let smartChatVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "chatGptVC") as! ChatGPTBotView
  960. smartChatVC.hidesBottomBarWhenPushed = true
  961. smartChatVC.fromNotification = false
  962. navigationController?.show(smartChatVC, sender: nil)
  963. } else if data.messageScope == "3" {
  964. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  965. editorPersonalVC.hidesBottomBarWhenPushed = true
  966. editorPersonalVC.unique_l_pin = data.pin
  967. navigationController?.show(editorPersonalVC, sender: nil)
  968. } else {
  969. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  970. editorGroupVC.hidesBottomBarWhenPushed = true
  971. editorGroupVC.unique_l_pin = data.pin
  972. navigationController?.show(editorGroupVC, sender: nil)
  973. }
  974. case 1:
  975. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  976. default:
  977. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  978. }
  979. }
  980. func expandCollapseChats(tableView: UITableView, indexPath: IndexPath) {
  981. let data: Chat
  982. if isFiltering || selectedTag == UNREAD_TAG {
  983. data = fillteredData[indexPath.row] as! Chat
  984. } else {
  985. data = chats[indexPath.row]
  986. }
  987. data.isSelected = !data.isSelected
  988. if data.isSelected {
  989. for dataSubChat in self.chatGroupMaps[data.groupId]! {
  990. if var indexParent = chats.firstIndex(where: { $0.isParent && $0.groupId == data.groupId }) {
  991. if isFiltering || selectedTag == UNREAD_TAG {
  992. fillteredData.insert(dataSubChat, at: indexParent + 1)
  993. indexParent+=1
  994. } else {
  995. chats.insert(dataSubChat, at: indexParent + 1)
  996. indexParent+=1
  997. }
  998. }
  999. }
  1000. } else {
  1001. if isFiltering || selectedTag == UNREAD_TAG {
  1002. if var changedFillteredData = fillteredData as? [Chat] {
  1003. changedFillteredData.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1004. self.fillteredData = changedFillteredData
  1005. }
  1006. } else {
  1007. chats.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1008. }
  1009. }
  1010. tableView.reloadData()
  1011. }
  1012. func expandCollapseGroup(tableView: UITableView, indexPath: IndexPath) {
  1013. let group: Group
  1014. if isFiltering {
  1015. if indexPath.row == 0 {
  1016. group = fillteredData[indexPath.section] as! Group
  1017. } else {
  1018. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  1019. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  1020. } else {
  1021. return
  1022. }
  1023. }
  1024. } else {
  1025. if indexPath.row == 0 {
  1026. group = groups[indexPath.section]
  1027. } else {
  1028. group = groups[indexPath.section].childs[indexPath.row - 1]
  1029. }
  1030. }
  1031. if (checkOverrideAction(groupHolder: group)) {
  1032. return;
  1033. }
  1034. group.isSelected = !group.isSelected
  1035. if !group.isSelected{
  1036. var sects = 0
  1037. var sect = indexPath.section
  1038. var id = group.id
  1039. if let _ = groupMap[id] {
  1040. var loooop = true
  1041. repeat {
  1042. let c = sect + 1
  1043. if isFiltering {
  1044. if let o = self.fillteredData[c] as? Group {
  1045. if o.parent == id {
  1046. sects = sects + 1
  1047. sect = c
  1048. id = o.id
  1049. (self.fillteredData[c] as! Group).isSelected = false
  1050. self.groupMap.removeValue(forKey: (self.fillteredData[c] as! Group).id)
  1051. }
  1052. else {
  1053. loooop = false
  1054. }
  1055. }
  1056. }
  1057. else {
  1058. if c < self.groups.count && self.groups[c].parent == id {
  1059. sects = sects + 1
  1060. sect = c
  1061. id = self.groups[c].id
  1062. self.groups[c].isSelected = false
  1063. self.groupMap.removeValue(forKey: self.groups[c].id)
  1064. }
  1065. else {
  1066. loooop = false
  1067. }
  1068. }
  1069. } while(loooop)
  1070. }
  1071. for i in stride(from: sects, to: 0, by: -1){
  1072. if isFiltering {
  1073. self.fillteredData.remove(at: indexPath.section + i)
  1074. }
  1075. else {
  1076. self.groups.remove(at: indexPath.section + i)
  1077. }
  1078. }
  1079. groupMap.removeValue(forKey: group.id)
  1080. }
  1081. if group.groupType == "NOTJOINED" {
  1082. let alert = LibAlertController(title: "Do you want to join this group?".localized(), message: "Groups : \(group.name)\nMembers: \(group.by)".localized(), preferredStyle: .alert)
  1083. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  1084. alert.addAction(UIAlertAction(title: "Join".localized(), style: .default, handler: {(_) in
  1085. self.joinOpenGroup(groupId: group.id, completion: { result in
  1086. if result {
  1087. DispatchQueue.main.async {
  1088. self.groupMap.removeAll()
  1089. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  1090. editorGroupVC.hidesBottomBarWhenPushed = true
  1091. editorGroupVC.unique_l_pin = group.id
  1092. self.navigationController?.show(editorGroupVC, sender: nil)
  1093. }
  1094. }
  1095. })
  1096. }))
  1097. self.present(alert, animated: true, completion: nil)
  1098. return
  1099. }
  1100. if group.childs.count == 0 {
  1101. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1102. let idMe = User.getMyPin() as String?
  1103. 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() {
  1104. let groupId = group.chatId.isEmpty ? group.id : group.chatId
  1105. if let chooser = isChooser {
  1106. chooser("4", groupId)
  1107. dismiss(animated: true, completion: nil)
  1108. return
  1109. }
  1110. self.groupMap.removeAll()
  1111. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  1112. editorGroupVC.hidesBottomBarWhenPushed = true
  1113. editorGroupVC.unique_l_pin = groupId
  1114. navigationController?.show(editorGroupVC, sender: nil)
  1115. cursorMember.close()
  1116. } else {
  1117. var viewController = UIApplication.shared.windows.first!.rootViewController
  1118. if !(viewController is ViewController) {
  1119. viewController = self.parent
  1120. }
  1121. if let viewController = viewController as? ViewController {
  1122. viewController.view.makeToast("You are not a member of this group".localized(), duration: 3)
  1123. }
  1124. }
  1125. })
  1126. } else {
  1127. if indexPath.row == 0 {
  1128. tableView.reloadData()
  1129. } else {
  1130. getGroups(id: group.id) { g in
  1131. DispatchQueue.main.async {
  1132. if self.isFiltering {
  1133. if self.fillteredData[indexPath.section] is Group {
  1134. self.groupMap[(self.fillteredData[indexPath.section] as! Group).id] = 1
  1135. self.fillteredData.insert(contentsOf: g, at: indexPath.section + 1)
  1136. }
  1137. } else {
  1138. self.groupMap[self.groups[indexPath.section].id] = 1
  1139. self.groups.insert(contentsOf: g, at: indexPath.section + 1)
  1140. }
  1141. //print("groupMap: \(self.groupMap)")
  1142. tableView.reloadData()
  1143. self.expandCollapseGroup(tableView: tableView, indexPath: IndexPath(row: 0, section: indexPath.section + 1))
  1144. }
  1145. }
  1146. }
  1147. }
  1148. }
  1149. func checkOverrideAction(groupHolder: Group) -> Bool {
  1150. if groupHolder.isLounge {
  1151. return false
  1152. }
  1153. let groupId = groupHolder.chatId.isEmpty ? groupHolder.id : groupHolder.chatId
  1154. switch (groupId){
  1155. case "18d1c6cffb70215af7b49" //bpkh konsultasi
  1156. , "18d1c6e37a20215af7b49"
  1157. , "18d1c6f852d0215af7b49"
  1158. , "18d1c6ff83a0215af7b49"
  1159. , "18d1c705e970215af7b49"
  1160. , "18d30db3bde0230d00c15" //ina konsultasi bot
  1161. , "18d30e64ce30230d00c15"
  1162. , "18d30e9b6d80230d00c15"
  1163. , "18d30ee00610230d00c15"
  1164. , "18d30f02f850230d00c15":
  1165. APIS.openSmartChatbot();
  1166. return true;
  1167. case "18d30daa4540230d00c15" //ina cc
  1168. , "18d30e59a950230d00c15"
  1169. , "18d30e9292b0230d00c15"
  1170. , "18d30ed8e250230d00c15"
  1171. , "18d30efa66c0230d00c15"
  1172. , "18d35b220540215af7b49" //bpkhcc
  1173. , "18d35b2f5ee0215af7b49"
  1174. , "18d35b356530215af7b49"
  1175. , "18d35b411510215af7b49"
  1176. , "18d35b46ae90215af7b49":
  1177. APIS.openContactCenter();
  1178. return true;
  1179. case "18d1c6d9f330215af7b49": //bpkh haji
  1180. APIS.openUrl(url: Utils.decrypt(str: "6]tov!l_opgn=hgz?ykmgv?yoro3kt?uo>yoro3kt??@yvzzn"))
  1181. return true;
  1182. case "18d1c6eefd40215af7b49": //bpkh bpjs
  1183. APIS.openUrl(url: Utils.decrypt(str: "1>ojq`g@tkqc.cbu:tfhbq:tjmjyfo:pj/tjmjyfo::;tquui"))
  1184. return true;
  1185. case "18d30e711c20230d00c15": //ina bpjs
  1186. APIS.openUrl(url: Utils.decrypt(str: "6]tov!l_ypvh=hgz?ykmgv?yoro3kt?sui>ykrgyomojrkyz??@yvzzn"))
  1187. return true;
  1188. case "18d30e47ae60230d00c15": //ina KTP, KK, SKL
  1189. APIS.openUrl(url: Utils.decrypt(str: "1>ojq`g@qul.cbu:tfhbq:tjmjyfo:npd/tfmbtjhjemftu::;tquui"))
  1190. return true;
  1191. case "18d30eb2e910230d00c15": //SIM, SKKB, SKBN
  1192. APIS.openUrl(url: Utils.decrypt(str: "4[rmt}j]qmw;fex=wiket=wmpm1ir=qsg<wipewmkmhpiwx==>wtxxl"))
  1193. return true;
  1194. case "18da1c0200f0215af7b49": //BPKH index BMI
  1195. APIS.openUrl(url: Utils.decrypt(str: "4[rmt}j]mqf}1ihrm=mqf=wmpm1ir=sm<wmpm1ir==>wtxxl"))
  1196. return true;
  1197. default:
  1198. break;
  1199. }
  1200. return false
  1201. }
  1202. func numberOfSections(in tableView: UITableView) -> Int {
  1203. if isFiltering {
  1204. if segment.selectedSegmentIndex == 1 {
  1205. return fillteredData.count
  1206. }
  1207. return 1
  1208. } else {
  1209. if segment.selectedSegmentIndex == 1 {
  1210. return groups.count
  1211. }
  1212. return 1
  1213. }
  1214. }
  1215. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  1216. var value = 0
  1217. if isFiltering {
  1218. if segment.selectedSegmentIndex == 1, let groups = fillteredData as? [Group] {
  1219. let group = groups[section]
  1220. if group.isSelected {
  1221. if let _ = groupMap[group.id] {
  1222. value = 1
  1223. }
  1224. else {
  1225. value = group.childs.count + 1
  1226. }
  1227. } else {
  1228. value = 1
  1229. }
  1230. } else {
  1231. value = fillteredData.count
  1232. }
  1233. if value == 0 {
  1234. value = 1
  1235. tableView.separatorStyle = .none
  1236. } else {
  1237. tableView.separatorStyle = .singleLine
  1238. }
  1239. return value
  1240. }
  1241. switch segment.selectedSegmentIndex {
  1242. case 0:
  1243. value = chats.count
  1244. case 1:
  1245. let group = groups[section]
  1246. if group.isSelected {
  1247. if let _ = groupMap[group.id] {
  1248. value = 1
  1249. }
  1250. else {
  1251. value = group.childs.count + 1
  1252. }
  1253. } else {
  1254. value = 1
  1255. }
  1256. default:
  1257. value = chats.count
  1258. }
  1259. if value == 0 {
  1260. noData = true
  1261. value = 1
  1262. tableView.separatorStyle = .none
  1263. } else {
  1264. noData = false
  1265. tableView.separatorStyle = .singleLine
  1266. }
  1267. return value
  1268. }
  1269. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  1270. var cell: UITableViewCell!
  1271. switch segment.selectedSegmentIndex {
  1272. case 0:
  1273. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierChat", for: indexPath)
  1274. let content = cell.contentView
  1275. if content.subviews.count > 0 {
  1276. content.subviews.forEach { $0.removeFromSuperview() }
  1277. }
  1278. if noData || (isFiltering && fillteredData.count == 0) {
  1279. let labelNochat = UILabel()
  1280. labelNochat.text = isFiltering ? "No Result".localized() : loadingData ? "Loading Data...".localized() : "There are no conversations".localized()
  1281. labelNochat.font = .systemFont(ofSize: 13)
  1282. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1283. content.addSubview(labelNochat)
  1284. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  1285. cell.backgroundColor = .clear
  1286. cell.selectionStyle = .none
  1287. return cell
  1288. }
  1289. let data: Chat
  1290. if isFiltering {
  1291. data = fillteredData[indexPath.row] as! Chat
  1292. } else {
  1293. if chats.count == 0 || (indexPath.row > (chats.count - 1)) {
  1294. let labelNochat = UILabel()
  1295. labelNochat.text = loadingData ? "Loading Data...".localized() : "There are no conversations".localized()
  1296. labelNochat.font = .systemFont(ofSize: 13)
  1297. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1298. content.addSubview(labelNochat)
  1299. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  1300. cell.backgroundColor = .clear
  1301. cell.selectionStyle = .none
  1302. return cell
  1303. }
  1304. data = chats[indexPath.row]
  1305. }
  1306. if selectedTag != UNREAD_TAG && selectedTag != 0 {
  1307. let title = UILabel()
  1308. let subtitle = UILabel()
  1309. title.textColor = .black
  1310. subtitle.textColor = .gray
  1311. title.font = .systemFont(ofSize: 16, weight: .medium)
  1312. subtitle.font = .systemFont(ofSize: 14)
  1313. content.addSubview(title)
  1314. content.addSubview(subtitle)
  1315. title.anchor(top: content.topAnchor, left: content.leftAnchor, paddingTop: 10, paddingLeft: 20)
  1316. subtitle.anchor(top: title.bottomAnchor, left: content.leftAnchor, right: content.rightAnchor, paddingLeft: 20, paddingRight: 20)
  1317. subtitle.numberOfLines = 2
  1318. title.text = data.name
  1319. let imageArrowRight = UIImageView(image: UIImage(systemName: "chevron.right"))
  1320. content.addSubview(imageArrowRight)
  1321. imageArrowRight.tintColor = .gray
  1322. imageArrowRight.anchor(top: content.topAnchor, right: content.rightAnchor, paddingTop: 10, paddingRight: 20)
  1323. let timeView = UILabel()
  1324. content.addSubview(timeView)
  1325. timeView.anchor(top: content.topAnchor, right: imageArrowRight.leftAnchor, paddingTop: 10, paddingRight: 20)
  1326. timeView.textColor = .gray
  1327. timeView.font = UIFont.systemFont(ofSize: 16)
  1328. let date = Date(milliseconds: Int64(data.serverDate)!)
  1329. let calendar = Calendar.current
  1330. if (calendar.isDateInToday(date)) {
  1331. let formatter = DateFormatter()
  1332. formatter.dateFormat = "HH:mm"
  1333. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1334. timeView.text = formatter.string(from: date as Date)
  1335. } else {
  1336. let startOfNow = calendar.startOfDay(for: Date())
  1337. let startOfTimeStamp = calendar.startOfDay(for: date)
  1338. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  1339. let day = -(components.day!)
  1340. if day == 1 {
  1341. timeView.text = "Yesterday".localized()
  1342. } else {
  1343. if day < 7 {
  1344. let formatter = DateFormatter()
  1345. formatter.dateFormat = "EEEE"
  1346. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  1347. if lang == "id" {
  1348. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1349. }
  1350. timeView.text = formatter.string(from: date)
  1351. } else {
  1352. let formatter = DateFormatter()
  1353. formatter.dateFormat = "M/dd/yy"
  1354. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1355. let stringFormat = formatter.string(from: date as Date)
  1356. timeView.text = stringFormat
  1357. }
  1358. }
  1359. }
  1360. cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
  1361. let container = UIView()
  1362. content.addSubview(container)
  1363. container.anchor(top: subtitle.bottomAnchor, left: content.leftAnchor, right: content.rightAnchor, paddingTop: 5, paddingLeft: 20, paddingRight: 20, height: selectedTag == LINKS_TAG ? 75 : 60)
  1364. container.backgroundColor = .lightGray.withAlphaComponent(0.3)
  1365. container.layer.cornerRadius = 15
  1366. container.clipsToBounds = true
  1367. container.isUserInteractionEnabled = true
  1368. if selectedTag == DOCUMENTS_TAG {
  1369. subtitle.text = "📄 " + "Document".localized()
  1370. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 45)))
  1371. container.addSubview(imageFile)
  1372. imageFile.tintColor = .black
  1373. imageFile.anchor(top: container.topAnchor, left: container.leftAnchor, bottom: container.bottomAnchor, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, width: 45)
  1374. let nameFile = UILabel()
  1375. container.addSubview(nameFile)
  1376. nameFile.font = .systemFont(ofSize: 12, weight: .medium)
  1377. nameFile.textColor = .black
  1378. nameFile.numberOfLines = 2
  1379. nameFile.anchor(top: container.topAnchor, left: imageFile.rightAnchor, right: container.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingRight: 5)
  1380. nameFile.text = data.messageText.components(separatedBy: "|")[0]
  1381. let fileSub = UILabel()
  1382. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1383. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1384. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1385. let arrExtFile = (data.messageText.components(separatedBy: "|")[0]).split(separator: ".")
  1386. let finalExtFile = arrExtFile[arrExtFile.count - 1]
  1387. if let dirPath = paths.first {
  1388. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(data.file)
  1389. if FileManager.default.fileExists(atPath: fileURL.path) {
  1390. if let dataFile = try? Data(contentsOf: fileURL) {
  1391. var sizeOfFile = Int(dataFile.count / 1000000)
  1392. if (sizeOfFile < 1) {
  1393. sizeOfFile = Int(dataFile.count / 1000)
  1394. if (finalExtFile.count > 4) {
  1395. fileSub.text = "\(sizeOfFile) kB \u{2022} TXT"
  1396. }else {
  1397. fileSub.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  1398. }
  1399. } else {
  1400. if (finalExtFile.count > 4) {
  1401. fileSub.text = "\(sizeOfFile) MB \u{2022} TXT"
  1402. }else {
  1403. fileSub.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  1404. }
  1405. }
  1406. } else {
  1407. fileSub.text = ""
  1408. }
  1409. }
  1410. else if FileEncryption.shared.isSecureExists(filename: data.file) {
  1411. if let dataFile = try? FileEncryption.shared.readSecure(filename: data.file) {
  1412. var sizeOfFile = Int(dataFile.count / 1000000)
  1413. if (sizeOfFile < 1) {
  1414. sizeOfFile = Int(dataFile.count / 1000)
  1415. if (finalExtFile.count > 4) {
  1416. fileSub.text = "\(sizeOfFile) kB \u{2022} TXT"
  1417. }else {
  1418. fileSub.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  1419. }
  1420. } else {
  1421. if (finalExtFile.count > 4) {
  1422. fileSub.text = "\(sizeOfFile) MB \u{2022} TXT"
  1423. }else {
  1424. fileSub.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  1425. }
  1426. }
  1427. } else {
  1428. fileSub.text = ""
  1429. }
  1430. }
  1431. container.addSubview(fileSub)
  1432. fileSub.anchor(top: nameFile.bottomAnchor, left: imageFile.rightAnchor, bottom: container.bottomAnchor, paddingLeft: 10, paddingBottom: 5)
  1433. fileSub.font = .systemFont(ofSize: 10)
  1434. fileSub.textColor = .gray
  1435. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  1436. objectTap.file_id = data.file
  1437. container.addGestureRecognizer(objectTap)
  1438. }
  1439. } else if selectedTag == LINKS_TAG {
  1440. var text = ""
  1441. var txtData = data.messageText
  1442. if txtData.contains("■"){
  1443. txtData = txtData.components(separatedBy: "■")[0]
  1444. txtData = txtData.trimmingCharacters(in: .whitespacesAndNewlines)
  1445. }
  1446. let listTextSplitBreak = txtData.components(separatedBy: "\n")
  1447. let indexFirstLinkSplitBreak = listTextSplitBreak.firstIndex(where: { $0.contains("www.") || $0.contains("http://") || $0.contains("https://") })
  1448. if indexFirstLinkSplitBreak != nil {
  1449. let listTextSplitSpace = listTextSplitBreak[indexFirstLinkSplitBreak!].components(separatedBy: " ")
  1450. let indexFirstLinkSplitSpace = listTextSplitSpace.firstIndex(where: { ($0.starts(with: "www.") && $0.components(separatedBy: ".").count > 2) || ($0.starts(with: "http://") && $0.components(separatedBy: ".").count > 1) || ($0.starts(with: "https://") && $0.components(separatedBy: ".").count > 1) })
  1451. if indexFirstLinkSplitSpace != nil {
  1452. text = listTextSplitSpace[indexFirstLinkSplitSpace!]
  1453. }
  1454. }
  1455. var dataURL = ""
  1456. subtitle.text = txtData
  1457. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1458. do {
  1459. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(text)'"), cursor.next() {
  1460. if let data = cursor.string(forColumnIndex: 0) {
  1461. dataURL = data
  1462. }
  1463. cursor.close()
  1464. }
  1465. } catch {
  1466. rollback.pointee = true
  1467. print("Access database error: \(error.localizedDescription)")
  1468. }
  1469. })
  1470. var title = ""
  1471. var description = ""
  1472. var imageUrl: String?
  1473. var link = text
  1474. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  1475. objectTap.message_id = link
  1476. container.addGestureRecognizer(objectTap)
  1477. let imagePreview = UIImageView()
  1478. container.addSubview(imagePreview)
  1479. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  1480. imagePreview.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
  1481. imagePreview.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  1482. imagePreview.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
  1483. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  1484. imagePreview.image = UIImage(systemName: "link", withConfiguration: UIImage.SymbolConfiguration(pointSize: 45))
  1485. imagePreview.contentMode = .center
  1486. imagePreview.clipsToBounds = true
  1487. imagePreview.tintColor = .black
  1488. imagePreview.backgroundColor = .gray.withAlphaComponent(0.3)
  1489. let titlePreview = UILabel()
  1490. container.addSubview(titlePreview)
  1491. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  1492. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1493. titlePreview.topAnchor.constraint(equalTo: container.topAnchor, constant: 10.0).isActive = true
  1494. titlePreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  1495. titlePreview.text = title
  1496. titlePreview.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
  1497. titlePreview.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1498. let descPreview = UILabel()
  1499. container.addSubview(descPreview)
  1500. descPreview.translatesAutoresizingMaskIntoConstraints = false
  1501. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1502. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  1503. descPreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  1504. descPreview.text = description
  1505. descPreview.font = UIFont.systemFont(ofSize: 12.0)
  1506. descPreview.textColor = .gray
  1507. descPreview.numberOfLines = 1
  1508. let linkPreview = UILabel()
  1509. container.addSubview(linkPreview)
  1510. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  1511. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1512. linkPreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  1513. linkPreview.font = UIFont.systemFont(ofSize: 10.0)
  1514. linkPreview.textColor = .gray
  1515. linkPreview.numberOfLines = 1
  1516. if !dataURL.isEmpty {
  1517. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  1518. title = data["title"] as! String
  1519. description = data["description"] as! String
  1520. imageUrl = data["imageUrl"] as? String
  1521. link = data["link"] as! String
  1522. if imageUrl != nil {
  1523. imagePreview.loadImageAsync(with: imageUrl)
  1524. imagePreview.contentMode = .scaleToFill
  1525. imagePreview.clipsToBounds = true
  1526. }
  1527. titlePreview.text = title
  1528. descPreview.text = description
  1529. linkPreview.text = link
  1530. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  1531. }
  1532. } else {
  1533. linkPreview.text = link
  1534. linkPreview.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
  1535. }
  1536. } else if selectedTag == AUDIOS_TAG {
  1537. subtitle.text = "♫ " + "Audio".localized()
  1538. let imageAudio = UIImageView()
  1539. imageAudio.image = UIImage(systemName: "music.note", withConfiguration: UIImage.SymbolConfiguration(pointSize: 35))
  1540. container.addSubview(imageAudio)
  1541. imageAudio.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  1542. imageAudio.tintColor = .black
  1543. let nameAudio = UILabel()
  1544. container.addSubview(nameAudio)
  1545. nameAudio.anchor(left: imageAudio.rightAnchor, right: container.rightAnchor, paddingLeft: 10, paddingRight: 10, centerY: container.centerYAnchor)
  1546. nameAudio.numberOfLines = 2
  1547. nameAudio.text = data.messageText.components(separatedBy: "|")[0]
  1548. nameAudio.font = .systemFont(ofSize: 16, weight: .medium)
  1549. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1550. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1551. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1552. if let dirPath = paths.first {
  1553. let audioURL = URL(fileURLWithPath: dirPath).appendingPathComponent(data.audio)
  1554. if !FileManager.default.fileExists(atPath: audioURL.path) && !FileEncryption.shared.isSecureExists(filename: data.audio) {
  1555. Download().startHTTP(forKey: data.audio, isImage: false) { (name, progress) in
  1556. guard progress == 100 else {
  1557. return
  1558. }
  1559. tableView.reloadRows(at: [indexPath], with: .none)
  1560. }
  1561. } else {
  1562. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  1563. objectTap.audio_id = data.audio
  1564. container.addGestureRecognizer(objectTap)
  1565. }
  1566. }
  1567. }
  1568. return cell
  1569. }
  1570. let imageView = UIImageView()
  1571. content.addSubview(imageView)
  1572. imageView.translatesAutoresizingMaskIntoConstraints = false
  1573. NSLayoutConstraint.activate([
  1574. imageView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  1575. imageView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -10.0),
  1576. imageView.widthAnchor.constraint(equalToConstant: 55.0),
  1577. imageView.heightAnchor.constraint(equalToConstant: 55.0)
  1578. ])
  1579. var leadingAnchor = imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 10.0)
  1580. if data.profile.isEmpty && data.pin != "-999" && data.pin != "-997" {
  1581. if data.messageScope == "3" {
  1582. imageView.image = UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1583. } else {
  1584. imageView.image = UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1585. }
  1586. } else if data.pin == "-997" {
  1587. imageView.frame = CGRect(x: 0, y: 0, width: 55.0, height: 55.0)
  1588. imageView.circle()
  1589. if let urlGif = Bundle.resourceBundle(for: Nexilis.self).url(forResource: "pb_gpt_bot", withExtension: "gif") {
  1590. imageView.sd_setImage(with: urlGif) { (image, error, cacheType, imageURL) in
  1591. if error == nil {
  1592. imageView.animationImages = image?.images
  1593. imageView.animationDuration = image?.duration ?? 0.0
  1594. imageView.animationRepeatCount = 0
  1595. imageView.startAnimating()
  1596. }
  1597. }
  1598. } else if let urlGif = Bundle.resourcesMediaBundle(for: Nexilis.self).url(forResource: "pb_gpt_bot", withExtension: "gif") {
  1599. imageView.sd_setImage(with: urlGif) { (image, error, cacheType, imageURL) in
  1600. if error == nil {
  1601. imageView.animationImages = image?.images
  1602. imageView.animationDuration = image?.duration ?? 0.0
  1603. imageView.animationRepeatCount = 0
  1604. imageView.startAnimating()
  1605. }
  1606. }
  1607. }
  1608. } else {
  1609. if !Utils.getIconDock().isEmpty && data.profile.isEmpty {
  1610. let urlString = Utils.getUrlDock()!
  1611. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  1612. let imageData = cachedImage
  1613. imageView.image = imageData
  1614. } else {
  1615. DispatchQueue.global().async{
  1616. Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
  1617. guard let data = data, error == nil else { return }
  1618. DispatchQueue.main.async() {
  1619. if UIImage(data: data) != nil {
  1620. let imageData = UIImage(data: data)!
  1621. imageView.image = imageData
  1622. ImageCache.shared.save(image: imageData, forKey: urlString)
  1623. }
  1624. }
  1625. }
  1626. }
  1627. }
  1628. } else {
  1629. if data.messageScope == "3" || data.isParent || data.pin == "-999" {
  1630. 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
  1631. imageView.image = image
  1632. })
  1633. } else {
  1634. leadingAnchor = imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 40.0)
  1635. let image = UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1636. imageView.image = image
  1637. }
  1638. }
  1639. }
  1640. leadingAnchor.isActive = true
  1641. let titleView = UILabel()
  1642. content.addSubview(titleView)
  1643. titleView.translatesAutoresizingMaskIntoConstraints = false
  1644. NSLayoutConstraint.activate([
  1645. titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  1646. titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  1647. ])
  1648. titleView.font = UIFont.systemFont(ofSize: 14, weight: .medium)
  1649. let timeView = UILabel()
  1650. let viewCounter = UIView()
  1651. if data.counter != "0" {
  1652. timeView.textColor = .systemRed
  1653. content.addSubview(viewCounter)
  1654. viewCounter.translatesAutoresizingMaskIntoConstraints = false
  1655. NSLayoutConstraint.activate([
  1656. viewCounter.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
  1657. viewCounter.heightAnchor.constraint(equalToConstant: 20)
  1658. ])
  1659. viewCounter.backgroundColor = .systemRed
  1660. viewCounter.layer.cornerRadius = 10
  1661. viewCounter.clipsToBounds = true
  1662. viewCounter.layer.borderWidth = 0.5
  1663. viewCounter.layer.borderColor = UIColor.secondaryColor.cgColor
  1664. let labelCounter = UILabel()
  1665. viewCounter.addSubview(labelCounter)
  1666. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  1667. NSLayoutConstraint.activate([
  1668. labelCounter.centerYAnchor.constraint(equalTo: viewCounter.centerYAnchor),
  1669. labelCounter.leadingAnchor.constraint(equalTo: viewCounter.leadingAnchor, constant: 2),
  1670. labelCounter.trailingAnchor.constraint(equalTo: viewCounter.trailingAnchor, constant: -2),
  1671. ])
  1672. labelCounter.font = UIFont.systemFont(ofSize: 11)
  1673. if Int(data.counter)! > 99 {
  1674. labelCounter.text = "99+"
  1675. } else {
  1676. labelCounter.text = data.counter
  1677. }
  1678. labelCounter.textColor = .secondaryColor
  1679. labelCounter.textAlignment = .center
  1680. }
  1681. if !data.isParent {
  1682. titleView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0).isActive = true
  1683. titleView.text = data.name
  1684. content.addSubview(timeView)
  1685. timeView.translatesAutoresizingMaskIntoConstraints = false
  1686. NSLayoutConstraint.activate([
  1687. timeView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  1688. timeView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20.0),
  1689. ])
  1690. timeView.textColor = .gray
  1691. timeView.font = UIFont.systemFont(ofSize: 14)
  1692. let date = Date(milliseconds: Int64(data.serverDate) ?? 0)
  1693. let calendar = Calendar.current
  1694. if (calendar.isDateInToday(date)) {
  1695. let formatter = DateFormatter()
  1696. formatter.dateFormat = "HH:mm"
  1697. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1698. timeView.text = formatter.string(from: date as Date)
  1699. } else {
  1700. let startOfNow = calendar.startOfDay(for: Date())
  1701. let startOfTimeStamp = calendar.startOfDay(for: date)
  1702. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  1703. let day = -(components.day!)
  1704. if day == 1 {
  1705. timeView.text = "Yesterday".localized()
  1706. } else {
  1707. if day < 7 {
  1708. let formatter = DateFormatter()
  1709. formatter.dateFormat = "EEEE"
  1710. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  1711. if lang == "id" {
  1712. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1713. }
  1714. timeView.text = formatter.string(from: date)
  1715. } else {
  1716. let formatter = DateFormatter()
  1717. formatter.dateFormat = "M/dd/yy"
  1718. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1719. let stringFormat = formatter.string(from: date as Date)
  1720. timeView.text = stringFormat
  1721. }
  1722. }
  1723. }
  1724. let messageView = UILabel()
  1725. content.addSubview(messageView)
  1726. messageView.translatesAutoresizingMaskIntoConstraints = false
  1727. NSLayoutConstraint.activate([
  1728. messageView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  1729. messageView.topAnchor.constraint(equalTo: titleView.bottomAnchor),
  1730. messageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  1731. ])
  1732. messageView.textColor = .gray
  1733. if data.messageText.contains("■") {
  1734. data.messageText = data.messageText.components(separatedBy: "■")[0]
  1735. data.messageText = data.messageText.trimmingCharacters(in: .whitespacesAndNewlines)
  1736. }
  1737. let text = Utils.previewMessageText(chat: data)
  1738. let idMe = User.getMyPin() as String?
  1739. if let attributeText = text as? NSMutableAttributedString {
  1740. let stringMessage = NSMutableAttributedString(string: "")
  1741. if data.fpin == idMe {
  1742. if data.lock == "1" {
  1743. if data.messageScope == "4" {
  1744. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
  1745. }
  1746. stringMessage.append(("🚫 _"+"You were deleted this message".localized()+"_").richText())
  1747. } else {
  1748. let imageStatus = NSTextAttachment()
  1749. let status = getRealStatus(messageId: data.messageId)
  1750. if status == "0" {
  1751. imageStatus.image = UIImage(systemName: "xmark.circle")!.withTintColor(UIColor.red, renderingMode: .alwaysOriginal)
  1752. } else if status == "1" {
  1753. imageStatus.image = UIImage(systemName: "clock.arrow.circlepath")!.withTintColor(UIColor.lightGray, renderingMode: .alwaysOriginal)
  1754. } else if status == "2" {
  1755. imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1756. } else if (status == "3") {
  1757. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1758. } else if (status == "8") {
  1759. imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1760. } else {
  1761. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  1762. }
  1763. imageStatus.bounds = CGRect(x: 0, y: -5, width: 15, height: 15)
  1764. let imageStatusString = NSAttributedString(attachment: imageStatus)
  1765. stringMessage.append(imageStatusString)
  1766. stringMessage.append(NSAttributedString(string: " "))
  1767. if data.messageScope == "4" {
  1768. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
  1769. }
  1770. stringMessage.append(attributeText)
  1771. }
  1772. } else {
  1773. if data.messageScope == "4" {
  1774. var fullname = User.getData(pin: data.fpin, lPin: data.pin)!.fullName
  1775. let components = fullname.split(separator: " ")
  1776. if components.count >= 2 {
  1777. fullname = components.prefix(2).joined(separator: " ")
  1778. }
  1779. stringMessage.append(NSAttributedString(string: fullname + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .medium)]))
  1780. }
  1781. if data.lock == "1" {
  1782. stringMessage.append(("🚫 _"+"This message was deleted".localized()+"_").richText())
  1783. } else {
  1784. stringMessage.append(attributeText)
  1785. }
  1786. }
  1787. messageView.attributedText = stringMessage
  1788. }
  1789. messageView.numberOfLines = 2
  1790. if data.counter != "0" {
  1791. viewCounter.topAnchor.constraint(equalTo: timeView.bottomAnchor, constant: 5.0).isActive = true
  1792. viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20).isActive = true
  1793. }
  1794. } else {
  1795. titleView.centerYAnchor.constraint(equalTo: content.centerYAnchor).isActive = true
  1796. titleView.text = data.groupName
  1797. let iconName = (data.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  1798. let imageView = UIImageView(image: UIImage(systemName: iconName))
  1799. imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1800. content.addSubview(imageView)
  1801. imageView.translatesAutoresizingMaskIntoConstraints = false
  1802. NSLayoutConstraint.activate([
  1803. imageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
  1804. imageView.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  1805. imageView.widthAnchor.constraint(equalToConstant: 20),
  1806. imageView.heightAnchor.constraint(equalToConstant: 20)
  1807. ])
  1808. if data.counter != "0" {
  1809. viewCounter.trailingAnchor.constraint(equalTo: imageView.leadingAnchor, constant: -5).isActive = true
  1810. viewCounter.centerYAnchor.constraint(equalTo: content.centerYAnchor).isActive = true
  1811. }
  1812. }
  1813. case 1:
  1814. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  1815. var content = cell.defaultContentConfiguration()
  1816. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  1817. let group: Group
  1818. if isFiltering {
  1819. if indexPath.row == 0 {
  1820. group = fillteredData[indexPath.section] as! Group
  1821. } else {
  1822. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  1823. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  1824. } else {
  1825. return cell
  1826. }
  1827. }
  1828. } else {
  1829. if indexPath.row == 0 {
  1830. if indexPath.section > (groups.count - 1) {
  1831. return cell
  1832. }
  1833. group = groups[indexPath.section]
  1834. } else {
  1835. group = groups[indexPath.section].childs[indexPath.row - 1]
  1836. }
  1837. }
  1838. if group.official == "1" && group.parent == "" {
  1839. 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)
  1840. }
  1841. else if group.isOpen == "1" && group.parent == "" {
  1842. if self.traitCollection.userInterfaceStyle == .dark {
  1843. content.attributedText = self.set(image: UIImage(systemName: "globe")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1844. } else {
  1845. content.attributedText = self.set(image: UIImage(systemName: "globe")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1846. }
  1847. } else if group.parent == "" {
  1848. if self.traitCollection.userInterfaceStyle == .dark {
  1849. 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)
  1850. } else {
  1851. content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1852. }
  1853. } else {
  1854. content.text = group.name
  1855. }
  1856. if group.childs.count > 0 {
  1857. let iconName = (group.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  1858. let imageView = UIImageView(image: UIImage(systemName: iconName))
  1859. imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1860. cell.accessoryView = imageView
  1861. }
  1862. else {
  1863. cell.accessoryView = nil
  1864. cell.accessoryType = .none
  1865. }
  1866. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  1867. 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
  1868. content.image = image
  1869. }
  1870. cell.contentConfiguration = content
  1871. if !group.level.isEmpty {
  1872. if group.level != "-1" && Int(group.level)! < 7 {
  1873. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * Int(group.level)!), bottom: 0.0, right: 0)
  1874. } else if Int(group.level)! > 6 {
  1875. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * (Int(group.level)! - 6)), bottom: 0.0, right: 0)
  1876. }
  1877. }
  1878. default:
  1879. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  1880. var content = cell.defaultContentConfiguration()
  1881. content.text = ""
  1882. cell.contentConfiguration = content
  1883. }
  1884. cell.backgroundColor = .clear
  1885. cell.separatorInset = UIEdgeInsets(top: 0, left: 60.0, bottom: 0, right: 0)
  1886. return cell
  1887. }
  1888. @objc func onContSearch(_ sender: ObjectGesture) {
  1889. if selectedTag == PHOTOS_TAG {
  1890. } else if selectedTag == VIDEOS_TAG {
  1891. } else if selectedTag == DOCUMENTS_TAG {
  1892. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1893. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1894. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1895. if let dirPath = paths.first {
  1896. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  1897. if FileManager.default.fileExists(atPath: fileURL.path) {
  1898. self.previewItem = fileURL as NSURL
  1899. let previewController = QLPreviewController()
  1900. let rightBarButton = UIBarButtonItem()
  1901. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1902. previewController.dataSource = self
  1903. previewController.modalPresentationStyle = .custom
  1904. self.present(previewController, animated: true)
  1905. } else if FileEncryption.shared.isSecureExists(filename: sender.file_id) {
  1906. do {
  1907. if let docData = try FileEncryption.shared.readSecure(filename: sender.file_id) {
  1908. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  1909. let tempPath = cachesDirectory.appendingPathComponent(sender.file_id)
  1910. try docData.write(to: tempPath)
  1911. self.previewItem = tempPath as NSURL
  1912. let previewController = QLPreviewController()
  1913. let rightBarButton = UIBarButtonItem()
  1914. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1915. previewController.dataSource = self
  1916. previewController.modalPresentationStyle = .custom
  1917. self.present(previewController,animated: true)
  1918. }
  1919. }
  1920. catch {
  1921. }
  1922. }
  1923. }
  1924. } else if selectedTag == LINKS_TAG {
  1925. var stringURl = sender.message_id
  1926. if stringURl.lowercased().starts(with: "www.") {
  1927. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  1928. }
  1929. guard let url = URL(string: stringURl) else { return }
  1930. UIApplication.shared.open(url)
  1931. } else if selectedTag == AUDIOS_TAG {
  1932. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1933. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1934. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1935. if let dirPath = paths.first {
  1936. let audioURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.audio_id)
  1937. if FileManager.default.fileExists(atPath: audioURL.path) {
  1938. do {
  1939. if audioPlayer == nil || audioPlayer?.url != audioURL {
  1940. audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
  1941. audioPlayer?.prepareToPlay()
  1942. audioPlayer?.play()
  1943. } else if audioPlayer!.isPlaying {
  1944. audioPlayer?.pause()
  1945. } else {
  1946. audioPlayer?.play()
  1947. }
  1948. } catch {
  1949. }
  1950. } else if FileEncryption.shared.isSecureExists(filename: sender.audio_id) {
  1951. do {
  1952. if let audioData = try FileEncryption.shared.readSecure(filename: sender.audio_id) {
  1953. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  1954. let tempPath = cachesDirectory.appendingPathComponent(sender.audio_id)
  1955. try audioData.write(to: tempPath)
  1956. if audioPlayer == nil || audioPlayer?.url != tempPath {
  1957. audioPlayer = try AVAudioPlayer(contentsOf: tempPath)
  1958. audioPlayer?.prepareToPlay()
  1959. audioPlayer?.play()
  1960. } else if audioPlayer!.isPlaying {
  1961. audioPlayer?.pause()
  1962. } else {
  1963. audioPlayer?.play()
  1964. }
  1965. }
  1966. } catch {
  1967. }
  1968. }
  1969. }
  1970. }
  1971. }
  1972. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  1973. if fillteredData.count > 0 && selectedTag != UNREAD_TAG && selectedTag != 0 {
  1974. if selectedTag == LINKS_TAG {
  1975. return 160.0
  1976. }
  1977. return 130.0
  1978. }
  1979. return 75.0
  1980. }
  1981. private func getRealStatus(messageId: String) -> String {
  1982. var status = "1"
  1983. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1984. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
  1985. var listStatus: [Int] = []
  1986. while cursorStatus.next() {
  1987. listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
  1988. }
  1989. cursorStatus.close()
  1990. status = "\(listStatus.min() ?? 2)"
  1991. }
  1992. })
  1993. return status
  1994. }
  1995. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1996. return fillteredData.count
  1997. }
  1998. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1999. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath)
  2000. if cell.contentView.subviews.count > 0 {
  2001. cell.contentView.subviews.forEach { $0.removeFromSuperview() }
  2002. }
  2003. let data = fillteredData[indexPath.row] as! Chat
  2004. let thumb = data.thumb
  2005. let imgData = data.image
  2006. let vidData = data.video
  2007. let gifData = data.gif
  2008. let image = UIImageView()
  2009. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2010. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2011. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2012. if let dirPath = paths.first {
  2013. if selectedTag == GIFS_TAG {
  2014. let gifURL = URL(fileURLWithPath: dirPath).appendingPathComponent(gifData)
  2015. if !FileManager.default.fileExists(atPath: gifURL.path) && !FileEncryption.shared.isSecureExists(filename: gifData) {
  2016. Download().startHTTP(forKey: gifData, isImage: false) { (name, progress) in
  2017. guard progress == 100 else {
  2018. return
  2019. }
  2020. collectionView.reloadItems(at: [indexPath])
  2021. }
  2022. } else {
  2023. let imageGif = SDAnimatedImageView()
  2024. cell.contentView.addSubview(imageGif)
  2025. imageGif.contentMode = .scaleAspectFill
  2026. imageGif.clipsToBounds = true
  2027. imageGif.translatesAutoresizingMaskIntoConstraints = false
  2028. imageGif.anchor(top: cell.contentView.topAnchor, left: cell.contentView.leftAnchor, bottom: cell.contentView.bottomAnchor, right: cell.contentView.rightAnchor)
  2029. if FileManager.default.fileExists(atPath: gifURL.path) {
  2030. imageGif.image = SDAnimatedImage(contentsOfFile: gifURL.path)
  2031. // imageGif.shouldCustomLoopCount = true
  2032. // imageGif.animationRepeatCount = 4
  2033. } else if FileEncryption.shared.isSecureExists(filename: gifData){
  2034. do {
  2035. let data = try FileEncryption.shared.readSecure(filename: gifData)
  2036. if let imageData = SDAnimatedImage(data: data!) {
  2037. imageGif.image = imageData
  2038. // imageGif.shouldCustomLoopCount = true
  2039. // imageGif.animationRepeatCount = 4
  2040. }
  2041. }
  2042. catch {
  2043. print("Error reading secure file")
  2044. }
  2045. }
  2046. }
  2047. return cell
  2048. }
  2049. cell.contentView.addSubview(image)
  2050. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb)
  2051. let imageT : UIImage? = {
  2052. if let img = Nexilis.imageCache.object(forKey: thumb as NSString) {
  2053. return img
  2054. }
  2055. else if let img = UIImage(contentsOfFile: thumbURL.path)?.resize(target: CGSize(width: 500, height: 500)) {
  2056. Nexilis.imageCache.setObject(img, forKey: thumb as NSString)
  2057. return img
  2058. }
  2059. return nil
  2060. }()
  2061. if imageT != nil {
  2062. image.image = imageT
  2063. }
  2064. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imgData)
  2065. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(vidData)
  2066. if (!FileManager.default.fileExists(atPath: imageURL.path) && !FileEncryption.shared.isSecureExists(filename: imageURL.lastPathComponent)) || (!FileManager.default.fileExists(atPath: videoURL.path) && !FileEncryption.shared.isSecureExists(filename: videoURL.lastPathComponent)) {
  2067. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  2068. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  2069. blurEffectView.frame = CGRect(x: 0, y: 0, width: image.frame.size.width, height: image.frame.size.height)
  2070. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  2071. image.addSubview(blurEffectView)
  2072. if !imgData.isEmpty {
  2073. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
  2074. image.addSubview(imageDownload)
  2075. imageDownload.tintColor = .black.withAlphaComponent(0.3)
  2076. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  2077. imageDownload.centerXAnchor.constraint(equalTo: image.centerXAnchor).isActive = true
  2078. imageDownload.centerYAnchor.constraint(equalTo: image.centerYAnchor).isActive = true
  2079. }
  2080. }
  2081. if (!vidData.isEmpty) {
  2082. let imagePlay = UIImageView(image: UIImage(systemName: "play.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .bold, scale: .default))?.imageWithInsets(insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))?.withTintColor(.white))
  2083. imagePlay.circle()
  2084. image.addSubview(imagePlay)
  2085. imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
  2086. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2087. imagePlay.centerXAnchor.constraint(equalTo: image.centerXAnchor).isActive = true
  2088. imagePlay.centerYAnchor.constraint(equalTo: image.centerYAnchor).isActive = true
  2089. }
  2090. }
  2091. image.contentMode = .scaleAspectFill
  2092. image.clipsToBounds = true
  2093. image.anchor(top: cell.contentView.topAnchor, left: cell.contentView.leftAnchor, bottom: cell.contentView.bottomAnchor, right: cell.contentView.rightAnchor)
  2094. return cell
  2095. }
  2096. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  2097. let data = fillteredData[indexPath.row] as! Chat
  2098. let imgData = data.image
  2099. let vidData = data.video
  2100. let gifData = data.gif
  2101. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2102. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2103. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2104. if let dirPath = paths.first {
  2105. if selectedTag == PHOTOS_TAG {
  2106. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imgData)
  2107. if FileManager.default.fileExists(atPath: imageURL.path) {
  2108. let image = UIImage(contentsOfFile: imageURL.path) ?? UIImage()
  2109. APIS.openImageNexilis(image: image)
  2110. } else if FileEncryption.shared.isSecureExists(filename: imgData) {
  2111. do {
  2112. let data = try FileEncryption.shared.readSecure(filename: imgData)
  2113. let image = UIImage(data: data!) ?? UIImage()
  2114. APIS.openImageNexilis(image: image)
  2115. }
  2116. catch {
  2117. }
  2118. } else {
  2119. Download().startHTTP(forKey: imgData) { (name, progress) in
  2120. guard progress == 100 else {
  2121. return
  2122. }
  2123. DispatchQueue.main.async {
  2124. collectionView.reloadItems(at: [indexPath])
  2125. }
  2126. }
  2127. }
  2128. } else if selectedTag == VIDEOS_TAG {
  2129. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(vidData)
  2130. if FileManager.default.fileExists(atPath: videoURL.path) {
  2131. APIS.openVideoNexilis(videoURL: videoURL)
  2132. } else if FileEncryption.shared.isSecureExists(filename: vidData) {
  2133. do {
  2134. if let secureData = try FileEncryption.shared.readSecure(filename: vidData) {
  2135. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  2136. let tempPath = cachesDirectory.appendingPathComponent(vidData)
  2137. try secureData.write(to: tempPath)
  2138. APIS.openVideoNexilis(videoURL: tempPath)
  2139. }
  2140. } catch {
  2141. }
  2142. } else {
  2143. Download().startHTTP(forKey: vidData, isImage: false) { (name, progress) in
  2144. guard progress == 100 else {
  2145. return
  2146. }
  2147. DispatchQueue.main.async {
  2148. collectionView.reloadItems(at: [indexPath])
  2149. }
  2150. }
  2151. }
  2152. } else {
  2153. let gifURL = URL(fileURLWithPath: dirPath).appendingPathComponent(gifData)
  2154. if FileManager.default.fileExists(atPath: gifURL.path) {
  2155. do {
  2156. let data = try Data(contentsOf: gifURL)
  2157. APIS.openImageNexilis(image: UIImage(), data: data, isGIF: true)
  2158. } catch {
  2159. }
  2160. } else if FileEncryption.shared.isSecureExists(filename: gifData) {
  2161. do {
  2162. if let secureData = try FileEncryption.shared.readSecure(filename: gifData) {
  2163. APIS.openImageNexilis(image: UIImage(), data: secureData, isGIF: true)
  2164. }
  2165. } catch {
  2166. }
  2167. }
  2168. }
  2169. }
  2170. }
  2171. func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  2172. return self.previewItem != nil ? 1 : 0
  2173. }
  2174. func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> any QLPreviewItem {
  2175. return self.previewItem!
  2176. }
  2177. }
  2178. extension SecondTabViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  2179. func updateSearchResults(for searchController: UISearchController) {
  2180. filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
  2181. }
  2182. func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
  2183. recordAudio()
  2184. }
  2185. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
  2186. let attachment = NSTextAttachment()
  2187. attachment.image = image
  2188. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  2189. let attachmentStr = NSAttributedString(attachment: attachment)
  2190. let mutableAttributedString = NSMutableAttributedString()
  2191. mutableAttributedString.append(attachmentStr)
  2192. let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
  2193. let textString = NSAttributedString(string: text, attributes: attributedStringColor)
  2194. mutableAttributedString.append(textString)
  2195. return mutableAttributedString
  2196. }
  2197. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  2198. searchBar.showsCancelButton = true
  2199. let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
  2200. cBtn.setTitle("Cancel".localized(), for: .normal)
  2201. }
  2202. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  2203. searchBar.showsCancelButton = false
  2204. }
  2205. }
  2206. extension SecondTabViewController: SFSpeechRecognizerDelegate {
  2207. func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
  2208. if available {
  2209. self.isAllowSpeech = true
  2210. } else {
  2211. self.isAllowSpeech = false
  2212. }
  2213. }
  2214. }