NCMainCommon.swift 78 KB

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