NCActivity.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import SwiftRichString
  25. import NCCommunication
  26. import RealmSwift
  27. class NCActivity: UIViewController, NCEmptyDataSetDelegate {
  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. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  37. var emptyDataSet: NCEmptyDataSet?
  38. // var allActivities: [tableActivity] = []
  39. // var filterActivities: [tableActivity] = []
  40. var allItems: [DateCompareable] = []
  41. var sectionDates: [Date] {
  42. allItems.reduce(into: Set<Date>()) { partialResult, next in
  43. let newDay = Calendar.current.startOfDay(for: next.dateKey)
  44. partialResult.insert(newDay)
  45. }.sorted(by: >)
  46. }
  47. // var sectionDate: [Date] = []
  48. var insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  49. var didSelectItemEnable: Bool = true
  50. // var filterFileId: String?
  51. var objectType: String?
  52. var canFetchActivity = true
  53. var dateAutomaticFetch : Date?
  54. // MARK: - View Life Cycle
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. self.navigationController?.navigationBar.prefersLargeTitles = true
  58. view.backgroundColor = NCBrandColor.shared.systemBackground
  59. self.title = NSLocalizedString("_activity_", comment: "")
  60. // Empty
  61. emptyDataSet = NCEmptyDataSet(view: tableView, offset: 0, delegate: self)
  62. tableView.allowsSelection = false
  63. tableView.separatorColor = UIColor.clear
  64. tableView.tableFooterView = UIView()
  65. tableView.contentInset = insets
  66. tableView.backgroundColor = NCBrandColor.shared.systemBackground
  67. NotificationCenter.default.addObserver(self, selector: #selector(self.changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  68. changeTheming()
  69. setupComments()
  70. }
  71. func setupComments() {
  72. tableView.register(UINib.init(nibName: "NCShareCommentsCell", bundle: nil), forCellReuseIdentifier: "cell")
  73. newCommentField.placeholder = NSLocalizedString("_new_comment_", comment: "")
  74. viewContainerConstraint.constant = height
  75. // Display Name & Quota
  76. guard let activeAccount = NCManageDatabase.shared.getActiveAccount(), height > 0 else {
  77. commentView.isHidden = true
  78. return
  79. }
  80. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + appDelegate.user + ".png"
  81. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  82. if let image = UIImage(contentsOfFile: fileNameLocalPath) {
  83. imageItem.image = image
  84. } else {
  85. imageItem.image = UIImage(named: "avatar")
  86. }
  87. if activeAccount.displayName.isEmpty {
  88. labelUser.text = activeAccount.user
  89. } else {
  90. labelUser.text = activeAccount.displayName
  91. }
  92. labelUser.textColor = NCBrandColor.shared.label
  93. }
  94. override func viewWillAppear(_ animated: Bool) {
  95. super.viewWillAppear(animated)
  96. appDelegate.activeViewController = self
  97. //
  98. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  99. }
  100. override func viewDidAppear(_ animated: Bool) {
  101. super.viewDidAppear(animated)
  102. initialize()
  103. }
  104. override func viewWillDisappear(_ animated: Bool) {
  105. super.viewWillDisappear(animated)
  106. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  107. }
  108. // MARK: - NotificationCenter
  109. @objc func initialize() {
  110. loadDataSource()
  111. loadActivity(idActivity: 0)
  112. }
  113. @objc func changeTheming() {
  114. tableView.reloadData()
  115. }
  116. // MARK: - Empty
  117. func emptyDataSetView(_ view: NCEmptyView) {
  118. view.emptyImage.image = UIImage.init(named: "bolt")?.image(color: .gray, size: UIScreen.main.bounds.width)
  119. view.emptyTitle.text = NSLocalizedString("_no_activity_", comment: "")
  120. view.emptyDescription.text = ""
  121. }
  122. @IBAction func newCommentFieldDidEndOnExit(textField: UITextField) {
  123. guard
  124. let message = textField.text,
  125. !message.isEmpty,
  126. let metadata = self.metadata
  127. else { return }
  128. NCCommunication.shared.putComments(fileId: metadata.fileId, message: message) { (account, errorCode, errorDescription) in
  129. if errorCode == 0 {
  130. self.newCommentField.text = ""
  131. self.loadDataSource()
  132. } else {
  133. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  134. }
  135. }
  136. }
  137. }
  138. class activityTableViewCell: UITableViewCell, NCCellProtocol {
  139. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  140. @IBOutlet weak var collectionView: UICollectionView!
  141. @IBOutlet weak var icon: UIImageView!
  142. @IBOutlet weak var avatar: UIImageView!
  143. @IBOutlet weak var subject: UILabel!
  144. @IBOutlet weak var subjectTrailingConstraint: NSLayoutConstraint!
  145. @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
  146. private var user: String = ""
  147. var idActivity: Int = 0
  148. var account: String = ""
  149. var activityPreviews: [tableActivityPreview] = []
  150. var didSelectItemEnable: Bool = true
  151. var viewController: UIViewController? = nil
  152. var fileAvatarImageView: UIImageView? {
  153. get {
  154. return avatar
  155. }
  156. }
  157. var fileObjectId: String? {
  158. get {
  159. return nil
  160. }
  161. }
  162. var filePreviewImageView: UIImageView? {
  163. get {
  164. return nil
  165. }
  166. }
  167. var fileUser: String? {
  168. get {
  169. return user
  170. }
  171. set {
  172. user = newValue ?? ""
  173. }
  174. }
  175. override func awakeFromNib() {
  176. super.awakeFromNib()
  177. collectionView.delegate = self
  178. collectionView.dataSource = self
  179. }
  180. }
  181. // MARK: - Table View
  182. extension NCActivity: UITableViewDelegate {
  183. func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  184. return 120
  185. }
  186. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  187. return 60
  188. }
  189. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  190. return UITableView.automaticDimension
  191. }
  192. func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  193. let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 60))
  194. view.backgroundColor = .clear
  195. let label = UILabel()
  196. label.font = UIFont.boldSystemFont(ofSize: 13)
  197. label.textColor = NCBrandColor.shared.label
  198. label.text = CCUtility.getTitleSectionDate(sectionDates[section])
  199. label.textAlignment = .center
  200. label.layer.cornerRadius = 11
  201. label.layer.masksToBounds = true
  202. label.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  203. let widthFrame = label.intrinsicContentSize.width + 30
  204. let xFrame = tableView.bounds.width / 2 - widthFrame / 2
  205. label.frame = CGRect(x: xFrame, y: 10, width: widthFrame, height: 22)
  206. view.addSubview(label)
  207. return view
  208. }
  209. }
  210. extension NCActivity: UITableViewDataSource {
  211. func numberOfSections(in tableView: UITableView) -> Int {
  212. return sectionDates.count
  213. }
  214. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  215. let date = sectionDates[section]
  216. return allItems.filter({ Calendar.current.isDate($0.dateKey, inSameDayAs: date) }).count
  217. // getTableActivitiesFromSection(section).count
  218. // emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  219. // return numberItems
  220. }
  221. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  222. let date = sectionDates[indexPath.section]
  223. let sectionItems = allItems
  224. .filter({ Calendar.current.isDate($0.dateKey, inSameDayAs: date) })
  225. let cellData = sectionItems[indexPath.row]
  226. if let activityData = cellData as? tableActivity {
  227. return makeActivityCell(activityData, for: indexPath)
  228. } else if let commentData = cellData as? tableComments {
  229. return makeCommentCell(commentData, for: indexPath)
  230. } else {
  231. return UITableViewCell()
  232. }
  233. }
  234. func makeCommentCell(_ comment: tableComments, for indexPath: IndexPath) -> UITableViewCell {
  235. guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? NCShareCommentsCell else {
  236. return UITableViewCell()
  237. }
  238. cell.tableComments = comment
  239. cell.delegate = self
  240. cell.sizeToFit()
  241. // Image
  242. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + comment.actorId + ".png"
  243. NCOperationQueue.shared.downloadAvatar(user: comment.actorId, fileName: fileName, placeholder: UIImage(named: "avatar"), cell: cell, view: tableView)
  244. // Username
  245. cell.labelUser.text = comment.actorDisplayName
  246. cell.labelUser.textColor = NCBrandColor.shared.label
  247. // Date
  248. cell.labelDate.text = CCUtility.dateDiff(comment.creationDateTime as Date)
  249. cell.labelDate.textColor = NCBrandColor.shared.systemGray4
  250. // Message
  251. cell.labelMessage.text = comment.message
  252. cell.labelMessage.textColor = NCBrandColor.shared.label
  253. // Button Menu
  254. if comment.actorId == appDelegate.userId {
  255. cell.buttonMenu.isHidden = false
  256. } else {
  257. cell.buttonMenu.isHidden = true
  258. }
  259. return cell
  260. }
  261. func makeActivityCell(_ activity: tableActivity, for indexPath: IndexPath) -> UITableViewCell {
  262. guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? activityTableViewCell else {
  263. return UITableViewCell()
  264. }
  265. var orderKeysId: [String] = []
  266. cell.idActivity = activity.idActivity
  267. cell.account = activity.account
  268. cell.avatar.image = nil
  269. cell.avatar.isHidden = true
  270. cell.subjectTrailingConstraint.constant = 10
  271. cell.didSelectItemEnable = self.didSelectItemEnable
  272. cell.subject.textColor = NCBrandColor.shared.label
  273. cell.viewController = self
  274. // icon
  275. if activity.icon.count > 0 {
  276. let fileNameIcon = (activity.icon as NSString).lastPathComponent
  277. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + fileNameIcon
  278. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  279. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.icon.image = image }
  280. } else {
  281. NCCommunication.shared.downloadContent(serverUrl: activity.icon) { (account, data, errorCode, errorMessage) in
  282. if errorCode == 0 {
  283. do {
  284. try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
  285. self.tableView.reloadData()
  286. } catch { return }
  287. }
  288. }
  289. }
  290. }
  291. // avatar
  292. if activity.user.count > 0 && activity.user != appDelegate.userId {
  293. cell.subjectTrailingConstraint.constant = 50
  294. cell.avatar.isHidden = false
  295. cell.fileUser = activity.user
  296. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + activity.user + ".png"
  297. NCOperationQueue.shared.downloadAvatar(user: activity.user, fileName: fileName, placeholder: UIImage(named: "avatar"), cell: cell, view: tableView)
  298. }
  299. // subject
  300. if activity.subjectRich.count > 0 {
  301. var subject = activity.subjectRich
  302. var keys: [String] = []
  303. if let regex = try? NSRegularExpression(pattern: "\\{[a-z0-9]+\\}", options: .caseInsensitive) {
  304. let string = subject as NSString
  305. keys = regex.matches(in: subject, options: [], range: NSRange(location: 0, length: string.length)).map {
  306. string.substring(with: $0.range).replacingOccurrences(of: "[\\{\\}]", with: "", options: .regularExpression)
  307. }
  308. }
  309. for key in keys {
  310. if let result = NCManageDatabase.shared.getActivitySubjectRich(account: appDelegate.account, idActivity: activity.idActivity, key: key) {
  311. orderKeysId.append(result.id)
  312. subject = subject.replacingOccurrences(of: "{\(key)}", with: "<bold>" + result.name + "</bold>")
  313. }
  314. }
  315. let normal = Style {
  316. $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize)
  317. $0.lineSpacing = 1.5
  318. }
  319. let bold = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize, weight: .bold) }
  320. let date = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize - 3)
  321. $0.color = UIColor.lightGray
  322. }
  323. subject = subject + "\n" + "<date>" + CCUtility.dateDiff(activity.date as Date) + "</date>"
  324. cell.subject.attributedText = subject.set(style: StyleGroup(base: normal, ["bold": bold, "date": date]))
  325. }
  326. // CollectionView
  327. cell.activityPreviews = NCManageDatabase.shared.getActivityPreview(account: activity.account, idActivity: activity.idActivity, orderKeysId: orderKeysId)
  328. if cell.activityPreviews.count == 0 {
  329. cell.collectionViewHeightConstraint.constant = 0
  330. } else {
  331. cell.collectionViewHeightConstraint.constant = 60
  332. }
  333. cell.collectionView.reloadData()
  334. return cell
  335. }
  336. }
  337. /*
  338. extension NCActivity: UITableViewDataSourcePrefetching {
  339. func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
  340. let section = indexPaths.last?.section ?? 0
  341. let row = indexPaths.last?.row ?? 0
  342. let lastSection = self.sectionDate.count - 1
  343. let lastRow = getTableActivitiesFromSection(section).count - 1
  344. if section == lastSection && row > lastRow - 1 {
  345. //loadActivity(idActivity: allActivities.last!.idActivity)
  346. }
  347. }
  348. func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
  349. //print("cancelPrefetchingForRowsAt \(indexPaths)")
  350. }
  351. }
  352. */
  353. // MARK: - ScrollView
  354. extension NCActivity: UIScrollViewDelegate {
  355. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  356. if scrollView.contentSize.height - scrollView.contentOffset.y - scrollView.frame.height < 100 {
  357. // comments are always loaded in full..? only load more acitvities
  358. if let activity = allItems.compactMap({ $0 as? tableActivity }).last {
  359. loadActivity(idActivity: activity.objectId)
  360. }
  361. }
  362. }
  363. }
  364. // MARK: - Collection View
  365. extension activityTableViewCell: UICollectionViewDelegate {
  366. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  367. // Select not permitted
  368. if !didSelectItemEnable {
  369. return
  370. }
  371. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? activityCollectionViewCell
  372. let activityPreview = activityPreviews[indexPath.row]
  373. if activityPreview.view == "trashbin" {
  374. var responder: UIResponder? = collectionView
  375. while !(responder is UIViewController) {
  376. responder = responder?.next
  377. if nil == responder {
  378. break
  379. }
  380. }
  381. if (responder as? UIViewController)!.navigationController != nil {
  382. if let viewController = UIStoryboard.init(name: "NCTrash", bundle: nil).instantiateInitialViewController() as? NCTrash {
  383. if let result = NCManageDatabase.shared.getTrashItem(fileId: String(activityPreview.fileId), account: activityPreview.account) {
  384. viewController.blinkFileId = result.fileId
  385. viewController.trashPath = result.filePath
  386. (responder as? UIViewController)!.navigationController?.pushViewController(viewController, animated: true)
  387. } else {
  388. NCContentPresenter.shared.messageNotification("_error_", description: "_trash_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError)
  389. }
  390. }
  391. }
  392. return
  393. }
  394. if activityPreview.view == "files" && activityPreview.mimeType != "dir" {
  395. guard let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: activityPreview.account, idActivity: activityPreview.idActivity, id: String(activityPreview.fileId)) else {
  396. return
  397. }
  398. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileId == %@", activitySubjectRich.id)) {
  399. if let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) {
  400. do {
  401. let attr = try FileManager.default.attributesOfItem(atPath: filePath)
  402. let fileSize = attr[FileAttributeKey.size] as! UInt64
  403. if fileSize > 0 {
  404. if let viewController = self.viewController {
  405. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: cell?.imageView.image)
  406. }
  407. return
  408. }
  409. } catch {
  410. print("Error: \(error)")
  411. }
  412. }
  413. }
  414. var pathComponents = activityPreview.link.components(separatedBy: "?")
  415. pathComponents = pathComponents[1].components(separatedBy: "&")
  416. var serverUrlFileName = pathComponents[0].replacingOccurrences(of: "dir=", with: "").removingPercentEncoding!
  417. serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: activityPreview.account) + serverUrlFileName + "/" + activitySubjectRich.name
  418. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(activitySubjectRich.id, fileNameView: activitySubjectRich.name)!
  419. NCUtility.shared.startActivityIndicator(backgroundView: (appDelegate.window?.rootViewController?.view)!, blurEffect: true)
  420. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  421. }, taskHandler: { (_) in
  422. }, progressHandler: { (_) in
  423. }) { (account, etag, date, lenght, allHeaderFields, error, errorCode, errorDescription) in
  424. if account == self.appDelegate.account && errorCode == 0 {
  425. let serverUrl = (serverUrlFileName as NSString).deletingLastPathComponent
  426. let fileName = (serverUrlFileName as NSString).lastPathComponent
  427. let serverUrlFileName = serverUrl + "/" + fileName
  428. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, account: activityPreview.account) { (account, metadata, errorCode, errorDescription) in
  429. NCUtility.shared.stopActivityIndicator()
  430. if account == self.appDelegate.account && errorCode == 0 {
  431. // move from id to oc:id + instanceid (ocId)
  432. let atPath = CCUtility.getDirectoryProviderStorage()! + "/" + activitySubjectRich.id
  433. let toPath = CCUtility.getDirectoryProviderStorage()! + "/" + metadata!.ocId
  434. CCUtility.moveFile(atPath: atPath, toPath: toPath)
  435. NCManageDatabase.shared.addMetadata(metadata!)
  436. if let viewController = self.viewController {
  437. NCViewer.shared.view(viewController: viewController, metadata: metadata!, metadatas: [metadata!], imageIcon: cell?.imageView.image)
  438. }
  439. }
  440. }
  441. } else {
  442. NCUtility.shared.stopActivityIndicator()
  443. }
  444. }
  445. }
  446. }
  447. }
  448. extension activityTableViewCell: UICollectionViewDataSource {
  449. func numberOfSections(in collectionView: UICollectionView) -> Int {
  450. return 1
  451. }
  452. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  453. return activityPreviews.count
  454. }
  455. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  456. let cell: activityCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! activityCollectionViewCell
  457. cell.imageView.image = nil
  458. let activityPreview = activityPreviews[indexPath.row]
  459. let fileId = String(activityPreview.fileId)
  460. // Trashbin
  461. if activityPreview.view == "trashbin" {
  462. let source = activityPreview.source
  463. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { (imageNamePath) in
  464. if imageNamePath != nil {
  465. if let image = UIImage(contentsOfFile: imageNamePath!) {
  466. cell.imageView.image = image
  467. }
  468. } else {
  469. cell.imageView.image = UIImage.init(named: "file")
  470. }
  471. }
  472. } else {
  473. if activityPreview.isMimeTypeIcon {
  474. let source = activityPreview.source
  475. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { (imageNamePath) in
  476. if imageNamePath != nil {
  477. if let image = UIImage(contentsOfFile: imageNamePath!) {
  478. cell.imageView.image = image
  479. }
  480. } else {
  481. cell.imageView.image = UIImage.init(named: "file")
  482. }
  483. }
  484. } else {
  485. if let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: account, idActivity: idActivity, id: fileId) {
  486. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + activitySubjectRich.name
  487. if FileManager.default.fileExists(atPath: fileNamePath) {
  488. if let image = UIImage(contentsOfFile: fileNamePath) {
  489. cell.imageView.image = image
  490. }
  491. } else {
  492. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: activityPreview.source, fileNamePreviewLocalPath: fileNamePath, widthPreview: 0, heightPreview: 0, etag: nil, useInternalEndpoint: false) { (account, imagePreview, imageIcon, imageOriginal, etag, errorCode, errorDescription) in
  493. if errorCode == 0 && imagePreview != nil {
  494. self.collectionView.reloadData()
  495. }
  496. }
  497. }
  498. }
  499. }
  500. }
  501. return cell
  502. }
  503. }
  504. class activityCollectionViewCell: UICollectionViewCell {
  505. @IBOutlet weak var imageView: UIImageView!
  506. override func awakeFromNib() {
  507. super.awakeFromNib()
  508. }
  509. }
  510. extension activityTableViewCell: UICollectionViewDelegateFlowLayout {
  511. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  512. return CGSize(width: 50, height: 50)
  513. }
  514. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  515. return 20
  516. }
  517. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  518. return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
  519. }
  520. }
  521. // MARK: - NC API & Algorithm
  522. extension NCActivity {
  523. @objc func getComments(account: String, objectId: String) -> [tableComments] {
  524. let realm = try! Realm()
  525. let results = realm.objects(tableComments.self).filter("account == %@ AND objectId == %@", account, objectId).sorted(byKeyPath: "creationDateTime", ascending: false)
  526. return Array(results.map(tableComments.init))
  527. }
  528. func loadDataSource() {
  529. guard let metadata = self.metadata else { return }
  530. let reloadDispatch = DispatchGroup()
  531. self.allItems = []
  532. reloadDispatch.enter()
  533. reloadDispatch.enter()
  534. NCCommunication.shared.getComments(fileId: metadata.fileId) { (account, comments, errorCode, errorDescription) in
  535. if errorCode == 0 && comments != nil {
  536. NCManageDatabase.shared.addComments(comments!, account: metadata.account, objectId: metadata.fileId)
  537. self.allItems += self.getComments(account: metadata.account, objectId: metadata.fileId)
  538. reloadDispatch.leave()
  539. } else {
  540. if errorCode != NCGlobal.shared.errorResourceNotFound {
  541. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  542. }
  543. }
  544. }
  545. let activities = NCManageDatabase.shared.getActivity(
  546. predicate: NSPredicate(format: "account == %@", appDelegate.account),
  547. filterFileId: metadata.fileId)
  548. // self.allActivities = activities.all
  549. // self.filterActivities = activities.filter
  550. self.allItems += activities.filter
  551. reloadDispatch.leave()
  552. reloadDispatch.notify(qos: .userInitiated, flags: .enforceQoS, queue: .main) {
  553. self.allItems.sort(by: { $0.dateKey > $1.dateKey })
  554. self.tableView.reloadData()
  555. }
  556. }
  557. func getTableActivitiesForSection(_ section: Int) -> [tableActivity] {
  558. let startDate = sectionDates[section]
  559. let endDate: Date = {
  560. let components = DateComponents(day: 1, second: -1)
  561. return Calendar.current.date(byAdding: components, to: startDate)!
  562. }()
  563. let activities = NCManageDatabase.shared.getActivity(
  564. predicate: NSPredicate(
  565. format: "account == %@ && date BETWEEN %@",
  566. appDelegate.account,
  567. [startDate, endDate]),
  568. filterFileId: metadata?.fileId)
  569. return activities.filter
  570. }
  571. @objc func loadActivity(idActivity: Int) {
  572. if !canFetchActivity { return }
  573. canFetchActivity = false
  574. if idActivity > 0 {
  575. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  576. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: false, bottom: height + 50, style: .gray)
  577. }
  578. NCCommunication.shared.getActivity(
  579. since: idActivity,
  580. limit: 200,
  581. objectId: metadata?.fileId,
  582. objectType: objectType,
  583. previews: true) { (account, activities, errorCode, errorDescription) in
  584. if errorCode == 0 && account == self.appDelegate.account {
  585. NCManageDatabase.shared.addActivity(activities, account: account)
  586. }
  587. NCUtility.shared.stopActivityIndicator()
  588. if errorCode == NCGlobal.shared.errorNotModified {
  589. self.canFetchActivity = false
  590. } else {
  591. self.canFetchActivity = true
  592. }
  593. self.loadDataSource()
  594. }
  595. }
  596. }
  597. extension NCActivity: NCShareCommentsCellDelegate {
  598. func tapMenu(with tableComments: tableComments?, sender: Any) {
  599. toggleMenu(with: tableComments)
  600. }
  601. func toggleMenu(with tableComments: tableComments?) {
  602. let menuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateInitialViewController() as! NCMenu
  603. var actions = [NCMenuAction]()
  604. actions.append(
  605. NCMenuAction(
  606. title: NSLocalizedString("_edit_comment_", comment: ""),
  607. icon: UIImage(named: "edit")!.image(color: NCBrandColor.shared.gray, size: 50),
  608. action: { menuAction in
  609. guard let metadata = self.metadata else { return }
  610. guard let tableComments = tableComments else { return }
  611. let alert = UIAlertController(title: NSLocalizedString("_edit_comment_", comment: ""), message: nil, preferredStyle: .alert)
  612. alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  613. alert.addTextField(configurationHandler: { textField in
  614. textField.placeholder = NSLocalizedString("_new_comment_", comment: "")
  615. })
  616. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
  617. if let message = alert.textFields?.first?.text {
  618. if message != "" {
  619. NCCommunication.shared.updateComments(fileId: metadata.fileId, messageId: tableComments.messageId, message: message) { (account, errorCode, errorDescription) in
  620. if errorCode == 0 {
  621. //TODO:..
  622. // self.reloadData()
  623. } else {
  624. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  625. }
  626. }
  627. }
  628. }
  629. }))
  630. self.present(alert, animated: true)
  631. }
  632. )
  633. )
  634. actions.append(
  635. NCMenuAction(
  636. title: NSLocalizedString("_delete_comment_", comment: ""),
  637. icon: NCUtility.shared.loadImage(named: "trash"),
  638. action: { menuAction in
  639. guard let metadata = self.metadata else { return }
  640. guard let tableComments = tableComments else { return }
  641. NCCommunication.shared.deleteComments(fileId: metadata.fileId, messageId: tableComments.messageId) { (account, errorCode, errorDescription) in
  642. if errorCode == 0 {
  643. //TODO: ...
  644. // self.reloadData()
  645. } else {
  646. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  647. }
  648. }
  649. }
  650. )
  651. )
  652. actions.append(
  653. NCMenuAction(
  654. title: NSLocalizedString("_cancel_", comment: ""),
  655. icon: UIImage(named: "cancel")!.image(color: NCBrandColor.shared.gray, size: 50),
  656. action: { menuAction in
  657. }
  658. )
  659. )
  660. menuViewController.actions = actions
  661. let menuPanelController = NCMenuPanelController()
  662. menuPanelController.parentPresenter = self
  663. menuPanelController.delegate = menuViewController
  664. menuPanelController.set(contentViewController: menuViewController)
  665. menuPanelController.track(scrollView: menuViewController.tableView)
  666. self.present(menuPanelController, animated: true, completion: nil)
  667. }
  668. }