NCCollectionCommon.swift 60 KB

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