NCActivity.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. //
  2. // NCActivity.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 17/01/2019.
  6. // Copyright © 2019 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 SwiftRichString
  26. import NCCommunication
  27. import RealmSwift
  28. class NCActivity: UIViewController {
  29. @IBOutlet weak var tableView: UITableView!
  30. @IBOutlet weak var commentView: UIView!
  31. @IBOutlet weak var imageItem: UIImageView!
  32. @IBOutlet weak var labelUser: UILabel!
  33. @IBOutlet weak var newCommentField: UITextField!
  34. @IBOutlet weak var viewContainerConstraint: NSLayoutConstraint!
  35. var height: CGFloat = 0
  36. var metadata: tableMetadata?
  37. var showComments: Bool = false
  38. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  39. var allItems: [DateCompareable] = []
  40. var sectionDates: [Date] = []
  41. var insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  42. var didSelectItemEnable: Bool = true
  43. var objectType: String?
  44. var canFetchActivity = true
  45. var dateAutomaticFetch : Date?
  46. // MARK: - View Life Cycle
  47. override func viewDidLoad() {
  48. super.viewDidLoad()
  49. self.navigationController?.navigationBar.prefersLargeTitles = true
  50. view.backgroundColor = NCBrandColor.shared.systemBackground
  51. self.title = NSLocalizedString("_activity_", comment: "")
  52. tableView.allowsSelection = false
  53. tableView.separatorColor = UIColor.clear
  54. tableView.tableFooterView = UIView()
  55. tableView.contentInset = insets
  56. tableView.backgroundColor = NCBrandColor.shared.systemBackground
  57. NotificationCenter.default.addObserver(self, selector: #selector(self.changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  58. changeTheming()
  59. if showComments {
  60. setupComments()
  61. } else {
  62. commentView.isHidden = true
  63. }
  64. }
  65. func setupComments() {
  66. tableView.register(UINib.init(nibName: "NCShareCommentsCell", bundle: nil), forCellReuseIdentifier: "cell")
  67. newCommentField.placeholder = NSLocalizedString("_new_comment_", comment: "")
  68. viewContainerConstraint.constant = height
  69. // Display Name & Quota
  70. guard let activeAccount = NCManageDatabase.shared.getActiveAccount(), height > 0 else {
  71. commentView.isHidden = true
  72. return
  73. }
  74. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + appDelegate.user + ".png"
  75. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  76. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  77. imageItem.image = image
  78. } else {
  79. imageItem.image = UIImage(named: "avatar")
  80. }
  81. if activeAccount.displayName.isEmpty {
  82. labelUser.text = activeAccount.user
  83. } else {
  84. labelUser.text = activeAccount.displayName
  85. }
  86. labelUser.textColor = NCBrandColor.shared.label
  87. }
  88. override func viewWillAppear(_ animated: Bool) {
  89. super.viewWillAppear(animated)
  90. appDelegate.activeViewController = self
  91. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  92. }
  93. override func viewDidAppear(_ animated: Bool) {
  94. super.viewDidAppear(animated)
  95. initialize()
  96. }
  97. override func viewWillDisappear(_ animated: Bool) {
  98. super.viewWillDisappear(animated)
  99. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  100. }
  101. // MARK: - NotificationCenter
  102. @objc func initialize() {
  103. fetchAll(isInitial: true)
  104. }
  105. @objc func changeTheming() {
  106. tableView.reloadData()
  107. }
  108. @IBAction func newCommentFieldDidEndOnExit(textField: UITextField) {
  109. guard
  110. let message = textField.text,
  111. !message.isEmpty,
  112. let metadata = self.metadata
  113. else { return }
  114. NCCommunication.shared.putComments(fileId: metadata.fileId, message: message) { (account, errorCode, errorDescription) in
  115. if errorCode == 0 {
  116. self.newCommentField.text = ""
  117. self.loadComments()
  118. } else {
  119. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  120. }
  121. }
  122. }
  123. }
  124. // MARK: - Table View
  125. extension NCActivity: UITableViewDelegate {
  126. func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  127. return 120
  128. }
  129. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  130. return 60
  131. }
  132. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  133. return UITableView.automaticDimension
  134. }
  135. func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  136. let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 60))
  137. view.backgroundColor = .clear
  138. let label = UILabel()
  139. label.font = UIFont.boldSystemFont(ofSize: 13)
  140. label.textColor = NCBrandColor.shared.label
  141. label.text = CCUtility.getTitleSectionDate(sectionDates[section])
  142. label.textAlignment = .center
  143. label.layer.cornerRadius = 11
  144. label.layer.masksToBounds = true
  145. label.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  146. let widthFrame = label.intrinsicContentSize.width + 30
  147. let xFrame = tableView.bounds.width / 2 - widthFrame / 2
  148. label.frame = CGRect(x: xFrame, y: 10, width: widthFrame, height: 22)
  149. view.addSubview(label)
  150. return view
  151. }
  152. }
  153. extension NCActivity: UITableViewDataSource {
  154. func numberOfSections(in tableView: UITableView) -> Int {
  155. return sectionDates.count
  156. }
  157. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  158. let date = sectionDates[section]
  159. return allItems.filter({ Calendar.current.isDate($0.dateKey, inSameDayAs: date) }).count
  160. }
  161. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  162. let date = sectionDates[indexPath.section]
  163. let sectionItems = allItems
  164. .filter({ Calendar.current.isDate($0.dateKey, inSameDayAs: date) })
  165. let cellData = sectionItems[indexPath.row]
  166. if let activityData = cellData as? tableActivity {
  167. return makeActivityCell(activityData, for: indexPath)
  168. } else if let commentData = cellData as? tableComments {
  169. return makeCommentCell(commentData, for: indexPath)
  170. } else {
  171. return UITableViewCell()
  172. }
  173. }
  174. func makeCommentCell(_ comment: tableComments, for indexPath: IndexPath) -> UITableViewCell {
  175. guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? NCShareCommentsCell else {
  176. return UITableViewCell()
  177. }
  178. cell.tableComments = comment
  179. cell.delegate = self
  180. cell.sizeToFit()
  181. // Image
  182. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + comment.actorId + ".png"
  183. NCOperationQueue.shared.downloadAvatar(user: comment.actorId, fileName: fileName, placeholder: UIImage(named: "avatar"), cell: cell, view: tableView)
  184. // Username
  185. cell.labelUser.text = comment.actorDisplayName
  186. cell.labelUser.textColor = NCBrandColor.shared.label
  187. // Date
  188. cell.labelDate.text = CCUtility.dateDiff(comment.creationDateTime as Date)
  189. cell.labelDate.textColor = NCBrandColor.shared.systemGray4
  190. // Message
  191. cell.labelMessage.text = comment.message
  192. cell.labelMessage.textColor = NCBrandColor.shared.label
  193. // Button Menu
  194. if comment.actorId == appDelegate.userId {
  195. cell.buttonMenu.isHidden = false
  196. } else {
  197. cell.buttonMenu.isHidden = true
  198. }
  199. return cell
  200. }
  201. func makeActivityCell(_ activity: tableActivity, for indexPath: IndexPath) -> UITableViewCell {
  202. guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? NCActivityTableViewCell else {
  203. return UITableViewCell()
  204. }
  205. var orderKeysId: [String] = []
  206. cell.idActivity = activity.idActivity
  207. cell.account = activity.account
  208. cell.avatar.image = nil
  209. cell.avatar.isHidden = true
  210. cell.subjectTrailingConstraint.constant = 10
  211. cell.didSelectItemEnable = self.didSelectItemEnable
  212. cell.subject.textColor = NCBrandColor.shared.label
  213. cell.viewController = self
  214. // icon
  215. if activity.icon.count > 0 {
  216. let fileNameIcon = (activity.icon as NSString).lastPathComponent
  217. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + fileNameIcon
  218. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  219. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.icon.image = image }
  220. } else {
  221. NCCommunication.shared.downloadContent(serverUrl: activity.icon) { (account, data, errorCode, errorMessage) in
  222. if errorCode == 0 {
  223. do {
  224. try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
  225. self.tableView.reloadData()
  226. } catch { return }
  227. }
  228. }
  229. }
  230. }
  231. // avatar
  232. if activity.user.count > 0 && activity.user != appDelegate.userId {
  233. cell.subjectTrailingConstraint.constant = 50
  234. cell.avatar.isHidden = false
  235. cell.fileUser = activity.user
  236. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + activity.user + ".png"
  237. NCOperationQueue.shared.downloadAvatar(user: activity.user, fileName: fileName, placeholder: UIImage(named: "avatar"), cell: cell, view: tableView)
  238. }
  239. // subject
  240. if activity.subjectRich.count > 0 {
  241. var subject = activity.subjectRich
  242. var keys: [String] = []
  243. if let regex = try? NSRegularExpression(pattern: "\\{[a-z0-9]+\\}", options: .caseInsensitive) {
  244. let string = subject as NSString
  245. keys = regex.matches(in: subject, options: [], range: NSRange(location: 0, length: string.length)).map {
  246. string.substring(with: $0.range).replacingOccurrences(of: "[\\{\\}]", with: "", options: .regularExpression)
  247. }
  248. }
  249. for key in keys {
  250. if let result = NCManageDatabase.shared.getActivitySubjectRich(account: appDelegate.account, idActivity: activity.idActivity, key: key) {
  251. orderKeysId.append(result.id)
  252. subject = subject.replacingOccurrences(of: "{\(key)}", with: "<bold>" + result.name + "</bold>")
  253. }
  254. }
  255. let normal = Style {
  256. $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize)
  257. $0.lineSpacing = 1.5
  258. }
  259. let bold = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize, weight: .bold) }
  260. let date = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize - 3)
  261. $0.color = UIColor.lightGray
  262. }
  263. subject = subject + "\n" + "<date>" + CCUtility.dateDiff(activity.date as Date) + "</date>"
  264. cell.subject.attributedText = subject.set(style: StyleGroup(base: normal, ["bold": bold, "date": date]))
  265. }
  266. // CollectionView
  267. cell.activityPreviews = NCManageDatabase.shared.getActivityPreview(account: activity.account, idActivity: activity.idActivity, orderKeysId: orderKeysId)
  268. if cell.activityPreviews.count == 0 {
  269. cell.collectionViewHeightConstraint.constant = 0
  270. } else {
  271. cell.collectionViewHeightConstraint.constant = 60
  272. }
  273. cell.collectionView.reloadData()
  274. return cell
  275. }
  276. }
  277. // MARK: - ScrollView
  278. extension NCActivity: UIScrollViewDelegate {
  279. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  280. guard
  281. scrollView.contentOffset.y > 50,
  282. scrollView.contentSize.height - scrollView.frame.height - scrollView.contentOffset.y < -50
  283. else { return }
  284. fetchAll(isInitial: false)
  285. }
  286. }
  287. // MARK: - NC API & Algorithm
  288. extension NCActivity {
  289. func fetchAll(isInitial: Bool) {
  290. guard canFetchActivity else { return }
  291. self.canFetchActivity = false
  292. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  293. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: false, bottom: height + 50, style: .gray)
  294. let dispatchGroup = DispatchGroup()
  295. loadComments(disptachGroup: dispatchGroup)
  296. if !isInitial, let activity = allItems.compactMap({ $0 as? tableActivity }).last {
  297. loadActivity(idActivity: activity.objectId, disptachGroup: dispatchGroup)
  298. } else {
  299. loadActivity(idActivity: 0, disptachGroup: dispatchGroup)
  300. }
  301. dispatchGroup.notify(queue: .main) {
  302. self.loadDataSource()
  303. NCUtility.shared.stopActivityIndicator()
  304. // otherwise is triggered again
  305. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  306. self.canFetchActivity = true
  307. }
  308. }
  309. }
  310. func loadDataSource() {
  311. var newItems = [DateCompareable]()
  312. if showComments, let metadata = metadata, let account = NCManageDatabase.shared.getActiveAccount() {
  313. let comments = NCManageDatabase.shared.getComments(account: account.account, objectId: metadata.fileId)
  314. newItems += comments
  315. }
  316. let activities = NCManageDatabase.shared.getActivity(
  317. predicate: NSPredicate(format: "account == %@", appDelegate.account),
  318. filterFileId: metadata?.fileId)
  319. newItems += activities.filter
  320. self.allItems = newItems.sorted(by: { $0.dateKey > $1.dateKey })
  321. self.sectionDates = self.allItems.reduce(into: Set<Date>()) { partialResult, next in
  322. let newDay = Calendar.current.startOfDay(for: next.dateKey)
  323. partialResult.insert(newDay)
  324. }.sorted(by: >)
  325. self.tableView.reloadData()
  326. }
  327. func loadComments(disptachGroup: DispatchGroup? = nil) {
  328. guard showComments, let metadata = metadata else { return }
  329. disptachGroup?.enter()
  330. NCCommunication.shared.getComments(fileId: metadata.fileId) { (account, comments, errorCode, errorDescription) in
  331. if errorCode == 0, let comments = comments {
  332. NCManageDatabase.shared.addComments(comments, account: metadata.account, objectId: metadata.fileId)
  333. } else if errorCode != NCGlobal.shared.errorResourceNotFound {
  334. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  335. }
  336. if let disptachGroup = disptachGroup {
  337. disptachGroup.leave()
  338. } else {
  339. self.loadDataSource()
  340. }
  341. }
  342. }
  343. func loadActivity(idActivity: Int, disptachGroup: DispatchGroup) {
  344. disptachGroup.enter()
  345. NCCommunication.shared.getActivity(
  346. since: idActivity,
  347. limit: 200,
  348. objectId: metadata?.fileId,
  349. objectType: objectType,
  350. previews: true) { (account, activities, errorCode, errorDescription) in
  351. if errorCode == 0 && account == self.appDelegate.account {
  352. NCManageDatabase.shared.addActivity(activities, account: account)
  353. }
  354. disptachGroup.leave()
  355. }
  356. }
  357. }
  358. extension NCActivity: NCShareCommentsCellDelegate {
  359. func tapMenu(with tableComments: tableComments?, sender: Any) {
  360. toggleMenu(with: tableComments)
  361. }
  362. func toggleMenu(with tableComments: tableComments?) {
  363. let menuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateInitialViewController() as! NCMenu
  364. var actions = [NCMenuAction]()
  365. actions.append(
  366. NCMenuAction(
  367. title: NSLocalizedString("_edit_comment_", comment: ""),
  368. icon: UIImage(named: "edit")!.image(color: NCBrandColor.shared.gray, size: 50),
  369. action: { menuAction in
  370. guard let metadata = self.metadata, let tableComments = tableComments else { return }
  371. let alert = UIAlertController(title: NSLocalizedString("_edit_comment_", comment: ""), message: nil, preferredStyle: .alert)
  372. alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  373. alert.addTextField(configurationHandler: { textField in
  374. textField.placeholder = NSLocalizedString("_new_comment_", comment: "")
  375. })
  376. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
  377. guard let message = alert.textFields?.first?.text, message != "" else { return }
  378. NCCommunication.shared.updateComments(fileId: metadata.fileId, messageId: tableComments.messageId, message: message) { (account, errorCode, errorDescription) in
  379. if errorCode == 0 {
  380. self.loadComments()
  381. } else {
  382. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  383. }
  384. }
  385. }))
  386. self.present(alert, animated: true)
  387. }
  388. )
  389. )
  390. actions.append(
  391. NCMenuAction(
  392. title: NSLocalizedString("_delete_comment_", comment: ""),
  393. icon: NCUtility.shared.loadImage(named: "trash"),
  394. action: { menuAction in
  395. guard let metadata = self.metadata, let tableComments = tableComments else { return }
  396. NCCommunication.shared.deleteComments(fileId: metadata.fileId, messageId: tableComments.messageId) { (account, errorCode, errorDescription) in
  397. if errorCode == 0 {
  398. self.loadComments()
  399. } else {
  400. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  401. }
  402. }
  403. }
  404. )
  405. )
  406. menuViewController.actions = actions
  407. let menuPanelController = NCMenuPanelController()
  408. menuPanelController.parentPresenter = self
  409. menuPanelController.delegate = menuViewController
  410. menuPanelController.set(contentViewController: menuViewController)
  411. menuPanelController.track(scrollView: menuViewController.tableView)
  412. self.present(menuPanelController, animated: true, completion: nil)
  413. }
  414. }