NCActivity.swift 22 KB

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