NCMainCommon.swift 79 KB

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