NCNotification.swift 14 KB

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