NCMainCommon.swift 75 KB

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