NCNotification.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. var notifications: [NKNotifications] = []
  31. var emptyDataSet: NCEmptyDataSet?
  32. var isReloadDataSourceNetworkInProgress: Bool = false
  33. // MARK: - View Life Cycle
  34. override func viewDidLoad() {
  35. super.viewDidLoad()
  36. title = NSLocalizedString("_notifications_", comment: "")
  37. view.backgroundColor = .systemBackground
  38. tableView.tableFooterView = UIView()
  39. tableView.rowHeight = UITableView.automaticDimension
  40. tableView.estimatedRowHeight = 50.0
  41. tableView.backgroundColor = .systemBackground
  42. refreshControl?.addTarget(self, action: #selector(getNetwokingNotification), for: .valueChanged)
  43. // Navigation controller is being presented modally
  44. if navigationController?.presentingViewController != nil {
  45. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, action: { [weak self] in
  46. self?.dismiss(animated: true)
  47. })
  48. }
  49. // Empty
  50. let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
  51. emptyDataSet = NCEmptyDataSet(view: tableView, offset: -offset, delegate: self)
  52. }
  53. override func viewWillAppear(_ animated: Bool) {
  54. super.viewWillAppear(animated)
  55. appDelegate.activeViewController = self
  56. navigationController?.setFileAppreance()
  57. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  58. getNetwokingNotification()
  59. }
  60. override func viewWillDisappear(_ animated: Bool) {
  61. super.viewWillDisappear(animated)
  62. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  63. }
  64. @objc func viewClose() {
  65. self.dismiss(animated: true, completion: nil)
  66. }
  67. // MARK: - NotificationCenter
  68. @objc func initialize() {
  69. getNetwokingNotification()
  70. }
  71. // MARK: - Empty
  72. func emptyDataSetView(_ view: NCEmptyView) {
  73. if isReloadDataSourceNetworkInProgress {
  74. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  75. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  76. view.emptyDescription.text = ""
  77. } else {
  78. view.emptyImage.image = NCUtility.shared.loadImage(named: "bell", color: .gray, size: UIScreen.main.bounds.width)
  79. view.emptyTitle.text = NSLocalizedString("_no_notification_", comment: "")
  80. view.emptyDescription.text = ""
  81. }
  82. }
  83. // MARK: - Table
  84. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  85. emptyDataSet?.numberOfItemsInSection(notifications.count, section: section)
  86. return notifications.count
  87. }
  88. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  89. let notification = notifications[indexPath.row]
  90. if notification.app == "files_sharing" {
  91. NCActionCenter.shared.viewerFile(account: appDelegate.account, fileId: notification.objectId, viewController: self)
  92. } else {
  93. NCApplicationHandle().didSelectNotification(notification, viewController: self)
  94. }
  95. }
  96. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  97. let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NCNotificationCell
  98. cell.delegate = self
  99. cell.selectionStyle = .none
  100. let notification = notifications[indexPath.row]
  101. let urlIcon = URL(string: notification.icon)
  102. var image: UIImage?
  103. if let urlIcon = urlIcon {
  104. let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  105. image = UIImage(contentsOfFile: pathFileName)
  106. }
  107. if let image = image {
  108. cell.icon.image = image.withTintColor(NCBrandColor.shared.brandElement, renderingMode: .alwaysOriginal)
  109. } else {
  110. cell.icon.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  111. }
  112. // Avatar
  113. cell.avatar.isHidden = true
  114. cell.avatarLeadingMargin.constant = 10
  115. if let subjectRichParameters = notification.subjectRichParameters,
  116. let json = JSON(subjectRichParameters).dictionary,
  117. let user = json["user"]?["id"].stringValue {
  118. cell.avatar.isHidden = false
  119. cell.avatarLeadingMargin.constant = 50
  120. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  121. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  122. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  123. cell.avatar.image = image
  124. } else if !FileManager.default.fileExists(atPath: fileNameLocalPath) {
  125. cell.fileUser = user
  126. NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView, cellImageView: cell.fileAvatarImageView)
  127. }
  128. }
  129. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  130. cell.notification = notification
  131. cell.date.text = CCUtility.dateDiff(notification.date as Date)
  132. cell.date.textColor = .gray
  133. cell.subject.text = notification.subject
  134. cell.subject.textColor = .label
  135. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  136. cell.message.textColor = .gray
  137. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  138. cell.primary.isEnabled = false
  139. cell.primary.isHidden = true
  140. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  141. cell.primary.layer.cornerRadius = 15
  142. cell.primary.layer.masksToBounds = true
  143. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  144. cell.primary.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  145. cell.more.isEnabled = false
  146. cell.more.isHidden = true
  147. cell.more.titleLabel?.font = .systemFont(ofSize: 15)
  148. cell.more.layer.cornerRadius = 15
  149. cell.more.layer.masksToBounds = true
  150. cell.more.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  151. cell.more.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  152. cell.secondary.isEnabled = false
  153. cell.secondary.isHidden = true
  154. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  155. cell.secondary.layer.cornerRadius = 15
  156. cell.secondary.layer.masksToBounds = true
  157. cell.secondary.layer.borderWidth = 1
  158. cell.secondary.layer.borderColor = UIColor.systemGray.cgColor
  159. cell.secondary.layer.backgroundColor = UIColor.secondarySystemBackground.cgColor
  160. cell.secondary.setTitleColor(.gray, for: .normal)
  161. // Action
  162. if let actions = notification.actions,
  163. let jsonActions = JSON(actions).array {
  164. if jsonActions.count == 1 {
  165. let action = jsonActions[0]
  166. cell.primary.isEnabled = true
  167. cell.primary.isHidden = false
  168. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  169. } else if jsonActions.count == 2 {
  170. cell.primary.isEnabled = true
  171. cell.primary.isHidden = false
  172. cell.secondary.isEnabled = true
  173. cell.secondary.isHidden = false
  174. for action in jsonActions {
  175. let label = action["label"].stringValue
  176. let primary = action["primary"].boolValue
  177. if primary {
  178. cell.primary.setTitle(label, for: .normal)
  179. } else {
  180. cell.secondary.setTitle(label, for: .normal)
  181. }
  182. }
  183. } else if jsonActions.count >= 3 {
  184. cell.more.isEnabled = true
  185. cell.more.isHidden = false
  186. cell.more.setTitle("…", for: .normal)
  187. }
  188. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  189. buttonWidth += 30
  190. cell.primaryWidth.constant = buttonWidth
  191. cell.secondaryWidth.constant = buttonWidth
  192. }
  193. return cell
  194. }
  195. // MARK: - tap Action
  196. func tapRemove(with notification: NKNotifications) {
  197. NextcloudKit.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification , method: "DELETE") { (account, error) in
  198. if error == .success && account == self.appDelegate.account {
  199. if let index = self.notifications
  200. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  201. self.notifications.remove(at: index)
  202. }
  203. self.tableView.reloadData()
  204. } else if error != .success {
  205. NCContentPresenter.shared.showError(error: error)
  206. } else {
  207. print("[Error] The user has been changed during networking process.")
  208. }
  209. }
  210. }
  211. func tapAction(with notification: NKNotifications, label: String) {
  212. if notification.app == NCGlobal.shared.spreedName,
  213. let roomToken = notification.objectId.split(separator: "/").first,
  214. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(appDelegate.urlBase)&user=\(appDelegate.userId)&withRoomToken=\(roomToken)"),
  215. UIApplication.shared.canOpenURL(talkUrl) {
  216. UIApplication.shared.open(talkUrl)
  217. } else if let actions = notification.actions,
  218. let jsonActions = JSON(actions).array,
  219. let action = jsonActions.first(where: { $0["label"].string == label }) {
  220. let serverUrl = action["link"].stringValue
  221. let method = action["type"].stringValue
  222. if method == "WEB", let url = action["link"].url {
  223. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  224. return
  225. }
  226. NextcloudKit.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { (account, error) in
  227. if error == .success && account == self.appDelegate.account {
  228. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  229. self.notifications.remove(at: index)
  230. }
  231. self.tableView.reloadData()
  232. if self.navigationController?.presentingViewController != nil, notification.app == NCGlobal.shared.twoFactorNotificatioName {
  233. self.dismiss(animated: true)
  234. }
  235. } else if error != .success {
  236. NCContentPresenter.shared.showError(error: error)
  237. } else {
  238. print("[Error] The user has been changed during networking process.")
  239. }
  240. }
  241. } // else: Action not found
  242. }
  243. func tapMore(with notification: NKNotifications) {
  244. toggleMenu(notification: notification)
  245. }
  246. // MARK: - Load notification networking
  247. @objc func getNetwokingNotification() {
  248. isReloadDataSourceNetworkInProgress = true
  249. self.tableView.reloadData()
  250. NextcloudKit.shared.getNotifications { account, notifications, data, error in
  251. if error == .success && account == self.appDelegate.account {
  252. self.notifications.removeAll()
  253. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  254. for notification in sortedListOfNotifications {
  255. if let icon = (notification as! NKNotifications).icon {
  256. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, completion: { _, _ in })
  257. }
  258. self.notifications.append(notification as! NKNotifications)
  259. }
  260. self.refreshControl?.endRefreshing()
  261. self.isReloadDataSourceNetworkInProgress = false
  262. self.tableView.reloadData()
  263. }
  264. }
  265. }
  266. }
  267. // MARK: -
  268. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  269. @IBOutlet weak var icon: UIImageView!
  270. @IBOutlet weak var avatar: UIImageView!
  271. @IBOutlet weak var date: UILabel!
  272. @IBOutlet weak var subject: UILabel!
  273. @IBOutlet weak var message: UILabel!
  274. @IBOutlet weak var remove: UIButton!
  275. @IBOutlet weak var primary: UIButton!
  276. @IBOutlet weak var secondary: UIButton!
  277. @IBOutlet weak var more: UIButton!
  278. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  279. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  280. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  281. private var user = ""
  282. weak var delegate: NCNotificationCellDelegate?
  283. var notification: NKNotifications?
  284. var fileAvatarImageView: UIImageView? {
  285. get { return avatar }
  286. }
  287. var fileUser: String? {
  288. get { return user }
  289. set { user = newValue ?? "" }
  290. }
  291. override func awakeFromNib() {
  292. super.awakeFromNib()
  293. }
  294. @IBAction func touchUpInsideRemove(_ sender: Any) {
  295. guard let notification = notification else { return }
  296. delegate?.tapRemove(with: notification)
  297. }
  298. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  299. guard let notification = notification,
  300. let button = sender as? UIButton,
  301. let label = button.titleLabel?.text
  302. else { return }
  303. delegate?.tapAction(with: notification, label: label)
  304. }
  305. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  306. guard let notification = notification,
  307. let button = sender as? UIButton,
  308. let label = button.titleLabel?.text
  309. else { return }
  310. delegate?.tapAction(with: notification, label: label)
  311. }
  312. @IBAction func touchUpInsideMore(_ sender: Any) {
  313. guard let notification = notification else { return }
  314. delegate?.tapMore(with: notification)
  315. }
  316. }
  317. protocol NCNotificationCellDelegate: AnyObject {
  318. func tapRemove(with notification: NKNotifications)
  319. func tapAction(with notification: NKNotifications, label: String)
  320. func tapMore(with notification: NKNotifications)
  321. }