NCNotification.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. class NCNotification: UITableViewController, NCNotificationCellDelegate {
  28. let utilityFileSystem = NCUtilityFileSystem()
  29. let utility = NCUtility()
  30. var notifications: [NKNotifications] = []
  31. var dataSourceTask: URLSessionTask?
  32. var session: NCSession.Session!
  33. // MARK: - View Life Cycle
  34. override func viewDidLoad() {
  35. super.viewDidLoad()
  36. title = NSLocalizedString("_notifications_", comment: "")
  37. view.backgroundColor = .systemBackground
  38. tableView.tableFooterView = UIView()
  39. tableView.rowHeight = UITableView.automaticDimension
  40. tableView.estimatedRowHeight = 50.0
  41. tableView.backgroundColor = .systemBackground
  42. refreshControl?.addTarget(self, action: #selector(getNetwokingNotification), for: .valueChanged)
  43. // Navigation controller is being presented modally
  44. if navigationController?.presentingViewController != nil {
  45. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, action: { [weak self] in
  46. self?.dismiss(animated: true)
  47. })
  48. }
  49. }
  50. override func viewWillAppear(_ animated: Bool) {
  51. super.viewWillAppear(animated)
  52. navigationController?.setNavigationBarAppearance()
  53. }
  54. override func viewDidAppear(_ animated: Bool) {
  55. super.viewDidAppear(animated)
  56. getNetwokingNotification()
  57. }
  58. override func viewWillDisappear(_ animated: Bool) {
  59. super.viewWillDisappear(animated)
  60. // Cancel Queue & Retrieves Properties
  61. dataSourceTask?.cancel()
  62. }
  63. @objc func viewClose() {
  64. self.dismiss(animated: true, completion: nil)
  65. }
  66. // MARK: - Table
  67. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  68. return notifications.count
  69. }
  70. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  71. guard let notification = NCApplicationHandle().didSelectNotification(notifications[indexPath.row], viewController: self) else { return }
  72. do {
  73. if let subjectRichParameters = notification.subjectRichParameters,
  74. let json = try JSONSerialization.jsonObject(with: subjectRichParameters, options: .mutableContainers) as? [String: Any],
  75. let file = json["file"] as? [String: Any],
  76. file["type"] as? String == "file" {
  77. if let id = file["id"] {
  78. NCActionCenter.shared.viewerFile(account: session.account, fileId: ("\(id)"), viewController: self)
  79. }
  80. }
  81. } catch {
  82. print("Something went wrong")
  83. }
  84. }
  85. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  86. guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NCNotificationCell else { return UITableViewCell() }
  87. cell.delegate = self
  88. cell.selectionStyle = .none
  89. cell.indexPath = indexPath
  90. let notification = notifications[indexPath.row]
  91. let urlIcon = URL(string: notification.icon)
  92. var image: UIImage?
  93. if let urlIcon = urlIcon {
  94. let pathFileName = utilityFileSystem.directoryUserData + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  95. image = UIImage(contentsOfFile: pathFileName)
  96. }
  97. if let image = image {
  98. cell.icon.image = image.withTintColor(NCBrandColor.shared.getElement(account: session.account), renderingMode: .alwaysOriginal)
  99. }
  100. // Avatar
  101. cell.avatar.isHidden = true
  102. cell.avatarLeadingMargin.constant = 10
  103. if let subjectRichParameters = notification.subjectRichParameters,
  104. let json = JSON(subjectRichParameters).dictionary,
  105. let user = json["user"]?["id"].stringValue {
  106. cell.avatar.isHidden = false
  107. cell.avatarLeadingMargin.constant = 50
  108. let fileName = NCSession.shared.getFileName(urlBase: session.urlBase, user: user)
  109. let results = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName)
  110. if results.image == nil {
  111. cell.fileAvatarImageView?.image = utility.loadUserImage(for: user, displayName: json["user"]?["name"].string, urlBase: session.urlBase)
  112. } else {
  113. cell.fileAvatarImageView?.image = results.image
  114. }
  115. if !(results.tableAvatar?.loaded ?? false),
  116. NCNetworking.shared.downloadAvatarQueue.operations.filter({ ($0 as? NCOperationDownloadAvatar)?.fileName == fileName }).isEmpty {
  117. NCNetworking.shared.downloadAvatarQueue.addOperation(NCOperationDownloadAvatar(user: user, fileName: fileName, account: session.account, view: tableView))
  118. }
  119. }
  120. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  121. cell.notification = notification
  122. cell.date.text = utility.dateDiff(notification.date as Date)
  123. cell.date.textColor = NCBrandColor.shared.iconImageColor2
  124. cell.subject.text = notification.subject
  125. cell.subject.textColor = NCBrandColor.shared.textColor
  126. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  127. cell.message.textColor = NCBrandColor.shared.textColor2
  128. cell.remove.setImage(utility.loadImage(named: "xmark", colors: [NCBrandColor.shared.iconImageColor]), for: .normal)
  129. cell.primary.isEnabled = false
  130. cell.primary.isHidden = true
  131. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  132. cell.primary.layer.cornerRadius = 15
  133. cell.primary.layer.masksToBounds = true
  134. cell.primary.layer.backgroundColor = NCBrandColor.shared.getElement(account: session.account).cgColor
  135. cell.primary.setTitleColor(.white, for: .normal)
  136. cell.more.isEnabled = false
  137. cell.more.isHidden = true
  138. cell.more.titleLabel?.font = .systemFont(ofSize: 15)
  139. cell.more.layer.cornerRadius = 15
  140. cell.more.layer.masksToBounds = true
  141. cell.more.layer.backgroundColor = NCBrandColor.shared.getElement(account: session.account).cgColor
  142. cell.more.setTitleColor(.white, for: .normal)
  143. cell.secondary.isEnabled = false
  144. cell.secondary.isHidden = true
  145. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  146. cell.secondary.layer.cornerRadius = 15
  147. cell.secondary.layer.masksToBounds = true
  148. cell.secondary.layer.borderWidth = 1
  149. cell.secondary.layer.borderColor = NCBrandColor.shared.iconImageColor2.cgColor
  150. cell.secondary.layer.backgroundColor = UIColor.secondarySystemBackground.cgColor
  151. cell.secondary.setTitleColor(NCBrandColor.shared.iconImageColor2, for: .normal)
  152. // Action
  153. if let actions = notification.actions,
  154. let jsonActions = JSON(actions).array {
  155. if jsonActions.count == 1 {
  156. let action = jsonActions[0]
  157. cell.primary.isEnabled = true
  158. cell.primary.isHidden = false
  159. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  160. } else if jsonActions.count == 2 {
  161. cell.primary.isEnabled = true
  162. cell.primary.isHidden = false
  163. cell.secondary.isEnabled = true
  164. cell.secondary.isHidden = false
  165. for action in jsonActions {
  166. let label = action["label"].stringValue
  167. let primary = action["primary"].boolValue
  168. if primary {
  169. cell.primary.setTitle(label, for: .normal)
  170. } else {
  171. cell.secondary.setTitle(label, for: .normal)
  172. }
  173. }
  174. } else if jsonActions.count >= 3 {
  175. cell.more.isEnabled = true
  176. cell.more.isHidden = false
  177. cell.more.setTitle("…", for: .normal)
  178. }
  179. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  180. buttonWidth += 30
  181. cell.primaryWidth.constant = buttonWidth
  182. cell.secondaryWidth.constant = buttonWidth
  183. }
  184. return cell
  185. }
  186. // MARK: - tap Action
  187. func tapRemove(with notification: NKNotifications) {
  188. NextcloudKit.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification, method: "DELETE", account: session.account) { _, _, error in
  189. if error == .success {
  190. if let index = self.notifications
  191. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  192. self.notifications.remove(at: index)
  193. }
  194. self.tableView.reloadData()
  195. } else if error != .success {
  196. NCContentPresenter().showError(error: error)
  197. } else {
  198. print("[Error] The user has been changed during networking process.")
  199. }
  200. }
  201. }
  202. func tapAction(with notification: NKNotifications, label: String) {
  203. if notification.app == NCGlobal.shared.spreedName,
  204. let roomToken = notification.objectId.split(separator: "/").first,
  205. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(session.urlBase)&user=\(session.userId)&withRoomToken=\(roomToken)"),
  206. UIApplication.shared.canOpenURL(talkUrl) {
  207. UIApplication.shared.open(talkUrl)
  208. } else if let actions = notification.actions,
  209. let jsonActions = JSON(actions).array,
  210. let action = jsonActions.first(where: { $0["label"].string == label }) {
  211. let serverUrl = action["link"].stringValue
  212. let method = action["type"].stringValue
  213. if method == "WEB", let url = action["link"].url {
  214. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  215. return
  216. }
  217. NextcloudKit.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method, account: session.account) { _, _, error in
  218. if error == .success {
  219. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  220. self.notifications.remove(at: index)
  221. }
  222. self.tableView.reloadData()
  223. if self.navigationController?.presentingViewController != nil, notification.app == NCGlobal.shared.twoFactorNotificatioName {
  224. self.dismiss(animated: true)
  225. }
  226. } else if error != .success {
  227. NCContentPresenter().showError(error: error)
  228. } else {
  229. print("[Error] The user has been changed during networking process.")
  230. }
  231. }
  232. } // else: Action not found
  233. }
  234. func tapMore(with notification: NKNotifications) {
  235. toggleMenu(notification: notification)
  236. }
  237. // MARK: - Load notification networking
  238. @objc func getNetwokingNotification() {
  239. self.tableView.reloadData()
  240. NextcloudKit.shared.getNotifications(account: session.account) { task in
  241. self.dataSourceTask = task
  242. self.tableView.reloadData()
  243. } completion: { account, notifications, _, error in
  244. if error == .success, let notifications = notifications {
  245. self.notifications.removeAll()
  246. let sortedNotifications = notifications.sorted { $0.date > $1.date }
  247. for notification in sortedNotifications {
  248. if let icon = notification.icon {
  249. self.utility.convertSVGtoPNGWriteToUserData(svgUrlString: icon, width: 25, rewrite: false, account: account) { _, _ in
  250. self.tableView.reloadData()
  251. }
  252. }
  253. self.notifications.append(notification)
  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. }