SecondTabViewController.swift 128 KB

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