NCActivity.swift 21 KB

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