NCMainCommon.swift 72 KB

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