NCMedia.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 Sheeeeeeeeet
  25. import FastScroll
  26. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  27. @IBOutlet weak var collectionView : FastScrollCollectionView!
  28. @IBOutlet weak var menuButtonMore: UIButton!
  29. @IBOutlet weak var menuButtonSwitch: UIButton!
  30. @IBOutlet weak var menuView: UIView!
  31. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. private var metadataPush: tableMetadata?
  33. private var isEditMode = false
  34. private var selectFileID = [String]()
  35. private var filterTypeFileImage = false;
  36. private var filterTypeFileVideo = false;
  37. private var sectionDatasource = CCSectionDataSourceMetadata()
  38. private var autoUploadFileName = ""
  39. private var autoUploadDirectory = ""
  40. private var gridLayout: NCGridMediaLayout!
  41. private var actionSheet: ActionSheet?
  42. private let sectionHeaderHeight: CGFloat = 50
  43. private let footerHeight: CGFloat = 50
  44. private var stepImageWidth: CGFloat = 10
  45. private var isDistantPast = false
  46. private let refreshControl = UIRefreshControl()
  47. private var loadingSearch = false
  48. required init?(coder aDecoder: NSCoder) {
  49. super.init(coder: aDecoder)
  50. appDelegate.activeMedia = self
  51. }
  52. override func viewDidLoad() {
  53. super.viewDidLoad()
  54. // Cell
  55. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  56. // Header
  57. collectionView.register(UINib.init(nibName: "NCSectionMediaHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  58. // Footer
  59. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  60. collectionView.alwaysBounceVertical = true
  61. gridLayout = NCGridMediaLayout()
  62. gridLayout.preferenceWidth = CGFloat(CCUtility.getMediaWidthImage())
  63. gridLayout.sectionHeadersPinToVisibleBounds = true
  64. collectionView.collectionViewLayout = gridLayout
  65. // Add Refresh Control
  66. collectionView.refreshControl = refreshControl
  67. // empty Data Source
  68. collectionView.emptyDataSetDelegate = self
  69. collectionView.emptyDataSetSource = self
  70. // Notification
  71. NotificationCenter.default.addObserver(self, selector: #selector(self.changeTheming), name: NSNotification.Name(rawValue: "changeTheming"), object: nil)
  72. }
  73. override func viewWillAppear(_ animated: Bool) {
  74. super.viewWillAppear(animated)
  75. // Aspect Color
  76. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  77. appDelegate.aspectTabBar(self.tabBarController?.tabBar, hidden: false)
  78. // Configure Refresh Control
  79. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  80. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  81. refreshControl.addTarget(self, action: #selector(loadNetworkDatasource), for: .valueChanged)
  82. menuView.backgroundColor = NCBrandColor.sharedInstance.brand
  83. menuButtonSwitch.setImage(UIImage(named: "switchGridChange")?.withRenderingMode(.alwaysTemplate), for: .normal)
  84. menuButtonSwitch.tintColor = NCBrandColor.sharedInstance.brandText
  85. menuButtonMore.setImage(UIImage(named: "moreBig")?.withRenderingMode(.alwaysTemplate), for: .normal)
  86. menuButtonMore.tintColor = NCBrandColor.sharedInstance.brandText
  87. // get auto upload folder
  88. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  89. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  90. // Title
  91. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  92. // Fast Scrool
  93. configFastScroll()
  94. // Reload Data Source
  95. self.reloadDataSource(loadNetworkDatasource: true)
  96. }
  97. override func viewDidAppear(_ animated: Bool) {
  98. super.viewDidAppear(animated)
  99. collectionView?.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.collectionView?.reloadDataThenPerform {
  107. self.downloadThumbnail()
  108. }
  109. self.actionSheet?.viewDidLayoutSubviews()
  110. }
  111. }
  112. @objc func changeTheming() {
  113. if self.isViewLoaded && self.view?.window != nil {
  114. appDelegate.changeTheming(self)
  115. }
  116. }
  117. // MARK: DZNEmpty
  118. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  119. return NCBrandColor.sharedInstance.backgroundView
  120. }
  121. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  122. return CCGraphics.changeThemingColorImage(UIImage.init(named: "mediaNoRecord"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  123. }
  124. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  125. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  126. if loadingSearch {
  127. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  128. }
  129. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  130. return NSAttributedString.init(string: text, attributes: attributes)
  131. }
  132. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  133. return true
  134. }
  135. // MARK: IBAction
  136. @IBAction func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  137. let itemSizeStart = self.gridLayout.itemSize
  138. UIView.animate(withDuration: 0.0, animations: {
  139. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  140. self.stepImageWidth = -10
  141. } else if itemSizeStart.width < 50 {
  142. self.stepImageWidth = 10
  143. }
  144. repeat {
  145. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  146. } while (self.gridLayout.itemSize == itemSizeStart)
  147. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  148. self.collectionView.collectionViewLayout.invalidateLayout()
  149. if self.stepImageWidth < 0 {
  150. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  151. self.selectSearchSections()
  152. }
  153. }
  154. })
  155. }
  156. @IBAction func touchUpInsideMenuButtonMore(_ sender: Any) {
  157. var menu: DropdownMenu?
  158. if !isEditMode {
  159. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  160. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderMedia"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  161. var item2: DropdownItem
  162. if filterTypeFileImage {
  163. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  164. } else {
  165. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  166. }
  167. var item3: DropdownItem
  168. if filterTypeFileVideo {
  169. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  170. } else {
  171. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  172. }
  173. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  174. menu?.token = "menuButtonMore"
  175. } else {
  176. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "select"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  177. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_delete_", comment: ""))
  178. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1], selectedRow: -1)
  179. menu?.token = "menuButtonMoreSelect"
  180. }
  181. menu?.delegate = self
  182. menu?.rowHeight = 45
  183. menu?.highlightColor = NCBrandColor.sharedInstance.brand
  184. menu?.tableView.alwaysBounceVertical = false
  185. menu?.tableViewBackgroundColor = UIColor.white
  186. menu?.topOffsetY = menuView.bounds.height
  187. menu?.showMenu()
  188. }
  189. // MARK: DROP-DOWN-MENU
  190. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  191. if dropdownMenu.token == "menuButtonMore" {
  192. switch indexPath.row {
  193. case 0:
  194. isEditMode = true
  195. case 1:
  196. selectStartDirectoryPhotosTab()
  197. case 2:
  198. filterTypeFileImage = !filterTypeFileImage
  199. reloadDataSource(loadNetworkDatasource: false)
  200. case 3:
  201. filterTypeFileVideo = !filterTypeFileVideo
  202. reloadDataSource(loadNetworkDatasource: false)
  203. default: ()
  204. }
  205. }
  206. if dropdownMenu.token == "menuButtonMoreSelect" {
  207. switch indexPath.row {
  208. case 0:
  209. isEditMode = false
  210. selectFileID.removeAll()
  211. collectionView?.reloadDataThenPerform {
  212. self.downloadThumbnail()
  213. }
  214. case 1:
  215. deleteItems()
  216. default: ()
  217. }
  218. }
  219. }
  220. // MARK: Select Directory
  221. func selectStartDirectoryPhotosTab() {
  222. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  223. let viewController = navigationController.topViewController as! NCSelect
  224. viewController.delegate = self
  225. viewController.hideButtonCreateFolder = true
  226. viewController.includeDirectoryE2EEncryption = false
  227. viewController.includeImages = false
  228. viewController.layoutViewSelect = k_layout_view_move
  229. viewController.selectFile = false
  230. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  231. viewController.type = "mediaFolder"
  232. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  233. self.present(navigationController, animated: true, completion: nil)
  234. }
  235. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  236. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  237. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  238. // Save Start Directory
  239. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  240. //
  241. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  242. self.sectionDatasource = CCSectionDataSourceMetadata()
  243. //
  244. loadNetworkDatasource()
  245. }
  246. }
  247. // MARK: SEGUE
  248. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  249. let photoDataSource: NSMutableArray = []
  250. for fileID: String in sectionDatasource.allFileID as! [String] {
  251. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: fileID) as! tableMetadata
  252. if metadata.typeFile == k_metadataTypeFile_image {
  253. photoDataSource.add(metadata)
  254. }
  255. }
  256. if let segueNavigationController = segue.destination as? UINavigationController {
  257. if let segueViewController = segueNavigationController.topViewController as? CCDetail {
  258. segueViewController.metadataDetail = metadataPush
  259. segueViewController.dateFilterQuery = nil
  260. segueViewController.photoDataSource = photoDataSource
  261. segueViewController.title = metadataPush!.fileNameView
  262. }
  263. }
  264. }
  265. }
  266. // MARK: - Collection View
  267. extension NCMedia: UICollectionViewDelegate {
  268. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  269. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  270. return
  271. }
  272. metadataPush = metadata
  273. if isEditMode {
  274. if let index = selectFileID.index(of: metadata.fileID) {
  275. selectFileID.remove(at: index)
  276. } else {
  277. selectFileID.append(metadata.fileID)
  278. }
  279. collectionView.reloadItems(at: [indexPath])
  280. return
  281. }
  282. performSegue(withIdentifier: "segueDetail", sender: self)
  283. }
  284. }
  285. extension NCMedia: UICollectionViewDataSource {
  286. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  287. if kind == UICollectionView.elementKindSectionHeader {
  288. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  289. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  290. header.labelSection.textColor = .white
  291. header.labelHeightConstraint.constant = 20
  292. header.labelSection.layer.cornerRadius = 10
  293. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  294. let width = header.labelSection.intrinsicContentSize.width + 30
  295. let leading = collectionView.bounds.width / 2 - width / 2
  296. header.labelWidthConstraint.constant = width
  297. header.labelLeadingConstraint.constant = leading
  298. return header
  299. } else {
  300. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  301. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  302. return footer
  303. }
  304. }
  305. func numberOfSections(in collectionView: UICollectionView) -> Int {
  306. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  307. return sections
  308. }
  309. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  310. var numberOfItemsInSection: Int = 0
  311. if section < sectionDatasource.sections.count {
  312. let key = sectionDatasource.sections.object(at: section)
  313. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  314. numberOfItemsInSection = datasource.count
  315. }
  316. return numberOfItemsInSection
  317. }
  318. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  319. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  320. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  321. }
  322. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  323. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectFileID: selectFileID, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: true, downloadThumbnail: false, source: self)
  324. return cell
  325. }
  326. }
  327. extension NCMedia: UICollectionViewDelegateFlowLayout {
  328. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  329. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  330. }
  331. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  332. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  333. if (section == sections - 1) {
  334. return CGSize(width: collectionView.frame.width, height: footerHeight)
  335. } else {
  336. return CGSize(width: collectionView.frame.width, height: 0)
  337. }
  338. }
  339. }
  340. // MARK: NC API & Algorithm
  341. extension NCMedia {
  342. public func reloadDataSource(loadNetworkDatasource: Bool) {
  343. if appDelegate.activeAccount.count == 0 {
  344. return
  345. }
  346. DispatchQueue.global().async {
  347. let metadatas = NCManageDatabase.sharedInstance.getTableMedias(predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  348. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterFileID: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, sorted: "date", ascending: false, activeAccount: self.appDelegate.activeAccount)
  349. DispatchQueue.main.async {
  350. if loadNetworkDatasource {
  351. self.loadNetworkDatasource()
  352. }
  353. self.collectionView?.reloadDataThenPerform {
  354. self.downloadThumbnail()
  355. }
  356. }
  357. }
  358. }
  359. func deleteItems() {
  360. if appDelegate.activeAccount.count == 0 {
  361. return
  362. }
  363. var metadatas = [tableMetadata]()
  364. for fileID in selectFileID {
  365. if let metadata = NCManageDatabase.sharedInstance.getTableMedia(predicate: NSPredicate(format: "fileID == %@", fileID)) {
  366. metadatas.append(metadata)
  367. }
  368. }
  369. if metadatas.count > 0 {
  370. NCMainCommon.sharedInstance.deleteFile(metadatas: metadatas as NSArray, e2ee: false, serverUrl: "", folderFileID: "") { (errorCode, message) in
  371. self.isEditMode = false
  372. self.selectFileID.removeAll()
  373. self.selectSearchSections()
  374. }
  375. }
  376. }
  377. func search(lteDate: Date, gteDate: Date, addPast: Bool, setDistantPast: Bool) {
  378. // ----- DEBUG -----
  379. #if DEBUG
  380. let dateFormatter = DateFormatter()
  381. dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
  382. print("[LOG] Search: addPast \(addPast), distantPass: \(setDistantPast), Lte: " + dateFormatter.string(from: lteDate) + " - Gte: " + dateFormatter.string(from: gteDate))
  383. #endif
  384. // -----------------
  385. if appDelegate.activeAccount.count == 0 {
  386. return
  387. }
  388. if addPast && loadingSearch {
  389. return
  390. }
  391. if setDistantPast {
  392. isDistantPast = true
  393. }
  394. if addPast {
  395. //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)
  396. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  397. }
  398. loadingSearch = true
  399. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  400. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  401. self.refreshControl.endRefreshing()
  402. NCUtility.sharedInstance.stopActivityIndicator()
  403. //self.navigationItem.titleView = nil
  404. //self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  405. if errorCode == 0 && account == self.appDelegate.activeAccount {
  406. var differenceSizeInsert: Int64 = 0
  407. var differenceNumInsert: Int64 = 0
  408. let totalDistance = Calendar.current.dateComponents([Calendar.Component.day], from: gteDate, to: lteDate).value(for: .day) ?? 0
  409. let difference = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  410. differenceSizeInsert = difference.differenceSizeInsert
  411. differenceNumInsert = difference.differenceNumInsert
  412. self.loadingSearch = false
  413. print("[LOG] Totale Distance \(totalDistance) - Different Size \(differenceSizeInsert) - Different Num \(differenceNumInsert)")
  414. if differenceSizeInsert != 0 {
  415. self.reloadDataSource(loadNetworkDatasource: false)
  416. }
  417. if (differenceSizeInsert == 0 || differenceNumInsert < 100) && addPast && setDistantPast == false {
  418. switch totalDistance {
  419. case 0...89:
  420. if var gteDate90 = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  421. gteDate90 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate90) ?? Date()
  422. self.search(lteDate: lteDate, gteDate: gteDate90, addPast: addPast, setDistantPast: false)
  423. print("[LOG] Media search 90 gg")
  424. }
  425. case 90...179:
  426. if var gteDate180 = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  427. gteDate180 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate180) ?? Date()
  428. self.search(lteDate: lteDate, gteDate: gteDate180, addPast: addPast, setDistantPast: false)
  429. print("[LOG] Media search 180 gg")
  430. }
  431. case 180...364:
  432. if var gteDate365 = Calendar.current.date(byAdding: .day, value: -365, to: gteDate) {
  433. gteDate365 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate365) ?? Date()
  434. self.search(lteDate: lteDate, gteDate: gteDate365, addPast: addPast, setDistantPast: false)
  435. print("[LOG] Media search 365 gg")
  436. }
  437. default:
  438. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, setDistantPast: true)
  439. print("[LOG] Media search distant pass")
  440. }
  441. }
  442. self.collectionView?.reloadDataThenPerform {
  443. self.downloadThumbnail()
  444. }
  445. } else {
  446. self.loadingSearch = false
  447. self.reloadDataSource(loadNetworkDatasource: false)
  448. }
  449. })
  450. }
  451. @objc private func loadNetworkDatasource() {
  452. isDistantPast = false
  453. if appDelegate.activeAccount.count == 0 {
  454. return
  455. }
  456. if sectionDatasource.allRecordsDataSource.count == 0 {
  457. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  458. search(lteDate: Date(), gteDate: gteDate!, addPast: true, setDistantPast: false)
  459. } else {
  460. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  461. search(lteDate: Date(), gteDate: gteDate, addPast: false, setDistantPast: false)
  462. }
  463. collectionView?.reloadDataThenPerform {
  464. self.downloadThumbnail()
  465. }
  466. }
  467. private func selectSearchSections() {
  468. if appDelegate.activeAccount.count == 0 {
  469. return
  470. }
  471. let sections = NSMutableSet()
  472. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  473. var gteDate: Date?
  474. for item in collectionView.indexPathsForVisibleItems {
  475. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  476. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  477. sections.add(date)
  478. }
  479. }
  480. }
  481. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  482. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  483. }
  484. if sortedSections.count >= 1 {
  485. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  486. if lastDate == sortedSections.last as! Date {
  487. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  488. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, setDistantPast: false)
  489. } else {
  490. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  491. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, setDistantPast: false)
  492. }
  493. }
  494. }
  495. private func downloadThumbnail() {
  496. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  497. for item in self.collectionView.indexPathsForVisibleItems {
  498. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  499. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView, indexPath: item)
  500. }
  501. }
  502. }
  503. }
  504. }
  505. // MARK: FastScroll - ScrollView
  506. extension NCMedia: UIScrollViewDelegate {
  507. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  508. collectionView.scrollViewDidScroll(scrollView)
  509. }
  510. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  511. collectionView.scrollViewWillBeginDragging(scrollView)
  512. }
  513. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  514. collectionView.scrollViewDidEndDecelerating(scrollView)
  515. }
  516. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  517. collectionView.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  518. }
  519. }
  520. extension NCMedia: FastScrollCollectionViewDelegate {
  521. fileprivate func configFastScroll() {
  522. collectionView.fastScrollDelegate = self
  523. collectionView.handleTimeToDisappear = 1
  524. //bubble
  525. collectionView.deactivateBubble = true
  526. collectionView.bubbleFocus = .dynamic
  527. collectionView.bubbleTextSize = 14.0
  528. collectionView.bubbleMarginRight = 50.0
  529. collectionView.bubbleColor = UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  530. //handle
  531. /*
  532. collectionView.handleHeight = 40.0
  533. collectionView.handleWidth = 40.0
  534. collectionView.handleRadius = 20.0
  535. collectionView.handleMarginRight = -20
  536. */
  537. collectionView.handleColor = NCBrandColor.sharedInstance.brand
  538. //scrollbar
  539. collectionView.scrollbarWidth = 0.0
  540. collectionView.scrollbarMarginTop = 45.0
  541. collectionView.scrollbarMarginBottom = 5.0
  542. collectionView.scrollbarMarginRight = 10.0
  543. //callback action to display bubble name
  544. /*
  545. collectionView.bubbleNameForIndexPath = { indexPath in
  546. let visibleSection: Section = self.data[indexPath.section]
  547. return visibleSection.sectionTitle
  548. }
  549. */
  550. }
  551. func hideHandle() {
  552. selectSearchSections()
  553. }
  554. }
  555. extension FastScrollCollectionView
  556. {
  557. /// Calls reloadsData() on self, and ensures that the given closure is
  558. /// called after reloadData() has been completed.
  559. ///
  560. /// Discussion: reloadData() appears to be asynchronous. i.e. the
  561. /// reloading actually happens during the next layout pass. So, doing
  562. /// things like scrolling the collectionView immediately after a
  563. /// call to reloadData() can cause trouble.
  564. ///
  565. /// This method uses CATransaction to schedule the closure.
  566. func reloadDataThenPerform(_ closure: @escaping (() -> Void))
  567. {
  568. CATransaction.begin()
  569. CATransaction.setCompletionBlock(closure)
  570. self.reloadData()
  571. CATransaction.commit()
  572. }
  573. }