NCMainCommon.swift 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 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. //MARK: - Main Common
  27. class NCMainCommon: NSObject, PhotoEditorDelegate, NCAudioRecorderViewControllerDelegate, UIDocumentInteractionControllerDelegate {
  28. @objc static let sharedInstance: NCMainCommon = {
  29. let instance = NCMainCommon()
  30. return instance
  31. }()
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. var metadataEditPhoto: tableMetadata?
  34. var docController: UIDocumentInteractionController?
  35. lazy var operationQueueReloadDatasource: OperationQueue = {
  36. let queue = OperationQueue()
  37. queue.name = "Reload main datasource queue"
  38. queue.maxConcurrentOperationCount = 1
  39. return queue
  40. }()
  41. //MARK: -
  42. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  43. if viewController.viewIfLoaded?.window == nil {
  44. return
  45. }
  46. guard let dic = notification.userInfo else {
  47. return
  48. }
  49. let account = dic["account"] as? NSString ?? ""
  50. let fileID = dic["fileID"] as? NSString ?? ""
  51. let serverUrl = dic["serverUrl"] as? String ?? ""
  52. let status = dic["status"] as? Int ?? Int(k_taskIdentifierDone)
  53. let progress = dic["progress"] as? CGFloat ?? 0
  54. let totalBytes = dic["totalBytes"] as? Double ?? 0
  55. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  56. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  57. return
  58. }
  59. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  60. return
  61. }
  62. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  63. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  64. return
  65. }
  66. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  67. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  68. var image = ""
  69. if status == k_metadataStatusInDownload {
  70. image = "↓"
  71. } else if status == k_metadataStatusInUpload {
  72. image = "↑"
  73. }
  74. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  75. cell.transferButton?.progress = progress
  76. }
  77. }
  78. }
  79. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  80. var actionReloadDatasource = k_action_NULL
  81. var metadata = metadata
  82. if metadata.session.count == 0 {
  83. return
  84. }
  85. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  86. return
  87. }
  88. // SESSION EXTENSION
  89. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  90. if (metadata.session == k_upload_session_extension) {
  91. do {
  92. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  93. } catch { }
  94. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  95. actionReloadDatasource = k_action_DEL
  96. } else {
  97. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  98. actionReloadDatasource = k_action_MOD
  99. }
  100. self.reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  101. return
  102. }
  103. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  104. var cancel = false
  105. // DOWNLOAD
  106. if metadata.session.count > 0 && metadata.session.contains("download") {
  107. for task in downloadTasks {
  108. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  109. task.cancel()
  110. cancel = true
  111. }
  112. }
  113. if cancel == false {
  114. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  115. }
  116. actionReloadDatasource = k_action_MOD
  117. }
  118. // UPLOAD
  119. if metadata.session.count > 0 && metadata.session.contains("upload") {
  120. for task in uploadTasks {
  121. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  122. if uploadStatusForcedStart {
  123. metadata.status = Int(k_metadataStatusUploadForcedStart)
  124. metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) ?? metadata
  125. }
  126. task.cancel()
  127. cancel = true
  128. }
  129. }
  130. if cancel == false {
  131. do {
  132. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  133. }
  134. catch { }
  135. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  136. }
  137. actionReloadDatasource = k_action_DEL
  138. }
  139. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  140. self.reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  141. }
  142. }
  143. }
  144. @objc func cancelAllTransfer() {
  145. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  146. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  147. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  148. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d AND status != %d", k_metadataStatusNormal, k_metadataStatusHide), sorted: "fileName", ascending: true) {
  149. for metadata in metadatas {
  150. // Modify
  151. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  152. metadata.session = ""
  153. metadata.sessionSelector = ""
  154. metadata.status = Int(k_metadataStatusNormal)
  155. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  156. }
  157. // Cancel Task
  158. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  159. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  160. }
  161. }
  162. }
  163. }
  164. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  165. return
  166. }
  167. }
  168. //MARK: -
  169. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectFileID: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController) {
  170. var image: UIImage?
  171. var isImagePreviewLoaded = false
  172. var tableShare: tableShare?
  173. // Image Preview
  174. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName)) {
  175. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName))
  176. isImagePreviewLoaded = true
  177. } else {
  178. if metadata.iconName.count > 0 {
  179. image = UIImage.init(named: metadata.iconName)
  180. } else {
  181. image = UIImage.init(named: "file")
  182. }
  183. }
  184. // Share
  185. if shares != nil {
  186. for share in shares! {
  187. if share.fileName == metadata.fileName {
  188. tableShare = share
  189. break
  190. }
  191. }
  192. }
  193. // Download preview
  194. if downloadThumbnail {
  195. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  196. }
  197. var isShare = false
  198. var isMounted = false
  199. if metadataFolder != nil {
  200. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  201. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  202. }
  203. if cell is NCListCell {
  204. let cell = cell as! NCListCell
  205. cell.delegate = source as? NCListCellDelegate
  206. cell.fileID = metadata.fileID
  207. cell.indexPath = indexPath
  208. cell.labelTitle.text = metadata.fileNameView
  209. cell.imageStatus.image = nil
  210. cell.imageLocal.image = nil
  211. cell.imageFavorite.image = nil
  212. cell.imageShare.image = nil
  213. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  214. if metadata.directory {
  215. if metadata.e2eEncrypted {
  216. image = UIImage.init(named: "folderEncrypted")
  217. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  218. image = UIImage.init(named: "folderAutomaticUpload")
  219. } else if isShare {
  220. image = UIImage.init(named: "folder_shared_with_me")
  221. } else if isMounted {
  222. image = UIImage.init(named: "folder_external")
  223. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  224. image = UIImage.init(named: "folder_shared_with_me")
  225. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  226. image = UIImage.init(named: "folder_public")
  227. } else {
  228. image = UIImage.init(named: "folder")
  229. }
  230. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  231. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  232. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  233. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  234. // Status image: passcode
  235. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  236. cell.imageStatus.image = UIImage.init(named: "passcode")
  237. }
  238. // Local image: offline
  239. if tableDirectory != nil && tableDirectory!.offline {
  240. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  241. }
  242. } else {
  243. cell.imageItem.image = image
  244. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  245. // image Local
  246. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  247. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  248. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  249. else { cell.imageLocal.image = UIImage.init(named: "local") }
  250. }
  251. // Share
  252. if (isShare) {
  253. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  254. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  255. } else if (isMounted) {
  256. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  257. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  258. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  259. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  260. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  261. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  262. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  263. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  264. }
  265. }
  266. // image Favorite
  267. if metadata.favorite {
  268. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  269. }
  270. if isEditMode {
  271. cell.imageItemLeftConstraint.constant = 45
  272. cell.imageSelect.isHidden = false
  273. if selectFileID.contains(metadata.fileID) {
  274. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  275. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  276. } else {
  277. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  278. cell.backgroundView = nil
  279. }
  280. } else {
  281. cell.imageItemLeftConstraint.constant = 10
  282. cell.imageSelect.isHidden = true
  283. cell.backgroundView = nil
  284. }
  285. // Remove last separator
  286. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  287. cell.separator.isHidden = true
  288. } else {
  289. cell.separator.isHidden = false
  290. }
  291. } else if cell is NCGridCell {
  292. let cell = cell as! NCGridCell
  293. cell.delegate = source as? NCGridCellDelegate
  294. cell.fileID = metadata.fileID
  295. cell.indexPath = indexPath
  296. cell.labelTitle.text = metadata.fileNameView
  297. cell.imageStatus.image = nil
  298. cell.imageLocal.image = nil
  299. cell.imageFavorite.image = nil
  300. cell.imageShare.image = nil
  301. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  302. if metadata.directory {
  303. if metadata.e2eEncrypted {
  304. image = UIImage.init(named: "folderEncrypted")
  305. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  306. image = UIImage.init(named: "folderAutomaticUpload")
  307. } else if isShare {
  308. image = UIImage.init(named: "folder_shared_with_me")
  309. } else if isMounted {
  310. image = UIImage.init(named: "folder_external")
  311. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  312. image = UIImage.init(named: "folder_shared_with_me")
  313. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  314. image = UIImage.init(named: "folder_public")
  315. } else {
  316. image = UIImage.init(named: "folder")
  317. }
  318. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  319. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  320. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  321. // Status image: passcode
  322. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  323. cell.imageStatus.image = UIImage.init(named: "passcode")
  324. }
  325. // Local image: offline
  326. if tableDirectory != nil && tableDirectory!.offline {
  327. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  328. }
  329. } else {
  330. cell.imageItem.image = image
  331. if isImagePreviewLoaded == false {
  332. let width = cell.imageItem.image!.size.width * 2
  333. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  334. }
  335. // image Local
  336. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  337. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  338. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  339. else { cell.imageLocal.image = UIImage.init(named: "local") }
  340. }
  341. // Share
  342. if (isShare) {
  343. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  344. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  345. } else if (isMounted) {
  346. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  347. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  348. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  349. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  350. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  351. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  352. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  353. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  354. }
  355. }
  356. // image Favorite
  357. if metadata.favorite {
  358. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  359. }
  360. if isEditMode {
  361. cell.imageSelect.isHidden = false
  362. if selectFileID.contains(metadata.fileID) {
  363. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  364. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  365. } else {
  366. cell.imageSelect.isHidden = true
  367. cell.backgroundView = nil
  368. }
  369. } else {
  370. cell.imageSelect.isHidden = true
  371. cell.backgroundView = nil
  372. }
  373. } else if cell is NCGridMediaCell {
  374. let cell = cell as! NCGridMediaCell
  375. cell.imageStatus.image = nil
  376. cell.imageLocal.image = nil
  377. cell.imageFavorite.image = nil
  378. cell.imageItem.image = image
  379. // image Local
  380. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  381. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  382. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  383. else { cell.imageLocal.image = UIImage.init(named: "local") }
  384. }
  385. // image Favorite
  386. if metadata.favorite {
  387. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  388. }
  389. if isEditMode {
  390. cell.imageSelect.isHidden = false
  391. if selectFileID.contains(metadata.fileID) {
  392. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  393. cell.imageVisualEffect.isHidden = false
  394. cell.imageVisualEffect.alpha = 0.4
  395. } else {
  396. cell.imageSelect.isHidden = true
  397. cell.imageVisualEffect.isHidden = true
  398. }
  399. } else {
  400. cell.imageSelect.isHidden = true
  401. cell.imageVisualEffect.isHidden = true
  402. }
  403. }
  404. }
  405. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?) -> UITableViewCell {
  406. var image: UIImage?
  407. // Create File System
  408. if metadata.directory {
  409. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  410. } else {
  411. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  412. }
  413. // CCCell
  414. if metadata.status == k_metadataStatusNormal {
  415. // NORMAL
  416. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  417. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  418. cell.accessoryType = UITableViewCell.AccessoryType.none
  419. cell.file.image = nil
  420. cell.status.image = nil
  421. cell.favorite.image = nil
  422. cell.shared.image = nil
  423. cell.local.image = nil
  424. cell.shared.isUserInteractionEnabled = false
  425. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  426. // change color selection
  427. let selectionColor = UIView()
  428. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  429. cell.selectedBackgroundView = selectionColor
  430. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  431. cell.labelTitle.textColor = UIColor.black
  432. cell.labelTitle.text = metadata.fileNameView
  433. // Download preview
  434. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  435. // Share
  436. var isShare = false
  437. var isMounted = false
  438. if metadataFolder != nil {
  439. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  440. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  441. }
  442. if metadata.directory {
  443. // lable Info
  444. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  445. // File Image & Image Title Segue
  446. if metadata.e2eEncrypted {
  447. image = UIImage.init(named: "folderEncrypted")
  448. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  449. image = UIImage.init(named: "folderAutomaticUpload")
  450. } else if isShare {
  451. image = UIImage.init(named: "folder_shared_with_me")
  452. } else if isMounted {
  453. image = UIImage.init(named: "folder_external")
  454. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  455. image = UIImage.init(named: "folder_shared_with_me")
  456. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  457. image = UIImage.init(named: "folder_public")
  458. } else {
  459. image = UIImage.init(named: "folder")
  460. }
  461. cell.file.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  462. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  463. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  464. // Local image: offline
  465. if tableDirectory != nil && tableDirectory!.offline {
  466. cell.local.image = UIImage.init(named: "offlineFlag")
  467. }
  468. // Status image: passcode
  469. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  470. cell.status.image = UIImage.init(named: "passcode")
  471. }
  472. } else {
  473. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  474. // Lable Info
  475. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  476. // File Image
  477. if iconFileExists {
  478. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  479. } else {
  480. if metadata.iconName.count > 0 {
  481. cell.file.image = UIImage.init(named: metadata.iconName)
  482. } else {
  483. cell.file.image = UIImage.init(named: "file")
  484. }
  485. }
  486. // Local Image - Offline
  487. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  488. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  489. if tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  490. else { cell.local.image = UIImage.init(named: "local") }
  491. }
  492. // Status image: encrypted
  493. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  494. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  495. cell.status.image = UIImage.init(named: "encrypted")
  496. }
  497. }
  498. //
  499. // File & Directory
  500. //
  501. // Favorite
  502. if metadata.favorite {
  503. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  504. }
  505. // Share
  506. if (isShare) {
  507. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  508. } else if (isMounted) {
  509. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  510. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  511. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  512. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  513. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  514. }
  515. // More Image
  516. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  517. return cell
  518. } else {
  519. // TRASNFER
  520. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  521. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  522. cell.accessoryType = UITableViewCell.AccessoryType.none
  523. cell.file.image = nil
  524. cell.status.image = nil
  525. cell.user.image = nil
  526. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  527. cell.labelTitle.textColor = UIColor.black
  528. cell.labelTitle.text = metadata.fileNameView
  529. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  530. var progress: CGFloat = 0.0
  531. var totalBytes: Double = 0.0
  532. //var totalBytesExpected : Double = 0
  533. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  534. if progressArray != nil && progressArray?.count == 3 {
  535. progress = progressArray?.object(at: 0) as! CGFloat
  536. totalBytes = progressArray?.object(at: 1) as! Double
  537. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  538. }
  539. // Write status on Label Info
  540. switch metadata.status {
  541. case Int(k_metadataStatusWaitDownload):
  542. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  543. progress = 0.0
  544. break
  545. case Int(k_metadataStatusInDownload):
  546. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  547. progress = 0.0
  548. break
  549. case Int(k_metadataStatusDownloading):
  550. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  551. break
  552. case Int(k_metadataStatusWaitUpload):
  553. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  554. progress = 0.0
  555. break
  556. case Int(k_metadataStatusInUpload):
  557. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  558. progress = 0.0
  559. break
  560. case Int(k_metadataStatusUploading):
  561. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  562. break
  563. default:
  564. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  565. progress = 0.0
  566. }
  567. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  568. if iconFileExists {
  569. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  570. } else {
  571. if metadata.iconName.count > 0 {
  572. cell.file.image = UIImage.init(named: metadata.iconName)
  573. } else {
  574. cell.file.image = UIImage.init(named: "file")
  575. }
  576. }
  577. // Session Upload Extension
  578. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  579. cell.labelTitle.isEnabled = false
  580. cell.labelInfoFile.isEnabled = false
  581. } else {
  582. cell.labelTitle.isEnabled = true
  583. cell.labelInfoFile.isEnabled = true
  584. }
  585. // downloadFile
  586. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  587. //
  588. }
  589. // downloadFile Error
  590. if metadata.status == k_metadataStatusDownloadError {
  591. cell.status.image = UIImage.init(named: "statuserror")
  592. if metadata.sessionError.count == 0 {
  593. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  594. } else {
  595. cell.labelInfoFile.text = metadata.sessionError
  596. }
  597. }
  598. // uploadFile
  599. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  600. if (!iconFileExists) {
  601. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  602. }
  603. cell.labelTitle.isEnabled = false
  604. }
  605. // uploadFileError
  606. if metadata.status == k_metadataStatusUploadError {
  607. cell.labelTitle.isEnabled = false
  608. cell.status.image = UIImage.init(named: "statuserror")
  609. if !iconFileExists {
  610. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  611. }
  612. if metadata.sessionError.count == 0 {
  613. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  614. } else {
  615. cell.labelInfoFile.text = metadata.sessionError
  616. }
  617. }
  618. // Progress
  619. cell.transferButton.progress = progress
  620. // User
  621. if metadata.account != appDelegate.activeAccount {
  622. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  623. if tableAccount != nil {
  624. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  625. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  626. if avatar != nil {
  627. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  628. let imageSize = avatarImageView?.bounds.size
  629. UIGraphicsBeginImageContext(imageSize!)
  630. let context = UIGraphicsGetCurrentContext()
  631. avatarImageView?.layer.render(in: context!)
  632. avatar = UIGraphicsGetImageFromCurrentImageContext()
  633. UIGraphicsEndImageContext()
  634. cell.user.image = avatar
  635. }
  636. }
  637. }
  638. return cell
  639. }
  640. }
  641. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  642. guard let indexPath = indexPath else {
  643. return nil
  644. }
  645. guard let sectionDataSource = sectionDataSource else {
  646. return nil
  647. }
  648. let section = indexPath.section + 1
  649. let row = indexPath.row + 1
  650. let totSections = sectionDataSource.sections.count
  651. if totSections < section || section > totSections {
  652. return nil
  653. }
  654. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  655. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  656. return nil
  657. }
  658. let totRows = filesID.count
  659. if totRows < row || row > totRows {
  660. return nil
  661. }
  662. let fileID = filesID.object(at: indexPath.row)
  663. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  664. return metadata
  665. }
  666. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  667. if operationQueueReloadDatasource.operationCount > 0 {
  668. return
  669. }
  670. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  671. self.operationQueueReloadDatasource.addOperation {
  672. DispatchQueue.main.async {
  673. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  674. }
  675. }
  676. }
  677. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  678. self.operationQueueReloadDatasource.addOperation {
  679. DispatchQueue.main.async {
  680. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  681. }
  682. }
  683. }
  684. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  685. self.operationQueueReloadDatasource.addOperation {
  686. DispatchQueue.main.async {
  687. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  688. }
  689. }
  690. }
  691. }
  692. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  693. if view is UICollectionView {
  694. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  695. }
  696. if view is UITableView {
  697. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  698. }
  699. return true
  700. }
  701. //MARK: -
  702. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  703. var copyMetadatas = [tableMetadata]()
  704. for metadata in metadatas {
  705. copyMetadatas.append(tableMetadata.init(value: metadata))
  706. }
  707. if e2ee {
  708. DispatchQueue.global().async {
  709. let error = NCNetworkingEndToEnd.sharedManager().lockFolderEncrypted(onServerUrl: serverUrl, fileID: folderFileID, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  710. DispatchQueue.main.async {
  711. if error == nil {
  712. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  713. } else {
  714. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  715. return
  716. }
  717. }
  718. }
  719. } else {
  720. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  721. }
  722. }
  723. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  724. var count: Int = 0
  725. var completionErrorCode: Int = 0
  726. var completionMessage = ""
  727. for metadata in metadatas {
  728. self.appDelegate.filterFileID.add(metadata.fileID)
  729. let path = metadata.serverUrl + "/" + metadata.fileName
  730. OCNetworking.sharedManager().deleteFileOrFolder(withAccount: appDelegate.activeAccount, path: path, completion: { (account, message, errorCode) in
  731. if account == self.appDelegate.activeAccount {
  732. count += 1
  733. if errorCode == 0 || errorCode == kOCErrorServerPathNotFound {
  734. do {
  735. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  736. } catch { }
  737. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  738. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  739. if metadata.directory {
  740. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName), account: metadata.account)
  741. }
  742. if (e2ee) {
  743. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  744. }
  745. self.appDelegate.filterFileID.remove(metadata.fileID)
  746. } else {
  747. completionErrorCode = errorCode
  748. completionMessage = ""
  749. if message != nil {
  750. completionMessage = message!
  751. }
  752. self.appDelegate.filterFileID.remove(metadata.fileID)
  753. }
  754. if count == metadatas.count {
  755. if e2ee {
  756. DispatchQueue.global().async {
  757. NCNetworkingEndToEnd.sharedManager().rebuildAndSendMetadata(onServerUrl: serverUrl, account: self.appDelegate.activeAccount, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  758. DispatchQueue.main.async {
  759. completion(completionErrorCode, completionMessage)
  760. }
  761. }
  762. } else {
  763. completion(completionErrorCode, completionMessage)
  764. }
  765. }
  766. }
  767. })
  768. }
  769. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  770. }
  771. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  772. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  773. return
  774. }
  775. guard let image = UIImage(contentsOfFile: path) else {
  776. return
  777. }
  778. self.metadataEditPhoto = metadata
  779. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  780. photoEditor.image = image
  781. photoEditor.photoEditorDelegate = self
  782. photoEditor.hiddenControls = [.save, .share, .sticker]
  783. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  784. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  785. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  786. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  787. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  788. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  789. viewController.present(photoEditor, animated: true, completion: nil)
  790. }
  791. func doneEditing(image: UIImage) {
  792. guard let metadata = self.metadataEditPhoto else {
  793. return
  794. }
  795. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  796. return
  797. }
  798. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  799. return
  800. }
  801. if filetype == "PNG" {
  802. do {
  803. try image.pngData()?.write(to: NSURL(fileURLWithPath:path) as URL, options: .atomic)
  804. } catch { return }
  805. } else if filetype == "JPG" {
  806. let imageData = image.jpegData(compressionQuality: 1)
  807. do {
  808. try imageData?.write(to: NSURL(fileURLWithPath:path) as URL)
  809. } catch { return }
  810. }
  811. // write icon
  812. CCGraphics.createNewImage(from: metadata.fileNameView, fileID: metadata.fileID, extension: filetype, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  813. // upload
  814. metadata.session = k_upload_session
  815. metadata.sessionSelector = selectorUploadFile
  816. metadata.status = Int(k_metadataStatusWaitUpload)
  817. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  818. }
  819. func canceledEditing() {
  820. print("Canceled")
  821. }
  822. //MARK: - OpenIn
  823. @objc func downloadOpenIn(metadata: tableMetadata) {
  824. if CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  825. openIn(metadata: metadata)
  826. } else {
  827. metadata.session = k_download_session
  828. metadata.sessionError = ""
  829. metadata.sessionSelector = selectorOpenIn
  830. metadata.status = Int(k_metadataStatusWaitDownload)
  831. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  832. reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: k_action_MOD)
  833. }
  834. }
  835. func openIn(metadata: tableMetadata) {
  836. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)) as URL)
  837. docController?.delegate = self
  838. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController else {
  839. return
  840. }
  841. guard let view = splitViewController.viewControllers.first?.view else {
  842. return
  843. }
  844. guard let frame = splitViewController.viewControllers.first?.view.frame else {
  845. return
  846. }
  847. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  848. }
  849. //MARK: - NCAudioRecorder
  850. func startAudioRecorder() {
  851. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  852. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  853. viewController.delegate = self
  854. viewController.createRecorder(fileName: fileName)
  855. viewController.modalTransitionStyle = .crossDissolve
  856. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  857. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  858. }
  859. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  860. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  861. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  862. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  863. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  864. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  865. }
  866. }
  867. //MARK: - Main TabBarController
  868. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  869. override func viewDidLoad() {
  870. super.viewDidLoad()
  871. delegate = self
  872. }
  873. //Delegate methods
  874. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  875. let tabViewControllers = tabBarController.viewControllers!
  876. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  877. if let vc = viewController as? UINavigationController {
  878. vc.popToRootViewController(animated: true);
  879. }
  880. return false
  881. }
  882. animateToTab(toIndex: toIndex)
  883. return true
  884. }
  885. func animateToTab(toIndex: Int) {
  886. let tabViewControllers = viewControllers!
  887. let fromView = selectedViewController!.view!
  888. let toView = tabViewControllers[toIndex].view!
  889. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  890. guard fromIndex != toIndex else {return}
  891. // Add the toView to the tab bar view
  892. fromView.superview?.addSubview(toView)
  893. fromView.superview?.backgroundColor = UIColor.white
  894. // Position toView off screen (to the left/right of fromView)
  895. let screenWidth = UIScreen.main.bounds.size.width;
  896. let scrollRight = toIndex > fromIndex!;
  897. let offset = (scrollRight ? screenWidth : -screenWidth)
  898. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  899. // Disable interaction during animation
  900. view.isUserInteractionEnabled = false
  901. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  902. // Slide the views by -offset
  903. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  904. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  905. }, completion: { finished in
  906. // Remove the old view from the tabbar view.
  907. fromView.removeFromSuperview()
  908. self.selectedIndex = toIndex
  909. self.view.isUserInteractionEnabled = true
  910. })
  911. }
  912. }
  913. //
  914. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  915. //
  916. extension UITabBar {
  917. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  918. // the Master view controller shows the UITabBarItem icon next to the text
  919. override open var traitCollection: UITraitCollection {
  920. if UIDevice.current.userInterfaceIdiom == .pad {
  921. return UITraitCollection(horizontalSizeClass: .compact)
  922. }
  923. return super.traitCollection
  924. }
  925. }
  926. //MARK: - Networking Main
  927. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  928. @objc static let sharedInstance: NCNetworkingMain = {
  929. let instance = NCNetworkingMain()
  930. return instance
  931. }()
  932. lazy var operationQueueNetworkingMain: OperationQueue = {
  933. let queue = OperationQueue()
  934. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  935. queue.maxConcurrentOperationCount = 1
  936. return queue
  937. }()
  938. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  939. // DOWNLOAD
  940. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  941. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  942. appDelegate.updateApplicationIconBadgeNumber()
  943. }
  944. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  945. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  946. return
  947. }
  948. if metadata.account != appDelegate.activeAccount {
  949. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  950. return
  951. }
  952. if errorCode == 0 {
  953. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  954. // Synchronized
  955. if selector == selectorDownloadSynchronize {
  956. appDelegate.updateApplicationIconBadgeNumber()
  957. appDelegate.startLoadAutoDownloadUpload()
  958. return
  959. }
  960. // Modify Photo
  961. if selector == selectorDownloadEditPhoto {
  962. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  963. return
  964. }
  965. // open View File
  966. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  967. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  968. if uti == nil {
  969. uti = ""
  970. } else if uti!.contains("opendocument") && !NCUtility.sharedInstance.isRichDocument(metadata) {
  971. metadata.typeFile = k_metadataTypeFile_unknown
  972. }
  973. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  974. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  975. let destination = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  976. try? FileManager().unzipItem(at: source, to: destination)
  977. let bundleDirectory = IMImagemeter.sharedInstance.getBundleDirectory(metadata: metadata)
  978. if bundleDirectory.error {
  979. appDelegate.messageNotification("_error_", description: "Bundle imagemeter error. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  980. return
  981. }
  982. if let fileHandle = FileHandle(forReadingAtPath: bundleDirectory.immPath) {
  983. let dataFormat = fileHandle.readData(ofLength: 1)
  984. if dataFormat.starts(with: [0x01]) {
  985. appDelegate.messageNotification("_error_", description: "File format binary error, library imagemeter not present. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  986. return;
  987. }
  988. let dataZip = fileHandle.readData(ofLength: 4)
  989. if dataZip.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
  990. try? FileManager().unzipItem(at: NSURL(fileURLWithPath: bundleDirectory.immPath) as URL, to: NSURL(fileURLWithPath: bundleDirectory.bundleDirectory) as URL)
  991. }
  992. fileHandle.closeFile()
  993. }
  994. }
  995. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  996. NCMainCommon.sharedInstance.openIn(metadata: metadata)
  997. } else {
  998. if appDelegate.activeMain.view.window != nil {
  999. appDelegate.activeMain.shouldPerformSegue(metadata)
  1000. }
  1001. if appDelegate.activeFavorites.view.window != nil {
  1002. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  1003. }
  1004. }
  1005. }
  1006. // Open in...
  1007. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  1008. NCMainCommon.sharedInstance.openIn(metadata: metadata)
  1009. }
  1010. // Save to Photo Album
  1011. if selector == selectorSave {
  1012. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  1013. }
  1014. // Copy File
  1015. if selector == selectorLoadCopy {
  1016. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  1017. }
  1018. // Set as available offline
  1019. if selector == selectorLoadOffline {
  1020. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  1021. }
  1022. //selectorLoadViewImage
  1023. if selector == selectorLoadViewImage {
  1024. if appDelegate.activeDetail != nil {
  1025. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1026. }
  1027. }
  1028. appDelegate.startLoadAutoDownloadUpload()
  1029. } else {
  1030. // File do not exists on server, remove in local
  1031. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  1032. do {
  1033. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  1034. } catch { }
  1035. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  1036. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  1037. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  1038. }
  1039. if selector == selectorLoadViewImage {
  1040. if appDelegate.activeDetail.view.window != nil {
  1041. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1042. }
  1043. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1044. }
  1045. }
  1046. appDelegate.startLoadAutoDownloadUpload()
  1047. }
  1048. // UPLOAD
  1049. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  1050. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1051. appDelegate.updateApplicationIconBadgeNumber()
  1052. }
  1053. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  1054. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  1055. return
  1056. }
  1057. if metadata.account != appDelegate.activeAccount {
  1058. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1059. return
  1060. }
  1061. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1062. if errorCode == 0 {
  1063. appDelegate.startLoadAutoDownloadUpload()
  1064. } else {
  1065. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1066. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1067. }
  1068. }
  1069. }
  1070. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1071. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  1072. }
  1073. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  1074. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1075. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  1076. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  1077. OCNetworking.sharedManager().downloadPreview(withAccount: metadata.account, metadata: metadata, withWidth: width, andHeight: height, completion: { (account, image, message, errorCode) in
  1078. if errorCode == 0 && account == self.appDelegate.activeAccount && !metadata.isInvalidated && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  1079. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1080. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1081. if cell is NCListCell {
  1082. (cell as! NCListCell).imageItem.image = image
  1083. } else if cell is NCGridCell {
  1084. (cell as! NCGridCell).imageItem.image = image
  1085. } else if cell is NCGridMediaCell {
  1086. (cell as! NCGridMediaCell).imageItem.image = image
  1087. }
  1088. }
  1089. }
  1090. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1091. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1092. if cell is CCCellMainTransfer {
  1093. (cell as! CCCellMainTransfer).file.image = image
  1094. } else if cell is CCCellMain {
  1095. (cell as! CCCellMain).file.image = image
  1096. }
  1097. }
  1098. }
  1099. }
  1100. return closure()
  1101. })
  1102. }
  1103. return closure()
  1104. }
  1105. }
  1106. //MARK: - Operation Networking Main
  1107. class NCOperationNetworkingMain: Operation {
  1108. private var _executing : Bool = false
  1109. override var isExecuting : Bool {
  1110. get { return _executing }
  1111. set {
  1112. guard _executing != newValue else { return }
  1113. willChangeValue(forKey: "isExecuting")
  1114. _executing = newValue
  1115. didChangeValue(forKey: "isExecuting")
  1116. }
  1117. }
  1118. private var _finished : Bool = false
  1119. override var isFinished : Bool {
  1120. get { return _finished }
  1121. set {
  1122. guard _finished != newValue else { return }
  1123. willChangeValue(forKey: "isFinished")
  1124. _finished = newValue
  1125. didChangeValue(forKey: "isFinished")
  1126. }
  1127. }
  1128. private var metadata: tableMetadata?
  1129. private var view: Any?
  1130. private var indexPath: IndexPath?
  1131. private var networkingFunc: String = ""
  1132. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  1133. super.init()
  1134. if metadata != nil { self.metadata = metadata! }
  1135. if view != nil { self.view = view! }
  1136. if indexPath != nil { self.indexPath = indexPath! }
  1137. self.networkingFunc = networkingFunc
  1138. }
  1139. override func start() {
  1140. if !Thread.isMainThread {
  1141. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  1142. } else {
  1143. isExecuting = true
  1144. if isCancelled {
  1145. finish()
  1146. } else {
  1147. poolNetworking()
  1148. }
  1149. }
  1150. }
  1151. func finish() {
  1152. isExecuting = false
  1153. isFinished = true
  1154. }
  1155. override func cancel() {
  1156. super.cancel()
  1157. if isExecuting {
  1158. complete()
  1159. }
  1160. }
  1161. func complete() {
  1162. finish()
  1163. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  1164. }
  1165. func poolNetworking() {
  1166. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  1167. switch networkingFunc {
  1168. case "downloadThumbnail":
  1169. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  1170. self.complete()
  1171. }
  1172. default:
  1173. print("error")
  1174. }
  1175. }
  1176. }
  1177. //MARK: - Function Main
  1178. class NCFunctionMain: NSObject {
  1179. @objc static let sharedInstance: NCFunctionMain = {
  1180. let instance = NCFunctionMain()
  1181. return instance
  1182. }()
  1183. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1184. @objc func synchronizeOffline() {
  1185. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1186. if (directories != nil) {
  1187. for directory: tableDirectory in directories! {
  1188. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1189. }
  1190. }
  1191. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1192. if (files != nil) {
  1193. for file: tableLocalFile in files! {
  1194. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  1195. continue
  1196. }
  1197. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1198. }
  1199. }
  1200. }
  1201. }