NCMainCommon.swift 78 KB

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