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