NCNotification.swift 15 KB

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