NCMainCommon.swift 77 KB

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