NCActivity.swift 22 KB

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