SecondTabViewController.swift 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  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. if segment.selectedSegmentIndex == 0 {
  545. Utils.inTabChats = true
  546. }
  547. }
  548. func textFieldDidChangeSelection(_ textField: UITextField) {
  549. if textField == textViewSearch {
  550. var textSerch = textField.text ?? ""
  551. textSerch = textSerch.trimmingCharacters(in: .whitespacesAndNewlines)
  552. if !textSerch.isEmpty && buttonImageClearSearch.isHidden {
  553. buttonImageClearSearch.isHidden = false
  554. } else if textSerch.isEmpty && !buttonImageClearSearch.isHidden {
  555. buttonImageClearSearch.isHidden = true
  556. }
  557. if textField.text?.count == 1 && leftTVSearch.constant != 20 {
  558. selectedTag = 0
  559. if gridImage != nil && gridImage.isDescendant(of: self.view) {
  560. gridImage.removeFromSuperview()
  561. tableView.isHidden = false
  562. }
  563. textField.text = ""
  564. viewCatInTV.removeFromSuperview()
  565. leftTVSearch.constant = 20
  566. }
  567. filterContentForSearchText(textSerch)
  568. }
  569. if viewCatInTV != nil && viewCatInTV.isDescendant(of: imageViewSearch) {
  570. viewCategorySearch.isHidden = true
  571. heightToolbar.constant = 45
  572. } else if (viewCatInTV == nil || !viewCatInTV.isDescendant(of: imageViewSearch)) && segment.selectedSegmentIndex == 0 {
  573. viewCategorySearch.isHidden = false
  574. heightToolbar.constant = 85
  575. }
  576. }
  577. func textFieldDidBeginEditing(_ textField: UITextField) {
  578. if textField == textViewSearch {
  579. if segment.selectedSegmentIndex == 0 && (viewCatInTV == nil || !viewCatInTV.isDescendant(of: imageViewSearch)) {
  580. heightToolbar.constant = 85
  581. viewCategorySearch.isHidden = false
  582. buttonImageVoiceSb.isHidden = false
  583. }
  584. }
  585. }
  586. func textFieldDidEndEditing(_ textField: UITextField) {
  587. if textField == textViewSearch {
  588. if let text = textField.text {
  589. if text.isEmpty {
  590. viewCategorySearch.isHidden = true
  591. buttonImageVoiceSb.isHidden = true
  592. heightToolbar.constant = 45
  593. }
  594. }
  595. }
  596. }
  597. override func viewWillDisappear(_ animated: Bool) {
  598. tabBarController?.navigationItem.leftBarButtonItem = nil
  599. tabBarController?.navigationItem.searchController = nil
  600. tabBarController?.navigationItem.rightBarButtonItem = nil
  601. tabBarController?.navigationItem.rightBarButtonItems = nil
  602. tabBarController?.navigationItem.titleView = nil
  603. Utils.inTabChats = false
  604. if ViewController.isExpandButton {
  605. ViewController.expandButton()
  606. }
  607. }
  608. @objc func settingTapped() {
  609. // imageVoiceSb.isHidden = !imageVoiceSb.isHidden
  610. // imageNewChatSb.isHidden = !imageNewChatSb.isHidden
  611. startConversation()
  612. }
  613. @objc func onTapCategory(_ sender: UITapGestureRecognizer) {
  614. if let tappedView = sender.view {
  615. if viewCatInTV != nil && viewCatInTV.isDescendant(of: imageViewSearch) {
  616. viewCatInTV.removeFromSuperview()
  617. }
  618. var width1: CGFloat = 67
  619. var width2: CGFloat = 80
  620. viewCatInTV = UIView()
  621. imageViewSearch.addSubview(viewCatInTV)
  622. var iconCat = UIImage(systemName: "bubble.right")
  623. var textCat = "Unread".localized()
  624. selectedTag = tappedView.tag
  625. if tappedView.tag == PHOTOS_TAG {
  626. iconCat = UIImage(systemName: "photo")
  627. textCat = "Photos".localized()
  628. } else if tappedView.tag == DOCUMENTS_TAG {
  629. iconCat = UIImage(systemName: "doc")
  630. textCat = "Documents".localized()
  631. width1 = 97
  632. width2 = 110
  633. } else if tappedView.tag == LINKS_TAG {
  634. iconCat = UIImage(systemName: "link")
  635. textCat = "Links".localized()
  636. width1 = 57
  637. width2 = 70
  638. } else if tappedView.tag == VIDEOS_TAG {
  639. iconCat = UIImage(systemName: "video")
  640. textCat = "Videos".localized()
  641. } else if tappedView.tag == GIFS_TAG {
  642. iconCat = UIImage(systemName: "photo.on.rectangle")
  643. textCat = "GIFs".localized()
  644. width1 = 52
  645. width2 = 65
  646. } else if tappedView.tag == AUDIOS_TAG {
  647. iconCat = UIImage(systemName: "music.note")
  648. textCat = "Audio".localized()
  649. width1 = 62
  650. width2 = 75
  651. }
  652. viewCatInTV.frame = CGRect(x: 0, y: 0, width: width1, height: 30)
  653. viewCatInTV.anchor(left: imageViewSearch.leftAnchor, paddingLeft: 20, centerY: imageViewSearch.centerYAnchor, width: width1, height: 25)
  654. viewCatInTV.backgroundColor = .white
  655. viewCatInTV.layer.cornerRadius = 8
  656. viewCatInTV.clipsToBounds = true
  657. viewCatInTV.backgroundColor = .black
  658. textViewSearch.text = "~ "
  659. leftTVSearch.constant = width2
  660. let imageIcon = UIImageView()
  661. imageIcon.image = iconCat
  662. imageIcon.tintColor = .white
  663. viewCatInTV.addSubview(imageIcon)
  664. imageIcon.anchor(left: viewCatInTV.leftAnchor, paddingLeft: 5, centerY: viewCatInTV.centerYAnchor, width: 12, height: 12)
  665. let imageText = UILabel()
  666. imageText.text = textCat
  667. viewCatInTV.addSubview(imageText)
  668. imageText.textColor = .white
  669. imageText.anchor(left: imageIcon.rightAnchor, paddingLeft: 3, centerY: viewCatInTV.centerYAnchor, height: 12)
  670. imageText.font = .systemFont(ofSize: 12 + String.offset())
  671. }
  672. }
  673. private func reloadAllData() {
  674. DispatchQueue.global().async { [self] in
  675. if waitingLoading {
  676. return
  677. }
  678. waitingLoading = true
  679. while loadingData {
  680. Thread.sleep(forTimeInterval: 0.5)
  681. }
  682. waitingLoading = false
  683. getData()
  684. }
  685. }
  686. @objc func onReloadTab(notification: NSNotification) {
  687. reloadAllData()
  688. }
  689. @objc func onReload(notification: NSNotification) {
  690. let data:[AnyHashable : Any] = notification.userInfo!
  691. if data["member"] as? String == User.getMyPin()! {
  692. reloadAllData()
  693. } else if data["state"] as? Int == 99 {
  694. reloadAllData()
  695. }
  696. }
  697. @objc func onReceiveMessage(notification: NSNotification) {
  698. reloadAllData()
  699. }
  700. @objc func onStatusChat(notification: NSNotification) {
  701. reloadAllData()
  702. }
  703. @objc func segmentChanged(sender: Any) {
  704. switch segment.selectedSegmentIndex {
  705. case 1:
  706. Utils.inTabChats = false
  707. // searchController.searchBar.placeholder = "Search groups name".localized()
  708. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search groups name".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  709. DispatchQueue.global().async {
  710. self.getOpenGroups(listGroups: self.groups, completion: { g in
  711. DispatchQueue.main.async {
  712. for og in g {
  713. if self.groups.first(where: { $0.id == og.id }) == nil {
  714. self.groups.append(og)
  715. }
  716. }
  717. self.groups.sort { (a, b) -> Bool in
  718. if Int(a.official) == 1 {
  719. return true
  720. } else if Int(b.official) == 1 {
  721. return false
  722. } else {
  723. return Int(a.official) ?? 0 > Int(b.official) ?? 0
  724. }
  725. }
  726. DispatchQueue.main.async {
  727. self.tableView.reloadData()
  728. }
  729. }
  730. })
  731. }
  732. default:
  733. Utils.inTabChats = true
  734. // searchController.searchBar.placeholder = "Search chats & messages".localized()
  735. // searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search chats & messages".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  736. }
  737. // filterContentForSearchText(searchController.searchBar.text!)
  738. filterContentForSearchText(self.textViewSearch.text ?? "")
  739. }
  740. // MARK: - Data source
  741. func getData() {
  742. getChats {
  743. self.getGroups { g1 in
  744. self.groupMap.removeAll()
  745. self.groups = g1
  746. self.groups.sort { (a, b) -> Bool in
  747. if Int(a.official) == 1 {
  748. return true
  749. } else if Int(b.official) == 1 {
  750. return false
  751. } else {
  752. return Int(a.official) ?? 0 > Int(b.official) ?? 0
  753. }
  754. }
  755. DispatchQueue.main.async {
  756. self.tableView.reloadData()
  757. self.loadingData = false
  758. }
  759. }
  760. }
  761. }
  762. func getChats(completion: @escaping ()->()) {
  763. DispatchQueue.global().async {
  764. self.chatGroupMaps.removeAll()
  765. let previousChat = self.chats
  766. let allChats = Chat.getData()
  767. var tempChats: [Chat] = []
  768. for singleChat in allChats {
  769. guard !singleChat.groupId.isEmpty else {
  770. tempChats.append(singleChat)
  771. continue
  772. }
  773. let chatParentInPreviousChats = previousChat.first { $0.isParent && $0.groupId == singleChat.groupId }
  774. if var existingGroup = self.chatGroupMaps[singleChat.groupId] {
  775. existingGroup.insert(singleChat, at: 0)
  776. self.chatGroupMaps[singleChat.groupId] = existingGroup
  777. if let parentChatIndex = tempChats.firstIndex(where: { $0.groupId == singleChat.groupId && $0.isParent }) {
  778. if let counterParent = Int(tempChats[parentChatIndex].counter), let counterSingle = Int(singleChat.counter) {
  779. tempChats[parentChatIndex].counter = "\(counterParent + counterSingle)"
  780. }
  781. }
  782. if let parentExist = chatParentInPreviousChats, parentExist.isSelected,
  783. let indexParent = tempChats.firstIndex(where: { $0.isParent && $0.groupId == singleChat.groupId }) {
  784. tempChats.insert(singleChat, at: min(indexParent + existingGroup.count, tempChats.count))
  785. }
  786. } else {
  787. self.chatGroupMaps[singleChat.groupId] = [singleChat]
  788. let parentChat = Chat(profile: singleChat.profile, groupName: singleChat.groupName, counter: singleChat.counter, groupId: singleChat.groupId)
  789. parentChat.isParent = true
  790. if let parentExist = chatParentInPreviousChats, parentExist.isSelected {
  791. parentChat.isSelected = true
  792. tempChats.append(parentChat)
  793. tempChats.append(singleChat)
  794. } else {
  795. tempChats.append(parentChat)
  796. }
  797. }
  798. }
  799. self.chats = tempChats
  800. completion()
  801. }
  802. }
  803. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  804. var data: [Group] = []
  805. 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 "
  806. if id.isEmpty {
  807. query += "g.parent = '\(parent)'"
  808. } else {
  809. query += "g.group_id = '\(id)'"
  810. }
  811. query += "order by 12 asc, 13 asc, 2 asc"
  812. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  813. while cursor.next() {
  814. let group = Group(
  815. id: cursor.string(forColumnIndex: 0) ?? "",
  816. name: cursor.string(forColumnIndex: 1) ?? "",
  817. profile: cursor.string(forColumnIndex: 2) ?? "",
  818. quote: cursor.string(forColumnIndex: 3) ?? "",
  819. by: cursor.string(forColumnIndex: 4) ?? "",
  820. date: cursor.string(forColumnIndex: 5) ?? "",
  821. parent: cursor.string(forColumnIndex: 6) ?? "",
  822. chatId: "",
  823. groupType: cursor.string(forColumnIndex: 7) ?? "",
  824. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  825. official: cursor.string(forColumnIndex: 9) ?? "",
  826. isEducation: cursor.string(forColumnIndex: 10) ?? "",
  827. level: cursor.string(forColumnIndex: 11) ?? "")
  828. if group.chatId.isEmpty {
  829. 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")
  830. group.childs.append(lounge)
  831. }
  832. if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  833. while topicCursor.next() {
  834. let topic = Group(id: group.id,
  835. name: topicCursor.string(forColumnIndex: 1) ?? "",
  836. profile: topicCursor.string(forColumnIndex: 2) ?? "",
  837. quote: group.quote,
  838. by: group.by,
  839. date: group.date,
  840. parent: group.id,
  841. chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  842. groupType: group.groupType,
  843. isOpen: group.isOpen,
  844. official: group.official,
  845. isEducation: group.isEducation,
  846. level: group.level != "-1" ? group.level : "2")
  847. group.childs.append(topic)
  848. }
  849. topicCursor.close()
  850. }
  851. if !group.id.isEmpty {
  852. // if group.official == "1" {
  853. // let idMe = User.getMyPin() as String?
  854. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  855. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  856. // cursorUser.close()
  857. // }
  858. // } else if group.official != "1"{
  859. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  860. // }
  861. group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  862. // group.childs = group.childs.sorted(by: { $0.name < $1.name })
  863. // let dataLounge = group.childs.filter({$0.name == "Lounge".localized()})
  864. // group.childs = group.childs.filter({ $0.name != "Lounge".localized() })
  865. // group.childs.insert(contentsOf: dataLounge, at: 0)
  866. }
  867. data.append(group)
  868. }
  869. cursor.close()
  870. }
  871. return data
  872. }
  873. private func getOpenGroups(listGroups: [Group], completion: @escaping ([Group]) -> ()) {
  874. while Nexilis.isProcessWriteSync {
  875. Thread.sleep(forTimeInterval: 0.5)
  876. }
  877. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getOpenGroups(p_account: "1,2,3,6,5,7", offset: "0", search: "")) {
  878. var dataGroups: [Group] = []
  879. if (response.getBody(key: CoreMessage_TMessageKey.ERRCOD, default_value: "99") == "00") {
  880. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  881. if let json = try! JSONSerialization.jsonObject(with: data.data(using: String.Encoding.utf8)!, options: []) as? [[String: Any?]] {
  882. for dataJson in json {
  883. let group = Group(
  884. id: dataJson[CoreMessage_TMessageKey.GROUP_ID] as? String ?? "",
  885. name: dataJson[CoreMessage_TMessageKey.GROUP_NAME] as? String ?? "",
  886. profile: dataJson[CoreMessage_TMessageKey.THUMB_ID] as? String ?? "",
  887. quote: dataJson[CoreMessage_TMessageKey.QUOTE] as? String ?? "",
  888. by: dataJson[CoreMessage_TMessageKey.BLOCK] as? String ?? "",
  889. date: "",
  890. parent: "",
  891. chatId: "",
  892. groupType: "NOTJOINED",
  893. isOpen: dataJson[CoreMessage_TMessageKey.IS_OPEN] as? String ?? "",
  894. official: "0",
  895. isEducation: "")
  896. dataGroups.append(group)
  897. }
  898. }
  899. }
  900. completion(dataGroups)
  901. }
  902. }
  903. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  904. DispatchQueue.global().async {
  905. Database.shared.database?.inTransaction({ fmdb, rollback in
  906. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  907. })
  908. }
  909. }
  910. private func pullBuddy() {
  911. if let me = User.getMyPin() {
  912. DispatchQueue.global().async {
  913. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  914. }
  915. }
  916. }
  917. private func joinOpenGroup(groupId: String, flagMember: String = "0", completion: @escaping (Bool) -> ()) {
  918. DispatchQueue.global().async {
  919. var result: Bool = false
  920. let idMe = User.getMyPin() as String?
  921. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddGroupMember(p_group_id: groupId, p_member_pin: idMe!, p_position: "0")), response.isOk() {
  922. result = true
  923. }
  924. completion(result)
  925. }
  926. }
  927. @IBOutlet weak var backgroundImage: UIImageView!
  928. /*
  929. // MARK: - Navigation
  930. // In a storyboard-based application, you will often want to do a little preparation before navigation
  931. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  932. // Get the new view controller using segue.destination.
  933. // Pass the selected object to the new view controller.
  934. }
  935. */
  936. }
  937. // MARK: - Table view data source
  938. extension SecondTabViewController: UITableViewDelegate, UITableViewDataSource {
  939. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  940. if noData || (isFiltering && fillteredData.count == 0) {
  941. return
  942. }
  943. tableView.deselectRow(at: indexPath, animated: true)
  944. switch segment.selectedSegmentIndex {
  945. case 0:
  946. let data: Chat
  947. if isFiltering {
  948. data = fillteredData[indexPath.row] as! Chat
  949. } else {
  950. data = chats[indexPath.row]
  951. }
  952. if data.isParent {
  953. expandCollapseChats(tableView: tableView, indexPath: indexPath)
  954. return
  955. }
  956. if let chooser = isChooser {
  957. if data.pin == "-999"{
  958. return
  959. }
  960. chooser(data.messageScope, data.pin)
  961. dismiss(animated: true, completion: nil)
  962. return
  963. }
  964. if data.pin == "-997" {
  965. let smartChatVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "chatGptVC") as! ChatGPTBotView
  966. smartChatVC.hidesBottomBarWhenPushed = true
  967. smartChatVC.fromNotification = false
  968. navigationController?.show(smartChatVC, sender: nil)
  969. } else if data.messageScope == "3" {
  970. if data.pin.isEmpty {
  971. return
  972. }
  973. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  974. editorPersonalVC.hidesBottomBarWhenPushed = true
  975. editorPersonalVC.unique_l_pin = data.pin
  976. navigationController?.show(editorPersonalVC, sender: nil)
  977. } else {
  978. if data.pin.isEmpty {
  979. return
  980. }
  981. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  982. editorGroupVC.hidesBottomBarWhenPushed = true
  983. editorGroupVC.unique_l_pin = data.pin
  984. navigationController?.show(editorGroupVC, sender: nil)
  985. }
  986. case 1:
  987. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  988. default:
  989. expandCollapseGroup(tableView: tableView, indexPath: indexPath)
  990. }
  991. }
  992. func expandCollapseChats(tableView: UITableView, indexPath: IndexPath) {
  993. let data: Chat
  994. if isFiltering || selectedTag == UNREAD_TAG {
  995. data = fillteredData[indexPath.row] as! Chat
  996. } else {
  997. data = chats[indexPath.row]
  998. }
  999. data.isSelected = !data.isSelected
  1000. if data.isSelected {
  1001. for dataSubChat in self.chatGroupMaps[data.groupId]! {
  1002. if var indexParent = chats.firstIndex(where: { $0.isParent && $0.groupId == data.groupId }) {
  1003. if isFiltering || selectedTag == UNREAD_TAG {
  1004. if var indexParentFilter = fillteredData.firstIndex(where: { ($0 as! Chat).isParent && ($0 as! Chat).groupId == data.groupId }) {
  1005. fillteredData.insert(dataSubChat, at: indexParentFilter + 1)
  1006. indexParentFilter+=1
  1007. }
  1008. } else {
  1009. chats.insert(dataSubChat, at: indexParent + 1)
  1010. indexParent+=1
  1011. }
  1012. }
  1013. }
  1014. } else {
  1015. if isFiltering || selectedTag == UNREAD_TAG {
  1016. if var changedFillteredData = fillteredData as? [Chat] {
  1017. changedFillteredData.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1018. self.fillteredData = changedFillteredData
  1019. }
  1020. } else {
  1021. chats.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1022. }
  1023. }
  1024. tableView.reloadData()
  1025. }
  1026. func expandCollapseGroup(tableView: UITableView, indexPath: IndexPath) {
  1027. let group: Group
  1028. if isFiltering {
  1029. if indexPath.row == 0 {
  1030. group = fillteredData[indexPath.section] as! Group
  1031. } else {
  1032. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  1033. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  1034. } else {
  1035. return
  1036. }
  1037. }
  1038. } else {
  1039. if indexPath.row == 0 {
  1040. group = groups[indexPath.section]
  1041. } else {
  1042. group = groups[indexPath.section].childs[indexPath.row - 1]
  1043. }
  1044. }
  1045. if (checkOverrideAction(groupHolder: group)) {
  1046. return;
  1047. }
  1048. group.isSelected = !group.isSelected
  1049. if !group.isSelected{
  1050. var sects = 0
  1051. var sect = indexPath.section
  1052. var id = group.id
  1053. if let _ = groupMap[id] {
  1054. var loooop = true
  1055. repeat {
  1056. let c = sect + 1
  1057. if isFiltering {
  1058. if let o = self.fillteredData[c] as? Group {
  1059. if o.parent == id {
  1060. sects = sects + 1
  1061. sect = c
  1062. id = o.id
  1063. (self.fillteredData[c] as! Group).isSelected = false
  1064. self.groupMap.removeValue(forKey: (self.fillteredData[c] as! Group).id)
  1065. }
  1066. else {
  1067. loooop = false
  1068. }
  1069. }
  1070. }
  1071. else {
  1072. if c < self.groups.count && self.groups[c].parent == id {
  1073. sects = sects + 1
  1074. sect = c
  1075. id = self.groups[c].id
  1076. self.groups[c].isSelected = false
  1077. self.groupMap.removeValue(forKey: self.groups[c].id)
  1078. }
  1079. else {
  1080. loooop = false
  1081. }
  1082. }
  1083. } while(loooop)
  1084. }
  1085. for i in stride(from: sects, to: 0, by: -1){
  1086. if isFiltering {
  1087. self.fillteredData.remove(at: indexPath.section + i)
  1088. }
  1089. else {
  1090. self.groups.remove(at: indexPath.section + i)
  1091. }
  1092. }
  1093. groupMap.removeValue(forKey: group.id)
  1094. }
  1095. if group.groupType == "NOTJOINED" {
  1096. let alert = LibAlertController(title: "Do you want to join this group?".localized(), message: "Groups : \(group.name)\nMembers: \(group.by)".localized(), preferredStyle: .alert)
  1097. alert.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: nil))
  1098. alert.addAction(UIAlertAction(title: "Join".localized(), style: .default, handler: {(_) in
  1099. self.joinOpenGroup(groupId: group.id, completion: { result in
  1100. if result {
  1101. DispatchQueue.main.async {
  1102. self.groupMap.removeAll()
  1103. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  1104. editorGroupVC.hidesBottomBarWhenPushed = true
  1105. editorGroupVC.unique_l_pin = group.id
  1106. self.navigationController?.show(editorGroupVC, sender: nil)
  1107. }
  1108. }
  1109. })
  1110. }))
  1111. self.present(alert, animated: true, completion: nil)
  1112. return
  1113. }
  1114. if group.childs.count == 0 {
  1115. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1116. let idMe = User.getMyPin() as String?
  1117. 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() {
  1118. let groupId = group.chatId.isEmpty ? group.id : group.chatId
  1119. if let chooser = isChooser {
  1120. chooser("4", groupId)
  1121. dismiss(animated: true, completion: nil)
  1122. return
  1123. }
  1124. self.groupMap.removeAll()
  1125. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  1126. editorGroupVC.hidesBottomBarWhenPushed = true
  1127. editorGroupVC.unique_l_pin = groupId
  1128. navigationController?.show(editorGroupVC, sender: nil)
  1129. cursorMember.close()
  1130. } else {
  1131. var viewController = UIApplication.shared.windows.first!.rootViewController
  1132. if !(viewController is ViewController) {
  1133. viewController = self.parent
  1134. }
  1135. if let viewController = viewController as? ViewController {
  1136. viewController.view.makeToast("You are not a member of this group".localized(), duration: 3)
  1137. }
  1138. }
  1139. })
  1140. } else {
  1141. if indexPath.row == 0 {
  1142. tableView.reloadData()
  1143. } else {
  1144. getGroups(id: group.id) { g in
  1145. DispatchQueue.main.async {
  1146. if self.isFiltering {
  1147. if self.fillteredData[indexPath.section] is Group {
  1148. self.groupMap[(self.fillteredData[indexPath.section] as! Group).id] = 1
  1149. self.fillteredData.insert(contentsOf: g, at: indexPath.section + 1)
  1150. }
  1151. } else {
  1152. self.groupMap[self.groups[indexPath.section].id] = 1
  1153. self.groups.insert(contentsOf: g, at: indexPath.section + 1)
  1154. }
  1155. //print("groupMap: \(self.groupMap)")
  1156. tableView.reloadData()
  1157. self.expandCollapseGroup(tableView: tableView, indexPath: IndexPath(row: 0, section: indexPath.section + 1))
  1158. }
  1159. }
  1160. }
  1161. }
  1162. }
  1163. func checkOverrideAction(groupHolder: Group) -> Bool {
  1164. if groupHolder.isLounge {
  1165. return false
  1166. }
  1167. let groupId = groupHolder.chatId.isEmpty ? groupHolder.id : groupHolder.chatId
  1168. switch (groupId){
  1169. case "18d1c6cffb70215af7b49" //bpkh konsultasi
  1170. , "18d1c6e37a20215af7b49"
  1171. , "18d1c6f852d0215af7b49"
  1172. , "18d1c6ff83a0215af7b49"
  1173. , "18d1c705e970215af7b49"
  1174. , "18d30db3bde0230d00c15" //ina konsultasi bot
  1175. , "18d30e64ce30230d00c15"
  1176. , "18d30e9b6d80230d00c15"
  1177. , "18d30ee00610230d00c15"
  1178. , "18d30f02f850230d00c15":
  1179. APIS.openSmartChatbot();
  1180. return true;
  1181. case "18d30daa4540230d00c15" //ina cc
  1182. , "18d30e59a950230d00c15"
  1183. , "18d30e9292b0230d00c15"
  1184. , "18d30ed8e250230d00c15"
  1185. , "18d30efa66c0230d00c15"
  1186. , "18d35b220540215af7b49" //bpkhcc
  1187. , "18d35b2f5ee0215af7b49"
  1188. , "18d35b356530215af7b49"
  1189. , "18d35b411510215af7b49"
  1190. , "18d35b46ae90215af7b49":
  1191. APIS.openContactCenter();
  1192. return true;
  1193. case "18d1c6d9f330215af7b49": //bpkh haji
  1194. APIS.openUrl(url: Utils.decrypt(str: "6]tov!l_opgn=hgz?ykmgv?yoro3kt?uo>yoro3kt??@yvzzn"))
  1195. return true;
  1196. case "18d1c6eefd40215af7b49": //bpkh bpjs
  1197. APIS.openUrl(url: Utils.decrypt(str: "1>ojq`g@tkqc.cbu:tfhbq:tjmjyfo:pj/tjmjyfo::;tquui"))
  1198. return true;
  1199. case "18d30e711c20230d00c15": //ina bpjs
  1200. APIS.openUrl(url: Utils.decrypt(str: "6]tov!l_ypvh=hgz?ykmgv?yoro3kt?sui>ykrgyomojrkyz??@yvzzn"))
  1201. return true;
  1202. case "18d30e47ae60230d00c15": //ina KTP, KK, SKL
  1203. APIS.openUrl(url: Utils.decrypt(str: "1>ojq`g@qul.cbu:tfhbq:tjmjyfo:npd/tfmbtjhjemftu::;tquui"))
  1204. return true;
  1205. case "18d30eb2e910230d00c15": //SIM, SKKB, SKBN
  1206. APIS.openUrl(url: Utils.decrypt(str: "4[rmt}j]qmw;fex=wiket=wmpm1ir=qsg<wipewmkmhpiwx==>wtxxl"))
  1207. return true;
  1208. case "18da1c0200f0215af7b49": //BPKH index BMI
  1209. APIS.openUrl(url: Utils.decrypt(str: "4[rmt}j]mqf}1ihrm=mqf=wmpm1ir=sm<wmpm1ir==>wtxxl"))
  1210. return true;
  1211. default:
  1212. break;
  1213. }
  1214. return false
  1215. }
  1216. func numberOfSections(in tableView: UITableView) -> Int {
  1217. if isFiltering {
  1218. if segment.selectedSegmentIndex == 1 {
  1219. return fillteredData.count
  1220. } else if segment.selectedSegmentIndex == 0 && fillteredMessages.count > 0 {
  1221. return 2
  1222. }
  1223. return 1
  1224. } else {
  1225. if segment.selectedSegmentIndex == 1 {
  1226. return groups.count
  1227. }
  1228. return 1
  1229. }
  1230. }
  1231. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  1232. if isFiltering && segment.selectedSegmentIndex == 0 && section == 1 && fillteredMessages.count > 0 {
  1233. return 20
  1234. }
  1235. return 0.0
  1236. }
  1237. func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  1238. let containerView = UIView()
  1239. containerView.backgroundColor = .clear
  1240. if isFiltering && segment.selectedSegmentIndex == 0 && section == 1 && fillteredMessages.count > 0 {
  1241. let titleMessages = UILabel()
  1242. titleMessages.text = "Messages".localized()
  1243. titleMessages.font = .systemFont(ofSize: 16, weight: .medium)
  1244. titleMessages.textColor = .label
  1245. containerView.addSubview(titleMessages)
  1246. titleMessages.anchor(left: containerView.leftAnchor, paddingLeft: 10, centerY: containerView.centerYAnchor)
  1247. }
  1248. return containerView
  1249. }
  1250. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  1251. var value = 0
  1252. if isFiltering {
  1253. if segment.selectedSegmentIndex == 1, let groups = fillteredData as? [Group] {
  1254. let group = groups[section]
  1255. if group.isSelected {
  1256. if let _ = groupMap[group.id] {
  1257. value = 1
  1258. }
  1259. else {
  1260. value = group.childs.count + 1
  1261. }
  1262. } else {
  1263. value = 1
  1264. }
  1265. } else if segment.selectedSegmentIndex == 0 && section == 0 {
  1266. value = fillteredData.count
  1267. if value == 0 {
  1268. value = 1
  1269. tableView.separatorStyle = .none
  1270. } else {
  1271. tableView.separatorStyle = .singleLine
  1272. }
  1273. } else {
  1274. }
  1275. return value
  1276. }
  1277. switch segment.selectedSegmentIndex {
  1278. case 0:
  1279. value = chats.count
  1280. case 1:
  1281. let group = groups[section]
  1282. if group.isSelected {
  1283. if let _ = groupMap[group.id] {
  1284. value = 1
  1285. }
  1286. else {
  1287. value = group.childs.count + 1
  1288. }
  1289. } else {
  1290. value = 1
  1291. }
  1292. default:
  1293. value = chats.count
  1294. }
  1295. if value == 0 {
  1296. noData = true
  1297. value = 1
  1298. tableView.separatorStyle = .none
  1299. } else {
  1300. noData = false
  1301. tableView.separatorStyle = .singleLine
  1302. }
  1303. return value
  1304. }
  1305. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  1306. var cell: UITableViewCell!
  1307. switch segment.selectedSegmentIndex {
  1308. case 0:
  1309. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierChat", for: indexPath)
  1310. let content = cell.contentView
  1311. if content.subviews.count > 0 {
  1312. content.subviews.forEach { $0.removeFromSuperview() }
  1313. }
  1314. if noData || (isFiltering && fillteredData.count == 0) {
  1315. let labelNochat = UILabel()
  1316. labelNochat.text = isFiltering ? "No Result".localized() : loadingData ? "Loading Data...".localized() : "There are no conversations".localized()
  1317. labelNochat.font = .systemFont(ofSize: 13 + String.offset())
  1318. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1319. content.addSubview(labelNochat)
  1320. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  1321. cell.backgroundColor = .clear
  1322. cell.selectionStyle = .none
  1323. return cell
  1324. }
  1325. let data: Chat
  1326. if isFiltering {
  1327. data = fillteredData[indexPath.row] as! Chat
  1328. } else {
  1329. if chats.count == 0 || (indexPath.row > (chats.count - 1)) {
  1330. let labelNochat = UILabel()
  1331. labelNochat.text = loadingData ? "Loading Data...".localized() : "There are no conversations".localized()
  1332. labelNochat.font = .systemFont(ofSize: 13 + String.offset())
  1333. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1334. content.addSubview(labelNochat)
  1335. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  1336. cell.backgroundColor = .clear
  1337. cell.selectionStyle = .none
  1338. return cell
  1339. }
  1340. data = chats[indexPath.row]
  1341. }
  1342. if selectedTag != UNREAD_TAG && selectedTag != 0 {
  1343. let title = UILabel()
  1344. let subtitle = UILabel()
  1345. title.textColor = .black
  1346. subtitle.textColor = .gray
  1347. title.font = .systemFont(ofSize: 16 + String.offset(), weight: .medium)
  1348. subtitle.font = .systemFont(ofSize: 14 + String.offset())
  1349. content.addSubview(title)
  1350. content.addSubview(subtitle)
  1351. title.anchor(top: content.topAnchor, left: content.leftAnchor, paddingTop: 10, paddingLeft: 20)
  1352. subtitle.anchor(top: title.bottomAnchor, left: content.leftAnchor, right: content.rightAnchor, paddingLeft: 20, paddingRight: 20)
  1353. subtitle.numberOfLines = 2
  1354. title.text = data.name
  1355. let imageArrowRight = UIImageView(image: UIImage(systemName: "chevron.right"))
  1356. content.addSubview(imageArrowRight)
  1357. imageArrowRight.tintColor = .gray
  1358. imageArrowRight.anchor(top: content.topAnchor, right: content.rightAnchor, paddingTop: 10, paddingRight: 20)
  1359. let timeView = UILabel()
  1360. content.addSubview(timeView)
  1361. timeView.anchor(top: content.topAnchor, right: imageArrowRight.leftAnchor, paddingTop: 10, paddingRight: 20)
  1362. timeView.textColor = .gray
  1363. timeView.font = UIFont.systemFont(ofSize: 16 + String.offset())
  1364. let date = Date(milliseconds: Int64(data.serverDate)!)
  1365. let calendar = Calendar.current
  1366. if (calendar.isDateInToday(date)) {
  1367. let formatter = DateFormatter()
  1368. formatter.dateFormat = "HH:mm"
  1369. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1370. timeView.text = formatter.string(from: date as Date)
  1371. } else {
  1372. let startOfNow = calendar.startOfDay(for: Date())
  1373. let startOfTimeStamp = calendar.startOfDay(for: date)
  1374. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  1375. let day = -(components.day!)
  1376. if day == 1 {
  1377. timeView.text = "Yesterday".localized()
  1378. } else {
  1379. if day < 7 {
  1380. let formatter = DateFormatter()
  1381. formatter.dateFormat = "EEEE"
  1382. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  1383. if lang == "id" {
  1384. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1385. }
  1386. timeView.text = formatter.string(from: date)
  1387. } else {
  1388. let formatter = DateFormatter()
  1389. formatter.dateFormat = "M/dd/yy"
  1390. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  1391. let stringFormat = formatter.string(from: date as Date)
  1392. timeView.text = stringFormat
  1393. }
  1394. }
  1395. }
  1396. cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
  1397. let container = UIView()
  1398. content.addSubview(container)
  1399. container.anchor(top: subtitle.bottomAnchor, left: content.leftAnchor, right: content.rightAnchor, paddingTop: 5, paddingLeft: 20, paddingRight: 20, height: selectedTag == LINKS_TAG ? 75 : 60)
  1400. container.backgroundColor = .lightGray.withAlphaComponent(0.3)
  1401. container.layer.cornerRadius = 15
  1402. container.clipsToBounds = true
  1403. container.isUserInteractionEnabled = true
  1404. if selectedTag == DOCUMENTS_TAG {
  1405. subtitle.text = "📄 " + "Document".localized()
  1406. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 45)))
  1407. container.addSubview(imageFile)
  1408. imageFile.tintColor = .black
  1409. imageFile.anchor(top: container.topAnchor, left: container.leftAnchor, bottom: container.bottomAnchor, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, width: 45)
  1410. let nameFile = UILabel()
  1411. container.addSubview(nameFile)
  1412. nameFile.font = .systemFont(ofSize: 12 + String.offset(), weight: .medium)
  1413. nameFile.textColor = .black
  1414. nameFile.numberOfLines = 2
  1415. nameFile.anchor(top: container.topAnchor, left: imageFile.rightAnchor, right: container.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingRight: 5)
  1416. nameFile.text = data.messageText.components(separatedBy: "|")[0]
  1417. let fileSub = UILabel()
  1418. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1419. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1420. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1421. let arrExtFile = (data.messageText.components(separatedBy: "|")[0]).split(separator: ".")
  1422. let finalExtFile = arrExtFile[arrExtFile.count - 1]
  1423. if let dirPath = paths.first {
  1424. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(data.file)
  1425. if FileManager.default.fileExists(atPath: fileURL.path) {
  1426. if let dataFile = try? Data(contentsOf: fileURL) {
  1427. var sizeOfFile = Int(dataFile.count / 1000000)
  1428. if (sizeOfFile < 1) {
  1429. sizeOfFile = Int(dataFile.count / 1000)
  1430. if (finalExtFile.count > 4) {
  1431. fileSub.text = "\(sizeOfFile) kB \u{2022} TXT"
  1432. }else {
  1433. fileSub.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  1434. }
  1435. } else {
  1436. if (finalExtFile.count > 4) {
  1437. fileSub.text = "\(sizeOfFile) MB \u{2022} TXT"
  1438. }else {
  1439. fileSub.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  1440. }
  1441. }
  1442. } else {
  1443. fileSub.text = ""
  1444. }
  1445. }
  1446. else if FileEncryption.shared.isSecureExists(filename: data.file) {
  1447. if let dataFile = try? FileEncryption.shared.readSecure(filename: data.file) {
  1448. var sizeOfFile = Int(dataFile.count / 1000000)
  1449. if (sizeOfFile < 1) {
  1450. sizeOfFile = Int(dataFile.count / 1000)
  1451. if (finalExtFile.count > 4) {
  1452. fileSub.text = "\(sizeOfFile) kB \u{2022} TXT"
  1453. }else {
  1454. fileSub.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  1455. }
  1456. } else {
  1457. if (finalExtFile.count > 4) {
  1458. fileSub.text = "\(sizeOfFile) MB \u{2022} TXT"
  1459. }else {
  1460. fileSub.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  1461. }
  1462. }
  1463. } else {
  1464. fileSub.text = ""
  1465. }
  1466. }
  1467. container.addSubview(fileSub)
  1468. fileSub.anchor(top: nameFile.bottomAnchor, left: imageFile.rightAnchor, bottom: container.bottomAnchor, paddingLeft: 10, paddingBottom: 5)
  1469. fileSub.font = .systemFont(ofSize: 10 + String.offset())
  1470. fileSub.textColor = .gray
  1471. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  1472. objectTap.file_id = data.file
  1473. container.addGestureRecognizer(objectTap)
  1474. }
  1475. } else if selectedTag == LINKS_TAG {
  1476. var text = ""
  1477. var txtData = data.messageText
  1478. if txtData.contains("■"){
  1479. txtData = txtData.components(separatedBy: "■")[0]
  1480. txtData = txtData.trimmingCharacters(in: .whitespacesAndNewlines)
  1481. }
  1482. let listTextSplitBreak = txtData.components(separatedBy: "\n")
  1483. let indexFirstLinkSplitBreak = listTextSplitBreak.firstIndex(where: { $0.contains("www.") || $0.contains("http://") || $0.contains("https://") })
  1484. if indexFirstLinkSplitBreak != nil {
  1485. let listTextSplitSpace = listTextSplitBreak[indexFirstLinkSplitBreak!].components(separatedBy: " ")
  1486. 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) })
  1487. if indexFirstLinkSplitSpace != nil {
  1488. text = listTextSplitSpace[indexFirstLinkSplitSpace!]
  1489. }
  1490. }
  1491. var dataURL = ""
  1492. subtitle.text = txtData
  1493. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1494. do {
  1495. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(text)'"), cursor.next() {
  1496. if let data = cursor.string(forColumnIndex: 0) {
  1497. dataURL = data
  1498. }
  1499. cursor.close()
  1500. }
  1501. } catch {
  1502. rollback.pointee = true
  1503. print("Access database error: \(error.localizedDescription)")
  1504. }
  1505. })
  1506. var title = ""
  1507. var description = ""
  1508. var imageUrl: String?
  1509. var link = text
  1510. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  1511. objectTap.message_id = link
  1512. container.addGestureRecognizer(objectTap)
  1513. let imagePreview = UIImageView()
  1514. container.addSubview(imagePreview)
  1515. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  1516. imagePreview.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
  1517. imagePreview.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  1518. imagePreview.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
  1519. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  1520. imagePreview.image = UIImage(systemName: "link", withConfiguration: UIImage.SymbolConfiguration(pointSize: 45))
  1521. imagePreview.contentMode = .center
  1522. imagePreview.clipsToBounds = true
  1523. imagePreview.tintColor = .black
  1524. imagePreview.backgroundColor = .gray.withAlphaComponent(0.3)
  1525. let titlePreview = UILabel()
  1526. container.addSubview(titlePreview)
  1527. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  1528. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1529. titlePreview.topAnchor.constraint(equalTo: container.topAnchor, constant: 10.0).isActive = true
  1530. titlePreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  1531. titlePreview.text = title
  1532. titlePreview.font = UIFont.systemFont(ofSize: 14.0 + String.offset(), weight: .bold)
  1533. titlePreview.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1534. let descPreview = UILabel()
  1535. container.addSubview(descPreview)
  1536. descPreview.translatesAutoresizingMaskIntoConstraints = false
  1537. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1538. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  1539. descPreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  1540. descPreview.text = description
  1541. descPreview.font = UIFont.systemFont(ofSize: 12.0 + String.offset())
  1542. descPreview.textColor = .gray
  1543. descPreview.numberOfLines = 1
  1544. let linkPreview = UILabel()
  1545. container.addSubview(linkPreview)
  1546. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  1547. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  1548. linkPreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  1549. linkPreview.font = UIFont.systemFont(ofSize: 10.0 + String.offset())
  1550. linkPreview.textColor = .gray
  1551. linkPreview.numberOfLines = 1
  1552. if !dataURL.isEmpty {
  1553. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  1554. title = data["title"] as! String
  1555. description = data["description"] as! String
  1556. imageUrl = data["imageUrl"] as? String
  1557. link = data["link"] as! String
  1558. if imageUrl != nil {
  1559. imagePreview.loadImageAsync(with: imageUrl)
  1560. imagePreview.contentMode = .scaleToFill
  1561. imagePreview.clipsToBounds = true
  1562. }
  1563. titlePreview.text = title
  1564. descPreview.text = description
  1565. linkPreview.text = link
  1566. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  1567. }
  1568. } else {
  1569. linkPreview.text = link
  1570. linkPreview.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
  1571. }
  1572. } else if selectedTag == AUDIOS_TAG {
  1573. subtitle.text = "♫ " + "Audio".localized()
  1574. let imageAudio = UIImageView()
  1575. imageAudio.image = UIImage(systemName: "music.note", withConfiguration: UIImage.SymbolConfiguration(pointSize: 35))
  1576. container.addSubview(imageAudio)
  1577. imageAudio.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  1578. imageAudio.tintColor = .black
  1579. let nameAudio = UILabel()
  1580. container.addSubview(nameAudio)
  1581. nameAudio.anchor(left: imageAudio.rightAnchor, right: container.rightAnchor, paddingLeft: 10, paddingRight: 10, centerY: container.centerYAnchor)
  1582. nameAudio.numberOfLines = 2
  1583. nameAudio.text = data.messageText.components(separatedBy: "|")[0]
  1584. nameAudio.font = .systemFont(ofSize: 16 + String.offset(), weight: .medium)
  1585. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1586. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1587. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1588. if let dirPath = paths.first {
  1589. let audioURL = URL(fileURLWithPath: dirPath).appendingPathComponent(data.audio)
  1590. if !FileManager.default.fileExists(atPath: audioURL.path) && !FileEncryption.shared.isSecureExists(filename: data.audio) {
  1591. Download().startHTTP(forKey: data.audio, isImage: false) { (name, progress) in
  1592. guard progress == 100 else {
  1593. return
  1594. }
  1595. tableView.reloadRows(at: [indexPath], with: .none)
  1596. }
  1597. } else {
  1598. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  1599. objectTap.audio_id = data.audio
  1600. container.addGestureRecognizer(objectTap)
  1601. }
  1602. }
  1603. }
  1604. return cell
  1605. }
  1606. let imageView = UIImageView()
  1607. content.addSubview(imageView)
  1608. imageView.translatesAutoresizingMaskIntoConstraints = false
  1609. NSLayoutConstraint.activate([
  1610. imageView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  1611. imageView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -10.0),
  1612. imageView.widthAnchor.constraint(equalToConstant: 55.0),
  1613. imageView.heightAnchor.constraint(equalToConstant: 55.0)
  1614. ])
  1615. var leadingAnchor = imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 10.0)
  1616. if data.profile.isEmpty && data.pin != "-999" && data.pin != "-997" {
  1617. if data.messageScope == "3" {
  1618. imageView.image = UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1619. } else {
  1620. imageView.image = UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  1621. }
  1622. } else 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.profile.isEmpty {
  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 == "3" || data.isParent || data.pin == "-999" {
  1666. getImage(name: data.profile, placeholderImage: UIImage(named: data.pin == "-999" ? "pb_button" : data.messageScope == "3" ? "Profile---Purple" : "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  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. let status = getRealStatus(messageId: data.messageId)
  1786. if status == "0" {
  1787. imageStatus.image = UIImage(systemName: "xmark.circle")!.withTintColor(UIColor.red, renderingMode: .alwaysOriginal)
  1788. } else if status == "1" {
  1789. imageStatus.image = UIImage(systemName: "clock.arrow.circlepath")!.withTintColor(UIColor.lightGray, renderingMode: .alwaysOriginal)
  1790. } else if status == "2" {
  1791. imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1792. } else if (status == "3") {
  1793. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1794. } else if (status == "8") {
  1795. imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1796. } else {
  1797. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  1798. }
  1799. imageStatus.bounds = CGRect(x: 0, y: -5, width: 15, height: 15)
  1800. let imageStatusString = NSAttributedString(attachment: imageStatus)
  1801. stringMessage.append(imageStatusString)
  1802. stringMessage.append(NSAttributedString(string: " "))
  1803. if data.messageScope == "4" {
  1804. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12 + String.offset(), weight: .medium)]))
  1805. }
  1806. stringMessage.append(attributeText)
  1807. }
  1808. } else {
  1809. if data.messageScope == "4" {
  1810. var fullname = User.getData(pin: data.fpin, lPin: data.pin)!.fullName
  1811. let components = fullname.split(separator: " ")
  1812. if components.count >= 2 {
  1813. fullname = components.prefix(2).joined(separator: " ")
  1814. }
  1815. stringMessage.append(NSAttributedString(string: fullname + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12 + String.offset(), weight: .medium)]))
  1816. }
  1817. if data.lock == "1" {
  1818. stringMessage.append(("🚫 _"+"This message was deleted".localized()+"_").richText())
  1819. } else {
  1820. stringMessage.append(attributeText)
  1821. }
  1822. }
  1823. messageView.attributedText = stringMessage
  1824. }
  1825. messageView.numberOfLines = 2
  1826. if data.counter != "0" {
  1827. viewCounter.topAnchor.constraint(equalTo: timeView.bottomAnchor, constant: 5.0).isActive = true
  1828. viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20).isActive = true
  1829. }
  1830. } else {
  1831. titleView.centerYAnchor.constraint(equalTo: content.centerYAnchor).isActive = true
  1832. titleView.text = data.groupName
  1833. let iconName = (data.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  1834. let imageView = UIImageView(image: UIImage(systemName: iconName))
  1835. imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1836. content.addSubview(imageView)
  1837. imageView.translatesAutoresizingMaskIntoConstraints = false
  1838. NSLayoutConstraint.activate([
  1839. imageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
  1840. imageView.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  1841. imageView.widthAnchor.constraint(equalToConstant: 20),
  1842. imageView.heightAnchor.constraint(equalToConstant: 20)
  1843. ])
  1844. if data.counter != "0" {
  1845. viewCounter.trailingAnchor.constraint(equalTo: imageView.leadingAnchor, constant: -5).isActive = true
  1846. viewCounter.centerYAnchor.constraint(equalTo: content.centerYAnchor).isActive = true
  1847. }
  1848. }
  1849. case 1:
  1850. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  1851. var content = cell.defaultContentConfiguration()
  1852. content.textProperties.font = UIFont.systemFont(ofSize: 14 + String.offset())
  1853. let group: Group
  1854. if isFiltering {
  1855. if indexPath.row == 0 {
  1856. group = fillteredData[indexPath.section] as! Group
  1857. } else {
  1858. if (fillteredData[indexPath.section] as! Group).childs.count > 0 {
  1859. group = (fillteredData[indexPath.section] as! Group).childs[indexPath.row - 1]
  1860. } else {
  1861. return cell
  1862. }
  1863. }
  1864. } else {
  1865. if indexPath.row == 0 {
  1866. if indexPath.section > (groups.count - 1) {
  1867. return cell
  1868. }
  1869. group = groups[indexPath.section]
  1870. } else {
  1871. group = groups[indexPath.section].childs[indexPath.row - 1]
  1872. }
  1873. }
  1874. if group.official == "1" && group.parent == "" {
  1875. 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)
  1876. }
  1877. else if group.isOpen == "1" && group.parent == "" {
  1878. if self.traitCollection.userInterfaceStyle == .dark {
  1879. content.attributedText = self.set(image: UIImage(systemName: "globe")!.withTintColor(.white), with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1880. } else {
  1881. content.attributedText = self.set(image: UIImage(systemName: "globe")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1882. }
  1883. } else if group.parent == "" {
  1884. if self.traitCollection.userInterfaceStyle == .dark {
  1885. 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)
  1886. } else {
  1887. content.attributedText = self.set(image: UIImage(systemName: "lock.fill")!, with: " \(group.name)", size: 15, y: -4, colorText: self.traitCollection.userInterfaceStyle == .dark ? .white : .black)
  1888. }
  1889. } else {
  1890. content.text = group.name
  1891. }
  1892. if group.childs.count > 0 {
  1893. let iconName = (group.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  1894. let imageView = UIImageView(image: UIImage(systemName: iconName))
  1895. imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1896. cell.accessoryView = imageView
  1897. }
  1898. else {
  1899. cell.accessoryView = nil
  1900. cell.accessoryType = .none
  1901. }
  1902. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  1903. 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
  1904. content.image = image
  1905. }
  1906. cell.contentConfiguration = content
  1907. if !group.level.isEmpty {
  1908. if group.level != "-1" && Int(group.level)! < 7 {
  1909. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * Int(group.level)!), bottom: 0.0, right: 0)
  1910. } else if Int(group.level)! > 6 {
  1911. cell.contentView.layoutMargins = .init(top: 0.0, left: CGFloat(25 * (Int(group.level)! - 6)), bottom: 0.0, right: 0)
  1912. }
  1913. }
  1914. default:
  1915. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  1916. var content = cell.defaultContentConfiguration()
  1917. content.text = ""
  1918. cell.contentConfiguration = content
  1919. }
  1920. cell.backgroundColor = .clear
  1921. cell.separatorInset = UIEdgeInsets(top: 0, left: 60.0, bottom: 0, right: 0)
  1922. return cell
  1923. }
  1924. @objc func onContSearch(_ sender: ObjectGesture) {
  1925. if selectedTag == PHOTOS_TAG {
  1926. } else if selectedTag == VIDEOS_TAG {
  1927. } else if selectedTag == DOCUMENTS_TAG {
  1928. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1929. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1930. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1931. if let dirPath = paths.first {
  1932. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  1933. if FileManager.default.fileExists(atPath: fileURL.path) {
  1934. self.previewItem = fileURL as NSURL
  1935. let previewController = QLPreviewController()
  1936. let rightBarButton = UIBarButtonItem()
  1937. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1938. previewController.dataSource = self
  1939. previewController.modalPresentationStyle = .custom
  1940. self.present(previewController, animated: true)
  1941. } else if FileEncryption.shared.isSecureExists(filename: sender.file_id) {
  1942. do {
  1943. if let docData = try FileEncryption.shared.readSecure(filename: sender.file_id) {
  1944. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  1945. let tempPath = cachesDirectory.appendingPathComponent(sender.file_id)
  1946. try docData.write(to: tempPath)
  1947. self.previewItem = tempPath as NSURL
  1948. let previewController = QLPreviewController()
  1949. let rightBarButton = UIBarButtonItem()
  1950. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1951. previewController.dataSource = self
  1952. previewController.modalPresentationStyle = .custom
  1953. self.present(previewController,animated: true)
  1954. }
  1955. }
  1956. catch {
  1957. }
  1958. }
  1959. }
  1960. } else if selectedTag == LINKS_TAG {
  1961. var stringURl = sender.message_id
  1962. if stringURl.lowercased().starts(with: "www.") {
  1963. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  1964. }
  1965. guard let url = URL(string: stringURl) else { return }
  1966. UIApplication.shared.open(url)
  1967. } else if selectedTag == AUDIOS_TAG {
  1968. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1969. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1970. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1971. if let dirPath = paths.first {
  1972. let audioURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.audio_id)
  1973. if FileManager.default.fileExists(atPath: audioURL.path) {
  1974. do {
  1975. if audioPlayer == nil || audioPlayer?.url != audioURL {
  1976. do {
  1977. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  1978. try AVAudioSession.sharedInstance().setActive(true)
  1979. } catch {
  1980. }
  1981. audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
  1982. audioPlayer?.prepareToPlay()
  1983. audioPlayer?.play()
  1984. } else if audioPlayer!.isPlaying {
  1985. audioPlayer?.pause()
  1986. } else {
  1987. audioPlayer?.play()
  1988. }
  1989. } catch {
  1990. }
  1991. } else if FileEncryption.shared.isSecureExists(filename: sender.audio_id) {
  1992. do {
  1993. if let audioData = try FileEncryption.shared.readSecure(filename: sender.audio_id) {
  1994. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  1995. let tempPath = cachesDirectory.appendingPathComponent(sender.audio_id)
  1996. try audioData.write(to: tempPath)
  1997. if audioPlayer == nil || audioPlayer?.url != tempPath {
  1998. do {
  1999. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  2000. try AVAudioSession.sharedInstance().setActive(true)
  2001. } catch {
  2002. }
  2003. audioPlayer = try AVAudioPlayer(contentsOf: tempPath)
  2004. audioPlayer?.prepareToPlay()
  2005. audioPlayer?.play()
  2006. } else if audioPlayer!.isPlaying {
  2007. audioPlayer?.pause()
  2008. } else {
  2009. audioPlayer?.play()
  2010. }
  2011. }
  2012. } catch {
  2013. }
  2014. }
  2015. }
  2016. }
  2017. }
  2018. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  2019. if fillteredData.count > 0 && selectedTag != UNREAD_TAG && selectedTag != 0 {
  2020. if selectedTag == LINKS_TAG {
  2021. return 160.0
  2022. }
  2023. return 130.0
  2024. }
  2025. return 75.0
  2026. }
  2027. private func getRealStatus(messageId: String) -> String {
  2028. var status = "1"
  2029. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  2030. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
  2031. var listStatus: [Int] = []
  2032. while cursorStatus.next() {
  2033. listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
  2034. }
  2035. cursorStatus.close()
  2036. status = "\(listStatus.min() ?? 2)"
  2037. }
  2038. })
  2039. return status
  2040. }
  2041. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  2042. return fillteredData.count
  2043. }
  2044. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  2045. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath)
  2046. if cell.contentView.subviews.count > 0 {
  2047. cell.contentView.subviews.forEach { $0.removeFromSuperview() }
  2048. }
  2049. let data = fillteredData[indexPath.row] as! Chat
  2050. let thumb = data.thumb
  2051. let imgData = data.image
  2052. let vidData = data.video
  2053. let gifData = data.gif
  2054. let image = UIImageView()
  2055. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2056. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2057. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2058. if let dirPath = paths.first {
  2059. if selectedTag == GIFS_TAG {
  2060. let gifURL = URL(fileURLWithPath: dirPath).appendingPathComponent(gifData)
  2061. if !FileManager.default.fileExists(atPath: gifURL.path) && !FileEncryption.shared.isSecureExists(filename: gifData) {
  2062. Download().startHTTP(forKey: gifData, isImage: false) { (name, progress) in
  2063. guard progress == 100 else {
  2064. return
  2065. }
  2066. collectionView.reloadItems(at: [indexPath])
  2067. }
  2068. } else {
  2069. let imageGif = SDAnimatedImageView()
  2070. cell.contentView.addSubview(imageGif)
  2071. imageGif.contentMode = .scaleAspectFill
  2072. imageGif.clipsToBounds = true
  2073. imageGif.translatesAutoresizingMaskIntoConstraints = false
  2074. imageGif.anchor(top: cell.contentView.topAnchor, left: cell.contentView.leftAnchor, bottom: cell.contentView.bottomAnchor, right: cell.contentView.rightAnchor)
  2075. if FileManager.default.fileExists(atPath: gifURL.path) {
  2076. imageGif.image = SDAnimatedImage(contentsOfFile: gifURL.path)
  2077. // imageGif.shouldCustomLoopCount = true
  2078. // imageGif.animationRepeatCount = 4
  2079. } else if FileEncryption.shared.isSecureExists(filename: gifData){
  2080. do {
  2081. let data = try FileEncryption.shared.readSecure(filename: gifData)
  2082. if let imageData = SDAnimatedImage(data: data!) {
  2083. imageGif.image = imageData
  2084. // imageGif.shouldCustomLoopCount = true
  2085. // imageGif.animationRepeatCount = 4
  2086. }
  2087. }
  2088. catch {
  2089. print("Error reading secure file")
  2090. }
  2091. }
  2092. }
  2093. return cell
  2094. }
  2095. cell.contentView.addSubview(image)
  2096. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumb)
  2097. let imageT : UIImage? = {
  2098. if let img = Nexilis.imageCache.object(forKey: thumb as NSString) {
  2099. return img
  2100. }
  2101. else if let img = UIImage(contentsOfFile: thumbURL.path)?.resize(target: CGSize(width: 500, height: 500)) {
  2102. Nexilis.imageCache.setObject(img, forKey: thumb as NSString)
  2103. return img
  2104. }
  2105. return nil
  2106. }()
  2107. if imageT != nil {
  2108. image.image = imageT
  2109. }
  2110. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imgData)
  2111. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(vidData)
  2112. 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)) {
  2113. let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light)
  2114. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  2115. blurEffectView.frame = CGRect(x: 0, y: 0, width: image.frame.size.width, height: image.frame.size.height)
  2116. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  2117. image.addSubview(blurEffectView)
  2118. if !imgData.isEmpty {
  2119. let imageDownload = UIImageView(image: UIImage(systemName: "arrow.down.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 50, weight: .bold, scale: .default)))
  2120. image.addSubview(imageDownload)
  2121. imageDownload.tintColor = .black.withAlphaComponent(0.3)
  2122. imageDownload.translatesAutoresizingMaskIntoConstraints = false
  2123. imageDownload.centerXAnchor.constraint(equalTo: image.centerXAnchor).isActive = true
  2124. imageDownload.centerYAnchor.constraint(equalTo: image.centerYAnchor).isActive = true
  2125. }
  2126. }
  2127. if (!vidData.isEmpty) {
  2128. 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))
  2129. imagePlay.circle()
  2130. image.addSubview(imagePlay)
  2131. imagePlay.backgroundColor = .black.withAlphaComponent(0.3)
  2132. imagePlay.translatesAutoresizingMaskIntoConstraints = false
  2133. imagePlay.centerXAnchor.constraint(equalTo: image.centerXAnchor).isActive = true
  2134. imagePlay.centerYAnchor.constraint(equalTo: image.centerYAnchor).isActive = true
  2135. }
  2136. }
  2137. image.contentMode = .scaleAspectFill
  2138. image.clipsToBounds = true
  2139. image.anchor(top: cell.contentView.topAnchor, left: cell.contentView.leftAnchor, bottom: cell.contentView.bottomAnchor, right: cell.contentView.rightAnchor)
  2140. return cell
  2141. }
  2142. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  2143. let data = fillteredData[indexPath.row] as! Chat
  2144. let imgData = data.image
  2145. let vidData = data.video
  2146. let gifData = data.gif
  2147. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  2148. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  2149. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  2150. if let dirPath = paths.first {
  2151. if selectedTag == PHOTOS_TAG {
  2152. let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(imgData)
  2153. if FileManager.default.fileExists(atPath: imageURL.path) {
  2154. let image = UIImage(contentsOfFile: imageURL.path) ?? UIImage()
  2155. APIS.openImageNexilis(image: image)
  2156. } else if FileEncryption.shared.isSecureExists(filename: imgData) {
  2157. do {
  2158. let data = try FileEncryption.shared.readSecure(filename: imgData)
  2159. let image = UIImage(data: data!) ?? UIImage()
  2160. APIS.openImageNexilis(image: image)
  2161. }
  2162. catch {
  2163. }
  2164. } else {
  2165. Download().startHTTP(forKey: imgData) { (name, progress) in
  2166. guard progress == 100 else {
  2167. return
  2168. }
  2169. DispatchQueue.main.async {
  2170. collectionView.reloadItems(at: [indexPath])
  2171. }
  2172. }
  2173. }
  2174. } else if selectedTag == VIDEOS_TAG {
  2175. let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(vidData)
  2176. if FileManager.default.fileExists(atPath: videoURL.path) {
  2177. APIS.openVideoNexilis(videoURL: videoURL)
  2178. } else if FileEncryption.shared.isSecureExists(filename: vidData) {
  2179. do {
  2180. if let secureData = try FileEncryption.shared.readSecure(filename: vidData) {
  2181. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  2182. let tempPath = cachesDirectory.appendingPathComponent(vidData)
  2183. try secureData.write(to: tempPath)
  2184. APIS.openVideoNexilis(videoURL: tempPath)
  2185. }
  2186. } catch {
  2187. }
  2188. } else {
  2189. Download().startHTTP(forKey: vidData, isImage: false) { (name, progress) in
  2190. guard progress == 100 else {
  2191. return
  2192. }
  2193. DispatchQueue.main.async {
  2194. collectionView.reloadItems(at: [indexPath])
  2195. }
  2196. }
  2197. }
  2198. } else {
  2199. let gifURL = URL(fileURLWithPath: dirPath).appendingPathComponent(gifData)
  2200. if FileManager.default.fileExists(atPath: gifURL.path) {
  2201. do {
  2202. let data = try Data(contentsOf: gifURL)
  2203. APIS.openImageNexilis(image: UIImage(), data: data, isGIF: true)
  2204. } catch {
  2205. }
  2206. } else if FileEncryption.shared.isSecureExists(filename: gifData) {
  2207. do {
  2208. if let secureData = try FileEncryption.shared.readSecure(filename: gifData) {
  2209. APIS.openImageNexilis(image: UIImage(), data: secureData, isGIF: true)
  2210. }
  2211. } catch {
  2212. }
  2213. }
  2214. }
  2215. }
  2216. }
  2217. func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  2218. return self.previewItem != nil ? 1 : 0
  2219. }
  2220. func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> any QLPreviewItem {
  2221. return self.previewItem!
  2222. }
  2223. }
  2224. extension SecondTabViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  2225. func updateSearchResults(for searchController: UISearchController) {
  2226. filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
  2227. }
  2228. func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
  2229. recordAudio()
  2230. }
  2231. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
  2232. let attachment = NSTextAttachment()
  2233. attachment.image = image
  2234. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  2235. let attachmentStr = NSAttributedString(attachment: attachment)
  2236. let mutableAttributedString = NSMutableAttributedString()
  2237. mutableAttributedString.append(attachmentStr)
  2238. let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
  2239. let textString = NSAttributedString(string: text, attributes: attributedStringColor)
  2240. mutableAttributedString.append(textString)
  2241. return mutableAttributedString
  2242. }
  2243. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  2244. searchBar.showsCancelButton = true
  2245. let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
  2246. cBtn.setTitle("Cancel".localized(), for: .normal)
  2247. }
  2248. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  2249. searchBar.showsCancelButton = false
  2250. }
  2251. }
  2252. extension SecondTabViewController: SFSpeechRecognizerDelegate {
  2253. func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
  2254. if available {
  2255. self.isAllowSpeech = true
  2256. } else {
  2257. self.isAllowSpeech = false
  2258. }
  2259. }
  2260. }