NCMedia.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/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 Foundation
  24. import NCCommunication
  25. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  26. @IBOutlet weak var collectionView : UICollectionView!
  27. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. var sectionDatasource = CCSectionDataSourceMetadata()
  29. private var metadataPush: tableMetadata?
  30. private var isEditMode = false
  31. private var selectocId = [String]()
  32. private var filterTypeFileImage = false;
  33. private var filterTypeFileVideo = false;
  34. private var autoUploadFileName = ""
  35. private var autoUploadDirectory = ""
  36. private var gridLayout: NCGridMediaLayout!
  37. private let sectionHeaderHeight: CGFloat = 50
  38. private let footerHeight: CGFloat = 50
  39. private var stepImageWidth: CGFloat = 10
  40. private var isDistantPast = false
  41. private let refreshControl = UIRefreshControl()
  42. private var loadingSearch = false
  43. struct cacheImages {
  44. static var cellPlayImage = UIImage()
  45. static var cellFavouriteImage = UIImage()
  46. }
  47. required init?(coder aDecoder: NSCoder) {
  48. super.init(coder: aDecoder)
  49. appDelegate.activeMedia = self
  50. }
  51. override func viewDidLoad() {
  52. super.viewDidLoad()
  53. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonMore))
  54. self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "grid"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonSwitch))
  55. // Cell
  56. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  57. // Header
  58. collectionView.register(UINib.init(nibName: "NCSectionMediaHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  59. // Footer
  60. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  61. collectionView.alwaysBounceVertical = true
  62. gridLayout = NCGridMediaLayout()
  63. gridLayout.preferenceWidth = CGFloat(CCUtility.getMediaWidthImage())
  64. gridLayout.sectionHeadersPinToVisibleBounds = true
  65. collectionView.collectionViewLayout = gridLayout
  66. // Add Refresh Control
  67. collectionView.refreshControl = refreshControl
  68. // empty Data Source
  69. collectionView.emptyDataSetDelegate = self
  70. collectionView.emptyDataSetSource = self
  71. // 3D Touch peek and pop
  72. if traitCollection.forceTouchCapability == .available {
  73. registerForPreviewing(with: self, sourceView: view)
  74. }
  75. // Notification
  76. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  77. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  78. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  79. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  80. // changeTheming
  81. changeTheming()
  82. }
  83. override func viewWillAppear(_ animated: Bool) {
  84. super.viewWillAppear(animated)
  85. // Configure Refresh Control
  86. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  87. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  88. refreshControl.addTarget(self, action: #selector(loadNetworkDatasource), for: .valueChanged)
  89. // get auto upload folder
  90. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  91. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  92. // Title
  93. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  94. // Reload Data Source
  95. self.reloadDataSource(loadNetworkDatasource: true) { }
  96. }
  97. override func viewDidAppear(_ animated: Bool) {
  98. super.viewDidAppear(animated)
  99. reloadDataThenPerform {
  100. self.selectSearchSections()
  101. }
  102. }
  103. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  104. super.viewWillTransition(to: size, with: coordinator)
  105. coordinator.animate(alongsideTransition: nil) { _ in
  106. self.reloadDataThenPerform {
  107. self.downloadThumbnail()
  108. }
  109. }
  110. }
  111. //MARK: - NotificationCenter
  112. @objc func changeTheming() {
  113. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  114. cacheImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  115. cacheImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  116. }
  117. @objc func deleteFile(_ notification: NSNotification) {
  118. if let userInfo = notification.userInfo as NSDictionary? {
  119. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  120. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  121. self.reloadDataSource(loadNetworkDatasource: false) {
  122. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  123. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  124. }
  125. }
  126. }
  127. }
  128. }
  129. @objc func moveFile(_ notification: NSNotification) {
  130. if let userInfo = notification.userInfo as NSDictionary? {
  131. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  132. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  133. self.reloadDataSource(loadNetworkDatasource: false) {
  134. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  135. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  136. }
  137. }
  138. }
  139. }
  140. }
  141. @objc func renameFile(_ notification: NSNotification) {
  142. if let userInfo = notification.userInfo as NSDictionary? {
  143. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  144. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  145. self.reloadDataSource(loadNetworkDatasource: false) {
  146. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  147. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  148. }
  149. }
  150. }
  151. }
  152. }
  153. // MARK: DZNEmpty
  154. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  155. return NCBrandColor.sharedInstance.backgroundView
  156. }
  157. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  158. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  159. }
  160. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  161. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  162. if loadingSearch {
  163. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  164. }
  165. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  166. return NSAttributedString.init(string: text, attributes: attributes)
  167. }
  168. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  169. return true
  170. }
  171. // MARK: IBAction
  172. @objc func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  173. let itemSizeStart = self.gridLayout.itemSize
  174. UIView.animate(withDuration: 0.0, animations: {
  175. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  176. self.stepImageWidth = -10
  177. } else if itemSizeStart.width < 50 {
  178. self.stepImageWidth = 10
  179. }
  180. repeat {
  181. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  182. } while (self.gridLayout.itemSize == itemSizeStart)
  183. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  184. self.collectionView.collectionViewLayout.invalidateLayout()
  185. if self.stepImageWidth < 0 {
  186. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  187. self.selectSearchSections()
  188. }
  189. }
  190. })
  191. }
  192. @objc func touchUpInsideMenuButtonMore(_ sender: Any) {
  193. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  194. var actions = [NCMenuAction]()
  195. if !isEditMode {
  196. actions.append(
  197. NCMenuAction(
  198. title: NSLocalizedString("_select_", comment: ""),
  199. icon: CCGraphics.changeThemingColorImage(UIImage(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  200. action: { menuAction in
  201. self.isEditMode = true
  202. }
  203. )
  204. )
  205. actions.append(
  206. NCMenuAction(
  207. title: NSLocalizedString("_select_media_folder_", comment: ""),
  208. icon: CCGraphics.changeThemingColorImage(UIImage(named: "folderAutomaticUpload"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  209. action: { menuAction in
  210. self.selectStartDirectoryPhotosTab()
  211. }
  212. )
  213. )
  214. actions.append(
  215. NCMenuAction(
  216. title: NSLocalizedString(filterTypeFileImage ? "_media_viewimage_show_" : "_media_viewimage_hide_", comment: ""),
  217. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileImage ? "imageno" : "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  218. action: { menuAction in
  219. self.filterTypeFileImage = !self.filterTypeFileImage
  220. self.reloadDataSource(loadNetworkDatasource: false) { }
  221. }
  222. )
  223. )
  224. actions.append(
  225. NCMenuAction(
  226. title: NSLocalizedString(filterTypeFileVideo ? "_media_viewvideo_show_" : "_media_viewvideo_hide_", comment: ""),
  227. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileVideo ? "videono" : "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  228. action: { menuAction in
  229. self.filterTypeFileVideo = !self.filterTypeFileVideo
  230. self.reloadDataSource(loadNetworkDatasource: false) { }
  231. }
  232. )
  233. )
  234. } else {
  235. actions.append(
  236. NCMenuAction(
  237. title: NSLocalizedString("_deselect_", comment: ""),
  238. icon: CCGraphics.changeThemingColorImage(UIImage(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  239. action: { menuAction in
  240. self.isEditMode = false
  241. self.selectocId.removeAll()
  242. self.reloadDataThenPerform {
  243. self.downloadThumbnail()
  244. }
  245. }
  246. )
  247. )
  248. actions.append(
  249. NCMenuAction(
  250. title: NSLocalizedString("_delete_", comment: ""),
  251. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  252. action: { menuAction in
  253. self.deleteItems()
  254. }
  255. )
  256. )
  257. }
  258. mainMenuViewController.actions = actions
  259. let menuPanelController = NCMenuPanelController()
  260. menuPanelController.parentPresenter = self
  261. menuPanelController.delegate = mainMenuViewController
  262. menuPanelController.set(contentViewController: mainMenuViewController)
  263. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  264. self.present(menuPanelController, animated: true, completion: nil)
  265. }
  266. // MARK: Select Directory
  267. func selectStartDirectoryPhotosTab() {
  268. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  269. let viewController = navigationController.topViewController as! NCSelect
  270. viewController.delegate = self
  271. viewController.hideButtonCreateFolder = true
  272. viewController.includeDirectoryE2EEncryption = false
  273. viewController.includeImages = false
  274. viewController.layoutViewSelect = k_layout_view_move
  275. viewController.selectFile = false
  276. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  277. viewController.type = "mediaFolder"
  278. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  279. self.present(navigationController, animated: true, completion: nil)
  280. }
  281. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  282. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  283. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  284. // Save Start Directory
  285. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  286. //
  287. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  288. self.sectionDatasource = CCSectionDataSourceMetadata()
  289. //
  290. loadNetworkDatasource()
  291. }
  292. }
  293. // MARK: SEGUE
  294. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  295. let photoDataSource: NSMutableArray = []
  296. for ocId: String in sectionDatasource.allOcId as! [String] {
  297. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: ocId) as! tableMetadata
  298. if metadata.typeFile == k_metadataTypeFile_image {
  299. photoDataSource.add(metadata)
  300. }
  301. }
  302. if let segueNavigationController = segue.destination as? UINavigationController {
  303. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  304. segueViewController.metadata = metadataPush
  305. segueViewController.metadatas = sectionDatasource.metadatas as! [tableMetadata]
  306. segueViewController.mediaFilterImage = true
  307. }
  308. }
  309. }
  310. }
  311. // MARK: - 3D Touch peek and pop
  312. extension NCMedia: UIViewControllerPreviewingDelegate {
  313. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  314. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  315. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  316. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else { return nil }
  317. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  318. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  319. previewingContext.sourceRect = cell.frame
  320. viewController.metadata = metadata
  321. viewController.imageFile = cell.imageItem.image
  322. viewController.showOpenIn = true
  323. viewController.showShare = false
  324. viewController.showOpenInternalViewer = false
  325. return viewController
  326. }
  327. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  328. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  329. collectionView(collectionView, didSelectItemAt: indexPath)
  330. }
  331. }
  332. // MARK: - Collection View
  333. extension NCMedia: UICollectionViewDelegate {
  334. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  335. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  336. return
  337. }
  338. metadataPush = metadata
  339. if isEditMode {
  340. if let index = selectocId.firstIndex(of: metadata.ocId) {
  341. selectocId.remove(at: index)
  342. } else {
  343. selectocId.append(metadata.ocId)
  344. }
  345. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  346. collectionView.reloadItems(at: [indexPath])
  347. }
  348. return
  349. }
  350. performSegue(withIdentifier: "segueDetail", sender: self)
  351. }
  352. }
  353. extension NCMedia: UICollectionViewDataSource {
  354. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  355. CATransaction.begin()
  356. CATransaction.setCompletionBlock(closure)
  357. collectionView?.reloadData()
  358. CATransaction.commit()
  359. }
  360. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  361. if kind == UICollectionView.elementKindSectionHeader {
  362. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  363. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  364. header.labelSection.textColor = .white
  365. header.labelHeightConstraint.constant = 20
  366. header.labelSection.layer.cornerRadius = 10
  367. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  368. let width = header.labelSection.intrinsicContentSize.width + 30
  369. let leading = collectionView.bounds.width / 2 - width / 2
  370. header.labelWidthConstraint.constant = width
  371. header.labelLeadingConstraint.constant = leading
  372. return header
  373. } else {
  374. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  375. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  376. return footer
  377. }
  378. }
  379. func numberOfSections(in collectionView: UICollectionView) -> Int {
  380. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  381. return sections
  382. }
  383. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  384. var numberOfItemsInSection: Int = 0
  385. if section < sectionDatasource.sections.count {
  386. let key = sectionDatasource.sections.object(at: section)
  387. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  388. numberOfItemsInSection = datasource.count
  389. }
  390. return numberOfItemsInSection
  391. }
  392. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  393. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  394. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  395. }
  396. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  397. cell.imageStatus.image = nil
  398. cell.imageLocal.image = nil
  399. cell.imageFavorite.image = nil
  400. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  401. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  402. } else {
  403. if metadata.iconName.count > 0 {
  404. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  405. } else {
  406. cell.imageItem.image = UIImage.init(named: "file")
  407. }
  408. }
  409. // image status
  410. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  411. cell.imageStatus.image = cacheImages.cellPlayImage
  412. }
  413. // image Local
  414. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  415. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  416. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  417. else { cell.imageLocal.image = UIImage.init(named: "local") }
  418. }
  419. // image Favorite
  420. if metadata.favorite {
  421. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  422. }
  423. if isEditMode {
  424. cell.imageSelect.isHidden = false
  425. if selectocId.contains(metadata.ocId) {
  426. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  427. cell.imageVisualEffect.isHidden = false
  428. cell.imageVisualEffect.alpha = 0.4
  429. } else {
  430. cell.imageSelect.isHidden = true
  431. cell.imageVisualEffect.isHidden = true
  432. }
  433. } else {
  434. cell.imageSelect.isHidden = true
  435. cell.imageVisualEffect.isHidden = true
  436. }
  437. return cell
  438. }
  439. }
  440. extension NCMedia: UICollectionViewDelegateFlowLayout {
  441. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  442. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  443. }
  444. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  445. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  446. if (section == sections - 1) {
  447. return CGSize(width: collectionView.frame.width, height: footerHeight)
  448. } else {
  449. return CGSize(width: collectionView.frame.width, height: 0)
  450. }
  451. }
  452. }
  453. // MARK: - NC API & Algorithm
  454. extension NCMedia {
  455. public func reloadDataSource(loadNetworkDatasource: Bool, completion: @escaping ()->()) {
  456. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  457. return
  458. }
  459. DispatchQueue.global().async {
  460. let metadatas = NCManageDatabase.sharedInstance.getMedias(account: self.appDelegate.activeAccount, predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  461. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterocId: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, sorted: "date", ascending: false, activeAccount: self.appDelegate.activeAccount)
  462. DispatchQueue.main.async {
  463. self.collectionView?.reloadData()
  464. if loadNetworkDatasource {
  465. self.loadNetworkDatasource()
  466. }
  467. self.reloadDataThenPerform {
  468. self.downloadThumbnail()
  469. }
  470. completion()
  471. }
  472. }
  473. }
  474. func deleteItems() {
  475. self.isEditMode = false
  476. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  477. return
  478. }
  479. // copy in arrayDeleteMetadata
  480. for ocId in selectocId {
  481. if let metadata = NCManageDatabase.sharedInstance.getMedia(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  482. appDelegate.arrayDeleteMetadata.add(metadata)
  483. }
  484. }
  485. if let metadata = appDelegate.arrayDeleteMetadata.firstObject {
  486. appDelegate.arrayDeleteMetadata.removeObject(at: 0)
  487. NCNetworking.sharedInstance.deleteMetadata(metadata as! tableMetadata, user: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: appDelegate.activeUrl) { (errorCode, errorDescription) in }
  488. }
  489. }
  490. func search(lteDate: Date, gteDate: Date, addPast: Bool, insertPrevius: Int,setDistantPast: Bool, debug: String) {
  491. // ----- DEBUG -----
  492. #if DEBUG
  493. let dateFormatter = DateFormatter()
  494. dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
  495. print("[LOG] Search: addPast \(addPast), distantPass: \(setDistantPast), Lte: " + dateFormatter.string(from: lteDate) + " - Gte: " + dateFormatter.string(from: gteDate) + " DEBUG: " + debug)
  496. #endif
  497. // -----------------
  498. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  499. return
  500. }
  501. if addPast && loadingSearch {
  502. return
  503. }
  504. if setDistantPast {
  505. isDistantPast = true
  506. }
  507. if addPast {
  508. //CCGraphics.addImage(toTitle: NSLocalizedString("_media_", comment: ""), colorTitle: NCBrandColor.sharedInstance.brandText, imageTitle: CCGraphics.changeThemingColorImage(UIImage.init(named: "load"), multiplier: 2, color: NCBrandColor.sharedInstance.brandText), imageRight: false, navigationItem: self.navigationItem)
  509. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  510. }
  511. loadingSearch = true
  512. NCCommunication.sharedInstance.searchMedia(serverUrl: appDelegate.activeUrl, lteDateLastModified: lteDate, gteDateLastModified: gteDate, showHiddenFiles: CCUtility.getShowHiddenFiles(), customUserAgent: nil, addCustomHeaders: nil, user: appDelegate.activeUser, account: appDelegate.activeAccount) { (account, files, errorCode, errorDescription) in
  513. self.refreshControl.endRefreshing()
  514. NCUtility.sharedInstance.stopActivityIndicator()
  515. if errorCode == 0 && account == self.appDelegate.activeAccount && files != nil {
  516. var isDifferent: Bool = false
  517. var newInsert: Int = 0
  518. NCManageDatabase.sharedInstance.convertNCFilesToMetadatas(files!, useMetadataFolder: false, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  519. let totalDistance = Calendar.current.dateComponents([Calendar.Component.day], from: gteDate, to: lteDate).value(for: .day) ?? 0
  520. let difference = NCManageDatabase.sharedInstance.createTableMedia(metadatas, lteDate: lteDate, gteDate: gteDate, account: account)
  521. isDifferent = difference.isDifferent
  522. newInsert = difference.newInsert
  523. self.loadingSearch = false
  524. print("[LOG] Search: Totale Distance \(totalDistance) - It's Different \(isDifferent) - New insert \(newInsert)")
  525. if isDifferent {
  526. self.reloadDataSource(loadNetworkDatasource: false) { }
  527. }
  528. if (isDifferent == false || newInsert+insertPrevius < 100) && addPast && setDistantPast == false {
  529. switch totalDistance {
  530. case 0...89:
  531. if var gteDate90 = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  532. gteDate90 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate90) ?? Date()
  533. self.search(lteDate: lteDate, gteDate: gteDate90, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -90 gg")
  534. }
  535. case 90...179:
  536. if var gteDate180 = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  537. gteDate180 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate180) ?? Date()
  538. self.search(lteDate: lteDate, gteDate: gteDate180, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -180 gg")
  539. }
  540. case 180...364:
  541. if var gteDate365 = Calendar.current.date(byAdding: .day, value: -365, to: gteDate) {
  542. gteDate365 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate365) ?? Date()
  543. self.search(lteDate: lteDate, gteDate: gteDate365, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -365 gg")
  544. }
  545. default:
  546. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: true, debug: "search recursive distant pass")
  547. }
  548. }
  549. self.reloadDataThenPerform {
  550. self.downloadThumbnail()
  551. }
  552. }
  553. } else {
  554. self.loadingSearch = false
  555. self.reloadDataSource(loadNetworkDatasource: false) { }
  556. }
  557. }
  558. }
  559. @objc private func loadNetworkDatasource() {
  560. isDistantPast = false
  561. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  562. return
  563. }
  564. if sectionDatasource.allRecordsDataSource.count == 0 {
  565. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  566. search(lteDate: Date(), gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) today, -30 gg")
  567. } else {
  568. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  569. search(lteDate: Date(), gteDate: gteDate, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search today, first date record")
  570. }
  571. reloadDataThenPerform {
  572. self.downloadThumbnail()
  573. }
  574. }
  575. private func selectSearchSections() {
  576. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  577. return
  578. }
  579. let sections = NSMutableSet()
  580. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  581. var gteDate: Date?
  582. for item in collectionView.indexPathsForVisibleItems {
  583. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  584. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  585. sections.add(date)
  586. }
  587. }
  588. }
  589. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  590. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  591. }
  592. if sortedSections.count >= 1 {
  593. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  594. if lastDate == sortedSections.last as! Date {
  595. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  596. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) last record, -30 gg")
  597. } else {
  598. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  599. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search [refresh window]")
  600. }
  601. }
  602. }
  603. private func downloadThumbnail() {
  604. guard let collectionView = self.collectionView else { return }
  605. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  606. for item in collectionView.indexPathsForVisibleItems {
  607. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  608. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView as Any, indexPath: item)
  609. }
  610. }
  611. }
  612. }
  613. }
  614. // MARK: - ScrollView
  615. extension NCMedia: UIScrollViewDelegate {
  616. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  617. if !decelerate {
  618. selectSearchSections()
  619. }
  620. }
  621. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  622. selectSearchSections()
  623. }
  624. }