NCNotification.swift 15 KB

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