NCNotification.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. getNetwokingNotification()
  58. }
  59. override func viewWillDisappear(_ animated: Bool) {
  60. super.viewWillDisappear(animated)
  61. // Cancel Queue & Retrieves Properties
  62. dataSourceTask?.cancel()
  63. }
  64. @objc func viewClose() {
  65. self.dismiss(animated: true, completion: nil)
  66. }
  67. // MARK: - Table
  68. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  69. return notifications.count
  70. }
  71. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  72. guard let notification = NCApplicationHandle().didSelectNotification(notifications[indexPath.row], viewController: self) else { return }
  73. do {
  74. if let subjectRichParameters = notification.subjectRichParameters,
  75. let json = try JSONSerialization.jsonObject(with: subjectRichParameters, options: .mutableContainers) as? [String: Any],
  76. let file = json["file"] as? [String: Any],
  77. file["type"] as? String == "file" {
  78. if let id = file["id"] {
  79. NCActionCenter.shared.viewerFile(account: appDelegate.account, fileId: ("\(id)"), viewController: self)
  80. }
  81. }
  82. } catch {
  83. print("Something went wrong")
  84. }
  85. }
  86. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  87. guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NCNotificationCell else { return UITableViewCell() }
  88. cell.delegate = self
  89. cell.selectionStyle = .none
  90. cell.indexPath = indexPath
  91. let notification = notifications[indexPath.row]
  92. let urlIcon = URL(string: notification.icon)
  93. var image: UIImage?
  94. if let urlIcon = urlIcon {
  95. let pathFileName = utilityFileSystem.directoryUserData + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  96. image = UIImage(contentsOfFile: pathFileName)
  97. }
  98. if let image = image {
  99. cell.icon.image = image.withTintColor(NCBrandColor.shared.brandElement, renderingMode: .alwaysOriginal)
  100. }
  101. // Avatar
  102. cell.avatar.isHidden = true
  103. cell.avatarLeadingMargin.constant = 10
  104. if let subjectRichParameters = notification.subjectRichParameters,
  105. let json = JSON(subjectRichParameters).dictionary,
  106. let user = json["user"]?["id"].stringValue {
  107. cell.avatar.isHidden = false
  108. cell.avatarLeadingMargin.constant = 50
  109. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  110. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + fileName
  111. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  112. cell.avatar.image = image
  113. } else if !FileManager.default.fileExists(atPath: fileNameLocalPath) {
  114. cell.fileUser = user
  115. NCNetworking.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView)
  116. }
  117. }
  118. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  119. cell.notification = notification
  120. cell.date.text = utility.dateDiff(notification.date as Date)
  121. cell.date.textColor = NCBrandColor.shared.iconImageColor2
  122. cell.subject.text = notification.subject
  123. cell.subject.textColor = NCBrandColor.shared.textColor
  124. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  125. cell.message.textColor = NCBrandColor.shared.textColor2
  126. cell.remove.setImage(utility.loadImage(named: "xmark", colors: [NCBrandColor.shared.iconImageColor]), for: .normal)
  127. cell.primary.isEnabled = false
  128. cell.primary.isHidden = true
  129. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  130. cell.primary.layer.cornerRadius = 15
  131. cell.primary.layer.masksToBounds = true
  132. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  133. cell.primary.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  134. cell.more.isEnabled = false
  135. cell.more.isHidden = true
  136. cell.more.titleLabel?.font = .systemFont(ofSize: 15)
  137. cell.more.layer.cornerRadius = 15
  138. cell.more.layer.masksToBounds = true
  139. cell.more.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  140. cell.more.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  141. cell.secondary.isEnabled = false
  142. cell.secondary.isHidden = true
  143. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  144. cell.secondary.layer.cornerRadius = 15
  145. cell.secondary.layer.masksToBounds = true
  146. cell.secondary.layer.borderWidth = 1
  147. cell.secondary.layer.borderColor = NCBrandColor.shared.iconImageColor2.cgColor
  148. cell.secondary.layer.backgroundColor = UIColor.secondarySystemBackground.cgColor
  149. cell.secondary.setTitleColor(NCBrandColor.shared.iconImageColor2, for: .normal)
  150. // Action
  151. if let actions = notification.actions,
  152. let jsonActions = JSON(actions).array {
  153. if jsonActions.count == 1 {
  154. let action = jsonActions[0]
  155. cell.primary.isEnabled = true
  156. cell.primary.isHidden = false
  157. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  158. } else if jsonActions.count == 2 {
  159. cell.primary.isEnabled = true
  160. cell.primary.isHidden = false
  161. cell.secondary.isEnabled = true
  162. cell.secondary.isHidden = false
  163. for action in jsonActions {
  164. let label = action["label"].stringValue
  165. let primary = action["primary"].boolValue
  166. if primary {
  167. cell.primary.setTitle(label, for: .normal)
  168. } else {
  169. cell.secondary.setTitle(label, for: .normal)
  170. }
  171. }
  172. } else if jsonActions.count >= 3 {
  173. cell.more.isEnabled = true
  174. cell.more.isHidden = false
  175. cell.more.setTitle("…", for: .normal)
  176. }
  177. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  178. buttonWidth += 30
  179. cell.primaryWidth.constant = buttonWidth
  180. cell.secondaryWidth.constant = buttonWidth
  181. }
  182. return cell
  183. }
  184. // MARK: - tap Action
  185. func tapRemove(with notification: NKNotifications) {
  186. NextcloudKit.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification, method: "DELETE") { account, error in
  187. if error == .success && account == self.appDelegate.account {
  188. if let index = self.notifications
  189. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  190. self.notifications.remove(at: index)
  191. }
  192. self.tableView.reloadData()
  193. } else if error != .success {
  194. NCContentPresenter().showError(error: error)
  195. } else {
  196. print("[Error] The user has been changed during networking process.")
  197. }
  198. }
  199. }
  200. func tapAction(with notification: NKNotifications, label: String) {
  201. if notification.app == NCGlobal.shared.spreedName,
  202. let roomToken = notification.objectId.split(separator: "/").first,
  203. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(appDelegate.urlBase)&user=\(appDelegate.userId)&withRoomToken=\(roomToken)"),
  204. UIApplication.shared.canOpenURL(talkUrl) {
  205. UIApplication.shared.open(talkUrl)
  206. } else if let actions = notification.actions,
  207. let jsonActions = JSON(actions).array,
  208. let action = jsonActions.first(where: { $0["label"].string == label }) {
  209. let serverUrl = action["link"].stringValue
  210. let method = action["type"].stringValue
  211. if method == "WEB", let url = action["link"].url {
  212. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  213. return
  214. }
  215. NextcloudKit.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { account, error in
  216. if error == .success && account == self.appDelegate.account {
  217. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  218. self.notifications.remove(at: index)
  219. }
  220. self.tableView.reloadData()
  221. if self.navigationController?.presentingViewController != nil, notification.app == NCGlobal.shared.twoFactorNotificatioName {
  222. self.dismiss(animated: true)
  223. }
  224. } else if error != .success {
  225. NCContentPresenter().showError(error: error)
  226. } else {
  227. print("[Error] The user has been changed during networking process.")
  228. }
  229. }
  230. } // else: Action not found
  231. }
  232. func tapMore(with notification: NKNotifications) {
  233. toggleMenu(notification: notification)
  234. }
  235. // MARK: - Load notification networking
  236. @objc func getNetwokingNotification() {
  237. self.tableView.reloadData()
  238. NextcloudKit.shared.getNotifications { task in
  239. self.dataSourceTask = task
  240. self.tableView.reloadData()
  241. } completion: { account, notifications, _, error in
  242. if error == .success && account == self.appDelegate.account {
  243. self.notifications.removeAll()
  244. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  245. for notification in sortedListOfNotifications {
  246. if let icon = (notification as? NKNotifications)?.icon {
  247. self.utility.convertSVGtoPNGWriteToUserData(svgUrlString: icon, width: 25, rewrite: false, account: self.appDelegate.account) { _, _ in
  248. self.tableView.reloadData()
  249. }
  250. }
  251. if let notification = (notification as? NKNotifications) {
  252. self.notifications.append(notification)
  253. }
  254. }
  255. self.refreshControl?.endRefreshing()
  256. self.tableView.reloadData()
  257. }
  258. }
  259. }
  260. }
  261. // MARK: -
  262. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  263. @IBOutlet weak var icon: UIImageView!
  264. @IBOutlet weak var avatar: UIImageView!
  265. @IBOutlet weak var date: UILabel!
  266. @IBOutlet weak var subject: UILabel!
  267. @IBOutlet weak var message: UILabel!
  268. @IBOutlet weak var remove: UIButton!
  269. @IBOutlet weak var primary: UIButton!
  270. @IBOutlet weak var secondary: UIButton!
  271. @IBOutlet weak var more: UIButton!
  272. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  273. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  274. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  275. private var user = ""
  276. private var index = IndexPath()
  277. weak var delegate: NCNotificationCellDelegate?
  278. var notification: NKNotifications?
  279. var indexPath: IndexPath {
  280. get { return index }
  281. set { index = newValue }
  282. }
  283. var fileAvatarImageView: UIImageView? {
  284. return avatar
  285. }
  286. var fileUser: String? {
  287. get { return user }
  288. set { user = newValue ?? "" }
  289. }
  290. override func awakeFromNib() {
  291. super.awakeFromNib()
  292. }
  293. @IBAction func touchUpInsideRemove(_ sender: Any) {
  294. guard let notification = notification else { return }
  295. delegate?.tapRemove(with: notification)
  296. }
  297. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  298. guard let notification = notification,
  299. let button = sender as? UIButton,
  300. let label = button.titleLabel?.text
  301. else { return }
  302. delegate?.tapAction(with: notification, label: label)
  303. }
  304. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  305. guard let notification = notification,
  306. let button = sender as? UIButton,
  307. let label = button.titleLabel?.text
  308. else { return }
  309. delegate?.tapAction(with: notification, label: label)
  310. }
  311. @IBAction func touchUpInsideMore(_ sender: Any) {
  312. guard let notification = notification else { return }
  313. delegate?.tapMore(with: notification)
  314. }
  315. }
  316. protocol NCNotificationCellDelegate: AnyObject {
  317. func tapRemove(with notification: NKNotifications)
  318. func tapAction(with notification: NKNotifications, label: String)
  319. func tapMore(with notification: NKNotifications)
  320. }