SecondTabViewController.swift 126 KB

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