NCNotification.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import NCCommunication
  25. import SwiftyJSON
  26. class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmptyDataSetDelegate {
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. var notifications: [NCCommunicationNotifications] = []
  29. var emptyDataSet: NCEmptyDataSet?
  30. // MARK: - View Life Cycle
  31. override func viewDidLoad() {
  32. super.viewDidLoad()
  33. title = NSLocalizedString("_notification_", comment: "")
  34. view.backgroundColor = NCBrandColor.shared.systemBackground
  35. tableView.tableFooterView = UIView()
  36. tableView.rowHeight = UITableView.automaticDimension
  37. tableView.estimatedRowHeight = 50.0
  38. tableView.allowsSelection = false
  39. tableView.backgroundColor = NCBrandColor.shared.systemBackground
  40. // Empty
  41. let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
  42. emptyDataSet = NCEmptyDataSet.init(view: tableView, offset: -offset, delegate: self)
  43. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  44. changeTheming()
  45. }
  46. override func viewWillAppear(_ animated: Bool) {
  47. super.viewWillAppear(animated)
  48. appDelegate.activeViewController = self
  49. }
  50. override func viewDidAppear(_ animated: Bool) {
  51. super.viewDidAppear(animated)
  52. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  53. getNetwokingNotification()
  54. }
  55. override func viewDidDisappear(_ animated: Bool) {
  56. super.viewDidDisappear(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. @objc func changeTheming() {
  67. tableView.reloadData()
  68. }
  69. // MARK: - Empty
  70. func emptyDataSetView(_ view: NCEmptyView) {
  71. view.emptyImage.image = UIImage.init(named: "bell")?.image(color: .gray, size: UIScreen.main.bounds.width)
  72. view.emptyTitle.text = NSLocalizedString("_no_notification_", comment: "")
  73. view.emptyDescription.text = ""
  74. }
  75. // MARK: - Table
  76. @objc func reloadDatasource() {
  77. self.tableView.reloadData()
  78. }
  79. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  80. emptyDataSet?.numberOfItemsInSection(notifications.count, section: section)
  81. return notifications.count
  82. }
  83. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  84. let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NCNotificationCell
  85. cell.delegate = self
  86. let notification = notifications[indexPath.row]
  87. let urlIcon = URL(string: notification.icon)
  88. var image: UIImage?
  89. if let urlIcon = urlIcon {
  90. let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  91. image = UIImage(contentsOfFile: pathFileName)
  92. }
  93. if let image = image {
  94. cell.icon.image = image.imageColor(NCBrandColor.shared.brandElement)
  95. } else {
  96. cell.icon.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  97. }
  98. // Avatar
  99. cell.avatar.isHidden = true
  100. cell.avatarLeadingMargin.constant = 10
  101. if let subjectRichParameters = notification.subjectRichParameters {
  102. if let parameter = JSON(subjectRichParameters).dictionary {
  103. if let user = JSON(parameter).dictionary {
  104. if let userId = user["id"]?.string {
  105. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + userId + ".png"
  106. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  107. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  108. cell.avatar.isHidden = false
  109. cell.avatarLeadingMargin.constant = 50
  110. cell.avatar.image = image
  111. }
  112. } else {
  113. DispatchQueue.global().async {
  114. NCCommunication.shared.downloadAvatar(userId: userId, fileNameLocalPath: fileNameLocalPath, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  115. if errorCode == 0 && account == self.appDelegate.account && UIImage(data: data!) != nil {
  116. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  117. cell.avatar.isHidden = false
  118. cell.avatarLeadingMargin.constant = 50
  119. cell.avatar.image = image
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  130. cell.notification = notification
  131. cell.date.text = CCUtility.dateDiff(notification.date as Date)
  132. cell.date.textColor = .gray
  133. cell.subject.text = notification.subject
  134. cell.subject.textColor = NCBrandColor.shared.label
  135. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  136. cell.message.textColor = .gray
  137. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  138. cell.primary.isEnabled = false
  139. cell.primary.isHidden = true
  140. cell.primary.titleLabel?.font = .systemFont(ofSize: 14)
  141. cell.primary.setTitleColor(.white, for: .normal)
  142. cell.primary.layer.cornerRadius = 15
  143. cell.primary.layer.masksToBounds = true
  144. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  145. cell.secondary.isEnabled = false
  146. cell.secondary.isHidden = true
  147. cell.secondary.titleLabel?.font = .systemFont(ofSize: 14)
  148. cell.secondary.setTitleColor(.gray, for: .normal)
  149. cell.secondary.layer.cornerRadius = 15
  150. cell.secondary.layer.masksToBounds = true
  151. cell.secondary.layer.backgroundColor = NCBrandColor.shared.systemGray5.cgColor
  152. cell.secondary.layer.borderWidth = 0.3
  153. cell.secondary.layer.borderColor = UIColor.gray.cgColor
  154. cell.messageBottomMargin.constant = 10
  155. // Action
  156. if let actions = notification.actions {
  157. if let jsonActions = JSON(actions).array {
  158. if jsonActions.count == 1 {
  159. let action = jsonActions[0]
  160. cell.primary.isEnabled = true
  161. cell.primary.isHidden = false
  162. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  163. } else if jsonActions.count == 2 {
  164. cell.primary.isEnabled = true
  165. cell.primary.isHidden = false
  166. cell.secondary.isEnabled = true
  167. cell.secondary.isHidden = false
  168. for action in jsonActions {
  169. let label = action["label"].stringValue
  170. let primary = action["primary"].boolValue
  171. if primary {
  172. cell.primary.setTitle(label, for: .normal)
  173. } else {
  174. cell.secondary.setTitle(label, for: .normal)
  175. }
  176. }
  177. }
  178. let widthPrimary = cell.primary.intrinsicContentSize.width + 30;
  179. let widthSecondary = cell.secondary.intrinsicContentSize.width + 30;
  180. if widthPrimary > widthSecondary {
  181. cell.primaryWidth.constant = widthPrimary
  182. cell.secondaryWidth.constant = widthPrimary
  183. } else {
  184. cell.primaryWidth.constant = widthSecondary
  185. cell.secondaryWidth.constant = widthSecondary
  186. }
  187. cell.messageBottomMargin.constant = 40
  188. }
  189. }
  190. return cell
  191. }
  192. // MARK: - tap Action
  193. func tapRemove(with notification: NCCommunicationNotifications?) {
  194. NCCommunication.shared.setNotification(serverUrl:nil, idNotification: notification!.idNotification , method: "DELETE") { (account, errorCode, errorDescription) in
  195. if errorCode == 0 && account == self.appDelegate.account {
  196. if let index = self.notifications.firstIndex(where: {$0.idNotification == notification!.idNotification}) {
  197. self.notifications.remove(at: index)
  198. }
  199. self.reloadDatasource()
  200. } else if errorCode != 0 {
  201. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  202. } else {
  203. print("[LOG] It has been changed user during networking process, error.")
  204. }
  205. }
  206. }
  207. func tapAction(with notification: NCCommunicationNotifications?, label: String) {
  208. if let actions = notification!.actions {
  209. if let jsonActions = JSON(actions).array {
  210. for action in jsonActions {
  211. if action["label"].string == label {
  212. let serverUrl = action["link"].stringValue
  213. let method = action["type"].stringValue
  214. NCCommunication.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { (account, errorCode, errorDescription) in
  215. if errorCode == 0 && account == self.appDelegate.account {
  216. if let index = self.notifications.firstIndex(where: {$0.idNotification == notification!.idNotification}) {
  217. self.notifications.remove(at: index)
  218. }
  219. self.reloadDatasource()
  220. } else if errorCode != 0 {
  221. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  222. } else {
  223. print("[LOG] It has been changed user during networking process, error.")
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. }
  231. // MARK: - Load notification networking
  232. func getNetwokingNotification() {
  233. NCUtility.shared.startActivityIndicator(backgroundView: self.navigationController?.view, blurEffect: true)
  234. NCCommunication.shared.getNotifications() { (account, notifications, errorCode, errorDescription) in
  235. if errorCode == 0 && account == self.appDelegate.account {
  236. self.notifications.removeAll()
  237. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  238. for notification in sortedListOfNotifications {
  239. if let icon = (notification as! NCCommunicationNotifications).icon {
  240. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, closure: { (imageNamePath) in })
  241. }
  242. self.notifications.append(notification as! NCCommunicationNotifications)
  243. }
  244. self.reloadDatasource()
  245. }
  246. NCUtility.shared.stopActivityIndicator()
  247. }
  248. }
  249. }
  250. // MARK: -
  251. class NCNotificationCell: UITableViewCell {
  252. var delegate: NCNotificationCellDelegate?
  253. var notification: NCCommunicationNotifications?
  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 avatarLeadingMargin: NSLayoutConstraint!
  263. @IBOutlet weak var messageBottomMargin: NSLayoutConstraint!
  264. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  265. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  266. override func awakeFromNib() {
  267. super.awakeFromNib()
  268. }
  269. @IBAction func touchUpInsideRemove(_ sender: Any) {
  270. delegate?.tapRemove(with: notification)
  271. }
  272. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  273. let button = sender as! UIButton
  274. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  275. }
  276. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  277. let button = sender as! UIButton
  278. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  279. }
  280. }
  281. protocol NCNotificationCellDelegate {
  282. func tapRemove(with notification: NCCommunicationNotifications?)
  283. func tapAction(with notification: NCCommunicationNotifications?, label: String)
  284. }