NCCollectionCommon.swift 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. //
  2. // NCCollectionCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 08/09/2020.
  6. // Copyright © 2020 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 TLPhotoPicker
  25. import ZIPFoundation
  26. import NCCommunication
  27. class NCCollectionCommon: NSObject {
  28. @objc static let shared: NCCollectionCommon = {
  29. let instance = NCCollectionCommon()
  30. instance.createImagesThemingColor()
  31. return instance
  32. }()
  33. struct NCCollectionCommonImages {
  34. static var cellSharedImage = UIImage()
  35. static var cellCanShareImage = UIImage()
  36. static var cellShareByLinkImage = UIImage()
  37. static var cellFavouriteImage = UIImage()
  38. static var cellMoreImage = UIImage()
  39. static var cellCommentImage = UIImage()
  40. static var cellLivePhotoImage = UIImage()
  41. static var cellFolderEncryptedImage = UIImage()
  42. static var cellFolderSharedWithMeImage = UIImage()
  43. static var cellFolderPublicImage = UIImage()
  44. static var cellFolderGroupImage = UIImage()
  45. static var cellFolderExternalImage = UIImage()
  46. static var cellFolderAutomaticUploadImage = UIImage()
  47. static var cellFolderImage = UIImage()
  48. static var cellPlayImage = UIImage()
  49. }
  50. // MARK: -
  51. @objc func createImagesThemingColor() {
  52. NCCollectionCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  53. NCCollectionCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  54. NCCollectionCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  55. NCCollectionCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  56. NCCollectionCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  57. NCCollectionCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  58. NCCollectionCommonImages.cellLivePhotoImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  59. NCCollectionCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  60. NCCollectionCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  61. NCCollectionCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  62. NCCollectionCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  63. NCCollectionCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  64. NCCollectionCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  65. NCCollectionCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  66. NCCollectionCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  67. }
  68. // MARK: -
  69. func cellForItemAt(indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectocId: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController, dataSource: NCDataSource?) {
  70. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  71. var tableShare: tableShare?
  72. // Share
  73. if shares != nil {
  74. for share in shares! {
  75. if share.fileName == metadata.fileName {
  76. tableShare = share
  77. break
  78. }
  79. }
  80. }
  81. // Download preview
  82. if downloadThumbnail {
  83. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  84. }
  85. var isShare = false
  86. var isMounted = false
  87. if metadataFolder != nil {
  88. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  89. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  90. }
  91. if cell is NCListCell {
  92. let cell = cell as! NCListCell
  93. cell.delegate = source as? NCListCellDelegate
  94. cell.objectId = metadata.ocId
  95. cell.indexPath = indexPath
  96. cell.labelTitle.text = metadata.fileNameView
  97. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  98. cell.imageStatus.image = nil
  99. cell.imageLocal.image = nil
  100. cell.imageFavorite.image = nil
  101. cell.imageShared.image = nil
  102. cell.imageItem.image = nil
  103. cell.imageItem.backgroundColor = nil
  104. if metadata.directory {
  105. if metadata.e2eEncrypted {
  106. cell.imageItem.image = NCCollectionCommonImages.cellFolderEncryptedImage
  107. } else if isShare {
  108. cell.imageItem.image = NCCollectionCommonImages.cellFolderSharedWithMeImage
  109. } else if (tableShare != nil && tableShare!.shareType != 3) {
  110. cell.imageItem.image = NCCollectionCommonImages.cellFolderSharedWithMeImage
  111. } else if (tableShare != nil && tableShare!.shareType == 3) {
  112. cell.imageItem.image = NCCollectionCommonImages.cellFolderPublicImage
  113. } else if metadata.mountType == "group" {
  114. cell.imageItem.image = NCCollectionCommonImages.cellFolderGroupImage
  115. } else if isMounted {
  116. cell.imageItem.image = NCCollectionCommonImages.cellFolderExternalImage
  117. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  118. cell.imageItem.image = NCCollectionCommonImages.cellFolderAutomaticUploadImage
  119. } else {
  120. cell.imageItem.image = NCCollectionCommonImages.cellFolderImage
  121. }
  122. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  123. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  124. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  125. // Local image: offline
  126. if tableDirectory != nil && tableDirectory!.offline {
  127. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  128. }
  129. } else {
  130. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  131. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  132. } else {
  133. if metadata.hasPreview {
  134. cell.imageItem.backgroundColor = .lightGray
  135. } else {
  136. if metadata.iconName.count > 0 {
  137. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  138. } else {
  139. cell.imageItem.image = UIImage.init(named: "file")
  140. }
  141. }
  142. }
  143. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  144. // image local
  145. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  146. if size > 0 {
  147. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  148. if tableLocalFile == nil && size == metadata.size {
  149. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  150. }
  151. if tableLocalFile?.offline ?? false {
  152. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  153. } else{
  154. cell.imageLocal.image = UIImage.init(named: "local")
  155. }
  156. }
  157. }
  158. // image Favorite
  159. if metadata.favorite {
  160. cell.imageFavorite.image = NCCollectionCommonImages.cellFavouriteImage
  161. }
  162. // Share image
  163. if (isShare) {
  164. cell.imageShared.image = NCCollectionCommonImages.cellSharedImage
  165. } else if (tableShare != nil && tableShare!.shareType == 3) {
  166. cell.imageShared.image = NCCollectionCommonImages.cellShareByLinkImage
  167. } else if (tableShare != nil && tableShare!.shareType != 3) {
  168. cell.imageShared.image = NCCollectionCommonImages.cellSharedImage
  169. } else {
  170. cell.imageShared.image = NCCollectionCommonImages.cellCanShareImage
  171. }
  172. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  173. // Load avatar
  174. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  175. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  176. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  177. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  178. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  179. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  180. } else {
  181. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  182. if errorCode == 0 && account == appDelegate.account {
  183. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  184. }
  185. }
  186. }
  187. }
  188. if isEditMode {
  189. cell.imageItemLeftConstraint.constant = 45
  190. cell.imageSelect.isHidden = false
  191. if selectocId.contains(metadata.ocId) {
  192. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  193. cell.backgroundView = NCUtility.shared.cellBlurEffect(with: cell.bounds)
  194. } else {
  195. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  196. cell.backgroundView = nil
  197. }
  198. } else {
  199. cell.imageItemLeftConstraint.constant = 10
  200. cell.imageSelect.isHidden = true
  201. cell.backgroundView = nil
  202. }
  203. // Transfer
  204. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  205. cell.progressView.isHidden = false
  206. cell.setButtonMore(named: "stop")
  207. } else {
  208. cell.progressView.isHidden = true
  209. cell.progressView.progress = 0.0
  210. cell.setButtonMore(named: "more")
  211. }
  212. // Remove last separator
  213. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  214. cell.separator.isHidden = true
  215. } else {
  216. cell.separator.isHidden = false
  217. }
  218. } else if cell is NCGridCell {
  219. let cell = cell as! NCGridCell
  220. cell.delegate = source as? NCGridCellDelegate
  221. cell.objectId = metadata.ocId
  222. cell.indexPath = indexPath
  223. cell.labelTitle.text = metadata.fileNameView
  224. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  225. cell.imageStatus.image = nil
  226. cell.imageLocal.image = nil
  227. cell.imageFavorite.image = nil
  228. cell.imageItem.image = nil
  229. cell.imageItem.backgroundColor = nil
  230. if metadata.directory {
  231. if metadata.e2eEncrypted {
  232. cell.imageItem.image = NCCollectionCommonImages.cellFolderEncryptedImage
  233. } else if isShare {
  234. cell.imageItem.image = NCCollectionCommonImages.cellFolderSharedWithMeImage
  235. } else if (tableShare != nil && tableShare!.shareType != 3) {
  236. cell.imageItem.image = NCCollectionCommonImages.cellFolderSharedWithMeImage
  237. } else if (tableShare != nil && tableShare!.shareType == 3) {
  238. cell.imageItem.image = NCCollectionCommonImages.cellFolderPublicImage
  239. } else if metadata.mountType == "group" {
  240. cell.imageItem.image = NCCollectionCommonImages.cellFolderGroupImage
  241. } else if isMounted {
  242. cell.imageItem.image = NCCollectionCommonImages.cellFolderExternalImage
  243. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  244. cell.imageItem.image = NCCollectionCommonImages.cellFolderAutomaticUploadImage
  245. } else {
  246. cell.imageItem.image = NCCollectionCommonImages.cellFolderImage
  247. }
  248. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  249. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  250. // Local image: offline
  251. if tableDirectory != nil && tableDirectory!.offline {
  252. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  253. }
  254. } else {
  255. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  256. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  257. } else {
  258. if metadata.hasPreview {
  259. cell.imageItem.backgroundColor = .lightGray
  260. } else {
  261. if metadata.iconName.count > 0 {
  262. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  263. } else {
  264. cell.imageItem.image = UIImage.init(named: "file")
  265. }
  266. }
  267. }
  268. // image Local
  269. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  270. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  271. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  272. else { cell.imageLocal.image = UIImage.init(named: "local") }
  273. }
  274. }
  275. // image Favorite
  276. if metadata.favorite {
  277. cell.imageFavorite.image = NCCollectionCommonImages.cellFavouriteImage
  278. }
  279. if isEditMode {
  280. cell.imageSelect.isHidden = false
  281. if selectocId.contains(metadata.ocId) {
  282. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  283. cell.backgroundView = NCUtility.shared.cellBlurEffect(with: cell.bounds)
  284. } else {
  285. cell.imageSelect.isHidden = true
  286. cell.backgroundView = nil
  287. }
  288. } else {
  289. cell.imageSelect.isHidden = true
  290. cell.backgroundView = nil
  291. }
  292. // Transfer
  293. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  294. cell.progressView.isHidden = false
  295. cell.setButtonMore(named: "stop")
  296. } else {
  297. cell.progressView.isHidden = true
  298. cell.progressView.progress = 0.0
  299. cell.setButtonMore(named: "more")
  300. }
  301. }
  302. }
  303. }
  304. // MARK: - List Layout
  305. class NCListLayout: UICollectionViewFlowLayout {
  306. let itemHeight: CGFloat = 60
  307. override init() {
  308. super.init()
  309. sectionHeadersPinToVisibleBounds = false
  310. minimumInteritemSpacing = 0
  311. minimumLineSpacing = 1
  312. self.scrollDirection = .vertical
  313. self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  314. }
  315. required init?(coder aDecoder: NSCoder) {
  316. fatalError("init(coder:) has not been implemented")
  317. }
  318. override var itemSize: CGSize {
  319. get {
  320. if let collectionView = collectionView {
  321. let itemWidth: CGFloat = collectionView.frame.width
  322. return CGSize(width: itemWidth, height: self.itemHeight)
  323. }
  324. // Default fallback
  325. return CGSize(width: 100, height: 100)
  326. }
  327. set {
  328. super.itemSize = newValue
  329. }
  330. }
  331. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  332. return proposedContentOffset
  333. }
  334. }
  335. // MARK: - Grid Layout
  336. class NCGridLayout: UICollectionViewFlowLayout {
  337. var heightLabelPlusButton: CGFloat = 45
  338. var marginLeftRight: CGFloat = 6
  339. var itemForLine: CGFloat = 3
  340. override init() {
  341. super.init()
  342. sectionHeadersPinToVisibleBounds = false
  343. minimumInteritemSpacing = 1
  344. minimumLineSpacing = marginLeftRight
  345. self.scrollDirection = .vertical
  346. self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  347. }
  348. required init?(coder aDecoder: NSCoder) {
  349. fatalError("init(coder:) has not been implemented")
  350. }
  351. override var itemSize: CGSize {
  352. get {
  353. if let collectionView = collectionView {
  354. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  355. let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
  356. return CGSize(width: itemWidth, height: itemHeight)
  357. }
  358. // Default fallback
  359. return CGSize(width: 100, height: 100)
  360. }
  361. set {
  362. super.itemSize = newValue
  363. }
  364. }
  365. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  366. return proposedContentOffset
  367. }
  368. }
  369. // MARK: - NCSelect + Delegate
  370. extension NCCollectionCommon: NCSelectDelegate {
  371. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, array: [Any], buttonType: String, overwrite: Bool) {
  372. if (serverUrl != nil && array.count > 0) {
  373. var move = true
  374. if buttonType == "done1" { move = false }
  375. for metadata in array as! [tableMetadata] {
  376. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: move)
  377. }
  378. }
  379. }
  380. func openSelectView(viewController: UIViewController, array: [Any]) {
  381. let navigationController = UIStoryboard.init(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  382. let vc = navigationController.topViewController as! NCSelect
  383. vc.delegate = self
  384. vc.hideButtonCreateFolder = false
  385. vc.selectFile = false
  386. vc.includeDirectoryE2EEncryption = false
  387. vc.includeImages = false
  388. vc.type = ""
  389. vc.titleButtonDone = NSLocalizedString("_move_", comment: "")
  390. vc.titleButtonDone1 = NSLocalizedString("_copy_",comment: "")
  391. vc.isButtonDone1Hide = false
  392. vc.isOverwriteHide = false
  393. vc.keyLayout = k_layout_view_move
  394. vc.array = array
  395. navigationController.modalPresentationStyle = .fullScreen
  396. viewController.present(navigationController, animated: true, completion: nil)
  397. }
  398. }
  399. // MARK: - Nextcloud CollectionView Common
  400. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  401. @IBOutlet weak var collectionView: UICollectionView!
  402. internal let refreshControl = UIRefreshControl()
  403. internal var searchController: UISearchController?
  404. @objc var serverUrl = ""
  405. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  406. internal var metadataPush: tableMetadata?
  407. internal var isEditMode = false
  408. internal var selectOcId: [String] = []
  409. internal var metadatasSource: [tableMetadata] = []
  410. internal var dataSource: NCDataSource?
  411. internal var layout = ""
  412. internal var groupBy = ""
  413. internal var titleButton = ""
  414. internal var itemForLine = 0
  415. private var autoUploadFileName = ""
  416. private var autoUploadDirectory = ""
  417. private var listLayout: NCListLayout!
  418. private var gridLayout: NCGridLayout!
  419. private let headerMenuHeight: CGFloat = 50
  420. private let sectionHeaderHeight: CGFloat = 20
  421. private let footerHeight: CGFloat = 50
  422. private var timerInputSearch: Timer?
  423. internal var literalSearch: String?
  424. internal var isSearching: Bool = false
  425. internal var isReloadDataSourceNetworkInProgress: Bool = false
  426. // DECLARE
  427. internal var layoutKey = ""
  428. internal var titleCurrentFolder = ""
  429. internal var enableSearchBar: Bool = false
  430. internal var DZNimage: UIImage?
  431. internal var DZNtitle: String = ""
  432. internal var DZNdescription: String = ""
  433. required init?(coder aDecoder: NSCoder) {
  434. super.init(coder: aDecoder)
  435. }
  436. override func viewDidLoad() {
  437. super.viewDidLoad()
  438. self.navigationController?.navigationBar.prefersLargeTitles = true
  439. if enableSearchBar {
  440. searchController = UISearchController(searchResultsController: nil)
  441. searchController?.searchResultsUpdater = self
  442. self.navigationItem.searchController = searchController
  443. searchController?.dimsBackgroundDuringPresentation = false
  444. searchController?.delegate = self
  445. searchController?.searchBar.delegate = self
  446. }
  447. // Cell
  448. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  449. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  450. // Header
  451. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  452. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  453. // Footer
  454. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  455. collectionView.alwaysBounceVertical = true
  456. listLayout = NCListLayout()
  457. gridLayout = NCGridLayout()
  458. // Refresh Control
  459. collectionView.addSubview(refreshControl)
  460. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  461. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  462. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetwork), for: .valueChanged)
  463. // empty Data Source
  464. self.collectionView.emptyDataSetDelegate = self
  465. self.collectionView.emptyDataSetSource = self
  466. // 3D Touch peek and pop
  467. if traitCollection.forceTouchCapability == .available {
  468. registerForPreviewing(with: self, sourceView: view)
  469. }
  470. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  471. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  472. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  473. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  474. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  475. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  476. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  477. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  478. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  479. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  480. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  481. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  482. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  483. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  484. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  485. changeTheming()
  486. }
  487. override func viewWillAppear(_ animated: Bool) {
  488. super.viewWillAppear(animated)
  489. self.navigationItem.title = titleCurrentFolder
  490. // get auto upload folder
  491. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  492. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  493. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey)
  494. gridLayout.itemForLine = CGFloat(itemForLine)
  495. if layout == k_layout_list {
  496. collectionView?.collectionViewLayout = listLayout
  497. } else {
  498. collectionView?.collectionViewLayout = gridLayout
  499. }
  500. reloadDataSource()
  501. }
  502. override func viewDidAppear(_ animated: Bool) {
  503. super.viewDidAppear(animated)
  504. reloadDataSourceNetwork()
  505. }
  506. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  507. super.viewWillTransition(to: size, with: coordinator)
  508. coordinator.animate(alongsideTransition: nil) { _ in
  509. self.collectionView?.collectionViewLayout.invalidateLayout()
  510. }
  511. }
  512. // MARK: - Utility
  513. @objc func minCharTextFieldDidChange(sender: UITextField) {
  514. guard let alertController = self.presentedViewController as? UIAlertController else { return }
  515. guard let password = alertController.textFields?.first else { return }
  516. guard let ok = alertController.actions.last else { return }
  517. ok.isEnabled = password.text?.count ?? 0 >= 8
  518. }
  519. // MARK: - NotificationCenter
  520. @objc func changeTheming() {
  521. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  522. }
  523. @objc func deleteFile(_ notification: NSNotification) {
  524. if self.view?.window == nil { return }
  525. if let userInfo = notification.userInfo as NSDictionary? {
  526. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool, let errorCode = userInfo["errorCode"] as? Int, let _ = userInfo["errorDescription"] as? String {
  527. if errorCode == 0 {
  528. if onlyLocal {
  529. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  530. let indexPath = IndexPath(row: row, section: 0)
  531. collectionView?.reloadItems(at: [indexPath])
  532. }
  533. } else {
  534. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  535. let indexPath = IndexPath(row: row, section: 0)
  536. collectionView?.performBatchUpdates({
  537. collectionView?.deleteItems(at: [indexPath])
  538. }, completion: { (_) in
  539. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  540. self.collectionView?.reloadData()
  541. }
  542. })
  543. }
  544. }
  545. }
  546. }
  547. }
  548. }
  549. @objc func moveFile(_ notification: NSNotification) {
  550. if self.view?.window == nil { return }
  551. if let userInfo = notification.userInfo as NSDictionary? {
  552. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let _ = userInfo["errorDescription"] as? String {
  553. if errorCode == 0 {
  554. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  555. let indexPath = IndexPath(row: row, section: 0)
  556. collectionView?.performBatchUpdates({
  557. collectionView?.deleteItems(at: [indexPath])
  558. }, completion: { (_) in
  559. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  560. self.collectionView?.reloadData()
  561. }
  562. })
  563. }
  564. }
  565. }
  566. }
  567. }
  568. @objc func copyFile(_ notification: NSNotification) { }
  569. @objc func renameFile(_ notification: NSNotification) {
  570. if self.view?.window == nil { return }
  571. if let userInfo = notification.userInfo as NSDictionary? {
  572. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let _ = userInfo["errorDescription"] as? String {
  573. if errorCode == 0 {
  574. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  575. let indexPath = IndexPath(row: row, section: 0)
  576. collectionView?.performBatchUpdates({
  577. collectionView?.reloadItems(at: [indexPath])
  578. }, completion: { (_) in
  579. self.collectionView?.reloadData()
  580. })
  581. }
  582. }
  583. }
  584. }
  585. }
  586. @objc func createFolder(_ notification: NSNotification) {
  587. if self.view?.window == nil { return }
  588. // if let userInfo = notification.userInfo as NSDictionary? {
  589. // if let fileName = userInfo["fileName"] as? String, let serverUrl = userInfo["serverUrl"] as? String,let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  590. // }
  591. // }
  592. }
  593. @objc func favoriteFile(_ notification: NSNotification) {
  594. if self.view?.window == nil { return }
  595. if let userInfo = notification.userInfo as NSDictionary? {
  596. if let metadata = userInfo["metadata"] as? tableMetadata, let favorite = userInfo["favorite"] as? Bool, let errorCode = userInfo["errorCode"] as? Int, let _ = userInfo["errorDescription"] as? String {
  597. if errorCode == 0 {
  598. self.reloadDataSource()
  599. if favorite {
  600. if CCUtility.getFavoriteOffline() {
  601. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selectorDownloadAllFile)
  602. } else {
  603. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selectorReadFile)
  604. }
  605. }
  606. }
  607. }
  608. }
  609. }
  610. @objc func downloadStartFile(_ notification: NSNotification) {
  611. if self.view?.window == nil { return }
  612. if let userInfo = notification.userInfo as NSDictionary? {
  613. if let metadata = userInfo["metadata"] as? tableMetadata {
  614. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  615. let indexPath = IndexPath(row: row, section: 0)
  616. collectionView?.reloadItems(at: [indexPath])
  617. }
  618. }
  619. }
  620. }
  621. @objc func downloadedFile(_ notification: NSNotification) {
  622. if self.view?.window == nil { return }
  623. if let userInfo = notification.userInfo as NSDictionary? {
  624. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  625. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  626. let indexPath = IndexPath(row: row, section: 0)
  627. collectionView?.reloadItems(at: [indexPath])
  628. }
  629. }
  630. }
  631. }
  632. @objc func downloadCancelFile(_ notification: NSNotification) {
  633. if self.view?.window == nil { return }
  634. if let userInfo = notification.userInfo as NSDictionary? {
  635. if let metadata = userInfo["metadata"] as? tableMetadata {
  636. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  637. let indexPath = IndexPath(row: row, section: 0)
  638. collectionView?.reloadItems(at: [indexPath])
  639. }
  640. }
  641. }
  642. }
  643. @objc func uploadStartFile(_ notification: NSNotification) {
  644. if self.view?.window == nil { return }
  645. if let userInfo = notification.userInfo as NSDictionary? {
  646. if let metadata = userInfo["metadata"] as? tableMetadata {
  647. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  648. if let row = dataSource?.addMetadata(metadata) {
  649. let indexPath = IndexPath(row: row, section: 0)
  650. collectionView?.performBatchUpdates({
  651. collectionView?.insertItems(at: [indexPath])
  652. }, completion: { (_) in
  653. self.collectionView?.reloadData()
  654. })
  655. }
  656. }
  657. }
  658. }
  659. }
  660. @objc func uploadedFile(_ notification: NSNotification) {
  661. if self.view?.window == nil { return }
  662. if let userInfo = notification.userInfo as NSDictionary? {
  663. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  664. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  665. dataSource?.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  666. collectionView?.reloadData()
  667. }
  668. }
  669. }
  670. }
  671. @objc func uploadCancelFile(_ notification: NSNotification) {
  672. if self.view?.window == nil { return }
  673. if let userInfo = notification.userInfo as NSDictionary? {
  674. if let metadata = userInfo["metadata"] as? tableMetadata {
  675. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  676. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  677. let indexPath = IndexPath(row: row, section: 0)
  678. collectionView?.performBatchUpdates({
  679. collectionView?.deleteItems(at: [indexPath])
  680. }, completion: { (_) in
  681. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  682. self.collectionView?.reloadData()
  683. }
  684. })
  685. } else {
  686. self.reloadDataSource()
  687. }
  688. }
  689. }
  690. }
  691. }
  692. @objc func triggerProgressTask(_ notification: NSNotification) {
  693. if self.view?.window == nil { return }
  694. if let userInfo = notification.userInfo as NSDictionary? {
  695. if let ocId = userInfo["ocId"] as? String {
  696. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  697. let progress = progressNumber.floatValue
  698. if let index = dataSource?.getIndexMetadata(ocId: ocId) {
  699. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  700. if cell is NCListCell {
  701. let cell = cell as! NCListCell
  702. if progress > 0 {
  703. cell.progressView?.isHidden = false
  704. cell.progressView?.progress = progress
  705. cell.setButtonMore(named: "stop")
  706. }
  707. } else if cell is NCGridCell {
  708. let cell = cell as! NCGridCell
  709. if progress > 0 {
  710. cell.progressView.isHidden = false
  711. cell.progressView.progress = progress
  712. cell.setButtonMore(named: "stop")
  713. }
  714. }
  715. }
  716. }
  717. }
  718. }
  719. }
  720. // MARK: DZNEmpty
  721. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  722. return NCBrandColor.sharedInstance.backgroundView
  723. }
  724. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  725. if searchController?.isActive ?? false {
  726. return CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: NCBrandColor.sharedInstance.yellowFavorite)
  727. }
  728. return DZNimage
  729. }
  730. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  731. var text = "\n"+NSLocalizedString(DZNtitle, comment: "")
  732. if searchController?.isActive ?? false {
  733. if isReloadDataSourceNetworkInProgress {
  734. text = "\n"+NSLocalizedString("_search_in_progress_", comment: "")
  735. } else {
  736. text = "\n"+NSLocalizedString("_search_no_record_found_", comment: "")
  737. }
  738. }
  739. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  740. return NSAttributedString.init(string: text, attributes: attributes)
  741. }
  742. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  743. var text = "\n"+NSLocalizedString(DZNdescription, comment: "")
  744. if searchController?.isActive ?? false {
  745. text = "\n"+NSLocalizedString("_search_instruction_", comment: "")
  746. }
  747. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  748. return NSAttributedString.init(string: text, attributes: attributes)
  749. }
  750. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  751. return true
  752. }
  753. // MARK: SEARCH
  754. func updateSearchResults(for searchController: UISearchController) {
  755. timerInputSearch?.invalidate()
  756. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  757. literalSearch = searchController.searchBar.text
  758. collectionView?.reloadData()
  759. }
  760. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  761. isSearching = true
  762. metadatasSource.removeAll()
  763. reloadDataSource()
  764. }
  765. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  766. isSearching = false
  767. literalSearch = ""
  768. reloadDataSource()
  769. }
  770. // MARK: TAP EVENT
  771. func tapSwitchHeader(sender: Any) {
  772. if collectionView.collectionViewLayout == gridLayout {
  773. // list layout
  774. UIView.animate(withDuration: 0.0, animations: {
  775. self.collectionView.collectionViewLayout.invalidateLayout()
  776. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  777. self.collectionView.reloadData()
  778. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  779. })
  780. })
  781. layout = k_layout_list
  782. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  783. } else {
  784. // grid layout
  785. UIView.animate(withDuration: 0.0, animations: {
  786. self.collectionView.collectionViewLayout.invalidateLayout()
  787. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  788. self.collectionView.reloadData()
  789. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  790. })
  791. })
  792. layout = k_layout_grid
  793. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  794. }
  795. }
  796. func tapOrderHeader(sender: Any) {
  797. let sortMenu = NCSortMenu()
  798. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  799. }
  800. func tapMoreHeader(sender: Any) {
  801. }
  802. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  803. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  804. }
  805. func tapShareListItem(with objectId: String, sender: Any) {
  806. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else {
  807. return
  808. }
  809. NCMainCommon.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  810. }
  811. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  812. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  813. guard let tabBarController = self.tabBarController else { return }
  814. if namedButtonMore == "more" {
  815. toggleMoreMenu(viewController: tabBarController, metadata: metadata, selectOcId: selectOcId)
  816. } else if namedButtonMore == "stop" {
  817. NCMainCommon.shared.cancelTransferMetadata(metadata, uploadStatusForcedStart: false)
  818. }
  819. }
  820. // MARK: SEGUE
  821. @objc func segue(metadata: tableMetadata) {
  822. self.metadataPush = metadata
  823. performSegue(withIdentifier: "segueDetail", sender: self)
  824. }
  825. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  826. let photoDataSource: NSMutableArray = []
  827. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  828. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  829. photoDataSource.add(metadata)
  830. }
  831. }
  832. if let segueNavigationController = segue.destination as? UINavigationController {
  833. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  834. segueViewController.metadata = metadataPush
  835. }
  836. }
  837. }
  838. // MARK: - NC API & Algorithm
  839. @objc func reloadDataSource() { }
  840. @objc func reloadDataSourceNetwork() { }
  841. @objc func networkSearch() {
  842. if literalSearch?.count ?? 0 > 1 {
  843. isReloadDataSourceNetworkInProgress = true
  844. collectionView?.reloadData()
  845. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  846. if self.searchController?.isActive ?? false && errorCode == 0 {
  847. self.metadatasSource = metadatas!
  848. }
  849. self.isReloadDataSourceNetworkInProgress = false
  850. self.reloadDataSource()
  851. }
  852. }
  853. }
  854. }
  855. // MARK: - 3D Touch peek and pop
  856. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  857. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  858. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  859. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  860. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  861. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  862. viewController.metadata = metadata
  863. if layout == k_layout_grid {
  864. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  865. previewingContext.sourceRect = cell.frame
  866. viewController.imageFile = cell.imageItem.image
  867. } else {
  868. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  869. previewingContext.sourceRect = cell.frame
  870. viewController.imageFile = cell.imageItem.image
  871. }
  872. viewController.showOpenIn = true
  873. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  874. viewController.showShare = false
  875. return viewController
  876. }
  877. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  878. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  879. collectionView(collectionView, didSelectItemAt: indexPath)
  880. }
  881. }
  882. // MARK: - Collection View
  883. extension NCCollectionViewCommon: UICollectionViewDelegate {
  884. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { }
  885. }
  886. extension NCCollectionViewCommon: UICollectionViewDataSource {
  887. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  888. if (indexPath.section == 0) {
  889. if kind == UICollectionView.elementKindSectionHeader {
  890. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  891. if collectionView.collectionViewLayout == gridLayout {
  892. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  893. } else {
  894. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  895. }
  896. header.delegate = self
  897. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  898. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  899. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  900. header.setTitleSorted(datasourceTitleButton: titleButton)
  901. if groupBy == "none" {
  902. header.labelSection.isHidden = true
  903. header.labelSectionHeightConstraint.constant = 0
  904. } else {
  905. header.labelSection.isHidden = false
  906. header.setTitleLabel(title: "")
  907. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  908. }
  909. return header
  910. } else {
  911. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  912. let info = dataSource?.getFilesInformation()
  913. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  914. return footer
  915. }
  916. } else {
  917. if kind == UICollectionView.elementKindSectionHeader {
  918. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  919. header.setTitleLabel(title: "")
  920. return header
  921. } else {
  922. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  923. let info = dataSource?.getFilesInformation()
  924. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  925. return footer
  926. }
  927. }
  928. }
  929. func numberOfSections(in collectionView: UICollectionView) -> Int {
  930. return 1
  931. }
  932. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  933. return dataSource?.numberOfItemsInSection(section: section) ?? 1
  934. }
  935. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  936. let cell: UICollectionViewCell
  937. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  938. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  939. }
  940. if layout == k_layout_grid {
  941. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  942. } else {
  943. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  944. }
  945. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  946. NCCollectionCommon.shared.cellForItemAt(indexPath: indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectocId: selectOcId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, shares: shares, source: self, dataSource: dataSource)
  947. return cell
  948. }
  949. }
  950. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  951. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  952. if section == 0 {
  953. if groupBy == "none" {
  954. return CGSize(width: collectionView.frame.width, height: headerMenuHeight)
  955. } else {
  956. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  957. }
  958. } else {
  959. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  960. }
  961. }
  962. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  963. let sections = 1
  964. if (section == sections - 1) {
  965. return CGSize(width: collectionView.frame.width, height: footerHeight)
  966. } else {
  967. return CGSize(width: collectionView.frame.width, height: 0)
  968. }
  969. }
  970. }