NCCollectionCommon.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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], viewController: UIViewController) {
  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. viewController.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: - Save Photo - Video - Live Photo
  171. func saveAlbum(metadata: tableMetadata) {
  172. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  173. let status = PHPhotoLibrary.authorizationStatus()
  174. if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileImage && status == PHAuthorizationStatus.authorized {
  175. if let image = UIImage.init(contentsOfFile: fileNamePath) {
  176. UIImageWriteToSavedPhotosAlbum(image, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  177. } else {
  178. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorFileNotSaved)
  179. }
  180. } else if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo && status == PHAuthorizationStatus.authorized {
  181. if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath) {
  182. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  183. } else {
  184. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorFileNotSaved)
  185. }
  186. } else if status != PHAuthorizationStatus.authorized {
  187. NCContentPresenter.shared.messageNotification("_access_photo_not_enabled_", description: "_access_photo_not_enabled_msg_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorFileNotSaved)
  188. }
  189. }
  190. @objc private func SaveAlbum(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
  191. if error != nil {
  192. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorFileNotSaved)
  193. }
  194. }
  195. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  196. if !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  197. NCOperationQueue.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorSaveAlbumLivePhotoIMG)
  198. }
  199. if !CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  200. NCOperationQueue.shared.download(metadata: metadataMOV, selector: NCBrandGlobal.shared.selectorSaveAlbumLivePhotoMOV)
  201. }
  202. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  203. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV, progressView: nil, viewActivity: self.appDelegate.window.rootViewController?.view)
  204. }
  205. }
  206. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata, progressView: UIProgressView?, viewActivity: UIView?) {
  207. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  208. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  209. if let view = viewActivity {
  210. NCUtility.shared.startActivityIndicator(view: view)
  211. }
  212. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  213. DispatchQueue.main.async {
  214. progressView?.progress = Float(progress)
  215. }
  216. }, completion: { livePhoto, resources in
  217. NCUtility.shared.stopActivityIndicator()
  218. progressView?.progress = 0
  219. if resources != nil {
  220. NCLivePhoto.saveToLibrary(resources!) { (result) in
  221. if !result {
  222. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorInternalError)
  223. }
  224. }
  225. } else {
  226. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCBrandGlobal.shared.ErrorInternalError)
  227. }
  228. })
  229. }
  230. // MARK: - Context Menu COnfiguration
  231. @available(iOS 13.0, *)
  232. func contextMenuConfiguration(metadata: tableMetadata, viewController: UIViewController, enableDeleteLocal: Bool, enableViewInFolder: Bool) -> UIMenu {
  233. var titleDeleteConfirmFile = NSLocalizedString("_delete_file_", comment: "")
  234. if metadata.directory { titleDeleteConfirmFile = NSLocalizedString("_delete_folder_", comment: "") }
  235. var titleSave: String = NSLocalizedString("_save_selected_files_", comment: "")
  236. let metadataMOV = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  237. if metadataMOV != nil {
  238. titleSave = NSLocalizedString("_livephoto_save_", comment: "")
  239. }
  240. let copy = UIAction(title: NSLocalizedString("_copy_file_", comment: ""), image: UIImage(systemName: "doc.on.doc") ) { action in
  241. self.appDelegate.pasteboardOcIds = [metadata.ocId]
  242. self.copyPasteboard()
  243. }
  244. let detail = UIAction(title: NSLocalizedString("_details_", comment: ""), image: UIImage(systemName: "info") ) { action in
  245. NCNetworkingNotificationCenter.shared.openShare(ViewController: viewController, metadata: metadata, indexPage: 0)
  246. }
  247. let save = UIAction(title: titleSave, image: UIImage(systemName: "square.and.arrow.down")) { action in
  248. if metadataMOV != nil {
  249. NCCollectionCommon.shared.saveLivePhoto(metadata: metadata, metadataMOV: metadataMOV!)
  250. } else {
  251. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  252. self.saveAlbum(metadata: metadata)
  253. } else {
  254. NCOperationQueue.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorSaveAlbum)
  255. }
  256. }
  257. }
  258. let viewInFolder = UIAction(title: NSLocalizedString("_view_in_folder_", comment: ""), image: UIImage(systemName: "arrow.forward.square")) { action in
  259. NCCollectionCommon.shared.openFileViewInFolder(serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  260. }
  261. let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { action in
  262. NCNetworkingNotificationCenter.shared.downloadOpen(metadata: metadata, selector: NCBrandGlobal.shared.selectorOpenIn)
  263. }
  264. let openQuickLook = UIAction(title: NSLocalizedString("_open_quicklook_", comment: ""), image: UIImage(systemName: "eye")) { action in
  265. NCNetworkingNotificationCenter.shared.downloadOpen(metadata: metadata, selector: NCBrandGlobal.shared.selectorLoadFileQuickLook)
  266. }
  267. let open = UIMenu(title: NSLocalizedString("_open_", comment: ""), image: UIImage(systemName: "square.and.arrow.up"), children: [openIn, openQuickLook])
  268. let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { action in
  269. NCCollectionCommon.shared.openSelectView(items: [metadata], viewController: viewController)
  270. }
  271. let deleteConfirmFile = UIAction(title: titleDeleteConfirmFile, image: UIImage(systemName: "trash"), attributes: .destructive) { action in
  272. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: false) { (errorCode, errorDescription) in
  273. if errorCode != 0 {
  274. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  275. }
  276. }
  277. }
  278. let deleteConfirmLocal = UIAction(title: NSLocalizedString("_remove_local_file_", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { action in
  279. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: true) { (errorCode, errorDescription) in
  280. }
  281. }
  282. var delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmLocal, deleteConfirmFile])
  283. if !enableDeleteLocal {
  284. delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
  285. }
  286. if metadata.directory {
  287. delete = UIMenu(title: NSLocalizedString("_delete_folder_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
  288. }
  289. if metadata.directory {
  290. return UIMenu(title: "", children: [detail, moveCopy, delete])
  291. }
  292. var children: [UIMenuElement] = [copy, detail, moveCopy, open, delete]
  293. if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo {
  294. children.insert(save, at: 4)
  295. }
  296. if enableViewInFolder {
  297. children.insert(viewInFolder, at: 2)
  298. }
  299. return UIMenu(title: "", image: nil, identifier: nil, children: children)
  300. }
  301. // MARK: - Copy & Paste
  302. func copyPasteboard() {
  303. var metadatas: [tableMetadata] = []
  304. var items = [[String : Any]]()
  305. for ocId in appDelegate.pasteboardOcIds {
  306. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId as? String) {
  307. metadatas.append(metadata)
  308. if let metadataMOV = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  309. metadatas.append(metadataMOV)
  310. }
  311. }
  312. }
  313. for metadata in metadatas {
  314. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  315. do {
  316. // Get Data
  317. let data = try Data.init(contentsOf: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  318. // Pasteboard item
  319. if let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (metadata.fileNameView as NSString).pathExtension as CFString, nil) {
  320. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  321. items.append([fileUTI:data])
  322. }
  323. } catch {
  324. print("error")
  325. }
  326. } else {
  327. NCNetworking.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorLoadCopy) { (_) in }
  328. }
  329. }
  330. UIPasteboard.general.setItems(items, options: [:])
  331. }
  332. func pastePasteboard(serverUrl: String) {
  333. for (index, items) in UIPasteboard.general.items.enumerated() {
  334. for item in items {
  335. let contentType = item.key
  336. if let data = UIPasteboard.general.data(forPasteboardType: contentType, inItemSet: IndexSet([index]))?.first {
  337. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  338. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  339. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, serverUrl: serverUrl, data: data)
  340. }
  341. }
  342. }
  343. }
  344. }
  345. private func uploadPasteFile(fileName: String, ext: String, contentType: String, serverUrl: String, data: Data) {
  346. do {
  347. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  348. let ocId = UUID().uuidString
  349. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  350. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  351. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  352. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  353. metadataForUpload.sessionSelector = NCBrandGlobal.shared.selectorUploadFile
  354. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  355. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  356. NCManageDatabase.shared.addMetadata(metadataForUpload)
  357. } catch { }
  358. }
  359. }
  360. // MARK: - List Layout
  361. class NCListLayout: UICollectionViewFlowLayout {
  362. var itemHeight: CGFloat = 60
  363. override init() {
  364. super.init()
  365. sectionHeadersPinToVisibleBounds = false
  366. minimumInteritemSpacing = 0
  367. minimumLineSpacing = 1
  368. self.scrollDirection = .vertical
  369. self.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  370. }
  371. required init?(coder aDecoder: NSCoder) {
  372. fatalError("init(coder:) has not been implemented")
  373. }
  374. override var itemSize: CGSize {
  375. get {
  376. if let collectionView = collectionView {
  377. let itemWidth: CGFloat = collectionView.frame.width
  378. return CGSize(width: itemWidth, height: self.itemHeight)
  379. }
  380. // Default fallback
  381. return CGSize(width: 100, height: 100)
  382. }
  383. set {
  384. super.itemSize = newValue
  385. }
  386. }
  387. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  388. return proposedContentOffset
  389. }
  390. }
  391. // MARK: - Grid Layout
  392. class NCGridLayout: UICollectionViewFlowLayout {
  393. var heightLabelPlusButton: CGFloat = 45
  394. var marginLeftRight: CGFloat = 6
  395. var itemForLine: CGFloat = 3
  396. var itemWidthDefault: CGFloat = 120
  397. override init() {
  398. super.init()
  399. sectionHeadersPinToVisibleBounds = false
  400. minimumInteritemSpacing = 1
  401. minimumLineSpacing = marginLeftRight
  402. self.scrollDirection = .vertical
  403. self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  404. }
  405. required init?(coder aDecoder: NSCoder) {
  406. fatalError("init(coder:) has not been implemented")
  407. }
  408. override var itemSize: CGSize {
  409. get {
  410. if let collectionView = collectionView {
  411. if collectionView.frame.width < 400 {
  412. itemForLine = 3
  413. } else {
  414. itemForLine = collectionView.frame.width / itemWidthDefault
  415. }
  416. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  417. let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
  418. return CGSize(width: itemWidth, height: itemHeight)
  419. }
  420. // Default fallback
  421. return CGSize(width: itemWidthDefault, height: itemWidthDefault)
  422. }
  423. set {
  424. super.itemSize = newValue
  425. }
  426. }
  427. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  428. return proposedContentOffset
  429. }
  430. }