NCMainCommon.swift 76 KB

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