CCNotification.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. //
  2. // CCNotification.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. class CCNotification: UITableViewController, CCNotificationCelllDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  26. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  27. static var notifications = [OCNotifications]()
  28. static var notificationsAccount = ""
  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 backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  57. return NCBrandColor.sharedInstance.backgroundView
  58. }
  59. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  60. return CCGraphics.changeThemingColorImage(UIImage.init(named: "notification"), width: 300, height: 300, color: NCBrandColor.sharedInstance.graySoft)
  61. }
  62. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  63. let text = "\n"+NSLocalizedString("_no_notification_", comment: "")
  64. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  65. return NSAttributedString.init(string: text, attributes: attributes)
  66. }
  67. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  68. return true
  69. }
  70. // MARK: - Table
  71. @objc func reloadDatasource() {
  72. self.tableView.reloadData()
  73. }
  74. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  75. return CCNotification.notifications.count
  76. }
  77. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  78. let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CCNotificationCell
  79. cell.delegate = self
  80. let notification = CCNotification.notifications[indexPath.row]
  81. let urlIcon = URL(string: notification.icon)
  82. var image : UIImage?
  83. if let urlIcon = urlIcon {
  84. let pathFileName = CCUtility.getDirectoryUserData() + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  85. image = UIImage(contentsOfFile: pathFileName)
  86. }
  87. if let image = image {
  88. cell.icon.image = CCGraphics.changeThemingColorImage(image, multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  89. } else {
  90. cell.icon.image = CCGraphics.changeThemingColorImage(#imageLiteral(resourceName: "notification"), multiplier:2, color: NCBrandColor.sharedInstance.brandElement)
  91. }
  92. // Avatar
  93. cell.avatar.isHidden = true
  94. cell.avatarLeadingMargin.constant = 10
  95. if let parameter = notification.subjectRichParameters as? Dictionary<String, Any> {
  96. if let user = parameter["user"] as? Dictionary<String, Any> {
  97. if let name = user["id"] as? String {
  98. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + name + ".png"
  99. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  100. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  101. cell.avatar.isHidden = false
  102. cell.avatarLeadingMargin.constant = 50
  103. cell.avatar.image = image
  104. }
  105. } else {
  106. DispatchQueue.global().async {
  107. NCCommunication.sharedInstance.downloadAvatar(serverUrl: self.appDelegate.activeUrl, userID: name, fileNameLocalPath: fileNameLocalPath, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: self.appDelegate.activeAccount) { (account, data, errorCode, errorMessage) in
  108. if errorCode == 0 && account == self.appDelegate.activeAccount && UIImage(data: data!) != nil {
  109. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  110. cell.avatar.isHidden = false
  111. cell.avatarLeadingMargin.constant = 50
  112. cell.avatar.image = image
  113. }
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }
  120. }
  121. //
  122. //cell.date.text = DateFormatter.localizedString(from: notification.date, dateStyle: .medium, timeStyle: .medium)
  123. //
  124. cell.notification = notification
  125. cell.date.text = CCUtility.dateDiff(notification.date)
  126. cell.date.textColor = .gray
  127. cell.subject.text = notification.subject
  128. cell.subject.textColor = NCBrandColor.sharedInstance.textView
  129. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  130. cell.message.textColor = .gray
  131. cell.remove.setImage(CCGraphics.changeThemingColorImage(UIImage(named: "exit")!, width: 40, height: 40, color: .gray), for: .normal)
  132. cell.primary.isEnabled = false
  133. cell.primary.isHidden = true
  134. cell.primary.titleLabel?.font = .systemFont(ofSize: 14)
  135. cell.primary.setTitleColor(.white, for: .normal)
  136. cell.primary.layer.cornerRadius = 15
  137. cell.primary.layer.masksToBounds = true
  138. cell.primary.layer.backgroundColor = NCBrandColor.sharedInstance.brand.cgColor
  139. cell.secondary.isEnabled = false
  140. cell.secondary.isHidden = true
  141. cell.secondary.titleLabel?.font = .systemFont(ofSize: 14)
  142. cell.secondary.setTitleColor(.gray, for: .normal)
  143. cell.secondary.layer.cornerRadius = 15
  144. cell.secondary.layer.masksToBounds = true
  145. cell.secondary.layer.backgroundColor = NCBrandColor.sharedInstance.graySoft.withAlphaComponent(0.1).cgColor
  146. cell.secondary.layer.borderWidth = 0.3
  147. cell.secondary.layer.borderColor = UIColor.gray.cgColor
  148. cell.messageBottomMargin.constant = 10
  149. // Action
  150. if notification.actions.count > 0 {
  151. if notification.actions.count == 1 {
  152. let action = notification.actions[0] as! OCNotificationsAction
  153. cell.primary.isEnabled = true
  154. cell.primary.isHidden = false
  155. cell.primary.setTitle(action.label, for: .normal)
  156. } else if notification.actions.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 notification.actions {
  162. let label = (action as! OCNotificationsAction).label
  163. let primary = (action as! OCNotificationsAction).primary
  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. return cell
  183. }
  184. // MARK: tap Action
  185. func tapRemove(with notification: OCNotifications?) {
  186. let serverUrl = self.appDelegate.activeUrl + "/" + k_url_acces_remote_notification_api + "/" + String(notification!.idNotification)
  187. OCNetworking.sharedManager().setNotificationWithAccount(self.appDelegate.activeAccount, serverUrl: serverUrl, type: "DELETE", completion: { (account, message, errorCode) in
  188. if errorCode == 0 && account == self.appDelegate.activeAccount {
  189. //let listOfNotifications = self.appDelegate.listOfNotifications as NSArray as! [OCNotifications]
  190. if let index = CCNotification.self.notifications.firstIndex(where: {$0.idNotification == notification!.idNotification}) {
  191. CCNotification.self.notifications.remove(at: index)
  192. }
  193. self.reloadDatasource()
  194. } else if errorCode != 0 {
  195. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  196. } else {
  197. print("[LOG] It has been changed user during networking process, error.")
  198. }
  199. })
  200. }
  201. func tapAction(with notification: OCNotifications?, label: String) {
  202. for action in notification!.actions {
  203. if (action as! OCNotificationsAction).label == label {
  204. OCNetworking.sharedManager().setNotificationWithAccount(self.appDelegate.activeAccount, serverUrl: (action as! OCNotificationsAction).link, type: (action as! OCNotificationsAction).type, completion: { (account, message, errorCode) in
  205. if errorCode == 0 && account == self.appDelegate.activeAccount {
  206. if let index = CCNotification.self.notifications.firstIndex(where: {$0.idNotification == notification!.idNotification}) {
  207. CCNotification.self.notifications.remove(at: index)
  208. }
  209. self.reloadDatasource()
  210. } else if errorCode != 0 {
  211. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_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. // MARK: Load notification networking
  220. func getNetwokingNotification() {
  221. NCUtility.sharedInstance.startActivityIndicator(view: self.navigationController?.view, bottom: 0)
  222. // Verify User
  223. if appDelegate.activeAccount != CCNotification.notificationsAccount {
  224. CCNotification.notifications.removeAll()
  225. reloadDatasource()
  226. CCNotification.notificationsAccount = appDelegate.activeAccount
  227. }
  228. OCNetworking.sharedManager().getNotificationWithAccount(CCNotification.notificationsAccount, completion: { (account, listOfNotifications, message, errorCode) in
  229. if errorCode == 0 && account == CCNotification.self.notificationsAccount {
  230. CCNotification.self.notifications.removeAll()
  231. let sortedListOfNotifications = (listOfNotifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  232. for notification in sortedListOfNotifications {
  233. // download icon
  234. if let icon = (notification as! OCNotifications).icon {
  235. NCUtility.sharedInstance.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.activeAccount, closure: { (imageNamePath) in })
  236. }
  237. CCNotification.self.notifications.append(notification as! OCNotifications)
  238. }
  239. self.reloadDatasource()
  240. }
  241. NCUtility.sharedInstance.stopActivityIndicator()
  242. })
  243. }
  244. }
  245. // MARK: - Class UITableViewCell
  246. class CCNotificationCell: UITableViewCell {
  247. var delegate: CCNotificationCelllDelegate?
  248. var notification: OCNotifications?
  249. @IBOutlet weak var icon : UIImageView!
  250. @IBOutlet weak var avatar : UIImageView!
  251. @IBOutlet weak var date: UILabel!
  252. @IBOutlet weak var subject: UILabel!
  253. @IBOutlet weak var message: UILabel!
  254. @IBOutlet weak var remove: UIButton!
  255. @IBOutlet weak var primary: UIButton!
  256. @IBOutlet weak var secondary: UIButton!
  257. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  258. @IBOutlet weak var messageBottomMargin: NSLayoutConstraint!
  259. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  260. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  261. override func awakeFromNib() {
  262. super.awakeFromNib()
  263. }
  264. @IBAction func touchUpInsideRemove(_ sender: Any) {
  265. delegate?.tapRemove(with: notification)
  266. }
  267. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  268. let button = sender as! UIButton
  269. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  270. }
  271. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  272. let button = sender as! UIButton
  273. delegate?.tapAction(with: notification, label: button.titleLabel!.text!)
  274. }
  275. }
  276. protocol CCNotificationCelllDelegate {
  277. func tapRemove(with notification: OCNotifications?)
  278. func tapAction(with notification: OCNotifications?, label: String)
  279. }