SecondTabViewController.swift 126 KB

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