NCCollectionCommon.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 NCCommunication
  25. class NCCollectionCommon: NSObject, NCSelectDelegate {
  26. @objc static let shared: NCCollectionCommon = {
  27. let instance = NCCollectionCommon()
  28. instance.createImagesThemingColor()
  29. return instance
  30. }()
  31. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. struct images {
  33. static var cellFileImage = UIImage()
  34. static var cellSharedImage = UIImage()
  35. static var cellCanShareImage = UIImage()
  36. static var cellShareByLinkImage = UIImage()
  37. static var cellFavouriteImage = UIImage()
  38. static var cellCommentImage = UIImage()
  39. static var cellLivePhotoImage = UIImage()
  40. static var cellOfflineFlag = UIImage()
  41. static var cellLocal = UIImage()
  42. static var cellFolderEncryptedImage = UIImage()
  43. static var cellFolderSharedWithMeImage = UIImage()
  44. static var cellFolderPublicImage = UIImage()
  45. static var cellFolderGroupImage = UIImage()
  46. static var cellFolderExternalImage = UIImage()
  47. static var cellFolderAutomaticUploadImage = UIImage()
  48. static var cellFolderImage = UIImage()
  49. static var cellCheckedYes = UIImage()
  50. static var cellCheckedNo = UIImage()
  51. static var cellButtonMore = UIImage()
  52. static var cellButtonStop = UIImage()
  53. }
  54. // MARK: -
  55. @objc func createImagesThemingColor() {
  56. images.cellFileImage = UIImage.init(named: "file")!
  57. images.cellSharedImage = UIImage(named: "share")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  58. images.cellCanShareImage = UIImage(named: "share")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  59. images.cellShareByLinkImage = UIImage(named: "sharebylink")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  60. images.cellFavouriteImage = UIImage(named: "favorite")!.image(color: NCBrandColor.shared.yellowFavorite, size: 50)
  61. images.cellCommentImage = UIImage(named: "comment")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  62. images.cellLivePhotoImage = UIImage(named: "livePhoto")!.image(color: NCBrandColor.shared.textView, size: 50)
  63. images.cellOfflineFlag = UIImage.init(named: "offlineFlag")!
  64. images.cellLocal = UIImage.init(named: "local")!
  65. let folderWidth: CGFloat = UIScreen.main.bounds.width / 3
  66. images.cellFolderEncryptedImage = UIImage(named: "folderEncrypted")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  67. images.cellFolderSharedWithMeImage = UIImage(named: "folder_shared_with_me")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  68. images.cellFolderPublicImage = UIImage(named: "folder_public")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  69. images.cellFolderGroupImage = UIImage(named: "folder_group")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  70. images.cellFolderExternalImage = UIImage(named: "folder_external")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  71. images.cellFolderAutomaticUploadImage = UIImage(named: "folderAutomaticUpload")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  72. images.cellFolderImage = UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: folderWidth)
  73. images.cellCheckedYes = UIImage(named: "checkedYes")!.image(color: .darkGray, size: 50)
  74. images.cellCheckedNo = UIImage(named: "checkedNo")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  75. images.cellButtonMore = UIImage(named: "more")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  76. images.cellButtonStop = UIImage(named: "stop")!.image(color: NCBrandColor.shared.graySoft, size: 50)
  77. }
  78. // MARK: - NCSelect + Delegate
  79. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], buttonType: String, overwrite: Bool) {
  80. if (serverUrl != nil && items.count > 0) {
  81. var move = true
  82. if buttonType == "done1" { move = false }
  83. for metadata in items as! [tableMetadata] {
  84. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: move)
  85. }
  86. }
  87. }
  88. func openSelectView(items: [Any]) {
  89. let navigationController = UIStoryboard.init(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  90. let topViewController = navigationController.topViewController as! NCSelect
  91. var listViewController = [NCSelect]()
  92. var copyItems: [Any] = []
  93. for item in items {
  94. copyItems.append(item)
  95. }
  96. let homeUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  97. var serverUrl = (copyItems[0] as! Nextcloud.tableMetadata).serverUrl
  98. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  99. while true {
  100. // If not in the topmost directory, create a new view controller and set correct title.
  101. // If in the topmost directory, use the default view controller as the base.
  102. var viewController: NCSelect?
  103. if serverUrl != homeUrl {
  104. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  105. if viewController == nil {
  106. return
  107. }
  108. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  109. } else {
  110. viewController = topViewController
  111. }
  112. guard let vc = viewController else { return }
  113. vc.delegate = self
  114. vc.hideButtonCreateFolder = false
  115. vc.selectFile = false
  116. vc.includeDirectoryE2EEncryption = false
  117. vc.includeImages = false
  118. vc.type = ""
  119. vc.titleButtonDone = NSLocalizedString("_move_", comment: "")
  120. vc.titleButtonDone1 = NSLocalizedString("_copy_",comment: "")
  121. vc.isButtonDone1Hide = false
  122. vc.isOverwriteHide = false
  123. vc.items = copyItems
  124. vc.serverUrl = serverUrl
  125. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  126. listViewController.insert(vc, at: 0)
  127. if serverUrl != homeUrl {
  128. serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)
  129. } else {
  130. break
  131. }
  132. }
  133. navigationController.setViewControllers(listViewController, animated: false)
  134. navigationController.modalPresentationStyle = .formSheet
  135. appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  136. }
  137. @objc func openFileViewInFolder(serverUrl: String, fileName: String) {
  138. let viewController = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  139. let navigationController = UINavigationController.init(rootViewController: viewController)
  140. let topViewController = viewController
  141. var listViewController = [NCFileViewInFolder]()
  142. var serverUrl = serverUrl
  143. let homeUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  144. while true {
  145. var viewController: NCFileViewInFolder?
  146. if serverUrl != homeUrl {
  147. viewController = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder
  148. if viewController == nil {
  149. return
  150. }
  151. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  152. } else {
  153. viewController = topViewController
  154. }
  155. guard let vc = viewController else { return }
  156. vc.serverUrl = serverUrl
  157. vc.fileName = fileName
  158. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  159. listViewController.insert(vc, at: 0)
  160. if serverUrl != homeUrl {
  161. serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)
  162. } else {
  163. break
  164. }
  165. }
  166. navigationController.setViewControllers(listViewController, animated: false)
  167. navigationController.modalPresentationStyle = .formSheet
  168. appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  169. }
  170. // MARK: - Copy & Paste
  171. func copyFile(ocIds: [String]) {
  172. var metadatas: [tableMetadata] = []
  173. var items = [[String : Any]]()
  174. for ocId in ocIds {
  175. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  176. metadatas.append(metadata)
  177. }
  178. }
  179. for metadata in metadatas {
  180. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  181. do {
  182. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  183. items.append([NCBrandGlobal.shared.metadataKeyedUnarchiver:etagPasteboard])
  184. } catch {
  185. print("error")
  186. }
  187. } else {
  188. NCNetworking.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorLoadCopy, setFavorite: false) { (_) in }
  189. }
  190. }
  191. UIPasteboard.general.setItems(items, options: [:])
  192. }
  193. func pasteFiles(serverUrl: String) {
  194. var listData: [String] = []
  195. for item in UIPasteboard.general.items {
  196. for object in item {
  197. let contentType = object.key
  198. let data = object.value
  199. if contentType == NCBrandGlobal.shared.metadataKeyedUnarchiver {
  200. do {
  201. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  202. uploadPasteOcId(ocId, serverUrl: serverUrl)
  203. }
  204. } catch {
  205. print("error")
  206. }
  207. continue
  208. }
  209. if data is String {
  210. if listData.contains(data as! String) {
  211. continue
  212. } else {
  213. listData.append(data as! String)
  214. }
  215. }
  216. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  217. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  218. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, serverUrl: serverUrl, data: data)
  219. }
  220. }
  221. }
  222. }
  223. private func uploadPasteFile(fileName: String, ext: String, contentType: String, serverUrl: String, data: Any) {
  224. do {
  225. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  226. let ocId = UUID().uuidString
  227. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  228. if data is UIImage {
  229. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  230. } else if data is Data {
  231. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  232. } else if data is String {
  233. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  234. } else {
  235. return
  236. }
  237. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  238. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  239. metadataForUpload.sessionSelector = NCBrandGlobal.shared.selectorUploadFile
  240. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  241. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  242. NCManageDatabase.shared.addMetadata(metadataForUpload)
  243. } catch { }
  244. }
  245. private func uploadPasteOcId(_ ocId: String, serverUrl: String) {
  246. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  247. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  248. let fileNameView = NCUtilityFileSystem.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  249. let ocId = NSUUID().uuidString
  250. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  251. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  252. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  253. metadataForUpload.sessionSelector = NCBrandGlobal.shared.selectorUploadFile
  254. metadataForUpload.size = metadata.size
  255. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  256. NCManageDatabase.shared.addMetadata(metadataForUpload)
  257. }
  258. }
  259. }
  260. }
  261. // MARK: - List Layout
  262. class NCListLayout: UICollectionViewFlowLayout {
  263. var itemHeight: CGFloat = 60
  264. override init() {
  265. super.init()
  266. sectionHeadersPinToVisibleBounds = false
  267. minimumInteritemSpacing = 0
  268. minimumLineSpacing = 1
  269. self.scrollDirection = .vertical
  270. self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  271. }
  272. required init?(coder aDecoder: NSCoder) {
  273. fatalError("init(coder:) has not been implemented")
  274. }
  275. override var itemSize: CGSize {
  276. get {
  277. if let collectionView = collectionView {
  278. let itemWidth: CGFloat = collectionView.frame.width
  279. return CGSize(width: itemWidth, height: self.itemHeight)
  280. }
  281. // Default fallback
  282. return CGSize(width: 100, height: 100)
  283. }
  284. set {
  285. super.itemSize = newValue
  286. }
  287. }
  288. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  289. return proposedContentOffset
  290. }
  291. }
  292. // MARK: - Grid Layout
  293. class NCGridLayout: UICollectionViewFlowLayout {
  294. var heightLabelPlusButton: CGFloat = 45
  295. var marginLeftRight: CGFloat = 6
  296. var itemForLine: CGFloat = 3
  297. var itemWidthDefault: CGFloat = 120
  298. override init() {
  299. super.init()
  300. sectionHeadersPinToVisibleBounds = false
  301. minimumInteritemSpacing = 1
  302. minimumLineSpacing = marginLeftRight
  303. self.scrollDirection = .vertical
  304. self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  305. }
  306. required init?(coder aDecoder: NSCoder) {
  307. fatalError("init(coder:) has not been implemented")
  308. }
  309. override var itemSize: CGSize {
  310. get {
  311. if let collectionView = collectionView {
  312. if collectionView.frame.width < 400 {
  313. itemForLine = 3
  314. } else {
  315. itemForLine = collectionView.frame.width / itemWidthDefault
  316. }
  317. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  318. let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
  319. return CGSize(width: itemWidth, height: itemHeight)
  320. }
  321. // Default fallback
  322. return CGSize(width: itemWidthDefault, height: itemWidthDefault)
  323. }
  324. set {
  325. super.itemSize = newValue
  326. }
  327. }
  328. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  329. return proposedContentOffset
  330. }
  331. }