NCActivity.swift 23 KB

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