NCActivity.swift 21 KB

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