NCNotification.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. // Author Henrik Storch <henrik.storch@nextcloud.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import UIKit
  25. import NextcloudKit
  26. import SwiftyJSON
  27. import JGProgressHUD
  28. class NCNotification: UITableViewController, NCNotificationCellDelegate {
  29. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  30. let utilityFileSystem = NCUtilityFileSystem()
  31. let utility = NCUtility()
  32. var notifications: [NKNotifications] = []
  33. var dataSourceTask: URLSessionTask?
  34. // MARK: - View Life Cycle
  35. override func viewDidLoad() {
  36. super.viewDidLoad()
  37. title = NSLocalizedString("_notifications_", comment: "")
  38. view.backgroundColor = .systemBackground
  39. tableView.tableFooterView = UIView()
  40. tableView.rowHeight = UITableView.automaticDimension
  41. tableView.estimatedRowHeight = 50.0
  42. tableView.backgroundColor = .systemBackground
  43. refreshControl?.addTarget(self, action: #selector(getNetwokingNotification), for: .valueChanged)
  44. // Navigation controller is being presented modally
  45. if navigationController?.presentingViewController != nil {
  46. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, action: { [weak self] in
  47. self?.dismiss(animated: true)
  48. })
  49. }
  50. }
  51. override func viewWillAppear(_ animated: Bool) {
  52. super.viewWillAppear(animated)
  53. navigationController?.setNavigationBarAppearance()
  54. }
  55. override func viewDidAppear(_ animated: Bool) {
  56. super.viewDidAppear(animated)
  57. appDelegate.activeViewController = self
  58. getNetwokingNotification()
  59. }
  60. @objc func viewClose() {
  61. self.dismiss(animated: true, completion: nil)
  62. }
  63. // MARK: - Table
  64. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  65. return notifications.count
  66. }
  67. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  68. guard let notification = NCApplicationHandle().didSelectNotification(notifications[indexPath.row], viewController: self) else { return }
  69. do {
  70. if let subjectRichParameters = notification.subjectRichParameters,
  71. let json = try JSONSerialization.jsonObject(with: subjectRichParameters, options: .mutableContainers) as? [String: Any],
  72. let file = json["file"] as? [String: Any],
  73. file["type"] as? String == "file" {
  74. if let id = file["id"] {
  75. NCActionCenter.shared.viewerFile(account: appDelegate.account, fileId: ("\(id)"), viewController: self)
  76. }
  77. }
  78. } catch {
  79. print("Something went wrong")
  80. }
  81. }
  82. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  83. guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NCNotificationCell else { return UITableViewCell() }
  84. cell.delegate = self
  85. cell.selectionStyle = .none
  86. cell.indexPath = indexPath
  87. let notification = notifications[indexPath.row]
  88. let urlIcon = URL(string: notification.icon)
  89. var image: UIImage?
  90. if let urlIcon = urlIcon {
  91. let pathFileName = utilityFileSystem.directoryUserData + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  92. image = UIImage(contentsOfFile: pathFileName)
  93. }
  94. if let image = image {
  95. cell.icon.image = image.withTintColor(NCBrandColor.shared.brandElement, renderingMode: .alwaysOriginal)
  96. } else {
  97. cell.icon.image = utility.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  98. }
  99. // Avatar
  100. cell.avatar.isHidden = true
  101. cell.avatarLeadingMargin.constant = 10
  102. if let subjectRichParameters = notification.subjectRichParameters,
  103. let json = JSON(subjectRichParameters).dictionary,
  104. let user = json["user"]?["id"].stringValue {
  105. cell.avatar.isHidden = false
  106. cell.avatarLeadingMargin.constant = 50
  107. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  108. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + fileName
  109. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  110. cell.avatar.image = image
  111. } else if !FileManager.default.fileExists(atPath: fileNameLocalPath) {
  112. cell.fileUser = user
  113. NCNetworking.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView, cellImageView: cell.fileAvatarImageView)
  114. }
  115. }
  116. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  117. cell.notification = notification
  118. cell.date.text = utility.dateDiff(notification.date as Date)
  119. cell.date.textColor = .gray
  120. cell.subject.text = notification.subject
  121. cell.subject.textColor = .label
  122. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  123. cell.message.textColor = .gray
  124. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  125. cell.primary.isEnabled = false
  126. cell.primary.isHidden = true
  127. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  128. cell.primary.layer.cornerRadius = 15
  129. cell.primary.layer.masksToBounds = true
  130. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  131. cell.primary.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  132. cell.more.isEnabled = false
  133. cell.more.isHidden = true
  134. cell.more.titleLabel?.font = .systemFont(ofSize: 15)
  135. cell.more.layer.cornerRadius = 15
  136. cell.more.layer.masksToBounds = true
  137. cell.more.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  138. cell.more.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  139. cell.secondary.isEnabled = false
  140. cell.secondary.isHidden = true
  141. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  142. cell.secondary.layer.cornerRadius = 15
  143. cell.secondary.layer.masksToBounds = true
  144. cell.secondary.layer.borderWidth = 1
  145. cell.secondary.layer.borderColor = UIColor.systemGray.cgColor
  146. cell.secondary.layer.backgroundColor = UIColor.secondarySystemBackground.cgColor
  147. cell.secondary.setTitleColor(.gray, for: .normal)
  148. // Action
  149. if let actions = notification.actions,
  150. 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. } else if jsonActions.count >= 3 {
  171. cell.more.isEnabled = true
  172. cell.more.isHidden = false
  173. cell.more.setTitle("…", for: .normal)
  174. }
  175. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  176. buttonWidth += 30
  177. cell.primaryWidth.constant = buttonWidth
  178. cell.secondaryWidth.constant = buttonWidth
  179. }
  180. return cell
  181. }
  182. // MARK: - tap Action
  183. func tapRemove(with notification: NKNotifications) {
  184. NextcloudKit.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification, method: "DELETE") { account, error in
  185. if error == .success && account == self.appDelegate.account {
  186. if let index = self.notifications
  187. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  188. self.notifications.remove(at: index)
  189. }
  190. self.tableView.reloadData()
  191. } else if error != .success {
  192. NCContentPresenter().showError(error: error)
  193. } else {
  194. print("[Error] The user has been changed during networking process.")
  195. }
  196. }
  197. }
  198. func tapAction(with notification: NKNotifications, label: String) {
  199. if notification.app == NCGlobal.shared.spreedName,
  200. let roomToken = notification.objectId.split(separator: "/").first,
  201. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(appDelegate.urlBase)&user=\(appDelegate.userId)&withRoomToken=\(roomToken)"),
  202. UIApplication.shared.canOpenURL(talkUrl) {
  203. UIApplication.shared.open(talkUrl)
  204. } else if let actions = notification.actions,
  205. let jsonActions = JSON(actions).array,
  206. let action = jsonActions.first(where: { $0["label"].string == label }) {
  207. let serverUrl = action["link"].stringValue
  208. let method = action["type"].stringValue
  209. if method == "WEB", let url = action["link"].url {
  210. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  211. return
  212. }
  213. NextcloudKit.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { account, error in
  214. if error == .success && account == self.appDelegate.account {
  215. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  216. self.notifications.remove(at: index)
  217. }
  218. self.tableView.reloadData()
  219. if self.navigationController?.presentingViewController != nil, notification.app == NCGlobal.shared.twoFactorNotificatioName {
  220. self.dismiss(animated: true)
  221. }
  222. } else if error != .success {
  223. NCContentPresenter().showError(error: error)
  224. } else {
  225. print("[Error] The user has been changed during networking process.")
  226. }
  227. }
  228. } // else: Action not found
  229. }
  230. func tapMore(with notification: NKNotifications) {
  231. toggleMenu(notification: notification)
  232. }
  233. // MARK: - Load notification networking
  234. @objc func getNetwokingNotification() {
  235. self.tableView.reloadData()
  236. NextcloudKit.shared.getNotifications { task in
  237. self.dataSourceTask = task
  238. self.tableView.reloadData()
  239. } completion: { account, notifications, _, error in
  240. if error == .success && 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? NKNotifications)?.icon {
  245. self.utility.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, completion: { _, _ in })
  246. }
  247. if let notification = (notification as? NKNotifications) {
  248. self.notifications.append(notification)
  249. }
  250. }
  251. self.refreshControl?.endRefreshing()
  252. self.tableView.reloadData()
  253. }
  254. }
  255. }
  256. }
  257. // MARK: -
  258. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  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 more: UIButton!
  268. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  269. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  270. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  271. private var user = ""
  272. private var index = IndexPath()
  273. weak var delegate: NCNotificationCellDelegate?
  274. var notification: NKNotifications?
  275. var indexPath: IndexPath {
  276. get { return index }
  277. set { index = newValue }
  278. }
  279. var fileAvatarImageView: UIImageView? {
  280. return avatar
  281. }
  282. var fileUser: String? {
  283. get { return user }
  284. set { user = newValue ?? "" }
  285. }
  286. override func awakeFromNib() {
  287. super.awakeFromNib()
  288. }
  289. @IBAction func touchUpInsideRemove(_ sender: Any) {
  290. guard let notification = notification else { return }
  291. delegate?.tapRemove(with: notification)
  292. }
  293. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  294. guard let notification = notification,
  295. let button = sender as? UIButton,
  296. let label = button.titleLabel?.text
  297. else { return }
  298. delegate?.tapAction(with: notification, label: label)
  299. }
  300. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  301. guard let notification = notification,
  302. let button = sender as? UIButton,
  303. let label = button.titleLabel?.text
  304. else { return }
  305. delegate?.tapAction(with: notification, label: label)
  306. }
  307. @IBAction func touchUpInsideMore(_ sender: Any) {
  308. guard let notification = notification else { return }
  309. delegate?.tapMore(with: notification)
  310. }
  311. }
  312. protocol NCNotificationCellDelegate: AnyObject {
  313. func tapRemove(with notification: NKNotifications)
  314. func tapAction(with notification: NKNotifications, label: String)
  315. func tapMore(with notification: NKNotifications)
  316. }