NCNotification.swift 15 KB

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