NCMainCommon.swift 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  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(serverUrl: 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(serverUrl: 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. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  776. guard let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  777. return
  778. }
  779. guard let image = UIImage(contentsOfFile: path) else {
  780. return
  781. }
  782. self.metadataEditPhoto = metadata
  783. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  784. photoEditor.image = image
  785. photoEditor.photoEditorDelegate = self
  786. photoEditor.hiddenControls = [.save, .share, .sticker]
  787. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  788. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  789. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  790. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  791. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  792. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  793. photoEditor.modalPresentationStyle = .fullScreen
  794. viewController.present(photoEditor, animated: true, completion: nil)
  795. }
  796. func doneEditing(image: UIImage) {
  797. guard let metadata = self.metadataEditPhoto else {
  798. return
  799. }
  800. guard let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  801. return
  802. }
  803. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  804. return
  805. }
  806. if filetype == "PNG" {
  807. do {
  808. try image.pngData()?.write(to: NSURL(fileURLWithPath:path) as URL, options: .atomic)
  809. } catch { return }
  810. } else if filetype == "JPG" {
  811. let imageData = image.jpegData(compressionQuality: 1)
  812. do {
  813. try imageData?.write(to: NSURL(fileURLWithPath:path) as URL)
  814. } catch { return }
  815. }
  816. // write icon
  817. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  818. // upload
  819. metadata.session = k_upload_session
  820. metadata.sessionSelector = selectorUploadFile
  821. metadata.status = Int(k_metadataStatusWaitUpload)
  822. NCManageDatabase.sharedInstance.addMetadata(metadata)
  823. }
  824. func canceledEditing() {
  825. print("Canceled")
  826. }
  827. //MARK: - download Open Selector
  828. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  829. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  830. NCNetworkingMain.sharedInstance.downloadFileSuccessFailure(metadata.fileName, ocId: metadata.ocId, serverUrl: metadata.serverUrl, selector: selector, errorMessage: "", errorCode: 0)
  831. } else {
  832. metadata.session = k_download_session
  833. metadata.sessionError = ""
  834. metadata.sessionSelector = selector //selectorOpenIn
  835. metadata.status = Int(k_metadataStatusWaitDownload)
  836. NCManageDatabase.sharedInstance.addMetadata(metadata)
  837. reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: k_action_MOD)
  838. }
  839. }
  840. //MARK: - OpenIn
  841. func openIn(metadata: tableMetadata, selector: String) {
  842. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  843. docController?.delegate = self
  844. if selector == selectorOpenInDetail {
  845. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  846. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  847. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  848. } else {
  849. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  850. return }
  851. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  852. }
  853. }
  854. //MARK: - OpenShare
  855. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  856. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  857. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  858. shareViewController.metadata = metadata
  859. shareViewController.indexPage = indexPage
  860. shareNavigationController.modalPresentationStyle = .formSheet
  861. ViewController.present(shareNavigationController, animated: true, completion: nil)
  862. }
  863. //MARK: - NCAudioRecorder
  864. func startAudioRecorder() {
  865. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  866. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  867. viewController.delegate = self
  868. viewController.createRecorder(fileName: fileName)
  869. viewController.modalTransitionStyle = .crossDissolve
  870. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  871. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  872. }
  873. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  874. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  875. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  876. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  877. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  878. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  879. }
  880. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  881. }
  882. }
  883. //MARK: - Main TabBarController
  884. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  885. override func viewDidLoad() {
  886. super.viewDidLoad()
  887. delegate = self
  888. }
  889. //Delegate methods
  890. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  891. let tabViewControllers = tabBarController.viewControllers!
  892. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  893. if let vc = viewController as? UINavigationController {
  894. vc.popToRootViewController(animated: true);
  895. }
  896. return false
  897. }
  898. animateToTab(toIndex: toIndex)
  899. return true
  900. }
  901. func animateToTab(toIndex: Int) {
  902. let tabViewControllers = viewControllers!
  903. let fromView = selectedViewController!.view!
  904. let toView = tabViewControllers[toIndex].view!
  905. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  906. guard fromIndex != toIndex else {return}
  907. // Add the toView to the tab bar view
  908. fromView.superview?.addSubview(toView)
  909. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  910. // Position toView off screen (to the left/right of fromView)
  911. let screenWidth = UIScreen.main.bounds.size.width;
  912. let scrollRight = toIndex > fromIndex!;
  913. let offset = (scrollRight ? screenWidth : -screenWidth)
  914. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  915. // Disable interaction during animation
  916. view.isUserInteractionEnabled = false
  917. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  918. // Slide the views by -offset
  919. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  920. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  921. }, completion: { finished in
  922. // Remove the old view from the tabbar view.
  923. fromView.removeFromSuperview()
  924. self.selectedIndex = toIndex
  925. self.view.isUserInteractionEnabled = true
  926. })
  927. }
  928. }
  929. //
  930. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  931. //
  932. extension UITabBar {
  933. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  934. // the Master view controller shows the UITabBarItem icon next to the text
  935. override open var traitCollection: UITraitCollection {
  936. if UIDevice.current.userInterfaceIdiom == .pad {
  937. return UITraitCollection(horizontalSizeClass: .compact)
  938. }
  939. return super.traitCollection
  940. }
  941. }
  942. //MARK: - Networking Main
  943. class NCNetworkingMain: NSObject, CCNetworkingDelegate, IMImagemeterViewerDelegate {
  944. @objc static let sharedInstance: NCNetworkingMain = {
  945. let instance = NCNetworkingMain()
  946. return instance
  947. }()
  948. lazy var operationQueueNetworkingMain: OperationQueue = {
  949. let queue = OperationQueue()
  950. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  951. queue.maxConcurrentOperationCount = 1
  952. return queue
  953. }()
  954. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  955. // DOWNLOAD
  956. func downloadStart(_ ocId: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  957. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  958. appDelegate.updateApplicationIconBadgeNumber()
  959. }
  960. func downloadFileSuccessFailure(_ fileName: String!, ocId: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  961. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else {
  962. return
  963. }
  964. if metadata.account != appDelegate.activeAccount {
  965. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  966. return
  967. }
  968. if errorCode == 0 {
  969. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  970. // Synchronized
  971. if selector == selectorDownloadSynchronize {
  972. appDelegate.updateApplicationIconBadgeNumber()
  973. appDelegate.startLoadAutoDownloadUpload()
  974. return
  975. }
  976. // Modify Photo
  977. if selector == selectorDownloadEditPhoto {
  978. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  979. return
  980. }
  981. // open View File
  982. if (selector == selectorLoadFileView || selector == selectorLoadFileViewFavorite || selector == selectorLoadFileInternalView) && UIApplication.shared.applicationState == UIApplication.State.active {
  983. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  984. if uti == nil {
  985. uti = ""
  986. } else if uti!.contains("opendocument") && !NCUtility.sharedInstance.isRichDocument(metadata) {
  987. metadata.typeFile = k_metadataTypeFile_unknown
  988. }
  989. #if HC
  990. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  991. if !IMUtility.shared.IMUnzip(metadata: metadata) {
  992. NCContentPresenter.shared.messageNotification("_error_", description: "Bundle imagemeter error. 🤷‍♂️", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: 0)
  993. return
  994. }
  995. let storyboard = UIStoryboard(name: "IMImagemeter", bundle: nil)
  996. let imagemeterViewer = storyboard.instantiateInitialViewController() as! IMImagemeterViewer
  997. imagemeterViewer.metadata = metadata
  998. imagemeterViewer.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  999. imagemeterViewer.imagemeterViewerDelegate = self
  1000. self.appDelegate.window.rootViewController?.present(imagemeterViewer, animated: true, completion: nil)
  1001. return
  1002. }
  1003. #else
  1004. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  1005. NCMainCommon.sharedInstance.openIn(metadata: metadata, selector: selector)
  1006. return
  1007. }
  1008. #endif
  1009. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  1010. NCMainCommon.sharedInstance.openIn(metadata: metadata, selector: selector)
  1011. } else {
  1012. if appDelegate.activeMain.view.window != nil {
  1013. appDelegate.activeMain.shouldPerformSegue(metadata, selector: selector)
  1014. }
  1015. if appDelegate.activeFavorites.view.window != nil {
  1016. appDelegate.activeFavorites.shouldPerformSegue(metadata, selector: selector)
  1017. }
  1018. }
  1019. }
  1020. // Open in...
  1021. if (selector == selectorOpenIn || selector == selectorOpenInDetail) && UIApplication.shared.applicationState == UIApplication.State.active {
  1022. NCMainCommon.sharedInstance.openIn(metadata: metadata, selector: selector)
  1023. }
  1024. // Save to Photo Album
  1025. if selector == selectorSave {
  1026. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  1027. }
  1028. // Copy File
  1029. if selector == selectorLoadCopy {
  1030. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  1031. }
  1032. // Set as available offline
  1033. if selector == selectorLoadOffline {
  1034. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, offline: true)
  1035. }
  1036. appDelegate.startLoadAutoDownloadUpload()
  1037. } else {
  1038. // File do not exists on server, remove in local
  1039. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  1040. do {
  1041. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  1042. } catch { }
  1043. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1044. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1045. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_DEL))
  1046. }
  1047. }
  1048. appDelegate.startLoadAutoDownloadUpload()
  1049. }
  1050. #if HC
  1051. // IMImagemeterViewerDelegate
  1052. func closeImagemeterViewer(metadata: tableMetadata?, bundleDirectory: String) {
  1053. guard let metadata = metadata else { return }
  1054. let ocIdTemp = NSUUID().uuidString.lowercased()
  1055. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName)!
  1056. let bundleDirectoryURL = URL(fileURLWithPath: bundleDirectory)
  1057. let fileNameZipUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName))
  1058. // Create IMI
  1059. try? FileManager.default.removeItem(at: fileNameZipUrl)
  1060. do {
  1061. try FileManager().zipItem(at: bundleDirectoryURL, to:fileNameZipUrl)
  1062. } catch {
  1063. NCContentPresenter.shared.messageNotification("_error_", description: "Creation of IMI archive failed with error", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  1064. return
  1065. }
  1066. // Verify if is changed
  1067. if IMUtility.shared.IMIsChange(metadata: metadata, fileNameZipUrl: fileNameZipUrl) {
  1068. let com = IMCommunication.init()
  1069. _ = com.uploadFileIMI(serverUrl: metadata.serverUrl, fileName: metadata.fileName, fileNameLocalPath: fileNameLocalPath, ocId: ocIdTemp)
  1070. }
  1071. // Remove bundle directory
  1072. try? FileManager.default.removeItem(atPath: bundleDirectory)
  1073. }
  1074. #endif
  1075. // UPLOAD
  1076. func uploadStart(_ ocId: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  1077. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1078. appDelegate.updateApplicationIconBadgeNumber()
  1079. }
  1080. func uploadFileSuccessFailure(_ fileName: String!, ocId: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  1081. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else {
  1082. return
  1083. }
  1084. if metadata.account != appDelegate.activeAccount {
  1085. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1086. return
  1087. }
  1088. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1089. if errorCode == 0 {
  1090. appDelegate.startLoadAutoDownloadUpload()
  1091. } else {
  1092. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1093. NCContentPresenter.shared.messageNotification("_upload_file_", description: errorMessage, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  1094. }
  1095. }
  1096. }
  1097. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1098. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  1099. }
  1100. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  1101. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1102. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  1103. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  1104. NCCommunication.sharedInstance.downloadPreview(serverUrl: appDelegate.activeUrl, fileNamePath: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview), account: metadata.account) { (account, data, errorCode, errorMessage) in
  1105. if errorCode == 0 && data != nil {
  1106. if let image = UIImage.init(data: data!) {
  1107. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1108. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1109. if cell is NCListCell {
  1110. (cell as! NCListCell).imageItem.image = image
  1111. } else if cell is NCGridCell {
  1112. (cell as! NCGridCell).imageItem.image = image
  1113. } else if cell is NCGridMediaCell {
  1114. (cell as! NCGridMediaCell).imageItem.image = image
  1115. }
  1116. }
  1117. }
  1118. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1119. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1120. if cell is CCCellMainTransfer {
  1121. (cell as! CCCellMainTransfer).file.image = image
  1122. } else if cell is CCCellMain {
  1123. (cell as! CCCellMain).file.image = image
  1124. }
  1125. }
  1126. }
  1127. }
  1128. }
  1129. return closure()
  1130. }
  1131. }
  1132. return closure()
  1133. }
  1134. }
  1135. //MARK: - Operation Networking Main
  1136. class NCOperationNetworkingMain: Operation {
  1137. private var _executing : Bool = false
  1138. override var isExecuting : Bool {
  1139. get { return _executing }
  1140. set {
  1141. guard _executing != newValue else { return }
  1142. willChangeValue(forKey: "isExecuting")
  1143. _executing = newValue
  1144. didChangeValue(forKey: "isExecuting")
  1145. }
  1146. }
  1147. private var _finished : Bool = false
  1148. override var isFinished : Bool {
  1149. get { return _finished }
  1150. set {
  1151. guard _finished != newValue else { return }
  1152. willChangeValue(forKey: "isFinished")
  1153. _finished = newValue
  1154. didChangeValue(forKey: "isFinished")
  1155. }
  1156. }
  1157. private var metadata: tableMetadata?
  1158. private var view: Any?
  1159. private var indexPath: IndexPath?
  1160. private var networkingFunc: String = ""
  1161. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  1162. super.init()
  1163. if metadata != nil { self.metadata = metadata! }
  1164. if view != nil { self.view = view! }
  1165. if indexPath != nil { self.indexPath = indexPath! }
  1166. self.networkingFunc = networkingFunc
  1167. }
  1168. override func start() {
  1169. if !Thread.isMainThread {
  1170. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  1171. } else {
  1172. isExecuting = true
  1173. if isCancelled {
  1174. finish()
  1175. } else {
  1176. poolNetworking()
  1177. }
  1178. }
  1179. }
  1180. func finish() {
  1181. isExecuting = false
  1182. isFinished = true
  1183. }
  1184. override func cancel() {
  1185. super.cancel()
  1186. if isExecuting {
  1187. complete()
  1188. }
  1189. }
  1190. func complete() {
  1191. finish()
  1192. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  1193. }
  1194. func poolNetworking() {
  1195. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  1196. switch networkingFunc {
  1197. case "downloadThumbnail":
  1198. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  1199. self.complete()
  1200. }
  1201. default:
  1202. print("error")
  1203. }
  1204. }
  1205. }
  1206. //MARK: - Function Main
  1207. class NCFunctionMain: NSObject {
  1208. @objc static let sharedInstance: NCFunctionMain = {
  1209. let instance = NCFunctionMain()
  1210. return instance
  1211. }()
  1212. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1213. @objc func synchronizeOffline() {
  1214. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1215. if (directories != nil) {
  1216. for directory: tableDirectory in directories! {
  1217. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1218. }
  1219. }
  1220. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1221. if (files != nil) {
  1222. for file: tableLocalFile in files! {
  1223. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  1224. continue
  1225. }
  1226. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1227. }
  1228. }
  1229. }
  1230. }