NCMainCommon.swift 77 KB

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