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