NCActivity.swift 22 KB

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