NCActivity.swift 22 KB

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