NCNotification.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 NCCommunication
  26. import SwiftyJSON
  27. class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmptyDataSetDelegate {
  28. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. var notifications: [NCCommunicationNotifications] = []
  30. var emptyDataSet: NCEmptyDataSet?
  31. // MARK: - View Life Cycle
  32. override func viewDidLoad() {
  33. super.viewDidLoad()
  34. title = NSLocalizedString("_notification_", comment: "")
  35. view.backgroundColor = NCBrandColor.shared.systemBackground
  36. tableView.tableFooterView = UIView()
  37. tableView.rowHeight = UITableView.automaticDimension
  38. tableView.estimatedRowHeight = 50.0
  39. tableView.allowsSelection = false
  40. tableView.backgroundColor = NCBrandColor.shared.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. //
  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 = UIImage(named: "bell")?.image(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, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  81. let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NCNotificationCell
  82. cell.delegate = self
  83. let notification = notifications[indexPath.row]
  84. let urlIcon = URL(string: notification.icon)
  85. var image: UIImage?
  86. if let urlIcon = urlIcon {
  87. let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  88. image = UIImage(contentsOfFile: pathFileName)
  89. }
  90. if let image = image {
  91. cell.icon.image = image.imageColor(NCBrandColor.shared.brandElement)
  92. } else {
  93. cell.icon.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  94. }
  95. // Avatar
  96. cell.avatar.isHidden = true
  97. cell.avatarLeadingMargin.constant = 10
  98. if let subjectRichParameters = notification.subjectRichParameters,
  99. let json = JSON(subjectRichParameters).dictionary,
  100. let user = json["user"]?["id"].stringValue {
  101. cell.avatar.isHidden = false
  102. cell.avatarLeadingMargin.constant = 50
  103. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  104. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  105. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  106. cell.avatar.image = image
  107. } else if !FileManager.default.fileExists(atPath: fileNameLocalPath) {
  108. cell.fileUser = user
  109. NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView, cellImageView: cell.fileAvatarImageView)
  110. }
  111. }
  112. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  113. cell.notification = notification
  114. cell.date.text = CCUtility.dateDiff(notification.date as Date)
  115. cell.date.textColor = .gray
  116. cell.subject.text = notification.subject
  117. cell.subject.textColor = NCBrandColor.shared.label
  118. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  119. cell.message.textColor = .gray
  120. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  121. cell.primary.isEnabled = false
  122. cell.primary.isHidden = true
  123. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  124. cell.primary.layer.cornerRadius = 15
  125. cell.primary.layer.masksToBounds = true
  126. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  127. cell.primary.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  128. cell.secondary.isEnabled = false
  129. cell.secondary.isHidden = true
  130. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  131. cell.secondary.layer.cornerRadius = 15
  132. cell.secondary.layer.masksToBounds = true
  133. cell.secondary.layer.borderWidth = 1
  134. cell.secondary.layer.borderColor = NCBrandColor.shared.systemGray.cgColor
  135. cell.secondary.layer.backgroundColor = NCBrandColor.shared.secondarySystemBackground.cgColor
  136. cell.secondary.setTitleColor(.black, for: .normal)
  137. // Action
  138. if let actions = notification.actions,
  139. let jsonActions = JSON(actions).array {
  140. if jsonActions.count == 1 {
  141. let action = jsonActions[0]
  142. cell.primary.isEnabled = true
  143. cell.primary.isHidden = false
  144. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  145. } else if jsonActions.count == 2 {
  146. cell.primary.isEnabled = true
  147. cell.primary.isHidden = false
  148. cell.secondary.isEnabled = true
  149. cell.secondary.isHidden = false
  150. for action in jsonActions {
  151. let label = action["label"].stringValue
  152. let primary = action["primary"].boolValue
  153. if primary {
  154. cell.primary.setTitle(label, for: .normal)
  155. } else {
  156. cell.secondary.setTitle(label, for: .normal)
  157. }
  158. }
  159. }
  160. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  161. buttonWidth += 30
  162. cell.primaryWidth.constant = buttonWidth
  163. cell.secondaryWidth.constant = buttonWidth
  164. }
  165. return cell
  166. }
  167. // MARK: - tap Action
  168. func tapRemove(with notification: NCCommunicationNotifications) {
  169. NCCommunication.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification , method: "DELETE") { (account, errorCode, errorDescription) in
  170. if errorCode == 0 && account == self.appDelegate.account {
  171. if let index = self.notifications
  172. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  173. self.notifications.remove(at: index)
  174. }
  175. self.reloadDatasource()
  176. } else if errorCode != 0 {
  177. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  178. } else {
  179. print("[Error] The user has been changed during networking process.")
  180. }
  181. }
  182. }
  183. func tapAction(with notification: NCCommunicationNotifications, label: String) {
  184. if notification.app == "spreed",
  185. let roomToken = notification.objectId.split(separator: "/").first,
  186. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(appDelegate.urlBase)&user=\(appDelegate.userId)&withRoomToken=\(roomToken)"),
  187. UIApplication.shared.canOpenURL(talkUrl) {
  188. UIApplication.shared.open(talkUrl)
  189. } else if let actions = notification.actions,
  190. let jsonActions = JSON(actions).array,
  191. let action = jsonActions.first(where: { $0["label"].string == label }) {
  192. let serverUrl = action["link"].stringValue
  193. let method = action["type"].stringValue
  194. if method == "WEB", let url = action["link"].url {
  195. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  196. return
  197. }
  198. NCCommunication.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { (account, errorCode, errorDescription) in
  199. if errorCode == 0 && account == self.appDelegate.account {
  200. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  201. self.notifications.remove(at: index)
  202. }
  203. self.reloadDatasource()
  204. } else if errorCode != 0 {
  205. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  206. } else {
  207. print("[Error] The user has been changed during networking process.")
  208. }
  209. }
  210. } // else: Action not found
  211. }
  212. // MARK: - Load notification networking
  213. func getNetwokingNotification() {
  214. NCUtility.shared.startActivityIndicator(backgroundView: self.navigationController?.view, blurEffect: true)
  215. NCCommunication.shared.getNotifications { account, notifications, errorCode, _ in
  216. if errorCode == 0 && account == self.appDelegate.account {
  217. self.notifications.removeAll()
  218. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  219. for notification in sortedListOfNotifications {
  220. if let icon = (notification as! NCCommunicationNotifications).icon {
  221. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, closure: { _ in })
  222. }
  223. self.notifications.append(notification as! NCCommunicationNotifications)
  224. }
  225. self.reloadDatasource()
  226. }
  227. NCUtility.shared.stopActivityIndicator()
  228. }
  229. }
  230. }
  231. // MARK: -
  232. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  233. @IBOutlet weak var icon: UIImageView!
  234. @IBOutlet weak var avatar: UIImageView!
  235. @IBOutlet weak var date: UILabel!
  236. @IBOutlet weak var subject: UILabel!
  237. @IBOutlet weak var message: UILabel!
  238. @IBOutlet weak var remove: UIButton!
  239. @IBOutlet weak var primary: UIButton!
  240. @IBOutlet weak var secondary: UIButton!
  241. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  242. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  243. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  244. private var user = ""
  245. weak var delegate: NCNotificationCellDelegate?
  246. var notification: NCCommunicationNotifications?
  247. var fileAvatarImageView: UIImageView? {
  248. get { return avatar }
  249. }
  250. var fileUser: String? {
  251. get { return user }
  252. set { user = newValue ?? "" }
  253. }
  254. override func awakeFromNib() {
  255. super.awakeFromNib()
  256. }
  257. @IBAction func touchUpInsideRemove(_ sender: Any) {
  258. guard let notification = notification else { return }
  259. delegate?.tapRemove(with: notification)
  260. }
  261. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  262. guard let notification = notification,
  263. let button = sender as? UIButton,
  264. let label = button.titleLabel?.text
  265. else { return }
  266. delegate?.tapAction(with: notification, label: label)
  267. }
  268. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  269. guard let notification = notification,
  270. let button = sender as? UIButton,
  271. let label = button.titleLabel?.text
  272. else { return }
  273. delegate?.tapAction(with: notification, label: label)
  274. }
  275. }
  276. protocol NCNotificationCellDelegate: AnyObject {
  277. func tapRemove(with notification: NCCommunicationNotifications)
  278. func tapAction(with notification: NCCommunicationNotifications, label: String)
  279. }