NCActivity.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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: Set<Date> {
  42. allItems.reduce(into: Set<Date>()) { partialResult, next in
  43. let newDay = Calendar.current.startOfDay(for: next.dateKey)
  44. partialResult.insert(newDay)
  45. }
  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 user & 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 else { return }
  127. NCCommunication.shared.putComments(fileId: metadata.fileId, message: message) { (account, errorCode, errorDescription) in
  128. if errorCode == 0 {
  129. self.newCommentField.text = ""
  130. //TODO:...
  131. // self.reloadData()
  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.sorted()[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.sorted()[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.sorted()[indexPath.section]
  223. let sectionItems = allItems
  224. .filter({ Calendar.current.isDate($0.dateKey, inSameDayAs: date) })
  225. .sorted(by: { $0.dateKey > $1.dateKey })
  226. let cellData = sectionItems[indexPath.row]
  227. if let activityData = cellData as? tableActivity {
  228. return makeActivityCell(activityData, for: indexPath)
  229. } else if let commentData = cellData as? tableComments {
  230. return makeCommentCell(commentData, for: indexPath)
  231. } else {
  232. return UITableViewCell()
  233. }
  234. }
  235. func makeCommentCell(_ comment: tableComments, for indexPath: IndexPath) -> UITableViewCell {
  236. guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? NCShareCommentsCell else {
  237. return UITableViewCell()
  238. }
  239. cell.tableComments = comment
  240. cell.delegate = self
  241. cell.sizeToFit()
  242. // Image
  243. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + comment.actorId + ".png"
  244. NCOperationQueue.shared.downloadAvatar(user: comment.actorId, fileName: fileName, placeholder: UIImage(named: "avatar"), cell: cell, view: tableView)
  245. // Username
  246. cell.labelUser.text = comment.actorDisplayName
  247. cell.labelUser.textColor = NCBrandColor.shared.label
  248. // Date
  249. cell.labelDate.text = CCUtility.dateDiff(comment.creationDateTime as Date)
  250. cell.labelDate.textColor = NCBrandColor.shared.systemGray4
  251. // Message
  252. cell.labelMessage.text = comment.message
  253. cell.labelMessage.textColor = NCBrandColor.shared.label
  254. // Button Menu
  255. if comment.actorId == appDelegate.userId {
  256. cell.buttonMenu.isHidden = false
  257. } else {
  258. cell.buttonMenu.isHidden = true
  259. }
  260. return cell
  261. }
  262. func makeActivityCell(_ activity: tableActivity, for indexPath: IndexPath) -> UITableViewCell {
  263. guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? activityTableViewCell else {
  264. return UITableViewCell()
  265. }
  266. var orderKeysId: [String] = []
  267. cell.idActivity = activity.idActivity
  268. cell.account = activity.account
  269. cell.avatar.image = nil
  270. cell.avatar.isHidden = true
  271. cell.subjectTrailingConstraint.constant = 10
  272. cell.didSelectItemEnable = self.didSelectItemEnable
  273. cell.subject.textColor = NCBrandColor.shared.label
  274. cell.viewController = self
  275. // icon
  276. if activity.icon.count > 0 {
  277. let fileNameIcon = (activity.icon as NSString).lastPathComponent
  278. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + fileNameIcon
  279. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  280. if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.icon.image = image }
  281. } else {
  282. NCCommunication.shared.downloadContent(serverUrl: activity.icon) { (account, data, errorCode, errorMessage) in
  283. if errorCode == 0 {
  284. do {
  285. try data!.write(to: NSURL(fileURLWithPath: fileNameLocalPath) as URL, options: .atomic)
  286. self.tableView.reloadData()
  287. } catch { return }
  288. }
  289. }
  290. }
  291. }
  292. // avatar
  293. if activity.user.count > 0 && activity.user != appDelegate.userId {
  294. cell.subjectTrailingConstraint.constant = 50
  295. cell.avatar.isHidden = false
  296. cell.fileUser = activity.user
  297. let fileName = String(CCUtility.getUserUrlBase(appDelegate.user, urlBase: appDelegate.urlBase)) + "-" + activity.user + ".png"
  298. NCOperationQueue.shared.downloadAvatar(user: activity.user, fileName: fileName, placeholder: UIImage(named: "avatar"), cell: cell, view: tableView)
  299. }
  300. // subject
  301. if activity.subjectRich.count > 0 {
  302. var subject = activity.subjectRich
  303. var keys: [String] = []
  304. if let regex = try? NSRegularExpression(pattern: "\\{[a-z0-9]+\\}", options: .caseInsensitive) {
  305. let string = subject as NSString
  306. keys = regex.matches(in: subject, options: [], range: NSRange(location: 0, length: string.length)).map {
  307. string.substring(with: $0.range).replacingOccurrences(of: "[\\{\\}]", with: "", options: .regularExpression)
  308. }
  309. }
  310. for key in keys {
  311. if let result = NCManageDatabase.shared.getActivitySubjectRich(account: appDelegate.account, idActivity: activity.idActivity, key: key) {
  312. orderKeysId.append(result.id)
  313. subject = subject.replacingOccurrences(of: "{\(key)}", with: "<bold>" + result.name + "</bold>")
  314. }
  315. }
  316. let normal = Style {
  317. $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize)
  318. $0.lineSpacing = 1.5
  319. }
  320. let bold = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize, weight: .bold) }
  321. let date = Style { $0.font = UIFont.systemFont(ofSize: cell.subject.font.pointSize - 3)
  322. $0.color = UIColor.lightGray
  323. }
  324. subject = subject + "\n" + "<date>" + CCUtility.dateDiff(activity.date as Date) + "</date>"
  325. cell.subject.attributedText = subject.set(style: StyleGroup(base: normal, ["bold": bold, "date": date]))
  326. }
  327. // CollectionView
  328. cell.activityPreviews = NCManageDatabase.shared.getActivityPreview(account: activity.account, idActivity: activity.idActivity, orderKeysId: orderKeysId)
  329. if cell.activityPreviews.count == 0 {
  330. cell.collectionViewHeightConstraint.constant = 0
  331. } else {
  332. cell.collectionViewHeightConstraint.constant = 60
  333. }
  334. cell.collectionView.reloadData()
  335. return cell
  336. }
  337. }
  338. /*
  339. extension NCActivity: UITableViewDataSourcePrefetching {
  340. func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
  341. let section = indexPaths.last?.section ?? 0
  342. let row = indexPaths.last?.row ?? 0
  343. let lastSection = self.sectionDate.count - 1
  344. let lastRow = getTableActivitiesFromSection(section).count - 1
  345. if section == lastSection && row > lastRow - 1 {
  346. //loadActivity(idActivity: allActivities.last!.idActivity)
  347. }
  348. }
  349. func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
  350. //print("cancelPrefetchingForRowsAt \(indexPaths)")
  351. }
  352. }
  353. */
  354. // MARK: - ScrollView
  355. extension NCActivity: UIScrollViewDelegate {
  356. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  357. if scrollView.contentSize.height - scrollView.contentOffset.y - scrollView.frame.height < 100 {
  358. //TODO:...
  359. // if let activities = allActivities.last {
  360. // loadActivity(idActivity: activities.idActivity)
  361. // }
  362. }
  363. }
  364. }
  365. // MARK: - Collection View
  366. extension activityTableViewCell: UICollectionViewDelegate {
  367. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  368. // Select not permitted
  369. if !didSelectItemEnable {
  370. return
  371. }
  372. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? activityCollectionViewCell
  373. let activityPreview = activityPreviews[indexPath.row]
  374. if activityPreview.view == "trashbin" {
  375. var responder: UIResponder? = collectionView
  376. while !(responder is UIViewController) {
  377. responder = responder?.next
  378. if nil == responder {
  379. break
  380. }
  381. }
  382. if (responder as? UIViewController)!.navigationController != nil {
  383. if let viewController = UIStoryboard.init(name: "NCTrash", bundle: nil).instantiateInitialViewController() as? NCTrash {
  384. if let result = NCManageDatabase.shared.getTrashItem(fileId: String(activityPreview.fileId), account: activityPreview.account) {
  385. viewController.blinkFileId = result.fileId
  386. viewController.trashPath = result.filePath
  387. (responder as? UIViewController)!.navigationController?.pushViewController(viewController, animated: true)
  388. } else {
  389. NCContentPresenter.shared.messageNotification("_error_", description: "_trash_file_not_found_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError)
  390. }
  391. }
  392. }
  393. return
  394. }
  395. if activityPreview.view == "files" && activityPreview.mimeType != "dir" {
  396. guard let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: activityPreview.account, idActivity: activityPreview.idActivity, id: String(activityPreview.fileId)) else {
  397. return
  398. }
  399. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileId == %@", activitySubjectRich.id)) {
  400. if let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) {
  401. do {
  402. let attr = try FileManager.default.attributesOfItem(atPath: filePath)
  403. let fileSize = attr[FileAttributeKey.size] as! UInt64
  404. if fileSize > 0 {
  405. if let viewController = self.viewController {
  406. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: cell?.imageView.image)
  407. }
  408. return
  409. }
  410. } catch {
  411. print("Error: \(error)")
  412. }
  413. }
  414. }
  415. var pathComponents = activityPreview.link.components(separatedBy: "?")
  416. pathComponents = pathComponents[1].components(separatedBy: "&")
  417. var serverUrlFileName = pathComponents[0].replacingOccurrences(of: "dir=", with: "").removingPercentEncoding!
  418. serverUrlFileName = appDelegate.urlBase + "/" + NCUtilityFileSystem.shared.getWebDAV(account: activityPreview.account) + serverUrlFileName + "/" + activitySubjectRich.name
  419. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(activitySubjectRich.id, fileNameView: activitySubjectRich.name)!
  420. NCUtility.shared.startActivityIndicator(backgroundView: (appDelegate.window?.rootViewController?.view)!, blurEffect: true)
  421. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  422. }, taskHandler: { (_) in
  423. }, progressHandler: { (_) in
  424. }) { (account, etag, date, lenght, allHeaderFields, error, errorCode, errorDescription) in
  425. if account == self.appDelegate.account && errorCode == 0 {
  426. let serverUrl = (serverUrlFileName as NSString).deletingLastPathComponent
  427. let fileName = (serverUrlFileName as NSString).lastPathComponent
  428. let serverUrlFileName = serverUrl + "/" + fileName
  429. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, account: activityPreview.account) { (account, metadata, errorCode, errorDescription) in
  430. NCUtility.shared.stopActivityIndicator()
  431. if account == self.appDelegate.account && errorCode == 0 {
  432. // move from id to oc:id + instanceid (ocId)
  433. let atPath = CCUtility.getDirectoryProviderStorage()! + "/" + activitySubjectRich.id
  434. let toPath = CCUtility.getDirectoryProviderStorage()! + "/" + metadata!.ocId
  435. CCUtility.moveFile(atPath: atPath, toPath: toPath)
  436. NCManageDatabase.shared.addMetadata(metadata!)
  437. if let viewController = self.viewController {
  438. NCViewer.shared.view(viewController: viewController, metadata: metadata!, metadatas: [metadata!], imageIcon: cell?.imageView.image)
  439. }
  440. }
  441. }
  442. } else {
  443. NCUtility.shared.stopActivityIndicator()
  444. }
  445. }
  446. }
  447. }
  448. }
  449. extension activityTableViewCell: UICollectionViewDataSource {
  450. func numberOfSections(in collectionView: UICollectionView) -> Int {
  451. return 1
  452. }
  453. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  454. return activityPreviews.count
  455. }
  456. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  457. let cell: activityCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! activityCollectionViewCell
  458. cell.imageView.image = nil
  459. let activityPreview = activityPreviews[indexPath.row]
  460. let fileId = String(activityPreview.fileId)
  461. // Trashbin
  462. if activityPreview.view == "trashbin" {
  463. let source = activityPreview.source
  464. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { (imageNamePath) in
  465. if imageNamePath != nil {
  466. if let image = UIImage(contentsOfFile: imageNamePath!) {
  467. cell.imageView.image = image
  468. }
  469. } else {
  470. cell.imageView.image = UIImage.init(named: "file")
  471. }
  472. }
  473. } else {
  474. if activityPreview.isMimeTypeIcon {
  475. let source = activityPreview.source
  476. NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { (imageNamePath) in
  477. if imageNamePath != nil {
  478. if let image = UIImage(contentsOfFile: imageNamePath!) {
  479. cell.imageView.image = image
  480. }
  481. } else {
  482. cell.imageView.image = UIImage.init(named: "file")
  483. }
  484. }
  485. } else {
  486. if let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: account, idActivity: idActivity, id: fileId) {
  487. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + activitySubjectRich.name
  488. if FileManager.default.fileExists(atPath: fileNamePath) {
  489. if let image = UIImage(contentsOfFile: fileNamePath) {
  490. cell.imageView.image = image
  491. }
  492. } else {
  493. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: activityPreview.source, fileNamePreviewLocalPath: fileNamePath, widthPreview: 0, heightPreview: 0, etag: nil, useInternalEndpoint: false) { (account, imagePreview, imageIcon, imageOriginal, etag, errorCode, errorDescription) in
  494. if errorCode == 0 && imagePreview != nil {
  495. self.collectionView.reloadData()
  496. }
  497. }
  498. }
  499. }
  500. }
  501. }
  502. return cell
  503. }
  504. }
  505. class activityCollectionViewCell: UICollectionViewCell {
  506. @IBOutlet weak var imageView: UIImageView!
  507. override func awakeFromNib() {
  508. super.awakeFromNib()
  509. }
  510. }
  511. extension activityTableViewCell: UICollectionViewDelegateFlowLayout {
  512. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  513. return CGSize(width: 50, height: 50)
  514. }
  515. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  516. return 20
  517. }
  518. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  519. return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
  520. }
  521. }
  522. // MARK: - NC API & Algorithm
  523. extension NCActivity {
  524. @objc func getComments(account: String, objectId: String) -> [tableComments] {
  525. let realm = try! Realm()
  526. let results = realm.objects(tableComments.self).filter("account == %@ AND objectId == %@", account, objectId).sorted(byKeyPath: "creationDateTime", ascending: false)
  527. return Array(results.map(tableComments.init))
  528. }
  529. func loadDataSource() {
  530. // sectionDate.removeAll()
  531. let activities = NCManageDatabase.shared.getActivity(
  532. predicate: NSPredicate(format: "account == %@", appDelegate.account),
  533. filterFileId: metadata?.fileId)
  534. // self.allActivities = activities.all
  535. // self.filterActivities = activities.filter
  536. self.allItems = activities.filter
  537. if let metadata = metadata {
  538. self.allItems += getComments(account: metadata.account, objectId: metadata.fileId)
  539. }
  540. // for tableActivity in filterActivities {
  541. // guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: tableActivity.date as Date)) else {
  542. // continue
  543. // }
  544. // if !sectionDate.contains(date) {
  545. // sectionDate.append(date)
  546. // }
  547. // }
  548. //
  549. tableView.reloadData()
  550. }
  551. func getTableActivitiesFromSection(_ section: Int) -> [tableActivity] {
  552. let startDate = sectionDates.sorted()[section]
  553. let endDate: Date = {
  554. let components = DateComponents(day: 1, second: -1)
  555. return Calendar.current.date(byAdding: components, to: startDate)!
  556. }()
  557. let activities = NCManageDatabase.shared.getActivity(
  558. predicate: NSPredicate(
  559. format: "account == %@ && date BETWEEN %@",
  560. appDelegate.account,
  561. [startDate, endDate]),
  562. filterFileId: metadata?.fileId)
  563. return activities.filter
  564. }
  565. @objc func loadActivity(idActivity: Int) {
  566. if !canFetchActivity { return }
  567. canFetchActivity = false
  568. if idActivity > 0 {
  569. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  570. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: false, bottom: height + 50, style: .gray)
  571. }
  572. NCCommunication.shared.getActivity(
  573. since: idActivity,
  574. limit: 200,
  575. objectId: metadata?.fileId,
  576. objectType: objectType,
  577. previews: true) { (account, activities, errorCode, errorDescription) in
  578. if errorCode == 0 && account == self.appDelegate.account {
  579. NCManageDatabase.shared.addActivity(activities , account: account)
  580. }
  581. NCUtility.shared.stopActivityIndicator()
  582. if errorCode == NCGlobal.shared.errorNotModified {
  583. self.canFetchActivity = false
  584. } else {
  585. self.canFetchActivity = true
  586. }
  587. self.loadDataSource()
  588. }
  589. }
  590. }
  591. extension NCActivity: NCShareCommentsCellDelegate {
  592. func tapMenu(with tableComments: tableComments?, sender: Any) {
  593. toggleMenu(with: tableComments)
  594. }
  595. func toggleMenu(with tableComments: tableComments?) {
  596. let menuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateInitialViewController() as! NCMenu
  597. var actions = [NCMenuAction]()
  598. actions.append(
  599. NCMenuAction(
  600. title: NSLocalizedString("_edit_comment_", comment: ""),
  601. icon: UIImage(named: "edit")!.image(color: NCBrandColor.shared.gray, size: 50),
  602. action: { menuAction in
  603. guard let metadata = self.metadata else { return }
  604. guard let tableComments = tableComments else { return }
  605. let alert = UIAlertController(title: NSLocalizedString("_edit_comment_", comment: ""), message: nil, preferredStyle: .alert)
  606. alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
  607. alert.addTextField(configurationHandler: { textField in
  608. textField.placeholder = NSLocalizedString("_new_comment_", comment: "")
  609. })
  610. alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { action in
  611. if let message = alert.textFields?.first?.text {
  612. if message != "" {
  613. NCCommunication.shared.updateComments(fileId: metadata.fileId, messageId: tableComments.messageId, message: message) { (account, errorCode, errorDescription) in
  614. if errorCode == 0 {
  615. //TODO:..
  616. // self.reloadData()
  617. } else {
  618. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  619. }
  620. }
  621. }
  622. }
  623. }))
  624. self.present(alert, animated: true)
  625. }
  626. )
  627. )
  628. actions.append(
  629. NCMenuAction(
  630. title: NSLocalizedString("_delete_comment_", comment: ""),
  631. icon: NCUtility.shared.loadImage(named: "trash"),
  632. action: { menuAction in
  633. guard let metadata = self.metadata else { return }
  634. guard let tableComments = tableComments else { return }
  635. NCCommunication.shared.deleteComments(fileId: metadata.fileId, messageId: tableComments.messageId) { (account, errorCode, errorDescription) in
  636. if errorCode == 0 {
  637. //TODO: ...
  638. // self.reloadData()
  639. } else {
  640. NCContentPresenter.shared.messageNotification("_share_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  641. }
  642. }
  643. }
  644. )
  645. )
  646. actions.append(
  647. NCMenuAction(
  648. title: NSLocalizedString("_cancel_", comment: ""),
  649. icon: UIImage(named: "cancel")!.image(color: NCBrandColor.shared.gray, size: 50),
  650. action: { menuAction in
  651. }
  652. )
  653. )
  654. menuViewController.actions = actions
  655. let menuPanelController = NCMenuPanelController()
  656. menuPanelController.parentPresenter = self
  657. menuPanelController.delegate = menuViewController
  658. menuPanelController.set(contentViewController: menuViewController)
  659. menuPanelController.track(scrollView: menuViewController.tableView)
  660. self.present(menuPanelController, animated: true, completion: nil)
  661. }
  662. }