NCMainCommon.swift 75 KB

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