NCMainCommon.swift 80 KB

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