HistoryBroadcastViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. //
  2. // HistoryBroadcastViewController.swift
  3. // QmeraLite
  4. //
  5. // Created by Qindi on 19/01/22.
  6. //
  7. import UIKit
  8. class HistoryBroadcastViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  9. var isAdmin: Bool = false
  10. var chats: [Chat] = []
  11. private var historyTableView = UITableView()
  12. let viewCounter = UIView()
  13. override func viewWillAppear(_ animated: Bool) {
  14. getChats {
  15. DispatchQueue.main.async {
  16. self.historyTableView.reloadData()
  17. }
  18. }
  19. }
  20. override func viewDidLoad() {
  21. super.viewDidLoad()
  22. view.backgroundColor = .secondaryColor
  23. title = "Notification Center".localized()
  24. navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel(sender:)))
  25. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0), NSAttributedString.Key.foregroundColor: UIColor.white]
  26. let navBarAppearance = UINavigationBarAppearance()
  27. navBarAppearance.configureWithOpaqueBackground()
  28. navBarAppearance.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : UIColor.mainColor
  29. navBarAppearance.titleTextAttributes = attributes
  30. navigationController?.navigationBar.standardAppearance = navBarAppearance
  31. navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
  32. let me = User.getMyPin()!
  33. Database.shared.database?.inTransaction({ fmdb, rollback in
  34. do {
  35. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: "select official_account from BUDDY where F_PIN = '\(me)'"), cursor.next() {
  36. let official = cursor.string(forColumnIndex: 0)!
  37. isAdmin = User.isOfficial(official_account: official)
  38. cursor.close()
  39. }
  40. } catch {
  41. rollback.pointee = true
  42. print("Access database error: \(error.localizedDescription)")
  43. }
  44. })
  45. if isAdmin {
  46. let broadcastImage = UIImage(systemName: "plus.bubble.fill")
  47. let buttonBroadcast = UIBarButtonItem(image: broadcastImage, style: .plain, target: self, action: #selector(didTapBroadcastButton(sender:)))
  48. navigationItem.rightBarButtonItem = buttonBroadcast
  49. }
  50. historyTableView.register(UITableViewCell.self, forCellReuseIdentifier: "historyBroadcastCell")
  51. historyTableView.dataSource = self
  52. historyTableView.delegate = self
  53. view.addSubview(historyTableView)
  54. historyTableView.translatesAutoresizingMaskIntoConstraints = false
  55. NSLayoutConstraint.activate([
  56. historyTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  57. historyTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  58. historyTableView.topAnchor.constraint(equalTo: view.topAnchor),
  59. historyTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  60. ])
  61. historyTableView.tableFooterView = UIView()
  62. // getChats {
  63. // DispatchQueue.main.async {
  64. // self.historyTableView.reloadData()
  65. // }
  66. // }
  67. NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage(notification:)), name: NSNotification.Name(rawValue: Nexilis.listenerReceiveChat), object: nil)
  68. }
  69. @objc func onReceiveMessage(notification: NSNotification) {
  70. let data:[AnyHashable : Any] = notification.userInfo!
  71. guard let dataMessage = data["message"] as? TMessage else {
  72. return
  73. }
  74. let isUser = User.getDataCanNil(pin: dataMessage.getBody(key: CoreMessage_TMessageKey.L_PIN)) != nil
  75. let chatId = dataMessage.getBody(key: CoreMessage_TMessageKey.CHAT_ID, default_value: "").isEmpty ? dataMessage.getBody(key: CoreMessage_TMessageKey.L_PIN) : dataMessage.getBody(key: CoreMessage_TMessageKey.CHAT_ID, default_value: "")
  76. let pin = isUser ? dataMessage.getBody(key: CoreMessage_TMessageKey.F_PIN) : chatId
  77. if let _ = chats.firstIndex(of: Chat(pin: pin)) {
  78. getChats {
  79. DispatchQueue.main.async {
  80. self.historyTableView.reloadData()
  81. }
  82. }
  83. }
  84. }
  85. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  86. if chats.count != 0 {
  87. let data: Chat
  88. data = chats[indexPath.row]
  89. let editorPersonalVC = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "editorPersonalVC") as! EditorPersonal
  90. editorPersonalVC.hidesBottomBarWhenPushed = true
  91. editorPersonalVC.unique_l_pin = data.pin
  92. navigationController?.show(editorPersonalVC, sender: nil)
  93. }
  94. }
  95. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  96. if chats.count == 0 {
  97. return 1
  98. }
  99. return chats.count
  100. }
  101. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  102. let cell = tableView.dequeueReusableCell(withIdentifier: "historyBroadcastCell", for: indexPath)
  103. historyTableView.separatorStyle = .singleLine
  104. cell.textLabel!.text = ""
  105. cell.selectionStyle = .gray
  106. let content = cell.contentView
  107. if content.subviews.count > 0 {
  108. content.subviews.forEach { $0.removeFromSuperview() }
  109. }
  110. if chats.count == 0 {
  111. historyTableView.separatorStyle = .none
  112. cell.textLabel!.text = "No History".localized()
  113. cell.textLabel?.font = UIFont.systemFont(ofSize: 10)
  114. cell.selectionStyle = .none
  115. cell.textLabel?.textAlignment = .center
  116. } else {
  117. cell.separatorInset.left = 60.0
  118. let data: Chat
  119. data = chats[indexPath.row]
  120. let imageView = UIImageView()
  121. content.addSubview(imageView)
  122. imageView.translatesAutoresizingMaskIntoConstraints = false
  123. NSLayoutConstraint.activate([
  124. imageView.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 10.0),
  125. imageView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  126. imageView.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -20.0),
  127. imageView.widthAnchor.constraint(equalToConstant: 40.0),
  128. imageView.heightAnchor.constraint(equalToConstant: 40.0)
  129. ])
  130. if data.profile.isEmpty && data.pin != "-999" {
  131. let user = User.getDataCanNil(pin: data.pin)
  132. if user != nil {
  133. imageView.image = UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  134. } else {
  135. imageView.image = UIImage(named: "Conversation---Black", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)
  136. }
  137. } else {
  138. if !Utils.getIconDock().isEmpty {
  139. let urlString = Utils.getUrlDock()!
  140. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  141. let imageData = cachedImage
  142. imageView.image = imageData
  143. } else {
  144. DispatchQueue.global().async{
  145. Utils.fetchDataWithCookiesAndUserAgent(from: URL(string: urlString)!) { data, response, error in
  146. guard let data = data, error == nil else { return }
  147. DispatchQueue.main.async() {
  148. if UIImage(data: data) != nil {
  149. let imageData = UIImage(data: data)!
  150. imageView.image = imageData
  151. ImageCache.shared.save(image: imageData, forKey: urlString)
  152. }
  153. }
  154. }
  155. }
  156. }
  157. } else {
  158. getImage(name: data.profile, placeholderImage: UIImage(named: data.pin == "-999" ? "pb_button" : "Conversation---Black", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  159. imageView.image = image
  160. if !result {
  161. imageView.tintColor = .mainColor
  162. }
  163. })
  164. }
  165. }
  166. let titleView = UILabel()
  167. content.addSubview(titleView)
  168. titleView.translatesAutoresizingMaskIntoConstraints = false
  169. NSLayoutConstraint.activate([
  170. titleView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  171. titleView.topAnchor.constraint(equalTo: content.topAnchor, constant: 10.0),
  172. titleView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  173. ])
  174. titleView.text = data.name
  175. titleView.font = UIFont.systemFont(ofSize: 14, weight: .medium)
  176. let messageView = UILabel()
  177. content.addSubview(messageView)
  178. messageView.translatesAutoresizingMaskIntoConstraints = false
  179. NSLayoutConstraint.activate([
  180. messageView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10.0),
  181. messageView.topAnchor.constraint(equalTo: titleView.bottomAnchor, constant: 5.0),
  182. messageView.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -40.0),
  183. ])
  184. messageView.textColor = .gray
  185. let text = Utils.previewMessageText(chat: data)
  186. if let attributeText = text as? NSAttributedString {
  187. messageView.attributedText = attributeText
  188. } else if let stringText = text as? String {
  189. messageView.text = stringText
  190. }
  191. messageView.font = UIFont.systemFont(ofSize: 12)
  192. messageView.numberOfLines = 2
  193. if viewCounter.isDescendant(of: content) {
  194. viewCounter.subviews.forEach({ $0.removeFromSuperview() })
  195. viewCounter.removeConstraints(viewCounter.constraints)
  196. viewCounter.removeFromSuperview()
  197. }
  198. if data.counter != "0" {
  199. content.addSubview(viewCounter)
  200. viewCounter.translatesAutoresizingMaskIntoConstraints = false
  201. NSLayoutConstraint.activate([
  202. viewCounter.centerYAnchor.constraint(equalTo: content.centerYAnchor),
  203. viewCounter.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20),
  204. viewCounter.widthAnchor.constraint(greaterThanOrEqualToConstant: 20),
  205. viewCounter.heightAnchor.constraint(equalToConstant: 20)
  206. ])
  207. viewCounter.backgroundColor = .systemRed
  208. viewCounter.layer.cornerRadius = 10
  209. viewCounter.clipsToBounds = true
  210. viewCounter.layer.borderWidth = 0.5
  211. viewCounter.layer.borderColor = UIColor.secondaryColor.cgColor
  212. let labelCounter = UILabel()
  213. viewCounter.addSubview(labelCounter)
  214. labelCounter.translatesAutoresizingMaskIntoConstraints = false
  215. NSLayoutConstraint.activate([
  216. labelCounter.centerYAnchor.constraint(equalTo: viewCounter.centerYAnchor),
  217. labelCounter.leadingAnchor.constraint(equalTo: viewCounter.leadingAnchor, constant: 2),
  218. labelCounter.trailingAnchor.constraint(equalTo: viewCounter.trailingAnchor, constant: -2),
  219. ])
  220. labelCounter.font = UIFont.systemFont(ofSize: 11)
  221. if Int(data.counter) ?? 0 > 99 {
  222. labelCounter.text = "99+"
  223. } else {
  224. labelCounter.text = data.counter
  225. }
  226. labelCounter.textColor = .secondaryColor
  227. labelCounter.textAlignment = .center
  228. }
  229. }
  230. return cell
  231. }
  232. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  233. return 70.0
  234. }
  235. func getChats(completion: @escaping ()->()) {
  236. DispatchQueue.global().async {
  237. self.chats.removeAll()
  238. self.chats.append(contentsOf: Chat.getData())
  239. self.chats = self.chats.filter({($0.official == "1" || $0.pin == "-999") && $0.messageScope == MessageScope.WHISPER})
  240. completion()
  241. }
  242. }
  243. @objc func cancel(sender: Any) {
  244. navigationController?.dismiss(animated: true, completion: nil)
  245. }
  246. @objc func didTapBroadcastButton(sender: AnyObject){
  247. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "broadcastNav")
  248. self.navigationController?.present(controller, animated: true, completion: nil)
  249. }
  250. }