ChatWALikeVC.swift 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. //
  2. // ChatWALikeVC.swift
  3. // Pods
  4. //
  5. // Created by Qindi on 11/04/25.
  6. //
  7. import Foundation
  8. import UIKit
  9. import AVFAudio
  10. import QuickLook
  11. public class ChatWALikeVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, QLPreviewControllerDataSource, UISearchBarDelegate {
  12. private let tableView = UITableView(frame: .zero, style: .plain)
  13. private let searchController = UISearchController(searchResultsController: nil)
  14. var chats: [Chat] = []
  15. var tempChats: [Chat] = []
  16. var chatGroupMaps: [String: [Chat]] = [:]
  17. var loadingData = true
  18. private let textChatEmpty = UILabel()
  19. let contAll = UIButton(type: .custom)
  20. let textAll = UILabel()
  21. let contUnread = UIButton(type: .custom)
  22. let textUnread = UILabel()
  23. let contGroups = UIButton(type: .custom)
  24. let textGroups = UILabel()
  25. private static var filterMain = 0
  26. var fillteredData: [Any] = []
  27. var fillteredMessages: [Chat] = []
  28. var isFiltering: Bool {
  29. return !searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && searchController.searchBar.text!.count > 1
  30. }
  31. var previewItem: NSURL?
  32. var audioPlayer: AVAudioPlayer?
  33. let UNREAD_TAG = 10
  34. let PHOTOS_TAG = 11
  35. let DOCUMENTS_TAG = 12
  36. let LINKS_TAG = 13
  37. let VIDEOS_TAG = 14
  38. let GIFS_TAG = 15
  39. let AUDIOS_TAG = 16
  40. var selectedTag = 0
  41. var archivedChats: [Chat] = []
  42. var listMaxArchived: [String: [String]] = [:]
  43. var isGettingData = false
  44. var timerReloadData: Timer?
  45. public override func viewDidLoad() {
  46. NotificationCenter.default.addObserver(self, selector: #selector(onStatusChat(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerStatusChat), object: nil)
  47. NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil)
  48. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onMember"), object: nil)
  49. NotificationCenter.default.addObserver(self, selector: #selector(onReload(notification:)), name: NSNotification.Name(rawValue: "onUpdatePersonInfo"), object: nil)
  50. NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "reloadTabChats"), object: nil)
  51. NotificationCenter.default.addObserver(self, selector: #selector(onReloadTab(notification:)), name: NSNotification.Name(rawValue: "onTopic"), object: nil)
  52. NotificationCenter.default.addObserver(self, selector: #selector(onDisconnected(notification:)), name: NSNotification.Name(rawValue: "disconnected_nexilis"), object: nil)
  53. NotificationCenter.default.addObserver(self, selector: #selector(onDatabaseOpened(notification:)), name: NSNotification.Name(rawValue: "databaseOpened"), object: nil)
  54. tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellChatWA")
  55. tableView.dataSource = self
  56. tableView.delegate = self
  57. tableView.tableFooterView = UIView()
  58. tableView.sectionHeaderHeight = 0
  59. tableView.sectionFooterHeight = 0
  60. tableView.backgroundColor = .clear
  61. tableView.automaticallyAdjustsScrollIndicatorInsets = false
  62. if #available(iOS 15.0, *) {
  63. tableView.sectionHeaderTopPadding = 0
  64. }
  65. setupTableView()
  66. }
  67. @objc func onDatabaseOpened(notification: NSNotification) {
  68. reloadAllData()
  69. }
  70. @objc func onDisconnected(notification: NSNotification) {
  71. DispatchQueue.main.async {
  72. self.loadingData = true
  73. self.chatGroupMaps.removeAll()
  74. self.chats.removeAll()
  75. self.tableView.reloadData()
  76. self.reloadAllData()
  77. }
  78. }
  79. @objc func onReloadTab(notification: NSNotification) {
  80. reloadAllData()
  81. }
  82. @objc func onReload(notification: NSNotification) {
  83. DispatchQueue.main.async {
  84. let data:[AnyHashable : Any] = notification.userInfo!
  85. if data["member"] as? String == User.getMyPin()! {
  86. self.reloadAllData()
  87. } else if data["state"] as? Int == 99 {
  88. self.reloadAllData()
  89. }
  90. }
  91. }
  92. @objc func onReceiveMessage(notification: NSNotification) {
  93. reloadAllData()
  94. }
  95. @objc func onStatusChat(notification: NSNotification) {
  96. reloadAllData()
  97. }
  98. private func reloadAllData() {
  99. // print("reloadAllData")
  100. DispatchQueue.main.async { [weak self] in
  101. guard let self = self else { return }
  102. if self.timerReloadData == nil && !self.isGettingData {
  103. self.refresh()
  104. } else {
  105. self.timerReloadData?.invalidate()
  106. self.timerReloadData = nil
  107. self.timerReloadData = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in
  108. if self != nil && !self!.isGettingData {
  109. guard let self = self else { return }
  110. self.refresh()
  111. self.timerReloadData = nil
  112. }
  113. }
  114. }
  115. }
  116. }
  117. public override func viewWillAppear(_ animated: Bool) {
  118. navigationItem.title = "Chats".localized()
  119. navigationItem.hidesSearchBarWhenScrolling = true
  120. tabBarController?.navigationController?.setNavigationBarHidden(true, animated: false)
  121. navigationController?.navigationBar.prefersLargeTitles = true
  122. navigationController?.navigationItem.largeTitleDisplayMode = .always
  123. navigationController?.navigationBar.backgroundColor = .clear
  124. navigationController?.navigationBar.tintColor = .black
  125. navigationController?.navigationBar.overrideUserInterfaceStyle = .light
  126. self.setNeedsStatusBarAppearanceUpdate()
  127. let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16)]
  128. let largeAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: self.traitCollection.userInterfaceStyle == .dark ? .white : UIColor.black, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 34)]
  129. let appearance = UINavigationBarAppearance()
  130. appearance.configureWithTransparentBackground()
  131. appearance.backgroundColor = .clear
  132. appearance.titleTextAttributes = attributes
  133. appearance.largeTitleTextAttributes = largeAttributes
  134. navigationController?.navigationBar.standardAppearance = appearance
  135. navigationController?.navigationBar.scrollEdgeAppearance = appearance
  136. let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]
  137. UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
  138. // let leftButton = UIButton(type: .system)
  139. // let imageLeft = UIImage(systemName: "ellipsis", withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .bold))
  140. // leftButton.setImage(imageLeft, for: .normal)
  141. // leftButton.tintColor = .black
  142. // leftButton.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
  143. // leftButton.layer.cornerRadius = 15
  144. // leftButton.clipsToBounds = true
  145. // leftButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
  146. // leftButton.addTarget(self, action: #selector(leftBarButtonTapped), for: .touchUpInside)
  147. // let leftBarButtonItem = UIBarButtonItem(customView: leftButton)
  148. // navigationItem.leftBarButtonItem = leftBarButtonItem
  149. let rightButton = UIButton(type: .system)
  150. let imageRight = UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .bold))
  151. rightButton.setImage(imageRight, for: .normal)
  152. if #unavailable(iOS 26.0) {
  153. rightButton.tintColor = .white
  154. rightButton.backgroundColor = .whatsappGreenColor
  155. } else {
  156. rightButton.tintColor = .black
  157. }
  158. rightButton.layer.cornerRadius = 15
  159. rightButton.clipsToBounds = true
  160. rightButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
  161. rightButton.addTarget(self, action: #selector(rightBarButtonTapped), for: .touchUpInside)
  162. let rightBarButtonItem = UIBarButtonItem(customView: rightButton)
  163. navigationItem.rightBarButtonItem = rightBarButtonItem
  164. searchController.searchResultsUpdater = self
  165. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  166. searchController.obscuresBackgroundDuringPresentation = false
  167. searchController.hidesNavigationBarDuringPresentation = true
  168. searchController.searchBar.delegate = self
  169. navigationItem.searchController = searchController
  170. definesPresentationContext = true
  171. DispatchQueue.main.async {
  172. self.navigationController?.navigationBar.sizeToFit()
  173. }
  174. }
  175. private func refresh() {
  176. if self.isGettingData {
  177. return
  178. }
  179. getData { [self] in
  180. if tempChats.count == 0 {
  181. searchController.searchBar.isHidden = true
  182. if textChatEmpty.isDescendant(of: view) {
  183. textChatEmpty.removeFromSuperview()
  184. }
  185. textChatEmpty.numberOfLines = 0
  186. let fullText = "To place chats, tap ⊕ at the top and select a contact.".localized()
  187. let attributedString = NSMutableAttributedString(string: fullText)
  188. attributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: 0, length: attributedString.length))
  189. if let plusRange = fullText.range(of: "⊕") {
  190. let nsRange = NSRange(plusRange, in: fullText)
  191. attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 40), range: nsRange)
  192. }
  193. textChatEmpty.attributedText = attributedString
  194. tableView.addSubview(textChatEmpty)
  195. textChatEmpty.anchor(left: tableView.leftAnchor, right: tableView.rightAnchor, paddingLeft: 20, paddingRight: 20, centerX: tableView.centerXAnchor)
  196. textChatEmpty.centerYAnchor.constraint(equalTo: tableView.centerYAnchor, constant: -60).isActive = true
  197. } else {
  198. if textChatEmpty.isDescendant(of: view) {
  199. textChatEmpty.removeFromSuperview()
  200. }
  201. searchController.searchBar.isHidden = false
  202. }
  203. }
  204. }
  205. public override func viewDidAppear(_ animated: Bool) {
  206. if Nexilis.floatingButton.isHidden {
  207. Nexilis.floatingButton.isHidden = false
  208. }
  209. refresh()
  210. }
  211. private func getData(completion: @escaping ()->()) {
  212. getChats {
  213. DispatchQueue.main.async {
  214. self.tableView.reloadData()
  215. self.loadingData = false
  216. self.isGettingData = false
  217. completion()
  218. }
  219. }
  220. }
  221. func getChats(completion: @escaping ()->()) {
  222. DispatchQueue.global().async {
  223. self.isGettingData = true
  224. self.chatGroupMaps.removeAll()
  225. self.listMaxArchived.removeAll()
  226. let previousChat = self.chats
  227. let allChats = Chat.getData()
  228. self.archivedChats = Chat.getData(isArchived: true)
  229. var tempChats: [Chat] = []
  230. var lowestPinned: [String: Int64] = [:]
  231. for singleChat in allChats {
  232. guard !singleChat.groupId.isEmpty else {
  233. tempChats.append(singleChat)
  234. if singleChat.pinned > 0 {
  235. self.listMaxArchived[singleChat.pin] = [""]
  236. }
  237. continue
  238. }
  239. let chatParentInPreviousChats = previousChat.first { $0.isParent && $0.groupId == singleChat.groupId }
  240. if var existingGroup = self.chatGroupMaps[singleChat.groupId] {
  241. existingGroup.insert(singleChat, at: 0)
  242. self.chatGroupMaps[singleChat.groupId] = existingGroup
  243. if let parentChatIndex = tempChats.firstIndex(where: { $0.groupId == singleChat.groupId && $0.isParent }) {
  244. if let counterParent = Int(tempChats[parentChatIndex].counter), let counterSingle = Int(singleChat.counter) {
  245. tempChats[parentChatIndex].counter = "\(counterParent + counterSingle)"
  246. }
  247. if singleChat.pinned != 0 && (lowestPinned[singleChat.groupId] == 0 || lowestPinned[singleChat.groupId]! > singleChat.pinned) {
  248. lowestPinned[singleChat.groupId] = singleChat.pinned
  249. }
  250. if singleChat.pinned != 0 {
  251. if !self.listMaxArchived.keys.contains(singleChat.groupId) {
  252. self.listMaxArchived[singleChat.groupId] = [singleChat.pin]
  253. } else {
  254. self.listMaxArchived[singleChat.groupId]?.append(singleChat.pin)
  255. }
  256. }
  257. if tempChats[parentChatIndex].pinned < singleChat.pinned {
  258. tempChats[parentChatIndex].pinned = singleChat.pinned
  259. }
  260. if tempChats[parentChatIndex].pinned > 0 {
  261. if singleChat.pinned == 0 {
  262. singleChat.pinned = lowestPinned[singleChat.groupId]! - 1
  263. singleChat.isFolPinned = true
  264. }
  265. tempChats.forEach { chat in
  266. if chat.groupId == singleChat.groupId && (chat.pinned == 0 || (chat.isFolPinned && chat.pinned != lowestPinned[singleChat.groupId]! - 1)) {
  267. chat.pinned = lowestPinned[singleChat.groupId]! - 1
  268. chat.isFolPinned = true
  269. }
  270. }
  271. }
  272. }
  273. if let parentExist = chatParentInPreviousChats, parentExist.isSelected,
  274. let indexParent = tempChats.firstIndex(where: { $0.isParent && $0.groupId == singleChat.groupId }) {
  275. tempChats.insert(singleChat, at: min(indexParent + existingGroup.count, tempChats.count))
  276. }
  277. } else {
  278. if lowestPinned[singleChat.groupId] == nil {
  279. lowestPinned[singleChat.groupId] = 0
  280. }
  281. if singleChat.pinned != 0 {
  282. lowestPinned[singleChat.groupId] = singleChat.pinned
  283. }
  284. self.chatGroupMaps[singleChat.groupId] = [singleChat]
  285. let parentChat = Chat(profile: singleChat.profile, groupName: singleChat.groupName, counter: singleChat.counter, groupId: singleChat.groupId)
  286. parentChat.isParent = true
  287. if parentChat.pinned != singleChat.pinned {
  288. parentChat.pinned = singleChat.pinned
  289. self.listMaxArchived[singleChat.groupId] = [singleChat.pin]
  290. }
  291. if let parentExist = chatParentInPreviousChats, parentExist.isSelected {
  292. parentChat.isSelected = true
  293. tempChats.append(parentChat)
  294. tempChats.append(singleChat)
  295. } else {
  296. tempChats.append(parentChat)
  297. }
  298. }
  299. }
  300. tempChats.sort(by: { $0.pinned > $1.pinned })
  301. if self.archivedChats.count > 0 {
  302. tempChats.insert(Chat(pin: "Archived"), at: 0)
  303. }
  304. self.chats = tempChats
  305. self.tempChats = tempChats
  306. completion()
  307. }
  308. }
  309. @objc func leftBarButtonTapped() {
  310. print("Left bar button tapped")
  311. }
  312. @objc func rightBarButtonTapped() {
  313. APIS.openChat()
  314. }
  315. private func setupTableView() {
  316. view.addSubview(tableView)
  317. tableView.translatesAutoresizingMaskIntoConstraints = false
  318. NSLayoutConstraint.activate([
  319. tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
  320. tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  321. tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
  322. tableView.rightAnchor.constraint(equalTo: view.rightAnchor)
  323. ])
  324. }
  325. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  326. let header = UIView()
  327. if tempChats.count > 0 {
  328. header.addSubview(contAll)
  329. contAll.anchor(top: header.topAnchor, left: header.leftAnchor, bottom: header.bottomAnchor, paddingLeft: 20, height: 30)
  330. contAll.layer.cornerRadius = 15
  331. contAll.clipsToBounds = true
  332. contAll.tag = 0
  333. contAll.backgroundColor = ChatWALikeVC.filterMain == 0 ? .whatsappGreenLightColor : .whiteBubbleColor
  334. contAll.addTarget(self, action: #selector(selectFilter), for: .touchUpInside)
  335. contAll.addSubview(textAll)
  336. textAll.text = "All".localized()
  337. textAll.font = .boldSystemFont(ofSize: 14)
  338. textAll.textColor = ChatWALikeVC.filterMain == 0 ? .whatsappGreenTitleColor : .grayTitleColor
  339. textAll.anchor(left: contAll.leftAnchor, right: contAll.rightAnchor, paddingLeft: 15, paddingRight: 15, centerX: contAll.centerXAnchor, centerY: contAll.centerYAnchor, height: 20)
  340. header.addSubview(contUnread)
  341. contUnread.anchor(top: header.topAnchor, left: contAll.rightAnchor, bottom: header.bottomAnchor, paddingLeft: 8, height: 30)
  342. contUnread.layer.cornerRadius = 15
  343. contUnread.clipsToBounds = true
  344. contUnread.tag = 1
  345. contUnread.backgroundColor = ChatWALikeVC.filterMain == 1 ? .whatsappGreenLightColor : .whiteBubbleColor
  346. contUnread.addTarget(self, action: #selector(selectFilter), for: .touchUpInside)
  347. contUnread.addSubview(textUnread)
  348. textUnread.text = "Unread".localized()
  349. textUnread.font = .boldSystemFont(ofSize: 14)
  350. textUnread.textColor = ChatWALikeVC.filterMain == 1 ? .whatsappGreenTitleColor : .grayTitleColor
  351. textUnread.anchor(left: contUnread.leftAnchor, right: contUnread.rightAnchor, paddingLeft: 15, paddingRight: 15, centerX: contUnread.centerXAnchor, centerY: contUnread.centerYAnchor, height: 20)
  352. header.addSubview(contGroups)
  353. contGroups.anchor(top: header.topAnchor, left: contUnread.rightAnchor, bottom: header.bottomAnchor, paddingLeft: 8, height: 30)
  354. contGroups.layer.cornerRadius = 15
  355. contGroups.clipsToBounds = true
  356. contGroups.tag = 2
  357. contGroups.backgroundColor = ChatWALikeVC.filterMain == 2 ? .whatsappGreenLightColor : .whiteBubbleColor
  358. contGroups.addTarget(self, action: #selector(selectFilter), for: .touchUpInside)
  359. contGroups.addSubview(textGroups)
  360. textGroups.text = "Groups".localized()
  361. textGroups.font = .boldSystemFont(ofSize: 14)
  362. textGroups.textColor = ChatWALikeVC.filterMain == 2 ? .whatsappGreenTitleColor : .grayTitleColor
  363. textGroups.anchor(left: contGroups.leftAnchor, right: contGroups.rightAnchor, paddingLeft: 15, paddingRight: 15, centerX: contGroups.centerXAnchor, centerY: contGroups.centerYAnchor, height: 20)
  364. }
  365. return header
  366. }
  367. @objc func selectFilter(_ sender: UIButton) {
  368. if sender.tag == 0 && ChatWALikeVC.filterMain != 0 {
  369. ChatWALikeVC.filterMain = 0
  370. self.chats = self.tempChats
  371. self.tableView.reloadData()
  372. } else if sender.tag == 1 && ChatWALikeVC.filterMain != 1 {
  373. ChatWALikeVC.filterMain = 1
  374. self.chats = self.tempChats.filter({ Int($0.counter) ?? 0 > 0 })
  375. self.tableView.reloadData()
  376. } else if sender.tag == 2 && ChatWALikeVC.filterMain != 2 {
  377. ChatWALikeVC.filterMain = 2
  378. self.chats = self.tempChats.filter({ !$0.groupId.isEmpty })
  379. self.tableView.reloadData()
  380. }
  381. }
  382. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  383. return 30
  384. }
  385. public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  386. if fillteredData.count > 0 && selectedTag != UNREAD_TAG && selectedTag != 0 {
  387. if selectedTag == LINKS_TAG {
  388. return 160.0
  389. }
  390. return 130.0
  391. }
  392. let fontSize = Int(SecureUserDefaults.shared.value(forKey: "font_size") ?? "0")
  393. var finalHeight = 75.0
  394. if self.archivedChats.count > 0 && indexPath.row == 0 {
  395. finalHeight = 50.0
  396. }
  397. if fontSize == 4 {
  398. finalHeight += 10
  399. } else if fontSize == 6 {
  400. finalHeight += 20
  401. }
  402. return finalHeight
  403. }
  404. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  405. let sectionHeaderHeight: CGFloat = 30
  406. if scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0 {
  407. scrollView.contentInset.top = -scrollView.contentOffset.y
  408. } else if scrollView.contentOffset.y >= sectionHeaderHeight {
  409. scrollView.contentInset.top = -sectionHeaderHeight
  410. }
  411. }
  412. public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  413. let data: Chat
  414. if isFiltering {
  415. data = fillteredData[indexPath.row] as! Chat
  416. } else {
  417. data = chats[indexPath.row]
  418. }
  419. if !data.isParent {
  420. if self.archivedChats.count > 0 && indexPath.row == 0 {
  421. return nil
  422. }
  423. let archiveAction = UIContextualAction(style: .normal, title: "Archive".localized()) { (_, _, completionHandler) in
  424. DispatchQueue.global().async {
  425. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  426. do {
  427. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  428. "pinned" : 0,
  429. "archived" : Date().currentTimeMillis()
  430. ], _where: "l_pin = '\(data.pin)'")
  431. } catch {
  432. rollback.pointee = true
  433. print("Access database error: \(error.localizedDescription)")
  434. }
  435. })
  436. }
  437. self.chats.remove(at: indexPath.row)
  438. tableView.deleteRows(at: [indexPath], with: .right)
  439. self.getChats() {
  440. DispatchQueue.main.async {
  441. self.tableView.reloadData()
  442. self.isGettingData = false
  443. }
  444. }
  445. completionHandler(true)
  446. }
  447. let archiveIcon = UIImage(systemName: "archivebox.fill")!
  448. archiveAction.backgroundColor = UIColor.mainColor
  449. archiveAction.image = archiveIcon
  450. var textPinned = "Pin".localized()
  451. var pinnedDate = Date().currentTimeMillis()
  452. var imagePinned = UIImage(systemName: "pin.fill")!
  453. if data.pinned != 0 && !data.isFolPinned {
  454. textPinned = "Unpin".localized()
  455. pinnedDate = 0
  456. imagePinned = UIImage(systemName: "pin.slash.fill")!
  457. }
  458. let unpinAction = UIContextualAction(style: .normal, title: textPinned) { (_, _, completionHandler) in
  459. if pinnedDate != 0 && ((self.listMaxArchived[data.groupId] != nil && self.listMaxArchived[data.groupId]!.count == 3) || (self.listMaxArchived.count == 3)) {
  460. let alertController = LibAlertController(
  461. title: "You can only pin 3 chats".localized(),
  462. message: nil,
  463. preferredStyle: .alert
  464. )
  465. alertController.addAction(UIAlertAction(title: "OK".localized(), style: .cancel, handler: nil))
  466. if UIApplication.shared.visibleViewController?.navigationController != nil {
  467. UIApplication.shared.visibleViewController?.navigationController?.present(alertController, animated: true, completion: nil)
  468. } else {
  469. UIApplication.shared.visibleViewController?.present(alertController, animated: true, completion: nil)
  470. }
  471. } else {
  472. DispatchQueue.global().async {
  473. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  474. do {
  475. _ = Database.shared.updateRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  476. "pinned" : pinnedDate
  477. ], _where: "l_pin = '\(data.pin)'")
  478. } catch {
  479. rollback.pointee = true
  480. print("Access database error: \(error.localizedDescription)")
  481. }
  482. })
  483. }
  484. self.chats.remove(at: indexPath.row)
  485. tableView.deleteRows(at: [indexPath], with: .right)
  486. self.getChats() {
  487. DispatchQueue.main.async {
  488. self.tableView.reloadData()
  489. self.isGettingData = false
  490. }
  491. }
  492. }
  493. completionHandler(true)
  494. }
  495. let pinIcon = imagePinned
  496. unpinAction.backgroundColor = UIColor.darkGray
  497. unpinAction.image = pinIcon
  498. let configuration = UISwipeActionsConfiguration(actions: [archiveAction, unpinAction])
  499. return configuration
  500. }
  501. return nil
  502. }
  503. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  504. if isFiltering {
  505. return fillteredData.count
  506. }
  507. return chats.count
  508. }
  509. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  510. let cell = tableView.dequeueReusableCell(withIdentifier: "cellChatWA", for: indexPath)
  511. cell.backgroundColor = .clear
  512. let content = cell.contentView
  513. if content.subviews.count > 0 {
  514. content.subviews.forEach { $0.removeFromSuperview() }
  515. }
  516. let data: Chat
  517. if isFiltering {
  518. data = fillteredData[indexPath.row] as! Chat
  519. } else {
  520. if chats.count == 0 || (indexPath.row > (chats.count - 1)) {
  521. let labelNochat = UILabel()
  522. labelNochat.text = loadingData ? "Loading Data...".localized() : "There are no conversations".localized()
  523. labelNochat.font = .systemFont(ofSize: 13 + String.offset())
  524. labelNochat.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  525. content.addSubview(labelNochat)
  526. labelNochat.anchor(centerX: content.centerXAnchor, centerY: content.centerYAnchor)
  527. cell.backgroundColor = .clear
  528. cell.selectionStyle = .none
  529. return cell
  530. }
  531. data = chats[indexPath.row]
  532. }
  533. if selectedTag != UNREAD_TAG && selectedTag != 0 {
  534. let title = UILabel()
  535. let subtitle = UILabel()
  536. title.textColor = .black
  537. subtitle.textColor = .gray
  538. title.font = .systemFont(ofSize: 16 + String.offset(), weight: .medium)
  539. subtitle.font = .systemFont(ofSize: 14 + String.offset())
  540. content.addSubview(title)
  541. content.addSubview(subtitle)
  542. title.anchor(top: content.topAnchor, left: content.leftAnchor, paddingTop: 10, paddingLeft: 20)
  543. subtitle.anchor(top: title.bottomAnchor, left: content.leftAnchor, right: content.rightAnchor, paddingLeft: 20, paddingRight: 20)
  544. subtitle.numberOfLines = 2
  545. title.text = data.name
  546. let imageArrowRight = UIImageView(image: UIImage(systemName: "chevron.right"))
  547. content.addSubview(imageArrowRight)
  548. imageArrowRight.tintColor = .gray
  549. imageArrowRight.anchor(top: content.topAnchor, right: content.rightAnchor, paddingTop: 10, paddingRight: 20)
  550. let timeView = UILabel()
  551. content.addSubview(timeView)
  552. timeView.anchor(top: content.topAnchor, right: imageArrowRight.leftAnchor, paddingTop: 10, paddingRight: 20)
  553. timeView.textColor = .gray
  554. timeView.font = UIFont.systemFont(ofSize: 16 + String.offset())
  555. let date = Date(milliseconds: Int64(data.serverDate)!)
  556. let calendar = Calendar.current
  557. if (calendar.isDateInToday(date)) {
  558. let formatter = DateFormatter()
  559. formatter.dateFormat = "HH:mm"
  560. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  561. timeView.text = formatter.string(from: date as Date)
  562. } else {
  563. let startOfNow = calendar.startOfDay(for: Date())
  564. let startOfTimeStamp = calendar.startOfDay(for: date)
  565. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  566. let day = -(components.day!)
  567. if day == 1 {
  568. timeView.text = "Yesterday".localized()
  569. } else {
  570. if day < 7 {
  571. let formatter = DateFormatter()
  572. formatter.dateFormat = "EEEE"
  573. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  574. if lang == "id" {
  575. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  576. }
  577. timeView.text = formatter.string(from: date)
  578. } else {
  579. let formatter = DateFormatter()
  580. formatter.dateFormat = "M/dd/yy"
  581. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  582. let stringFormat = formatter.string(from: date as Date)
  583. timeView.text = stringFormat
  584. }
  585. }
  586. }
  587. cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
  588. let container = UIView()
  589. content.addSubview(container)
  590. container.anchor(top: subtitle.bottomAnchor, left: content.leftAnchor, right: content.rightAnchor, paddingTop: 5, paddingLeft: 20, paddingRight: 20, height: selectedTag == LINKS_TAG ? 75 : 60)
  591. container.backgroundColor = .lightGray.withAlphaComponent(0.3)
  592. container.layer.cornerRadius = 15
  593. container.clipsToBounds = true
  594. container.isUserInteractionEnabled = true
  595. if selectedTag == DOCUMENTS_TAG {
  596. subtitle.text = "📄 " + "Document".localized()
  597. let imageFile = UIImageView(image: UIImage(systemName: "doc.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 45)))
  598. container.addSubview(imageFile)
  599. imageFile.tintColor = .black
  600. imageFile.anchor(top: container.topAnchor, left: container.leftAnchor, bottom: container.bottomAnchor, paddingTop: 5, paddingLeft: 5, paddingBottom: 5, width: 45)
  601. let nameFile = UILabel()
  602. container.addSubview(nameFile)
  603. nameFile.font = .systemFont(ofSize: 12 + String.offset(), weight: .medium)
  604. nameFile.textColor = .black
  605. nameFile.numberOfLines = 2
  606. nameFile.anchor(top: container.topAnchor, left: imageFile.rightAnchor, right: container.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingRight: 5)
  607. nameFile.text = data.messageText.components(separatedBy: "|")[0]
  608. let fileSub = UILabel()
  609. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  610. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  611. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  612. let arrExtFile = (data.messageText.components(separatedBy: "|")[0]).split(separator: ".")
  613. let finalExtFile = arrExtFile[arrExtFile.count - 1]
  614. if let dirPath = paths.first {
  615. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(data.file)
  616. if FileManager.default.fileExists(atPath: fileURL.path) {
  617. if let dataFile = try? Data(contentsOf: fileURL) {
  618. var sizeOfFile = Int(dataFile.count / 1000000)
  619. if (sizeOfFile < 1) {
  620. sizeOfFile = Int(dataFile.count / 1000)
  621. if (finalExtFile.count > 4) {
  622. fileSub.text = "\(sizeOfFile) kB \u{2022} TXT"
  623. }else {
  624. fileSub.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  625. }
  626. } else {
  627. if (finalExtFile.count > 4) {
  628. fileSub.text = "\(sizeOfFile) MB \u{2022} TXT"
  629. }else {
  630. fileSub.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  631. }
  632. }
  633. } else {
  634. fileSub.text = ""
  635. }
  636. }
  637. else if FileEncryption.shared.isSecureExists(filename: data.file) {
  638. if var dataFile = try? FileEncryption.shared.readSecure(filename: data.file) {
  639. let dataDecrypt = FileEncryption.shared.decryptFileFromServer(data: dataFile)
  640. if dataDecrypt != nil {
  641. dataFile = dataDecrypt!
  642. }
  643. var sizeOfFile = Int(dataFile.count / 1000000)
  644. if (sizeOfFile < 1) {
  645. sizeOfFile = Int(dataFile.count / 1000)
  646. if (finalExtFile.count > 4) {
  647. fileSub.text = "\(sizeOfFile) kB \u{2022} TXT"
  648. }else {
  649. fileSub.text = "\(sizeOfFile) kB \u{2022} \(finalExtFile.uppercased())"
  650. }
  651. } else {
  652. if (finalExtFile.count > 4) {
  653. fileSub.text = "\(sizeOfFile) MB \u{2022} TXT"
  654. }else {
  655. fileSub.text = "\(sizeOfFile) MB \u{2022} \(finalExtFile.uppercased())"
  656. }
  657. }
  658. } else {
  659. fileSub.text = ""
  660. }
  661. }
  662. container.addSubview(fileSub)
  663. fileSub.anchor(top: nameFile.bottomAnchor, left: imageFile.rightAnchor, bottom: container.bottomAnchor, paddingLeft: 10, paddingBottom: 5)
  664. fileSub.font = .systemFont(ofSize: 10 + String.offset())
  665. fileSub.textColor = .gray
  666. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  667. objectTap.file_id = data.file
  668. container.addGestureRecognizer(objectTap)
  669. }
  670. } else if selectedTag == LINKS_TAG {
  671. var text = ""
  672. var txtData = data.messageText
  673. if txtData.contains("■"){
  674. txtData = txtData.components(separatedBy: "■")[0]
  675. txtData = txtData.trimmingCharacters(in: .whitespacesAndNewlines)
  676. }
  677. let listTextSplitBreak = txtData.components(separatedBy: "\n")
  678. let indexFirstLinkSplitBreak = listTextSplitBreak.firstIndex(where: { $0.contains("www.") || $0.contains("http://") || $0.contains("https://") })
  679. if indexFirstLinkSplitBreak != nil {
  680. let listTextSplitSpace = listTextSplitBreak[indexFirstLinkSplitBreak!].components(separatedBy: " ")
  681. 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) })
  682. if indexFirstLinkSplitSpace != nil {
  683. text = listTextSplitSpace[indexFirstLinkSplitSpace!]
  684. }
  685. }
  686. var dataURL = ""
  687. subtitle.text = txtData
  688. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  689. do {
  690. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select data_link from LINK_PREVIEW where link='\(text)'"), cursor.next() {
  691. if let data = cursor.string(forColumnIndex: 0) {
  692. dataURL = data
  693. }
  694. cursor.close()
  695. }
  696. } catch {
  697. rollback.pointee = true
  698. print("Access database error: \(error.localizedDescription)")
  699. }
  700. })
  701. var title = ""
  702. var description = ""
  703. var imageUrl: String?
  704. var link = text
  705. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  706. objectTap.message_id = link
  707. container.addGestureRecognizer(objectTap)
  708. let imagePreview = UIImageView()
  709. container.addSubview(imagePreview)
  710. imagePreview.translatesAutoresizingMaskIntoConstraints = false
  711. imagePreview.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
  712. imagePreview.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  713. imagePreview.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
  714. imagePreview.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
  715. imagePreview.image = UIImage(systemName: "link", withConfiguration: UIImage.SymbolConfiguration(pointSize: 45))
  716. imagePreview.contentMode = .center
  717. imagePreview.clipsToBounds = true
  718. imagePreview.tintColor = .black
  719. imagePreview.backgroundColor = .gray.withAlphaComponent(0.3)
  720. let titlePreview = UILabel()
  721. container.addSubview(titlePreview)
  722. titlePreview.translatesAutoresizingMaskIntoConstraints = false
  723. titlePreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  724. titlePreview.topAnchor.constraint(equalTo: container.topAnchor, constant: 10.0).isActive = true
  725. titlePreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  726. titlePreview.text = title
  727. titlePreview.font = UIFont.systemFont(ofSize: 14.0 + String.offset(), weight: .bold)
  728. titlePreview.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  729. let descPreview = UILabel()
  730. container.addSubview(descPreview)
  731. descPreview.translatesAutoresizingMaskIntoConstraints = false
  732. descPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  733. descPreview.topAnchor.constraint(equalTo: titlePreview.bottomAnchor).isActive = true
  734. descPreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  735. descPreview.text = description
  736. descPreview.font = UIFont.systemFont(ofSize: 12.0 + String.offset())
  737. descPreview.textColor = .gray
  738. descPreview.numberOfLines = 1
  739. let linkPreview = UILabel()
  740. container.addSubview(linkPreview)
  741. linkPreview.translatesAutoresizingMaskIntoConstraints = false
  742. linkPreview.leadingAnchor.constraint(equalTo: imagePreview.trailingAnchor, constant: 5.0).isActive = true
  743. linkPreview.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -5.0).isActive = true
  744. linkPreview.font = UIFont.systemFont(ofSize: 10.0 + String.offset())
  745. linkPreview.textColor = .gray
  746. linkPreview.numberOfLines = 1
  747. if !dataURL.isEmpty {
  748. if let data = try! JSONSerialization.jsonObject(with: dataURL.data(using: String.Encoding.utf8)!, options: []) as? [String: Any] {
  749. title = data["title"] as! String
  750. description = data["description"] as! String
  751. imageUrl = data["imageUrl"] as? String
  752. link = data["link"] as! String
  753. if imageUrl != nil {
  754. imagePreview.loadImageAsync(with: imageUrl)
  755. imagePreview.contentMode = .scaleToFill
  756. imagePreview.clipsToBounds = true
  757. }
  758. titlePreview.text = title
  759. descPreview.text = description
  760. linkPreview.text = link
  761. linkPreview.topAnchor.constraint(equalTo: descPreview.bottomAnchor, constant: 8.0).isActive = true
  762. }
  763. } else {
  764. linkPreview.text = link
  765. linkPreview.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
  766. }
  767. } else if selectedTag == AUDIOS_TAG {
  768. subtitle.text = "♫ " + "Audio".localized()
  769. let imageAudio = UIImageView()
  770. imageAudio.image = UIImage(systemName: "music.note", withConfiguration: UIImage.SymbolConfiguration(pointSize: 35))
  771. container.addSubview(imageAudio)
  772. imageAudio.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  773. imageAudio.tintColor = .black
  774. let nameAudio = UILabel()
  775. container.addSubview(nameAudio)
  776. nameAudio.anchor(left: imageAudio.rightAnchor, right: container.rightAnchor, paddingLeft: 10, paddingRight: 10, centerY: container.centerYAnchor)
  777. nameAudio.numberOfLines = 2
  778. nameAudio.text = data.messageText.components(separatedBy: "|")[0]
  779. nameAudio.font = .systemFont(ofSize: 16 + String.offset(), weight: .medium)
  780. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  781. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  782. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  783. if let dirPath = paths.first {
  784. let audioURL = URL(fileURLWithPath: dirPath).appendingPathComponent(data.audio)
  785. if !FileManager.default.fileExists(atPath: audioURL.path) && !FileEncryption.shared.isSecureExists(filename: data.audio) {
  786. Download().startHTTP(forKey: data.audio) { (name, progress) in
  787. guard progress == 100 else {
  788. return
  789. }
  790. tableView.reloadRows(at: [indexPath], with: .none)
  791. }
  792. } else {
  793. let objectTap = ObjectGesture(target: self, action: #selector(onContSearch(_:)))
  794. objectTap.audio_id = data.audio
  795. container.addGestureRecognizer(objectTap)
  796. }
  797. }
  798. }
  799. return cell
  800. }
  801. if self.archivedChats.count > 0 && indexPath.row == 0 {
  802. let imageView = UIImageView()
  803. content.addSubview(imageView)
  804. imageView.translatesAutoresizingMaskIntoConstraints = false
  805. NSLayoutConstraint.activate([
  806. imageView.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  807. imageView.widthAnchor.constraint(equalToConstant: 20.0),
  808. imageView.heightAnchor.constraint(equalToConstant: 20.0),
  809. imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 25.0)
  810. ])
  811. imageView.image = UIImage(systemName: "archivebox")!
  812. imageView.tintColor = .darkGray
  813. let titleView = UILabel()
  814. content.addSubview(titleView)
  815. titleView.translatesAutoresizingMaskIntoConstraints = false
  816. NSLayoutConstraint.activate([
  817. titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 25.0),
  818. titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  819. titleView.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  820. ])
  821. titleView.font = UIFont.boldSystemFont(ofSize: 14 + String.offset())
  822. titleView.text = "Archived".localized()
  823. titleView.textColor = .darkGray
  824. cell.backgroundColor = .clear
  825. cell.separatorInset = UIEdgeInsets(top: 0, left: 60.0, bottom: 0, right: 0)
  826. return cell
  827. }
  828. let imageView = UIImageView()
  829. content.addSubview(imageView)
  830. imageView.translatesAutoresizingMaskIntoConstraints = false
  831. NSLayoutConstraint.activate([
  832. imageView.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  833. imageView.widthAnchor.constraint(equalToConstant: 55.0),
  834. imageView.heightAnchor.constraint(equalToConstant: 55.0)
  835. ])
  836. var leadingAnchor = imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 20.0)
  837. if data.pin == "-997" {
  838. imageView.frame = CGRect(x: 0, y: 0, width: 55.0, height: 55.0)
  839. imageView.circle()
  840. if let urlGif = Bundle.resourceBundle(for: Nexilis.self).url(forResource: "pb_gpt_bot", withExtension: "gif") {
  841. imageView.sd_setImage(with: urlGif) { (image, error, cacheType, imageURL) in
  842. if error == nil {
  843. imageView.animationImages = image?.images
  844. imageView.animationDuration = image?.duration ?? 0.0
  845. imageView.animationRepeatCount = 0
  846. imageView.startAnimating()
  847. }
  848. }
  849. } else if let urlGif = Bundle.resourcesMediaBundle(for: Nexilis.self).url(forResource: "pb_gpt_bot", withExtension: "gif") {
  850. imageView.sd_setImage(with: urlGif) { (image, error, cacheType, imageURL) in
  851. if error == nil {
  852. imageView.animationImages = image?.images
  853. imageView.animationDuration = image?.duration ?? 0.0
  854. imageView.animationRepeatCount = 0
  855. imageView.startAnimating()
  856. }
  857. }
  858. }
  859. } else {
  860. if !Utils.getIconDock().isEmpty && data.official == "1" {
  861. let urlString = Utils.getUrlDock()!
  862. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  863. let imageData = cachedImage
  864. imageView.image = imageData
  865. } else {
  866. DispatchQueue.global().async{
  867. Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
  868. guard let data = data, error == nil else { return }
  869. DispatchQueue.main.async() {
  870. if UIImage(data: data) != nil {
  871. let imageData = UIImage(data: data)!
  872. imageView.image = imageData
  873. ImageCache.shared.save(image: imageData, forKey: urlString)
  874. }
  875. }
  876. }
  877. }
  878. }
  879. } else {
  880. if data.messageScope == MessageScope.WHISPER || data.messageScope == MessageScope.CALL || data.messageScope == MessageScope.MISSED_CALL || data.isParent || data.pin == "-999" {
  881. getImage(name: data.profile, placeholderImage: UIImage(named: data.pin == "-999" ? "pb_button" : (data.messageScope == MessageScope.WHISPER || data.messageScope == MessageScope.CALL || data.messageScope == MessageScope.MISSED_CALL) ? "Profile---Purple" : "Conversation---Black", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  882. imageView.image = image
  883. })
  884. } else {
  885. leadingAnchor = imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 40.0)
  886. let image = UIImage(named: "Conversation---Black", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  887. imageView.image = image
  888. }
  889. }
  890. }
  891. leadingAnchor.isActive = true
  892. let titleView = UILabel()
  893. content.addSubview(titleView)
  894. titleView.translatesAutoresizingMaskIntoConstraints = false
  895. NSLayoutConstraint.activate([
  896. titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  897. titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  898. ])
  899. titleView.font = UIFont.systemFont(ofSize: 14 + String.offset(), weight: .medium)
  900. let timeView = UILabel()
  901. let viewCounter = UIView()
  902. if data.counter != "0" {
  903. timeView.textColor = .systemRed
  904. content.addSubview(viewCounter)
  905. viewCounter.translatesAutoresizingMaskIntoConstraints = false
  906. NSLayoutConstraint.activate([
  907. viewCounter.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
  908. viewCounter.heightAnchor.constraint(equalToConstant: 20)
  909. ])
  910. viewCounter.backgroundColor = .systemRed
  911. viewCounter.layer.cornerRadius = 10
  912. viewCounter.clipsToBounds = true
  913. viewCounter.layer.borderWidth = 0.5
  914. viewCounter.layer.borderColor = UIColor.secondaryColor.cgColor
  915. let labelCounter = UILabel()
  916. viewCounter.addSubview(labelCounter)
  917. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  918. NSLayoutConstraint.activate([
  919. labelCounter.centerYAnchor.constraint(equalTo: viewCounter.centerYAnchor),
  920. labelCounter.leadingAnchor.constraint(equalTo: viewCounter.leadingAnchor, constant: 2),
  921. labelCounter.trailingAnchor.constraint(equalTo: viewCounter.trailingAnchor, constant: -2),
  922. ])
  923. labelCounter.font = UIFont.systemFont(ofSize: 11 + String.offset())
  924. if Int(data.counter) ?? 0 > 99 {
  925. labelCounter.text = "99+"
  926. } else {
  927. labelCounter.text = data.counter
  928. }
  929. labelCounter.textColor = .secondaryColor
  930. labelCounter.textAlignment = .center
  931. }
  932. if !data.isParent {
  933. titleView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0).isActive = true
  934. titleView.text = data.name
  935. content.addSubview(timeView)
  936. timeView.translatesAutoresizingMaskIntoConstraints = false
  937. NSLayoutConstraint.activate([
  938. timeView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  939. timeView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20.0),
  940. ])
  941. timeView.textColor = .gray
  942. timeView.font = UIFont.systemFont(ofSize: 14 + String.offset())
  943. let date = Date(milliseconds: Int64(data.serverDate) ?? 0)
  944. let calendar = Calendar.current
  945. if (calendar.isDateInToday(date)) {
  946. let formatter = DateFormatter()
  947. formatter.dateFormat = "HH:mm"
  948. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  949. timeView.text = formatter.string(from: date as Date)
  950. } else {
  951. let startOfNow = calendar.startOfDay(for: Date())
  952. let startOfTimeStamp = calendar.startOfDay(for: date)
  953. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  954. let day = -(components.day!)
  955. if day == 1 {
  956. timeView.text = "Yesterday".localized()
  957. } else {
  958. if day < 7 {
  959. let formatter = DateFormatter()
  960. formatter.dateFormat = "EEEE"
  961. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  962. if lang == "id" {
  963. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  964. }
  965. timeView.text = formatter.string(from: date)
  966. } else {
  967. let formatter = DateFormatter()
  968. formatter.dateFormat = "M/dd/yy"
  969. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  970. let stringFormat = formatter.string(from: date as Date)
  971. timeView.text = stringFormat
  972. }
  973. }
  974. }
  975. let messageView = UILabel()
  976. content.addSubview(messageView)
  977. messageView.translatesAutoresizingMaskIntoConstraints = false
  978. NSLayoutConstraint.activate([
  979. messageView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  980. messageView.topAnchor.constraint(equalTo: titleView.bottomAnchor),
  981. messageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  982. ])
  983. messageView.textColor = .gray
  984. if data.messageText.contains("■") {
  985. data.messageText = data.messageText.components(separatedBy: "■")[0]
  986. data.messageText = data.messageText.trimmingCharacters(in: .whitespacesAndNewlines)
  987. }
  988. let text = Utils.previewMessageText(chat: data)
  989. let idMe = User.getMyPin() as String?
  990. if let attributeText = text as? NSMutableAttributedString {
  991. let stringMessage = NSMutableAttributedString(string: "")
  992. if data.fpin == idMe {
  993. if data.lock == "1" {
  994. if data.messageScope == "4" {
  995. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12 + String.offset(), weight: .medium)]))
  996. }
  997. stringMessage.append(("🚫 _"+"You were deleted this message".localized()+"_").richText())
  998. } else {
  999. let imageStatus = NSTextAttachment()
  1000. if data.messageScope != MessageScope.CALL && data.messageScope != MessageScope.MISSED_CALL && data.messageScope != MessageScope.GPT_CHATBOT {
  1001. let status = getRealStatus(messageId: data.messageId)
  1002. if status == "0" {
  1003. imageStatus.image = UIImage(systemName: "xmark.circle")!.withTintColor(UIColor.red, renderingMode: .alwaysOriginal)
  1004. } else if status == "1" {
  1005. imageStatus.image = UIImage(systemName: "clock.arrow.circlepath")!.withTintColor(UIColor.lightGray, renderingMode: .alwaysOriginal)
  1006. } else if status == "2" {
  1007. imageStatus.image = UIImage(named: "checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1008. } else if (status == "3") {
  1009. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.lightGray)
  1010. } else if (status == "8") {
  1011. imageStatus.image = UIImage(named: "message_status_ack", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withRenderingMode(.alwaysOriginal)
  1012. } else {
  1013. imageStatus.image = UIImage(named: "double-checklist", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!.withTintColor(UIColor.systemBlue)
  1014. }
  1015. imageStatus.bounds = CGRect(x: 0, y: -5, width: 15, height: 15)
  1016. let imageStatusString = NSAttributedString(attachment: imageStatus)
  1017. stringMessage.append(imageStatusString)
  1018. stringMessage.append(NSAttributedString(string: " "))
  1019. }
  1020. if data.messageScope == "4" {
  1021. stringMessage.append(NSAttributedString(string: "You".localized() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12 + String.offset(), weight: .medium)]))
  1022. }
  1023. stringMessage.append(attributeText)
  1024. }
  1025. } else {
  1026. if data.messageScope == "4" {
  1027. var fullname = User.getData(pin: data.fpin, lPin: data.pin)!.fullName
  1028. let components = fullname.split(separator: " ")
  1029. if components.count >= 2 {
  1030. fullname = components.prefix(2).joined(separator: " ")
  1031. }
  1032. stringMessage.append(NSAttributedString(string: fullname + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12 + String.offset(), weight: .medium)]))
  1033. }
  1034. if data.messageScope == MessageScope.WHISPER && data.isBot == 1 {
  1035. stringMessage.append(NSAttributedString(string: Utils.getGPTBotName() + ": ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12 + String.offset(), weight: .medium)]))
  1036. }
  1037. if data.lock == "1" {
  1038. stringMessage.append(("🚫 _"+"This message was deleted".localized()+"_").richText())
  1039. } else {
  1040. stringMessage.append(attributeText)
  1041. }
  1042. }
  1043. messageView.attributedText = stringMessage
  1044. }
  1045. messageView.numberOfLines = 2
  1046. if data.counter != "0" {
  1047. viewCounter.topAnchor.constraint(equalTo: timeView.bottomAnchor, constant: 5.0).isActive = true
  1048. viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20).isActive = true
  1049. }
  1050. } else {
  1051. titleView.centerYAnchor.constraint(equalTo: content.centerYAnchor).isActive = true
  1052. titleView.text = data.groupName
  1053. let iconName = (data.isSelected) ? "chevron.up.circle" : "chevron.down.circle"
  1054. let imageView = UIImageView(image: UIImage(systemName: iconName))
  1055. imageView.tintColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  1056. content.addSubview(imageView)
  1057. imageView.translatesAutoresizingMaskIntoConstraints = false
  1058. NSLayoutConstraint.activate([
  1059. imageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
  1060. imageView.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  1061. imageView.widthAnchor.constraint(equalToConstant: 20),
  1062. imageView.heightAnchor.constraint(equalToConstant: 20)
  1063. ])
  1064. if data.counter != "0" {
  1065. viewCounter.trailingAnchor.constraint(equalTo: imageView.leadingAnchor, constant: -5).isActive = true
  1066. viewCounter.centerYAnchor.constraint(equalTo: content.centerYAnchor).isActive = true
  1067. }
  1068. }
  1069. cell.separatorInset = UIEdgeInsets(top: 0, left: 85, bottom: 0, right: 0)
  1070. return cell
  1071. }
  1072. @objc func onContSearch(_ sender: ObjectGesture) {
  1073. if selectedTag == PHOTOS_TAG {
  1074. } else if selectedTag == VIDEOS_TAG {
  1075. } else if selectedTag == DOCUMENTS_TAG {
  1076. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1077. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1078. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1079. if let dirPath = paths.first {
  1080. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.file_id)
  1081. if FileManager.default.fileExists(atPath: fileURL.path) {
  1082. self.previewItem = fileURL as NSURL
  1083. let previewController = QLPreviewController()
  1084. let rightBarButton = UIBarButtonItem()
  1085. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1086. previewController.dataSource = self
  1087. previewController.modalPresentationStyle = .custom
  1088. self.present(previewController, animated: true)
  1089. } else if FileEncryption.shared.isSecureExists(filename: sender.file_id) {
  1090. do {
  1091. if var docData = try FileEncryption.shared.readSecure(filename: sender.file_id) {
  1092. let dataDecrypt = FileEncryption.shared.decryptFileFromServer(data: docData)
  1093. if dataDecrypt != nil {
  1094. docData = dataDecrypt!
  1095. }
  1096. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  1097. let tempPath = cachesDirectory.appendingPathComponent(sender.file_id)
  1098. try docData.write(to: tempPath)
  1099. self.previewItem = tempPath as NSURL
  1100. let previewController = QLPreviewController()
  1101. let rightBarButton = UIBarButtonItem()
  1102. previewController.navigationItem.rightBarButtonItem = rightBarButton
  1103. previewController.dataSource = self
  1104. previewController.modalPresentationStyle = .custom
  1105. self.present(previewController,animated: true)
  1106. }
  1107. }
  1108. catch {
  1109. }
  1110. }
  1111. }
  1112. } else if selectedTag == LINKS_TAG {
  1113. var stringURl = sender.message_id
  1114. if stringURl.lowercased().starts(with: "www.") {
  1115. stringURl = "https://" + stringURl.replacingOccurrences(of: "www.", with: "")
  1116. }
  1117. guard let url = URL(string: stringURl) else { return }
  1118. if Nexilis.checkingAccess(key: "secure_browser") {
  1119. APIS.openUrl(url: stringURl)
  1120. } else {
  1121. guard let url = URL(string: stringURl) else { return }
  1122. UIApplication.shared.open(url)
  1123. }
  1124. } else if selectedTag == AUDIOS_TAG {
  1125. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  1126. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  1127. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  1128. if let dirPath = paths.first {
  1129. let audioURL = URL(fileURLWithPath: dirPath).appendingPathComponent(sender.audio_id)
  1130. if FileManager.default.fileExists(atPath: audioURL.path) {
  1131. do {
  1132. if audioPlayer == nil || audioPlayer?.url != audioURL {
  1133. do {
  1134. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  1135. try AVAudioSession.sharedInstance().setActive(true)
  1136. } catch {
  1137. }
  1138. audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
  1139. audioPlayer?.prepareToPlay()
  1140. audioPlayer?.play()
  1141. } else if audioPlayer!.isPlaying {
  1142. audioPlayer?.pause()
  1143. } else {
  1144. audioPlayer?.play()
  1145. }
  1146. } catch {
  1147. }
  1148. } else if FileEncryption.shared.isSecureExists(filename: sender.audio_id) {
  1149. do {
  1150. if var audioData = try FileEncryption.shared.readSecure(filename: sender.audio_id) {
  1151. let dataDecrypt = FileEncryption.shared.decryptFileFromServer(data: audioData)
  1152. if dataDecrypt != nil {
  1153. audioData = dataDecrypt!
  1154. }
  1155. let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  1156. let tempPath = cachesDirectory.appendingPathComponent(sender.audio_id)
  1157. try audioData.write(to: tempPath)
  1158. if audioPlayer == nil || audioPlayer?.url != tempPath {
  1159. do {
  1160. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  1161. try AVAudioSession.sharedInstance().setActive(true)
  1162. } catch {
  1163. }
  1164. audioPlayer = try AVAudioPlayer(contentsOf: tempPath)
  1165. audioPlayer?.prepareToPlay()
  1166. audioPlayer?.play()
  1167. } else if audioPlayer!.isPlaying {
  1168. audioPlayer?.pause()
  1169. } else {
  1170. audioPlayer?.play()
  1171. }
  1172. }
  1173. } catch {
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  1180. tableView.deselectRow(at: indexPath, animated: true)
  1181. let data: Chat
  1182. if isFiltering {
  1183. data = fillteredData[indexPath.row] as! Chat
  1184. } else {
  1185. data = chats[indexPath.row]
  1186. }
  1187. if self.archivedChats.count > 0 && indexPath.row == 0 {
  1188. let controller = ArchivedChatView()
  1189. controller.archivedChats = archivedChats
  1190. controller.hidesBottomBarWhenPushed = true
  1191. navigationController?.show(controller, sender: nil)
  1192. return
  1193. }
  1194. if data.isParent {
  1195. expandCollapseChats(tableView: tableView, indexPath: indexPath)
  1196. return
  1197. }
  1198. if data.pin == "-997" {
  1199. let smartChatVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "chatGptVC") as! ChatGPTBotView
  1200. smartChatVC.hidesBottomBarWhenPushed = true
  1201. smartChatVC.fromNotification = false
  1202. navigationController?.show(smartChatVC, sender: nil)
  1203. } else if data.messageScope == MessageScope.WHISPER || data.messageScope == MessageScope.CALL || data.messageScope == MessageScope.MISSED_CALL {
  1204. if data.pin.isEmpty {
  1205. return
  1206. }
  1207. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  1208. editorPersonalVC.hidesBottomBarWhenPushed = true
  1209. editorPersonalVC.unique_l_pin = data.pin
  1210. navigationController?.show(editorPersonalVC, sender: nil)
  1211. } else {
  1212. if data.pin.isEmpty {
  1213. return
  1214. }
  1215. let editorGroupVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorGroupVC") as! EditorGroup
  1216. editorGroupVC.hidesBottomBarWhenPushed = true
  1217. editorGroupVC.unique_l_pin = data.pin
  1218. navigationController?.show(editorGroupVC, sender: nil)
  1219. }
  1220. }
  1221. func expandCollapseChats(tableView: UITableView, indexPath: IndexPath) {
  1222. let data: Chat
  1223. if isFiltering || selectedTag == UNREAD_TAG {
  1224. data = fillteredData[indexPath.row] as! Chat
  1225. } else {
  1226. data = chats[indexPath.row]
  1227. }
  1228. data.isSelected = !data.isSelected
  1229. if data.isSelected {
  1230. if let dataSubChats = self.chatGroupMaps[data.groupId] {
  1231. for dataSubChat in dataSubChats {
  1232. if var indexParent = chats.firstIndex(where: { $0.isParent && $0.groupId == data.groupId }) {
  1233. if isFiltering || selectedTag == UNREAD_TAG {
  1234. if var indexParentFilter = fillteredData.firstIndex(where: { ($0 as! Chat).isParent && ($0 as! Chat).groupId == data.groupId }) {
  1235. fillteredData.insert(dataSubChat, at: indexParentFilter + 1)
  1236. indexParentFilter+=1
  1237. }
  1238. } else {
  1239. chats.insert(dataSubChat, at: indexParent + 1)
  1240. indexParent+=1
  1241. if var indexParentFilter = tempChats.firstIndex(where: { $0.isParent && $0.groupId == data.groupId }) {
  1242. tempChats.insert(dataSubChat, at: indexParentFilter + 1)
  1243. indexParentFilter+=1
  1244. }
  1245. }
  1246. }
  1247. }
  1248. }
  1249. } else {
  1250. if isFiltering || selectedTag == UNREAD_TAG {
  1251. if var changedFillteredData = fillteredData as? [Chat] {
  1252. changedFillteredData.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1253. self.fillteredData = changedFillteredData
  1254. }
  1255. } else {
  1256. chats.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1257. tempChats.removeAll(where: { $0.isParent == false && $0.groupId == data.groupId })
  1258. }
  1259. }
  1260. tableView.reloadData()
  1261. }
  1262. private func getRealStatus(messageId: String) -> String {
  1263. var status = "1"
  1264. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  1265. if let cursorStatus = Database.shared.getRecords(fmdb: fmdb, query: "SELECT status, f_pin FROM MESSAGE_STATUS WHERE message_id='\(messageId)'") {
  1266. var listStatus: [Int] = []
  1267. while cursorStatus.next() {
  1268. listStatus.append(Int(cursorStatus.string(forColumnIndex: 0)!)!)
  1269. }
  1270. cursorStatus.close()
  1271. status = "\(listStatus.min() ?? 2)"
  1272. }
  1273. })
  1274. return status
  1275. }
  1276. public func updateSearchResults(for searchController: UISearchController) {
  1277. }
  1278. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  1279. return self.previewItem != nil ? 1 : 0
  1280. }
  1281. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> any QLPreviewItem {
  1282. return self.previewItem!
  1283. }
  1284. }