NCNotification.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. //
  2. // NCNotification.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 27/01/17.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. // Author Henrik Storch <henrik.storch@nextcloud.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import UIKit
  25. import NextcloudKit
  26. import SwiftyJSON
  27. import JGProgressHUD
  28. class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmptyDataSetDelegate {
  29. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  30. let utilityFileSystem = NCUtilityFileSystem()
  31. let utility = NCUtility()
  32. var notifications: [NKNotifications] = []
  33. var emptyDataSet: NCEmptyDataSet?
  34. var dataSourceTask: URLSessionTask?
  35. // MARK: - View Life Cycle
  36. override func viewDidLoad() {
  37. super.viewDidLoad()
  38. title = NSLocalizedString("_notifications_", comment: "")
  39. view.backgroundColor = .systemBackground
  40. tableView.tableFooterView = UIView()
  41. tableView.rowHeight = UITableView.automaticDimension
  42. tableView.estimatedRowHeight = 50.0
  43. tableView.backgroundColor = .systemBackground
  44. refreshControl?.addTarget(self, action: #selector(getNetwokingNotification), for: .valueChanged)
  45. // Navigation controller is being presented modally
  46. if navigationController?.presentingViewController != nil {
  47. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, action: { [weak self] in
  48. self?.dismiss(animated: true)
  49. })
  50. }
  51. // Empty
  52. let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
  53. emptyDataSet = NCEmptyDataSet(view: tableView, offset: -offset, delegate: self)
  54. }
  55. override func viewWillAppear(_ animated: Bool) {
  56. super.viewWillAppear(animated)
  57. navigationController?.setNavigationBarAppearance()
  58. }
  59. override func viewDidAppear(_ animated: Bool) {
  60. super.viewDidAppear(animated)
  61. appDelegate.activeViewController = self
  62. getNetwokingNotification()
  63. }
  64. @objc func viewClose() {
  65. self.dismiss(animated: true, completion: nil)
  66. }
  67. // MARK: - Empty
  68. func emptyDataSetView(_ view: NCEmptyView) {
  69. if self.dataSourceTask?.state == .running {
  70. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  71. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  72. view.emptyDescription.text = ""
  73. } else {
  74. view.emptyImage.image = utility.loadImage(named: "bell", color: .gray, size: UIScreen.main.bounds.width)
  75. view.emptyTitle.text = NSLocalizedString("_no_notification_", comment: "")
  76. view.emptyDescription.text = ""
  77. }
  78. }
  79. // MARK: - Table
  80. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  81. emptyDataSet?.numberOfItemsInSection(notifications.count, section: section)
  82. return notifications.count
  83. }
  84. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  85. guard let notification = NCApplicationHandle().didSelectNotification(notifications[indexPath.row], viewController: self) else { return }
  86. do {
  87. if let subjectRichParameters = notification.subjectRichParameters,
  88. let json = try JSONSerialization.jsonObject(with: subjectRichParameters, options: .mutableContainers) as? [String: Any],
  89. let file = json["file"] as? [String: Any],
  90. file["type"] as? String == "file" {
  91. if let id = file["id"] {
  92. NCActionCenter.shared.viewerFile(account: appDelegate.account, fileId: ("\(id)"), viewController: self)
  93. }
  94. }
  95. } catch {
  96. print("Something went wrong")
  97. }
  98. }
  99. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  100. guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NCNotificationCell else { return UITableViewCell() }
  101. cell.delegate = self
  102. cell.selectionStyle = .none
  103. cell.indexPath = indexPath
  104. let notification = notifications[indexPath.row]
  105. let urlIcon = URL(string: notification.icon)
  106. var image: UIImage?
  107. if let urlIcon = urlIcon {
  108. let pathFileName = utilityFileSystem.directoryUserData + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  109. image = UIImage(contentsOfFile: pathFileName)
  110. }
  111. if let image = image {
  112. cell.icon.image = image.withTintColor(NCBrandColor.shared.brandElement, renderingMode: .alwaysOriginal)
  113. } else {
  114. cell.icon.image = utility.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  115. }
  116. // Avatar
  117. cell.avatar.isHidden = true
  118. cell.avatarLeadingMargin.constant = 10
  119. if let subjectRichParameters = notification.subjectRichParameters,
  120. let json = JSON(subjectRichParameters).dictionary,
  121. let user = json["user"]?["id"].stringValue {
  122. cell.avatar.isHidden = false
  123. cell.avatarLeadingMargin.constant = 50
  124. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  125. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + fileName
  126. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  127. cell.avatar.image = image
  128. } else if !FileManager.default.fileExists(atPath: fileNameLocalPath) {
  129. cell.fileUser = user
  130. NCNetworking.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView, cellImageView: cell.fileAvatarImageView)
  131. }
  132. }
  133. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  134. cell.notification = notification
  135. cell.date.text = utility.dateDiff(notification.date as Date)
  136. cell.date.textColor = .gray
  137. cell.subject.text = notification.subject
  138. cell.subject.textColor = .label
  139. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  140. cell.message.textColor = .gray
  141. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  142. cell.primary.isEnabled = false
  143. cell.primary.isHidden = true
  144. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  145. cell.primary.layer.cornerRadius = 15
  146. cell.primary.layer.masksToBounds = true
  147. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  148. cell.primary.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  149. cell.more.isEnabled = false
  150. cell.more.isHidden = true
  151. cell.more.titleLabel?.font = .systemFont(ofSize: 15)
  152. cell.more.layer.cornerRadius = 15
  153. cell.more.layer.masksToBounds = true
  154. cell.more.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  155. cell.more.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  156. cell.secondary.isEnabled = false
  157. cell.secondary.isHidden = true
  158. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  159. cell.secondary.layer.cornerRadius = 15
  160. cell.secondary.layer.masksToBounds = true
  161. cell.secondary.layer.borderWidth = 1
  162. cell.secondary.layer.borderColor = UIColor.systemGray.cgColor
  163. cell.secondary.layer.backgroundColor = UIColor.secondarySystemBackground.cgColor
  164. cell.secondary.setTitleColor(.gray, for: .normal)
  165. // Action
  166. if let actions = notification.actions,
  167. let jsonActions = JSON(actions).array {
  168. if jsonActions.count == 1 {
  169. let action = jsonActions[0]
  170. cell.primary.isEnabled = true
  171. cell.primary.isHidden = false
  172. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  173. } else if jsonActions.count == 2 {
  174. cell.primary.isEnabled = true
  175. cell.primary.isHidden = false
  176. cell.secondary.isEnabled = true
  177. cell.secondary.isHidden = false
  178. for action in jsonActions {
  179. let label = action["label"].stringValue
  180. let primary = action["primary"].boolValue
  181. if primary {
  182. cell.primary.setTitle(label, for: .normal)
  183. } else {
  184. cell.secondary.setTitle(label, for: .normal)
  185. }
  186. }
  187. } else if jsonActions.count >= 3 {
  188. cell.more.isEnabled = true
  189. cell.more.isHidden = false
  190. cell.more.setTitle("…", for: .normal)
  191. }
  192. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  193. buttonWidth += 30
  194. cell.primaryWidth.constant = buttonWidth
  195. cell.secondaryWidth.constant = buttonWidth
  196. }
  197. return cell
  198. }
  199. // MARK: - tap Action
  200. func tapRemove(with notification: NKNotifications) {
  201. NextcloudKit.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification, method: "DELETE") { account, error in
  202. if error == .success && account == self.appDelegate.account {
  203. if let index = self.notifications
  204. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  205. self.notifications.remove(at: index)
  206. }
  207. self.tableView.reloadData()
  208. } else if error != .success {
  209. NCContentPresenter().showError(error: error)
  210. } else {
  211. print("[Error] The user has been changed during networking process.")
  212. }
  213. }
  214. }
  215. func tapAction(with notification: NKNotifications, label: String) {
  216. if notification.app == NCGlobal.shared.spreedName,
  217. let roomToken = notification.objectId.split(separator: "/").first,
  218. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(appDelegate.urlBase)&user=\(appDelegate.userId)&withRoomToken=\(roomToken)"),
  219. UIApplication.shared.canOpenURL(talkUrl) {
  220. UIApplication.shared.open(talkUrl)
  221. } else if let actions = notification.actions,
  222. let jsonActions = JSON(actions).array,
  223. let action = jsonActions.first(where: { $0["label"].string == label }) {
  224. let serverUrl = action["link"].stringValue
  225. let method = action["type"].stringValue
  226. if method == "WEB", let url = action["link"].url {
  227. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  228. return
  229. }
  230. NextcloudKit.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { account, error in
  231. if error == .success && account == self.appDelegate.account {
  232. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  233. self.notifications.remove(at: index)
  234. }
  235. self.tableView.reloadData()
  236. if self.navigationController?.presentingViewController != nil, notification.app == NCGlobal.shared.twoFactorNotificatioName {
  237. self.dismiss(animated: true)
  238. }
  239. } else if error != .success {
  240. NCContentPresenter().showError(error: error)
  241. } else {
  242. print("[Error] The user has been changed during networking process.")
  243. }
  244. }
  245. } // else: Action not found
  246. }
  247. func tapMore(with notification: NKNotifications) {
  248. toggleMenu(notification: notification)
  249. }
  250. // MARK: - Load notification networking
  251. @objc func getNetwokingNotification() {
  252. self.tableView.reloadData()
  253. NextcloudKit.shared.getNotifications { task in
  254. self.dataSourceTask = task
  255. self.tableView.reloadData()
  256. } completion: { account, notifications, _, error in
  257. if error == .success && account == self.appDelegate.account {
  258. self.notifications.removeAll()
  259. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  260. for notification in sortedListOfNotifications {
  261. if let icon = (notification as? NKNotifications)?.icon {
  262. self.utility.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, completion: { _, _ in })
  263. }
  264. if let notification = (notification as? NKNotifications) {
  265. self.notifications.append(notification)
  266. }
  267. }
  268. self.refreshControl?.endRefreshing()
  269. self.tableView.reloadData()
  270. }
  271. }
  272. }
  273. }
  274. // MARK: -
  275. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  276. @IBOutlet weak var icon: UIImageView!
  277. @IBOutlet weak var avatar: UIImageView!
  278. @IBOutlet weak var date: UILabel!
  279. @IBOutlet weak var subject: UILabel!
  280. @IBOutlet weak var message: UILabel!
  281. @IBOutlet weak var remove: UIButton!
  282. @IBOutlet weak var primary: UIButton!
  283. @IBOutlet weak var secondary: UIButton!
  284. @IBOutlet weak var more: UIButton!
  285. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  286. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  287. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  288. private var user = ""
  289. private var index = IndexPath()
  290. weak var delegate: NCNotificationCellDelegate?
  291. var notification: NKNotifications?
  292. var indexPath: IndexPath {
  293. get { return index }
  294. set { index = newValue }
  295. }
  296. var fileAvatarImageView: UIImageView? {
  297. return avatar
  298. }
  299. var fileUser: String? {
  300. get { return user }
  301. set { user = newValue ?? "" }
  302. }
  303. override func awakeFromNib() {
  304. super.awakeFromNib()
  305. }
  306. @IBAction func touchUpInsideRemove(_ sender: Any) {
  307. guard let notification = notification else { return }
  308. delegate?.tapRemove(with: notification)
  309. }
  310. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  311. guard let notification = notification,
  312. let button = sender as? UIButton,
  313. let label = button.titleLabel?.text
  314. else { return }
  315. delegate?.tapAction(with: notification, label: label)
  316. }
  317. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  318. guard let notification = notification,
  319. let button = sender as? UIButton,
  320. let label = button.titleLabel?.text
  321. else { return }
  322. delegate?.tapAction(with: notification, label: label)
  323. }
  324. @IBAction func touchUpInsideMore(_ sender: Any) {
  325. guard let notification = notification else { return }
  326. delegate?.tapMore(with: notification)
  327. }
  328. }
  329. protocol NCNotificationCellDelegate: AnyObject {
  330. func tapRemove(with notification: NKNotifications)
  331. func tapAction(with notification: NKNotifications, label: String)
  332. func tapMore(with notification: NKNotifications)
  333. }