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