NCCollectionCommon.swift 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. // MARK: -
  304. func notificationDeleteFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata, errorCode: Int, errorDescription: String ,onlyLocal: Bool) {
  305. if errorCode == 0 {
  306. if onlyLocal {
  307. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  308. let indexPath = IndexPath(row: row, section: 0)
  309. collectionView?.reloadItems(at: [indexPath])
  310. }
  311. } else {
  312. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  313. let indexPath = IndexPath(row: row, section: 0)
  314. collectionView?.performBatchUpdates({
  315. collectionView?.deleteItems(at: [indexPath])
  316. }, completion: { (_) in
  317. collectionView?.reloadData()
  318. })
  319. }
  320. }
  321. } else {
  322. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  323. }
  324. }
  325. func notificationMoveFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata, errorCode: Int, errorDescription: String) {
  326. if errorCode == 0 {
  327. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  328. let indexPath = IndexPath(row: row, section: 0)
  329. collectionView?.performBatchUpdates({
  330. collectionView?.deleteItems(at: [indexPath])
  331. }, completion: { (_) in
  332. collectionView?.reloadData()
  333. })
  334. }
  335. } else {
  336. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  337. }
  338. }
  339. func notificationRenameFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata, errorCode: Int, errorDescription: String) {
  340. if errorCode == 0 {
  341. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  342. let indexPath = IndexPath(row: row, section: 0)
  343. collectionView?.performBatchUpdates({
  344. collectionView?.reloadItems(at: [indexPath])
  345. }, completion: { (_) in
  346. collectionView?.reloadData()
  347. })
  348. }
  349. } else {
  350. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  351. }
  352. }
  353. func notificationCreateFolder(collectionView: UICollectionView?, dataSource: NCDataSource?, fileName: String, serverUrl: String, errorCode: Int, errorDescription: String) {
  354. if errorCode == 0 {
  355. } else {
  356. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  357. }
  358. }
  359. func notificationFavoriteFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata, favorite: Bool, errorCode: Int, errorDescription: String) {
  360. if errorCode == 0 {
  361. } else {
  362. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  363. }
  364. }
  365. func notificationDownloadStartFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata) {
  366. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  367. let indexPath = IndexPath(row: row, section: 0)
  368. collectionView?.reloadItems(at: [indexPath])
  369. }
  370. }
  371. func notificationDownloadedFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata) {
  372. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  373. let indexPath = IndexPath(row: row, section: 0)
  374. collectionView?.reloadItems(at: [indexPath])
  375. }
  376. }
  377. func notificationDownloadCancelFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata) {
  378. if let row = dataSource?.reloadMetadata(ocId: metadata.ocId) {
  379. let indexPath = IndexPath(row: row, section: 0)
  380. collectionView?.reloadItems(at: [indexPath])
  381. }
  382. }
  383. func notificationUploadStartFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata) {
  384. if let row = dataSource?.addMetadata(metadata) {
  385. let indexPath = IndexPath(row: row, section: 0)
  386. collectionView?.performBatchUpdates({
  387. collectionView?.insertItems(at: [indexPath])
  388. }, completion: { (_) in
  389. collectionView?.reloadData()
  390. })
  391. }
  392. }
  393. func notificationUploadedFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata, ocIdTemp: String) {
  394. _ = dataSource?.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  395. collectionView?.reloadData()
  396. }
  397. func notificationUploadCancelFile(collectionView: UICollectionView?, dataSource: NCDataSource?, metadata: tableMetadata) -> Bool {
  398. if let row = dataSource?.deleteMetadata(ocId: metadata.ocId) {
  399. let indexPath = IndexPath(row: row, section: 0)
  400. collectionView?.performBatchUpdates({
  401. collectionView?.deleteItems(at: [indexPath])
  402. }, completion: { (_) in
  403. collectionView?.reloadData()
  404. })
  405. return true
  406. }
  407. return false
  408. }
  409. func notificationTriggerProgressTask(collectionView: UICollectionView?, dataSource: NCDataSource?, ocId: String, progress: Float) {
  410. if let index = dataSource?.getIndexMetadata(ocId: ocId) {
  411. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  412. if cell is NCListCell {
  413. let cell = cell as! NCListCell
  414. if progress > 0 {
  415. cell.progressView?.isHidden = false
  416. cell.progressView?.progress = progress
  417. cell.setButtonMore(named: "stop")
  418. }
  419. } else if cell is NCGridCell {
  420. let cell = cell as! NCGridCell
  421. if progress > 0 {
  422. cell.progressView.isHidden = false
  423. cell.progressView.progress = progress
  424. cell.setButtonMore(named: "stop")
  425. }
  426. }
  427. }
  428. }
  429. }
  430. }
  431. // MARK: - List Layout
  432. class NCListLayout: UICollectionViewFlowLayout {
  433. let itemHeight: CGFloat = 60
  434. override init() {
  435. super.init()
  436. sectionHeadersPinToVisibleBounds = false
  437. minimumInteritemSpacing = 0
  438. minimumLineSpacing = 1
  439. self.scrollDirection = .vertical
  440. self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  441. }
  442. required init?(coder aDecoder: NSCoder) {
  443. fatalError("init(coder:) has not been implemented")
  444. }
  445. override var itemSize: CGSize {
  446. get {
  447. if let collectionView = collectionView {
  448. let itemWidth: CGFloat = collectionView.frame.width
  449. return CGSize(width: itemWidth, height: self.itemHeight)
  450. }
  451. // Default fallback
  452. return CGSize(width: 100, height: 100)
  453. }
  454. set {
  455. super.itemSize = newValue
  456. }
  457. }
  458. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  459. return proposedContentOffset
  460. }
  461. }
  462. // MARK: - Grid Layout
  463. class NCGridLayout: UICollectionViewFlowLayout {
  464. var heightLabelPlusButton: CGFloat = 45
  465. var marginLeftRight: CGFloat = 6
  466. var itemForLine: CGFloat = 3
  467. override init() {
  468. super.init()
  469. sectionHeadersPinToVisibleBounds = false
  470. minimumInteritemSpacing = 1
  471. minimumLineSpacing = marginLeftRight
  472. self.scrollDirection = .vertical
  473. self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  474. }
  475. required init?(coder aDecoder: NSCoder) {
  476. fatalError("init(coder:) has not been implemented")
  477. }
  478. override var itemSize: CGSize {
  479. get {
  480. if let collectionView = collectionView {
  481. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  482. let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
  483. return CGSize(width: itemWidth, height: itemHeight)
  484. }
  485. // Default fallback
  486. return CGSize(width: 100, height: 100)
  487. }
  488. set {
  489. super.itemSize = newValue
  490. }
  491. }
  492. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  493. return proposedContentOffset
  494. }
  495. }
  496. // MARK: - NCSelect + Delegate
  497. extension NCCollectionCommon: NCSelectDelegate {
  498. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, array: [Any], buttonType: String, overwrite: Bool) {
  499. if (serverUrl != nil && array.count > 0) {
  500. var move = true
  501. if buttonType == "done1" { move = false }
  502. for metadata in array as! [tableMetadata] {
  503. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: move)
  504. }
  505. }
  506. }
  507. func openSelectView(viewController: UIViewController, array: [Any]) {
  508. let navigationController = UIStoryboard.init(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  509. let vc = navigationController.topViewController as! NCSelect
  510. vc.delegate = self
  511. vc.hideButtonCreateFolder = false
  512. vc.selectFile = false
  513. vc.includeDirectoryE2EEncryption = false
  514. vc.includeImages = false
  515. vc.type = ""
  516. vc.titleButtonDone = NSLocalizedString("_move_", comment: "")
  517. vc.titleButtonDone1 = NSLocalizedString("_copy_",comment: "")
  518. vc.isButtonDone1Hide = false
  519. vc.isOverwriteHide = false
  520. vc.keyLayout = k_layout_view_move
  521. vc.array = array
  522. navigationController.modalPresentationStyle = .fullScreen
  523. viewController.present(navigationController, animated: true, completion: nil)
  524. }
  525. }
  526. // MARK: - Nextcloud CollectionView Common
  527. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  528. @IBOutlet weak var collectionView: UICollectionView!
  529. @objc var serverUrl = ""
  530. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  531. internal var metadataPush: tableMetadata?
  532. internal var isEditMode = false
  533. internal var selectOcId: [String] = []
  534. internal var dataSource: NCDataSource?
  535. internal var layout = ""
  536. internal var groupBy = ""
  537. internal var titleButton = ""
  538. internal var itemForLine = 0
  539. private var autoUploadFileName = ""
  540. private var autoUploadDirectory = ""
  541. private var listLayout: NCListLayout!
  542. private var gridLayout: NCGridLayout!
  543. private let headerMenuHeight: CGFloat = 50
  544. private let sectionHeaderHeight: CGFloat = 20
  545. private let footerHeight: CGFloat = 50
  546. internal let refreshControl = UIRefreshControl()
  547. // DECLARE
  548. internal var layoutKey = ""
  549. internal var titleCurrentFolder = ""
  550. required init?(coder aDecoder: NSCoder) {
  551. super.init(coder: aDecoder)
  552. }
  553. override func viewDidLoad() {
  554. super.viewDidLoad()
  555. // Cell
  556. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  557. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  558. // Header
  559. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  560. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  561. // Footer
  562. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  563. collectionView.alwaysBounceVertical = true
  564. listLayout = NCListLayout()
  565. gridLayout = NCGridLayout()
  566. // Refresh Control
  567. collectionView.addSubview(refreshControl)
  568. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  569. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  570. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetwork), for: .valueChanged)
  571. // empty Data Source
  572. self.collectionView.emptyDataSetDelegate = self
  573. self.collectionView.emptyDataSetSource = self
  574. // 3D Touch peek and pop
  575. if traitCollection.forceTouchCapability == .available {
  576. registerForPreviewing(with: self, sourceView: view)
  577. }
  578. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  579. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  580. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  581. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  582. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  583. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  584. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  585. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  586. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  587. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  588. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  589. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  590. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  591. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  592. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  593. changeTheming()
  594. }
  595. override func viewWillAppear(_ animated: Bool) {
  596. super.viewWillAppear(animated)
  597. self.navigationItem.title = titleCurrentFolder
  598. // get auto upload folder
  599. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  600. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  601. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey)
  602. gridLayout.itemForLine = CGFloat(itemForLine)
  603. if layout == k_layout_list {
  604. collectionView?.collectionViewLayout = listLayout
  605. } else {
  606. collectionView?.collectionViewLayout = gridLayout
  607. }
  608. reloadDataSource()
  609. }
  610. override func viewDidAppear(_ animated: Bool) {
  611. super.viewDidAppear(animated)
  612. reloadDataSourceNetwork()
  613. }
  614. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  615. super.viewWillTransition(to: size, with: coordinator)
  616. coordinator.animate(alongsideTransition: nil) { _ in
  617. self.collectionView?.collectionViewLayout.invalidateLayout()
  618. }
  619. }
  620. // MARK: - Utility
  621. @objc func minCharTextFieldDidChange(sender: UITextField) {
  622. guard let alertController = self.presentedViewController as? UIAlertController else { return }
  623. guard let password = alertController.textFields?.first else { return }
  624. guard let ok = alertController.actions.last else { return }
  625. ok.isEnabled = password.text?.count ?? 0 >= 8
  626. }
  627. // MARK: - NotificationCenter
  628. @objc func changeTheming() {
  629. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  630. }
  631. @objc func deleteFile(_ notification: NSNotification) {
  632. if self.view?.window == nil { return }
  633. if let userInfo = notification.userInfo as NSDictionary? {
  634. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  635. NCCollectionCommon.shared.notificationDeleteFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata, errorCode: errorCode, errorDescription: errorDescription, onlyLocal: onlyLocal)
  636. }
  637. }
  638. }
  639. @objc func moveFile(_ notification: NSNotification) {
  640. if self.view?.window == nil { return }
  641. if let userInfo = notification.userInfo as NSDictionary? {
  642. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  643. NCCollectionCommon.shared.notificationMoveFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata, errorCode: errorCode, errorDescription: errorDescription)
  644. }
  645. }
  646. }
  647. @objc func copyFile(_ notification: NSNotification) { }
  648. @objc func renameFile(_ notification: NSNotification) {
  649. if self.view?.window == nil { return }
  650. if let userInfo = notification.userInfo as NSDictionary? {
  651. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  652. NCCollectionCommon.shared.notificationRenameFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata, errorCode: errorCode, errorDescription: errorDescription)
  653. }
  654. }
  655. }
  656. @objc func createFolder(_ notification: NSNotification) {
  657. if self.view?.window == nil { return }
  658. if let userInfo = notification.userInfo as NSDictionary? {
  659. 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 {
  660. NCCollectionCommon.shared.notificationCreateFolder(collectionView: collectionView, dataSource: dataSource, fileName: fileName, serverUrl: serverUrl, errorCode: errorCode, errorDescription: errorDescription)
  661. }
  662. }
  663. }
  664. @objc func favoriteFile(_ notification: NSNotification) {
  665. if self.view?.window == nil { return }
  666. if let userInfo = notification.userInfo as NSDictionary? {
  667. if let metadata = userInfo["metadata"] as? tableMetadata, let favorite = userInfo["favorite"] as? Bool, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  668. NCCollectionCommon.shared.notificationFavoriteFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata, favorite: favorite, errorCode: errorCode, errorDescription: errorDescription)
  669. }
  670. }
  671. }
  672. @objc func downloadStartFile(_ notification: NSNotification) {
  673. if self.view?.window == nil { return }
  674. if let userInfo = notification.userInfo as NSDictionary? {
  675. if let metadata = userInfo["metadata"] as? tableMetadata {
  676. NCCollectionCommon.shared.notificationDownloadStartFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata)
  677. }
  678. }
  679. }
  680. @objc func downloadedFile(_ notification: NSNotification) {
  681. if self.view?.window == nil { return }
  682. if let userInfo = notification.userInfo as NSDictionary? {
  683. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  684. NCCollectionCommon.shared.notificationDownloadedFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata)
  685. }
  686. }
  687. }
  688. @objc func downloadCancelFile(_ notification: NSNotification) {
  689. if self.view?.window == nil { return }
  690. if let userInfo = notification.userInfo as NSDictionary? {
  691. if let metadata = userInfo["metadata"] as? tableMetadata {
  692. NCCollectionCommon.shared.notificationDownloadCancelFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata)
  693. }
  694. }
  695. }
  696. @objc func uploadStartFile(_ notification: NSNotification) {
  697. if self.view?.window == nil { return }
  698. if let userInfo = notification.userInfo as NSDictionary? {
  699. if let metadata = userInfo["metadata"] as? tableMetadata {
  700. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  701. NCCollectionCommon.shared.notificationUploadStartFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata)
  702. }
  703. }
  704. }
  705. }
  706. @objc func uploadedFile(_ notification: NSNotification) {
  707. if self.view?.window == nil { return }
  708. if let userInfo = notification.userInfo as NSDictionary? {
  709. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  710. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  711. NCCollectionCommon.shared.notificationUploadedFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata, ocIdTemp:ocIdTemp)
  712. }
  713. }
  714. }
  715. }
  716. @objc func uploadCancelFile(_ notification: NSNotification) {
  717. if self.view?.window == nil { return }
  718. if let userInfo = notification.userInfo as NSDictionary? {
  719. if let metadata = userInfo["metadata"] as? tableMetadata {
  720. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  721. if !NCCollectionCommon.shared.notificationUploadCancelFile(collectionView: collectionView, dataSource: dataSource, metadata: metadata) {
  722. self.reloadDataSource()
  723. }
  724. }
  725. }
  726. }
  727. }
  728. @objc func triggerProgressTask(_ notification: NSNotification) {
  729. if self.view?.window == nil { return }
  730. if let userInfo = notification.userInfo as NSDictionary? {
  731. if let ocId = userInfo["ocId"] as? String {
  732. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  733. let progress = progressNumber.floatValue
  734. NCCollectionCommon.shared.notificationTriggerProgressTask(collectionView: collectionView, dataSource: dataSource, ocId: ocId, progress: progress)
  735. }
  736. }
  737. }
  738. // MARK: DZNEmpty
  739. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  740. return NCBrandColor.sharedInstance.backgroundView
  741. }
  742. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  743. return nil
  744. }
  745. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  746. return nil
  747. }
  748. func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
  749. return nil
  750. }
  751. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  752. return true
  753. }
  754. // MARK: TAP EVENT
  755. func tapSwitchHeader(sender: Any) {
  756. if collectionView.collectionViewLayout == gridLayout {
  757. // list layout
  758. UIView.animate(withDuration: 0.0, animations: {
  759. self.collectionView.collectionViewLayout.invalidateLayout()
  760. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  761. self.collectionView.reloadData()
  762. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  763. })
  764. })
  765. layout = k_layout_list
  766. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  767. } else {
  768. // grid layout
  769. UIView.animate(withDuration: 0.0, animations: {
  770. self.collectionView.collectionViewLayout.invalidateLayout()
  771. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  772. self.collectionView.reloadData()
  773. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  774. })
  775. })
  776. layout = k_layout_grid
  777. NCUtility.shared.setLayoutForView(key: layoutKey, layout: layout)
  778. }
  779. }
  780. func tapOrderHeader(sender: Any) {
  781. let sortMenu = NCSortMenu()
  782. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  783. }
  784. func tapMoreHeader(sender: Any) {
  785. }
  786. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  787. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  788. }
  789. func tapShareListItem(with objectId: String, sender: Any) {
  790. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else {
  791. return
  792. }
  793. NCMainCommon.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  794. }
  795. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  796. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  797. guard let tabBarController = self.tabBarController else { return }
  798. if namedButtonMore == "more" {
  799. toggleMoreMenu(viewController: tabBarController, metadata: metadata, selectOcId: selectOcId)
  800. } else if namedButtonMore == "stop" {
  801. NCMainCommon.shared.cancelTransferMetadata(metadata, uploadStatusForcedStart: false)
  802. }
  803. }
  804. // MARK: SEGUE
  805. @objc func segue(metadata: tableMetadata) {
  806. self.metadataPush = metadata
  807. performSegue(withIdentifier: "segueDetail", sender: self)
  808. }
  809. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  810. let photoDataSource: NSMutableArray = []
  811. for metadata in (dataSource?.metadatas ?? [tableMetadata]()) {
  812. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  813. photoDataSource.add(metadata)
  814. }
  815. }
  816. if let segueNavigationController = segue.destination as? UINavigationController {
  817. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  818. segueViewController.metadata = metadataPush
  819. }
  820. }
  821. }
  822. // MARK: - NC API & Algorithm
  823. @objc func reloadDataSource() { }
  824. @objc func reloadDataSourceNetwork() { }
  825. }
  826. // MARK: - 3D Touch peek and pop
  827. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  828. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  829. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  830. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  831. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else { return nil }
  832. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  833. viewController.metadata = metadata
  834. if layout == k_layout_grid {
  835. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  836. previewingContext.sourceRect = cell.frame
  837. viewController.imageFile = cell.imageItem.image
  838. } else {
  839. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  840. previewingContext.sourceRect = cell.frame
  841. viewController.imageFile = cell.imageItem.image
  842. }
  843. viewController.showOpenIn = true
  844. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  845. viewController.showShare = false
  846. return viewController
  847. }
  848. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  849. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  850. collectionView(collectionView, didSelectItemAt: indexPath)
  851. }
  852. }
  853. // MARK: - Collection View
  854. extension NCCollectionViewCommon: UICollectionViewDelegate {
  855. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { }
  856. }
  857. extension NCCollectionViewCommon: UICollectionViewDataSource {
  858. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  859. if (indexPath.section == 0) {
  860. if kind == UICollectionView.elementKindSectionHeader {
  861. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  862. if collectionView.collectionViewLayout == gridLayout {
  863. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  864. } else {
  865. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  866. }
  867. header.delegate = self
  868. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  869. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  870. header.setStatusButton(count: dataSource?.metadatas.count ?? 0)
  871. header.setTitleSorted(datasourceTitleButton: titleButton)
  872. if groupBy == "none" {
  873. header.labelSection.isHidden = true
  874. header.labelSectionHeightConstraint.constant = 0
  875. } else {
  876. header.labelSection.isHidden = false
  877. header.setTitleLabel(title: "")
  878. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  879. }
  880. return header
  881. } else {
  882. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  883. let info = dataSource?.getFilesInformation()
  884. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  885. return footer
  886. }
  887. } else {
  888. if kind == UICollectionView.elementKindSectionHeader {
  889. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  890. header.setTitleLabel(title: "")
  891. return header
  892. } else {
  893. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  894. let info = dataSource?.getFilesInformation()
  895. footer.setTitleLabel(directories: info?.directories ?? 0, files: info?.files ?? 0, size: info?.size ?? 0)
  896. return footer
  897. }
  898. }
  899. }
  900. func numberOfSections(in collectionView: UICollectionView) -> Int {
  901. return 1
  902. }
  903. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  904. return dataSource?.numberOfItemsInSection(section: section) ?? 1
  905. }
  906. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  907. let cell: UICollectionViewCell
  908. guard let metadata = dataSource?.cellForItemAt(indexPath: indexPath) else {
  909. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  910. }
  911. if layout == k_layout_grid {
  912. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  913. } else {
  914. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  915. }
  916. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  917. 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)
  918. return cell
  919. }
  920. }
  921. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  922. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  923. if section == 0 {
  924. if groupBy == "none" {
  925. return CGSize(width: collectionView.frame.width, height: headerMenuHeight)
  926. } else {
  927. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  928. }
  929. } else {
  930. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  931. }
  932. }
  933. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  934. let sections = 1
  935. if (section == sections - 1) {
  936. return CGSize(width: collectionView.frame.width, height: footerHeight)
  937. } else {
  938. return CGSize(width: collectionView.frame.width, height: 0)
  939. }
  940. }
  941. }