NCNotification.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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, NCEmptyDataSetDelegate {
  29. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. var notifications: [NKNotifications] = []
  31. var emptyDataSet: NCEmptyDataSet?
  32. // MARK: - View Life Cycle
  33. override func viewDidLoad() {
  34. super.viewDidLoad()
  35. title = NSLocalizedString("_notifications_", comment: "")
  36. view.backgroundColor = .systemBackground
  37. tableView.tableFooterView = UIView()
  38. tableView.rowHeight = UITableView.automaticDimension
  39. tableView.estimatedRowHeight = 50.0
  40. tableView.backgroundColor = .systemBackground
  41. // Empty
  42. let offset = (self.navigationController?.navigationBar.bounds.height ?? 0) - 20
  43. emptyDataSet = NCEmptyDataSet(view: tableView, offset: -offset, delegate: self)
  44. }
  45. override func viewWillAppear(_ animated: Bool) {
  46. super.viewWillAppear(animated)
  47. appDelegate.activeViewController = self
  48. navigationController?.setFileAppreance()
  49. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  50. }
  51. override func viewDidAppear(_ animated: Bool) {
  52. super.viewDidAppear(animated)
  53. getNetwokingNotification()
  54. }
  55. override func viewWillDisappear(_ animated: Bool) {
  56. super.viewWillDisappear(animated)
  57. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  58. }
  59. @objc func viewClose() {
  60. self.dismiss(animated: true, completion: nil)
  61. }
  62. // MARK: - NotificationCenter
  63. @objc func initialize() {
  64. getNetwokingNotification()
  65. }
  66. // MARK: - Empty
  67. func emptyDataSetView(_ view: NCEmptyView) {
  68. view.emptyImage.image = NCUtility.shared.loadImage(named: "bell", color: .gray, size: UIScreen.main.bounds.width)
  69. view.emptyTitle.text = NSLocalizedString("_no_notification_", comment: "")
  70. view.emptyDescription.text = ""
  71. }
  72. // MARK: - Table
  73. @objc func reloadDatasource() {
  74. self.tableView.reloadData()
  75. }
  76. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  77. emptyDataSet?.numberOfItemsInSection(notifications.count, section: section)
  78. return notifications.count
  79. }
  80. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  81. tableView.deselectRow(at: indexPath, animated: true)
  82. let notification = notifications[indexPath.row]
  83. if notification.app == "files_sharing" {
  84. if let metadata = NCManageDatabase.shared.getMetadataFromFileId(notification.objectId) {
  85. if let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) {
  86. do {
  87. let attr = try FileManager.default.attributesOfItem(atPath: filePath)
  88. let fileSize = attr[FileAttributeKey.size] as! UInt64
  89. if fileSize > 0 {
  90. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  91. return
  92. }
  93. } catch {
  94. print("Error: \(error)")
  95. }
  96. }
  97. }
  98. let hud = JGProgressHUD()
  99. hud.indicatorView = JGProgressHUDRingIndicatorView()
  100. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  101. indicatorView.ringWidth = 1.5
  102. }
  103. guard let view = appDelegate.window?.rootViewController?.view else { return }
  104. hud.show(in: view)
  105. NextcloudKit.shared.getFileFromFileId(fileId: notification.objectId) { account, file, data, error in
  106. if let file = file {
  107. let isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(file: file)
  108. let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  109. NCManageDatabase.shared.addMetadata(metadata)
  110. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  111. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  112. NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in
  113. }, taskHandler: { _ in
  114. }, progressHandler: { progress in
  115. hud.progress = Float(progress.fractionCompleted)
  116. }) { account, _, _, _, _, _, error in
  117. hud.dismiss()
  118. if account == self.appDelegate.account && error == .success {
  119. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  120. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  121. }
  122. }
  123. } else {
  124. hud.dismiss()
  125. NCContentPresenter.shared.showError(error: error)
  126. }
  127. }
  128. } else {
  129. NCApplicationHandle().didSelectNotification(notification, viewController: self)
  130. }
  131. }
  132. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  133. let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NCNotificationCell
  134. cell.delegate = self
  135. let notification = notifications[indexPath.row]
  136. let urlIcon = URL(string: notification.icon)
  137. var image: UIImage?
  138. if let urlIcon = urlIcon {
  139. let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png"
  140. image = UIImage(contentsOfFile: pathFileName)
  141. }
  142. if let image = image {
  143. cell.icon.image = image.withTintColor(NCBrandColor.shared.brandElement, renderingMode: .alwaysOriginal)
  144. } else {
  145. cell.icon.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.brandElement)
  146. }
  147. // Avatar
  148. cell.avatar.isHidden = true
  149. cell.avatarLeadingMargin.constant = 10
  150. if let subjectRichParameters = notification.subjectRichParameters,
  151. let json = JSON(subjectRichParameters).dictionary,
  152. let user = json["user"]?["id"].stringValue {
  153. cell.avatar.isHidden = false
  154. cell.avatarLeadingMargin.constant = 50
  155. let fileName = appDelegate.userBaseUrl + "-" + user + ".png"
  156. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  157. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  158. cell.avatar.image = image
  159. } else if !FileManager.default.fileExists(atPath: fileNameLocalPath) {
  160. cell.fileUser = user
  161. NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: json["user"]?["name"].string, fileName: fileName, cell: cell, view: tableView, cellImageView: cell.fileAvatarImageView)
  162. }
  163. }
  164. cell.date.text = DateFormatter.localizedString(from: notification.date as Date, dateStyle: .medium, timeStyle: .medium)
  165. cell.notification = notification
  166. cell.date.text = CCUtility.dateDiff(notification.date as Date)
  167. cell.date.textColor = .gray
  168. cell.subject.text = notification.subject
  169. cell.subject.textColor = .label
  170. cell.message.text = notification.message.replacingOccurrences(of: "<br />", with: "\n")
  171. cell.message.textColor = .gray
  172. cell.remove.setImage(UIImage(named: "xmark")!.image(color: .gray, size: 20), for: .normal)
  173. cell.primary.isEnabled = false
  174. cell.primary.isHidden = true
  175. cell.primary.titleLabel?.font = .systemFont(ofSize: 15)
  176. cell.primary.layer.cornerRadius = 15
  177. cell.primary.layer.masksToBounds = true
  178. cell.primary.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  179. cell.primary.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  180. cell.more.isEnabled = false
  181. cell.more.isHidden = true
  182. cell.more.titleLabel?.font = .systemFont(ofSize: 15)
  183. cell.more.layer.cornerRadius = 15
  184. cell.more.layer.masksToBounds = true
  185. cell.more.layer.backgroundColor = NCBrandColor.shared.brandElement.cgColor
  186. cell.more.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  187. cell.secondary.isEnabled = false
  188. cell.secondary.isHidden = true
  189. cell.secondary.titleLabel?.font = .systemFont(ofSize: 15)
  190. cell.secondary.layer.cornerRadius = 15
  191. cell.secondary.layer.masksToBounds = true
  192. cell.secondary.layer.borderWidth = 1
  193. cell.secondary.layer.borderColor = UIColor.systemGray.cgColor
  194. cell.secondary.layer.backgroundColor = UIColor.secondarySystemBackground.cgColor
  195. cell.secondary.setTitleColor(.black, for: .normal)
  196. // Action
  197. if let actions = notification.actions,
  198. let jsonActions = JSON(actions).array {
  199. if jsonActions.count == 1 {
  200. let action = jsonActions[0]
  201. cell.primary.isEnabled = true
  202. cell.primary.isHidden = false
  203. cell.primary.setTitle(action["label"].stringValue, for: .normal)
  204. } else if jsonActions.count == 2 {
  205. cell.primary.isEnabled = true
  206. cell.primary.isHidden = false
  207. cell.secondary.isEnabled = true
  208. cell.secondary.isHidden = false
  209. for action in jsonActions {
  210. let label = action["label"].stringValue
  211. let primary = action["primary"].boolValue
  212. if primary {
  213. cell.primary.setTitle(label, for: .normal)
  214. } else {
  215. cell.secondary.setTitle(label, for: .normal)
  216. }
  217. }
  218. } else if jsonActions.count >= 3 {
  219. cell.more.isEnabled = true
  220. cell.more.isHidden = false
  221. cell.more.setTitle("…", for: .normal)
  222. }
  223. var buttonWidth = max(cell.primary.intrinsicContentSize.width, cell.secondary.intrinsicContentSize.width)
  224. buttonWidth += 30
  225. cell.primaryWidth.constant = buttonWidth
  226. cell.secondaryWidth.constant = buttonWidth
  227. }
  228. return cell
  229. }
  230. // MARK: - tap Action
  231. func tapRemove(with notification: NKNotifications) {
  232. NextcloudKit.shared.setNotification(serverUrl: nil, idNotification: notification.idNotification , method: "DELETE") { (account, error) in
  233. if error == .success && account == self.appDelegate.account {
  234. if let index = self.notifications
  235. .firstIndex(where: { $0.idNotification == notification.idNotification }) {
  236. self.notifications.remove(at: index)
  237. }
  238. self.reloadDatasource()
  239. } else if error != .success {
  240. NCContentPresenter.shared.showError(error: error)
  241. } else {
  242. print("[Error] The user has been changed during networking process.")
  243. }
  244. }
  245. }
  246. func tapAction(with notification: NKNotifications, label: String) {
  247. if notification.app == "spreed",
  248. let roomToken = notification.objectId.split(separator: "/").first,
  249. let talkUrl = URL(string: "nextcloudtalk://open-conversation?server=\(appDelegate.urlBase)&user=\(appDelegate.userId)&withRoomToken=\(roomToken)"),
  250. UIApplication.shared.canOpenURL(talkUrl) {
  251. UIApplication.shared.open(talkUrl)
  252. } else if let actions = notification.actions,
  253. let jsonActions = JSON(actions).array,
  254. let action = jsonActions.first(where: { $0["label"].string == label }) {
  255. let serverUrl = action["link"].stringValue
  256. let method = action["type"].stringValue
  257. if method == "WEB", let url = action["link"].url {
  258. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  259. return
  260. }
  261. NextcloudKit.shared.setNotification(serverUrl: serverUrl, idNotification: 0, method: method) { (account, error) in
  262. if error == .success && account == self.appDelegate.account {
  263. if let index = self.notifications.firstIndex(where: { $0.idNotification == notification.idNotification }) {
  264. self.notifications.remove(at: index)
  265. }
  266. self.reloadDatasource()
  267. } else if error != .success {
  268. NCContentPresenter.shared.showError(error: error)
  269. } else {
  270. print("[Error] The user has been changed during networking process.")
  271. }
  272. }
  273. } // else: Action not found
  274. }
  275. func tapMore(with notification: NKNotifications) {
  276. toggleMenu(notification: notification)
  277. }
  278. // MARK: - Load notification networking
  279. func getNetwokingNotification() {
  280. NextcloudKit.shared.getNotifications { account, notifications, data, error in
  281. if error == .success && account == self.appDelegate.account {
  282. self.notifications.removeAll()
  283. let sortedListOfNotifications = (notifications! as NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
  284. for notification in sortedListOfNotifications {
  285. if let icon = (notification as! NKNotifications).icon {
  286. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, account: self.appDelegate.account, completion: { _, _ in })
  287. }
  288. self.notifications.append(notification as! NKNotifications)
  289. }
  290. self.reloadDatasource()
  291. }
  292. }
  293. }
  294. }
  295. // MARK: -
  296. class NCNotificationCell: UITableViewCell, NCCellProtocol {
  297. @IBOutlet weak var icon: UIImageView!
  298. @IBOutlet weak var avatar: UIImageView!
  299. @IBOutlet weak var date: UILabel!
  300. @IBOutlet weak var subject: UILabel!
  301. @IBOutlet weak var message: UILabel!
  302. @IBOutlet weak var remove: UIButton!
  303. @IBOutlet weak var primary: UIButton!
  304. @IBOutlet weak var secondary: UIButton!
  305. @IBOutlet weak var more: UIButton!
  306. @IBOutlet weak var avatarLeadingMargin: NSLayoutConstraint!
  307. @IBOutlet weak var primaryWidth: NSLayoutConstraint!
  308. @IBOutlet weak var secondaryWidth: NSLayoutConstraint!
  309. private var user = ""
  310. weak var delegate: NCNotificationCellDelegate?
  311. var notification: NKNotifications?
  312. var fileAvatarImageView: UIImageView? {
  313. get { return avatar }
  314. }
  315. var fileUser: String? {
  316. get { return user }
  317. set { user = newValue ?? "" }
  318. }
  319. override func awakeFromNib() {
  320. super.awakeFromNib()
  321. }
  322. @IBAction func touchUpInsideRemove(_ sender: Any) {
  323. guard let notification = notification else { return }
  324. delegate?.tapRemove(with: notification)
  325. }
  326. @IBAction func touchUpInsidePrimary(_ sender: Any) {
  327. guard let notification = notification,
  328. let button = sender as? UIButton,
  329. let label = button.titleLabel?.text
  330. else { return }
  331. delegate?.tapAction(with: notification, label: label)
  332. }
  333. @IBAction func touchUpInsideSecondary(_ sender: Any) {
  334. guard let notification = notification,
  335. let button = sender as? UIButton,
  336. let label = button.titleLabel?.text
  337. else { return }
  338. delegate?.tapAction(with: notification, label: label)
  339. }
  340. @IBAction func touchUpInsideMore(_ sender: Any) {
  341. guard let notification = notification else { return }
  342. delegate?.tapMore(with: notification)
  343. }
  344. }
  345. protocol NCNotificationCellDelegate: AnyObject {
  346. func tapRemove(with notification: NKNotifications)
  347. func tapAction(with notification: NKNotifications, label: String)
  348. func tapMore(with notification: NKNotifications)
  349. }