NCNotification.swift 15 KB

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