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