SecondTabViewController.swift 144 KB

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