NCNotification.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. override func viewDidLoad() {
  31. super.viewDidLoad()
  32. title = NSLocalizedString("_notification_", comment: "")
  33. view.backgroundColor = NCBrandColor.shared.systemBackground
  34. tableView.tableFooterView = UIView()
  35. tableView.rowHeight = UITableView.automaticDimension
  36. tableView.estimatedRowHeight = 50.0
  37. tableView.allowsSelection = false
  38. tableView.backgroundColor = NCBrandColor.shared.systemBackground
  39. // Empty
  40. let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
  41. emptyDataSet = NCEmptyDataSet.init(view: tableView, offset: -offset, delegate: self)
  42. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  43. changeTheming()
  44. }
  45. override func viewWillAppear(_ animated: Bool) {
  46. super.viewWillAppear(animated)
  47. appDelegate.activeViewController = self
  48. }
  49. override func viewDidAppear(_ animated: Bool) {
  50. super.viewDidAppear(animated)
  51. getNetwokingNotification()
  52. }
  53. @objc func changeTheming() {
  54. tableView.reloadData()
  55. }
  56. @objc func viewClose() {
  57. self.dismiss(animated: true, completion: nil)
  58. }
  59. // MARK: - Empty
  60. func emptyDataSetView(_ view: NCEmptyView) {
  61. view.emptyImage.image = UIImage.init(named: "bell")?.image(color: .gray, size: UIScreen.main.bounds.width)
  62. view.emptyTitle.text = NSLocalizedString("_no_notification_", comment: "")
  63. view.emptyDescription.text = ""
  64. }
  65. // MARK: - Table
  66. @objc func reloadDatasource() {
  67. self.tableView.reloadData()
  68. }
  69. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  70. emptyDataSet?.numberOfItemsInSection(notifications.count, section: section)
  71. return notifications.count
  72. }
  73. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  74. let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NCNotificationCell
  75. cell.delegate = self
  76. let notification = notifications[indexPath.row]
  77. let urlIcon = URL(string: notification.icon)
  78. var image: UIImage?
  79. if let urlIcon = urlIcon {
  80. let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  81. image = UIImage(contentsOfFile: pathFileName)
  82. }
  83. if let image = image {
  84. cell.icon.image = image.imageColor(NCBrandColor.shared.brandElement)
  85. } else {
  86. cell.icon.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  87. }
  88. // Avatar
  89. cell.avatar.isHidden = true
  90. cell.avatarLeadingMargin.constant = 10
  91. if let subjectRichParameters = notification.subjectRichParameters {
  92. if let parameter = JSON(subjectRichParameters).dictionary {
  93. if let user = JSON(parameter).dictionary {
  94. if let userId = user["id"]?.string {
  95. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + userId + ".png"
  96. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  97. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  98. cell.avatar.isHidden = false
  99. cell.avatarLeadingMargin.constant = 50
  100. cell.avatar.image = image
  101. }
  102. } else {
  103. DispatchQueue.global().async {
  104. NCCommunication.shared.downloadAvatar(userId: userId, fileNameLocalPath: fileNameLocalPath, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  105. if errorCode == 0 && account == self.appDelegate.account && UIImage(data: data!) != nil {
  106. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  107. cell.avatar.isHidden = false
  108. cell.avatarLeadingMargin.constant = 50
  109. cell.avatar.image = image
  110. }
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. }
  118. }
  119. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  120. cell.notification = notification
  121. cell.date.text = CCUtility.dateDiff(notification.date as Date)
  122. cell.date.textColor = .gray
  123. cell.subject.text = notification.subject
  124. cell.subject.textColor = NCBrandColor.shared.label
  125. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  126. cell.message.textColor = .gray
  127. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  128. cell.primary.isEnabled = false
  129. cell.primary.isHidden = true
  130. cell.primary.titleLabel?.font = .systemFont(ofSize: 14)
  131. cell.primary.setTitleColor(.white, for: .normal)
  132. cell.primary.layer.cornerRadius = 15
  133. cell.primary.layer.masksToBounds = true
  134. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  135. cell.secondary.isEnabled = false
  136. cell.secondary.isHidden = true
  137. cell.secondary.titleLabel?.font = .systemFont(ofSize: 14)
  138. cell.secondary.setTitleColor(.gray, for: .normal)
  139. cell.secondary.layer.cornerRadius = 15
  140. cell.secondary.layer.masksToBounds = true
  141. cell.secondary.layer.backgroundColor = NCBrandColor.shared.graySoft.withAlphaComponent(0.1).cgColor
  142. cell.secondary.layer.borderWidth = 0.3
  143. cell.secondary.layer.borderColor = UIColor.gray.cgColor
  144. cell.messageBottomMargin.constant = 10
  145. // Action
  146. if let actions = notification.actions {
  147. if let jsonActions = JSON(actions).array {
  148. if jsonActions.count == 1 {
  149. let action = jsonActions[0]
  150. cell.primary.isEnabled = true
  151. cell.primary.isHidden = false
  152. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  153. } else if jsonActions.count == 2 {
  154. cell.primary.isEnabled = true
  155. cell.primary.isHidden = false
  156. cell.secondary.isEnabled = true
  157. cell.secondary.isHidden = false
  158. for action in jsonActions {
  159. let label = action["label"].stringValue
  160. let primary = action["primary"].boolValue
  161. if primary {
  162. cell.primary.setTitle(label, for: .normal)
  163. } else {
  164. cell.secondary.setTitle(label, for: .normal)
  165. }
  166. }
  167. }
  168. let widthPrimary = cell.primary.intrinsicContentSize.width + 30;
  169. let widthSecondary = cell.secondary.intrinsicContentSize.width + 30;
  170. if widthPrimary > widthSecondary {
  171. cell.primaryWidth.constant = widthPrimary
  172. cell.secondaryWidth.constant = widthPrimary
  173. } else {
  174. cell.primaryWidth.constant = widthSecondary
  175. cell.secondaryWidth.constant = widthSecondary
  176. }
  177. cell.messageBottomMargin.constant = 40
  178. }
  179. }
  180. return cell
  181. }
  182. // MARK: - tap Action
  183. func tapRemove(with notification: NCCommunicationNotifications?) {
  184. NCCommunication.shared.setNotification(serverUrl:nil, idNotification: notification!.idNotification , method: "DELETE") { (account, errorCode, errorDescription) in
  185. if errorCode == 0 && account == self.appDelegate.account {
  186. if let index = self.notifications.firstIndex(where: {$0.idNotification == notification!.idNotification}) {
  187. self.notifications.remove(at: index)
  188. }
  189. self.reloadDatasource()
  190. } else if errorCode != 0 {
  191. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  192. } else {
  193. print("[LOG] It has been changed user during networking process, error.")
  194. }
  195. }
  196. }
  197. func tapAction(with notification: NCCommunicationNotifications?, label: String) {
  198. if let actions = notification!.actions {
  199. if let jsonActions = JSON(actions).array {
  200. for action in jsonActions {
  201. if action["label"].string == label {
  202. let serverUrl = action["link"].stringValue
  203. let method = action["type"].stringValue
  204. NCCommunication.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { (account, errorCode, errorDescription) in
  205. if errorCode == 0 && account == self.appDelegate.account {
  206. if let index = self.notifications.firstIndex(where: {$0.idNotification == notification!.idNotification}) {
  207. self.notifications.remove(at: index)
  208. }
  209. self.reloadDatasource()
  210. } else if errorCode != 0 {
  211. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  212. } else {
  213. print("[LOG] It has been changed user during networking process, error.")
  214. }
  215. }
  216. }
  217. }
  218. }
  219. }
  220. }
  221. // MARK: - Load notification networking
  222. func getNetwokingNotification() {
  223. NCUtility.shared.startActivityIndicator(backgroundView: self.navigationController?.view, blurEffect: true)
  224. NCCommunication.shared.getNotifications() { (account, notifications, errorCode, errorDescription) in
  225. if errorCode == 0 && account == self.appDelegate.account {
  226. self.notifications.removeAll()
  227. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  228. for notification in sortedListOfNotifications {
  229. if let icon = (notification as! NCCommunicationNotifications).icon {
  230. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, closure: { (imageNamePath) in })
  231. }
  232. self.notifications.append(notification as! NCCommunicationNotifications)
  233. }
  234. self.reloadDatasource()
  235. }
  236. NCUtility.shared.stopActivityIndicator()
  237. }
  238. }
  239. }
  240. // MARK: -
  241. class NCNotificationCell: UITableViewCell {
  242. var delegate: NCNotificationCellDelegate?
  243. var notification: NCCommunicationNotifications?
  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. override func awakeFromNib() {
  257. super.awakeFromNib()
  258. }
  259. @IBAction func touchUpInsideRemove(_ sender: Any) {
  260. delegate?.tapRemove(with: notification)
  261. }
  262. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  263. let button = sender as! UIButton
  264. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  265. }
  266. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  267. let button = sender as! UIButton
  268. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  269. }
  270. }
  271. protocol NCNotificationCellDelegate {
  272. func tapRemove(with notification: NCCommunicationNotifications?)
  273. func tapAction(with notification: NCCommunicationNotifications?, label: String)
  274. }