NCNotification.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. // 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.init(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.init(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. if let json = JSON(subjectRichParameters).dictionary {
  105. if let user = json["user"]?["id"].stringValue {
  106. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  107. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  108. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  109. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  110. cell.avatar.isHidden = false
  111. cell.avatarLeadingMargin.constant = 50
  112. cell.avatar.image = image
  113. }
  114. } else {
  115. cell.avatar.isHidden = false
  116. cell.avatarLeadingMargin.constant = 50
  117. cell.fileUser = user
  118. NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: nil, fileName: fileName, cell: cell, view: tableView)
  119. }
  120. }
  121. }
  122. }
  123. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  124. cell.notification = notification
  125. cell.date.text = CCUtility.dateDiff(notification.date as Date)
  126. cell.date.textColor = .gray
  127. cell.subject.text = notification.subject
  128. cell.subject.textColor = NCBrandColor.shared.label
  129. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  130. cell.message.textColor = .gray
  131. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  132. cell.primary.isEnabled = false
  133. cell.primary.isHidden = true
  134. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  135. cell.primary.setTitleColor(.white, for: .normal)
  136. cell.primary.layer.cornerRadius = 15
  137. cell.primary.layer.masksToBounds = true
  138. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  139. cell.secondary.isEnabled = false
  140. cell.secondary.isHidden = true
  141. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  142. cell.secondary.setTitleColor(.gray, for: .normal)
  143. cell.secondary.layer.cornerRadius = 15
  144. cell.secondary.layer.masksToBounds = true
  145. cell.secondary.layer.backgroundColor = NCBrandColor.shared.systemGray5.cgColor
  146. cell.secondary.layer.borderWidth = 0.3
  147. cell.secondary.layer.borderColor = UIColor.gray.cgColor
  148. // Action
  149. if let actions = notification.actions,
  150. let jsonActions = JSON(actions).array {
  151. if jsonActions.count == 1 {
  152. let action = jsonActions[0]
  153. cell.primary.isEnabled = true
  154. cell.primary.isHidden = false
  155. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  156. } else if jsonActions.count == 2 {
  157. cell.primary.isEnabled = true
  158. cell.primary.isHidden = false
  159. cell.secondary.isEnabled = true
  160. cell.secondary.isHidden = false
  161. for action in jsonActions {
  162. let label = action["label"].stringValue
  163. let primary = action["primary"].boolValue
  164. if primary {
  165. cell.primary.setTitle(label, for: .normal)
  166. } else {
  167. cell.secondary.setTitle(label, for: .normal)
  168. }
  169. }
  170. }
  171. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  172. buttonWidth += 30
  173. cell.primaryWidth.constant = buttonWidth
  174. cell.secondaryWidth.constant = buttonWidth
  175. }
  176. return cell
  177. }
  178. // MARK: - tap Action
  179. func tapRemove(with notification: NCCommunicationNotifications?) {
  180. NCCommunication.shared.setNotification(serverUrl:nil, idNotification: notification!.idNotification , method: "DELETE") { (account, errorCode, errorDescription) in
  181. if errorCode == 0 && account == self.appDelegate.account {
  182. if let index = self.notifications
  183. .firstIndex(where: { $0.idNotification == notification!.idNotification }) {
  184. self.notifications.remove(at: index)
  185. }
  186. self.reloadDatasource()
  187. } else if errorCode != 0 {
  188. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  189. } else {
  190. print("[LOG] It has been changed user during networking process, error.")
  191. }
  192. }
  193. }
  194. func tapAction(with notification: NCCommunicationNotifications?, label: String) {
  195. if let actions = notification!.actions {
  196. if let jsonActions = JSON(actions).array {
  197. for action in jsonActions {
  198. if action["label"].string == label {
  199. let serverUrl = action["link"].stringValue
  200. let method = action["type"].stringValue
  201. if method == "WEB", let url = action["link"].url {
  202. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  203. return
  204. }
  205. NCCommunication.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { (account, errorCode, errorDescription) in
  206. if errorCode == 0 && account == self.appDelegate.account {
  207. if let index = self.notifications
  208. .firstIndex(where: { $0.idNotification == notification!.idNotification }) {
  209. self.notifications.remove(at: index)
  210. }
  211. self.reloadDatasource()
  212. } else if errorCode != 0 {
  213. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  214. } else {
  215. print("[LOG] It has been changed user during networking process, error.")
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. }
  223. // MARK: - Load notification networking
  224. func getNetwokingNotification() {
  225. NCUtility.shared.startActivityIndicator(backgroundView: self.navigationController?.view, blurEffect: true)
  226. NCCommunication.shared.getNotifications() { (account, notifications, errorCode, errorDescription) in
  227. if errorCode == 0 && account == self.appDelegate.account {
  228. self.notifications.removeAll()
  229. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  230. for notification in sortedListOfNotifications {
  231. if let icon = (notification as! NCCommunicationNotifications).icon {
  232. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, closure: { (imageNamePath) in })
  233. }
  234. self.notifications.append(notification as! NCCommunicationNotifications)
  235. }
  236. self.reloadDatasource()
  237. }
  238. NCUtility.shared.stopActivityIndicator()
  239. }
  240. }
  241. }
  242. // MARK: -
  243. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  244. @IBOutlet weak var icon : UIImageView!
  245. @IBOutlet weak var avatar : UIImageView!
  246. @IBOutlet weak var date: UILabel!
  247. @IBOutlet weak var subject: UILabel!
  248. @IBOutlet weak var message: UILabel!
  249. @IBOutlet weak var remove: UIButton!
  250. @IBOutlet weak var primary: UIButton!
  251. @IBOutlet weak var secondary: UIButton!
  252. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  253. // @IBOutlet weak var messageBottomMargin: NSLayoutConstraint!
  254. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  255. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  256. private var user = ""
  257. var delegate: NCNotificationCellDelegate?
  258. var notification: NCCommunicationNotifications?
  259. var filePreviewImageView : UIImageView? {
  260. get {
  261. return nil
  262. }
  263. }
  264. var fileAvatarImageView: UIImageView? {
  265. get {
  266. return avatar
  267. }
  268. }
  269. var fileObjectId: String? {
  270. get {
  271. return nil
  272. }
  273. }
  274. var fileUser: String? {
  275. get {
  276. return user
  277. }
  278. set {
  279. user = newValue ?? ""
  280. }
  281. }
  282. override func awakeFromNib() {
  283. super.awakeFromNib()
  284. }
  285. @IBAction func touchUpInsideRemove(_ sender: Any) {
  286. delegate?.tapRemove(with: notification)
  287. }
  288. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  289. let button = sender as! UIButton
  290. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  291. }
  292. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  293. let button = sender as! UIButton
  294. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  295. }
  296. }
  297. protocol NCNotificationCellDelegate {
  298. func tapRemove(with notification: NCCommunicationNotifications?)
  299. func tapAction(with notification: NCCommunicationNotifications?, label: String)
  300. }