NCMainCommon.swift 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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, 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. static var cellPlayImage = UIImage()
  59. }
  60. @objc func createImagesThemingColor() {
  61. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  62. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  63. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  64. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  65. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  66. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  67. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  68. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  69. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  70. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  71. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  72. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  73. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  74. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  75. }
  76. //MARK: -
  77. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  78. if viewController.viewIfLoaded?.window == nil {
  79. return
  80. }
  81. guard let dic = notification.userInfo else {
  82. return
  83. }
  84. let account = dic["account"] as? NSString ?? ""
  85. let ocId = dic["ocId"] as? NSString ?? ""
  86. let serverUrl = dic["serverUrl"] as? String ?? ""
  87. let status = dic["status"] as? Int ?? Int(k_metadataStatusNormal)
  88. let progress = dic["progress"] as? CGFloat ?? 0
  89. let totalBytes = dic["totalBytes"] as? Double ?? 0
  90. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  91. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  92. return
  93. }
  94. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  95. return
  96. }
  97. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  98. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  99. return
  100. }
  101. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  102. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  103. var image = ""
  104. if status == k_metadataStatusInDownload {
  105. image = "↓"
  106. } else if status == k_metadataStatusInUpload {
  107. image = "↑"
  108. }
  109. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  110. cell.transferButton?.progress = progress
  111. }
  112. }
  113. }
  114. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  115. if metadata.session.count == 0 { return }
  116. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  117. NCNetworking.shared.cancelDownload(metadata: metadata)
  118. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  119. NCNetworking.shared.cancelUpload(metadata: metadata)
  120. } else {
  121. var actionReloadDatasource = k_action_NULL
  122. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else { return }
  123. var metadata = metadata
  124. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  125. var cancel = false
  126. if metadata.session.count > 0 && metadata.session.contains("upload") {
  127. for task in uploadTasks {
  128. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  129. if uploadStatusForcedStart {
  130. metadata.status = Int(k_metadataStatusUploadForcedStart)
  131. metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) ?? metadata
  132. }
  133. task.cancel()
  134. cancel = true
  135. }
  136. }
  137. if cancel == false {
  138. do {
  139. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  140. }
  141. catch { }
  142. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  143. }
  144. actionReloadDatasource = k_action_DEL
  145. }
  146. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  147. self.reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: actionReloadDatasource)
  148. }
  149. }
  150. }
  151. }
  152. @objc func cancelAllTransfer() {
  153. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  154. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  155. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  156. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d", k_metadataStatusNormal), sorted: "fileName", ascending: true) {
  157. for metadata in metadatas {
  158. // Modify
  159. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  160. metadata.session = ""
  161. metadata.sessionSelector = ""
  162. metadata.status = Int(k_metadataStatusNormal)
  163. NCManageDatabase.sharedInstance.addMetadata(metadata)
  164. }
  165. // Cancel Task
  166. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  167. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  168. }
  169. }
  170. }
  171. }
  172. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  173. return
  174. }
  175. }
  176. //MARK: -
  177. 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) {
  178. var tableShare: tableShare?
  179. // Share
  180. if shares != nil {
  181. for share in shares! {
  182. if share.fileName == metadata.fileName {
  183. tableShare = share
  184. break
  185. }
  186. }
  187. }
  188. // Download preview
  189. if downloadThumbnail {
  190. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  191. }
  192. var isShare = false
  193. var isMounted = false
  194. if metadataFolder != nil {
  195. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  196. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  197. }
  198. if cell is NCListCell {
  199. let cell = cell as! NCListCell
  200. cell.delegate = source as? NCListCellDelegate
  201. cell.objectId = metadata.ocId
  202. cell.indexPath = indexPath
  203. cell.labelTitle.text = metadata.fileNameView
  204. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  205. cell.imageStatus.image = nil
  206. cell.imageLocal.image = nil
  207. cell.imageFavorite.image = nil
  208. cell.shared.image = nil
  209. if metadata.directory {
  210. if metadata.e2eEncrypted {
  211. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  212. } else if isShare {
  213. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  214. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  215. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  216. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  217. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  218. } else if metadata.mountType == "group" {
  219. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  220. } else if isMounted {
  221. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  222. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  223. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  224. } else {
  225. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  226. }
  227. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  228. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  229. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  230. // Local image: offline
  231. if tableDirectory != nil && tableDirectory!.offline {
  232. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  233. }
  234. } else {
  235. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  236. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  237. } else {
  238. if metadata.iconName.count > 0 {
  239. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  240. } else {
  241. cell.imageItem.image = UIImage.init(named: "file")
  242. }
  243. }
  244. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  245. // image local
  246. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  247. if size > 0 {
  248. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  249. if tableLocalFile == nil && size == metadata.size {
  250. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  251. }
  252. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  253. else { cell.imageLocal.image = UIImage.init(named: "local") }
  254. }
  255. }
  256. // image Favorite
  257. if metadata.favorite {
  258. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  259. }
  260. // Share image
  261. if (isShare) {
  262. cell.shared.image = NCMainCommonImages.cellSharedImage
  263. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  264. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  265. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  266. cell.shared.image = NCMainCommonImages.cellSharedImage
  267. } else {
  268. cell.shared.image = NCMainCommonImages.cellCanShareImage
  269. }
  270. if metadata.ownerId != appDelegate.activeUserID {
  271. // Load avatar
  272. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  273. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  274. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  275. cell.shared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  276. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  277. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  278. } else {
  279. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  280. if errorCode == 0 && account == self.appDelegate.activeAccount {
  281. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  282. }
  283. }
  284. }
  285. }
  286. if isEditMode {
  287. cell.imageItemLeftConstraint.constant = 45
  288. cell.imageSelect.isHidden = false
  289. if selectocId.contains(metadata.ocId) {
  290. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  291. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  292. } else {
  293. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  294. cell.backgroundView = nil
  295. }
  296. } else {
  297. cell.imageItemLeftConstraint.constant = 10
  298. cell.imageSelect.isHidden = true
  299. cell.backgroundView = nil
  300. }
  301. // Remove last separator
  302. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  303. cell.separator.isHidden = true
  304. } else {
  305. cell.separator.isHidden = false
  306. }
  307. } else if cell is NCGridCell {
  308. let cell = cell as! NCGridCell
  309. cell.delegate = source as? NCGridCellDelegate
  310. cell.objectId = metadata.ocId
  311. cell.indexPath = indexPath
  312. cell.labelTitle.text = metadata.fileNameView
  313. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  314. cell.imageStatus.image = nil
  315. cell.imageLocal.image = nil
  316. cell.imageFavorite.image = nil
  317. if metadata.directory {
  318. if metadata.e2eEncrypted {
  319. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  320. } else if isShare {
  321. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  322. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  323. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  324. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  325. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  326. } else if metadata.mountType == "group" {
  327. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  328. } else if isMounted {
  329. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  330. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  331. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  332. } else {
  333. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  334. }
  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. // Local image: offline
  338. if tableDirectory != nil && tableDirectory!.offline {
  339. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  340. }
  341. } else {
  342. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  343. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  344. } else {
  345. if metadata.iconName.count > 0 {
  346. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  347. } else {
  348. cell.imageItem.image = UIImage.init(named: "file")
  349. }
  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 = NCMainCommonImages.cellFavouriteImage
  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. }
  376. }
  377. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?) -> UITableViewCell {
  378. // Create File System
  379. if metadata.directory {
  380. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  381. } else {
  382. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  383. }
  384. // CCCell
  385. if metadata.status == k_metadataStatusNormal || metadata.status == k_metadataStatusDownloadError {
  386. // NORMAL
  387. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  388. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  389. cell.accessoryType = UITableViewCell.AccessoryType.none
  390. cell.file.image = nil
  391. cell.status.image = nil
  392. cell.favorite.image = nil
  393. cell.shared.image = nil
  394. cell.local.image = nil
  395. cell.comment.image = nil
  396. cell.shared.isUserInteractionEnabled = false
  397. cell.viewShared.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  398. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  399. // change color selection
  400. let selectionColor = UIView()
  401. selectionColor.backgroundColor = NCBrandColor.sharedInstance.select
  402. cell.selectedBackgroundView = selectionColor
  403. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  404. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  405. cell.labelTitle.text = metadata.fileNameView
  406. // Download preview
  407. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  408. // Share
  409. var isShare = false
  410. var isMounted = false
  411. if metadataFolder != nil {
  412. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  413. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  414. }
  415. if metadata.directory {
  416. // lable Info
  417. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  418. // File Image & Image Title Segue
  419. if metadata.e2eEncrypted {
  420. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  421. } else if isShare {
  422. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  423. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  424. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  425. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  426. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  427. } else if metadata.mountType == "group" {
  428. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  429. } else if isMounted {
  430. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  431. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  432. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  433. } else {
  434. cell.file.image = NCMainCommonImages.cellFolderImage
  435. }
  436. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  437. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  438. // Local image: offline
  439. if tableDirectory != nil && tableDirectory!.offline {
  440. cell.local.image = UIImage.init(named: "offlineFlag")
  441. }
  442. } else {
  443. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  444. // Lable Info
  445. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  446. // File Image
  447. if iconFileExists {
  448. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  449. } else {
  450. if metadata.iconName.count > 0 {
  451. cell.file.image = UIImage.init(named: metadata.iconName)
  452. } else {
  453. cell.file.image = UIImage.init(named: "file")
  454. }
  455. }
  456. // Local Image - Offline
  457. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  458. if size > 0 {
  459. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  460. if tableLocalFile == nil && size == metadata.size {
  461. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  462. }
  463. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  464. else { cell.local.image = UIImage.init(named: "local") }
  465. }
  466. // Status image: encrypted
  467. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  468. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  469. cell.status.image = UIImage.init(named: "encrypted")
  470. }
  471. }
  472. //
  473. // File & Directory
  474. //
  475. // Favorite
  476. if metadata.favorite {
  477. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  478. }
  479. // Share image
  480. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  481. if (isShare) {
  482. cell.shared.image = NCMainCommonImages.cellSharedImage
  483. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  484. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  485. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  486. cell.shared.image = NCMainCommonImages.cellSharedImage
  487. } else {
  488. cell.shared.image = NCMainCommonImages.cellCanShareImage
  489. }
  490. if metadata.ownerId != appDelegate.activeUserID {
  491. // Load avatar
  492. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  493. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  494. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  495. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  496. cell.shared.image = avatar
  497. }
  498. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  499. if let avatar = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  500. cell.shared.image = avatar
  501. }
  502. } else {
  503. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  504. if errorCode == 0 && account == self.appDelegate.activeAccount {
  505. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  506. }
  507. }
  508. }
  509. }
  510. }
  511. // Comment
  512. if metadata.commentsUnread {
  513. cell.comment.image = NCMainCommonImages.cellCommentImage
  514. cell.labelTitleTrailingConstraint.constant = 160
  515. } else {
  516. cell.labelTitleTrailingConstraint.constant = 110
  517. }
  518. // More Image
  519. cell.more.image = NCMainCommonImages.cellMoreImage
  520. // downloadFile Error
  521. if metadata.status == k_metadataStatusDownloadError {
  522. cell.status.image = UIImage.init(named: "statuserror")
  523. if metadata.sessionError.count == 0 {
  524. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  525. } else {
  526. cell.labelInfoFile.text = metadata.sessionError
  527. }
  528. }
  529. return cell
  530. } else {
  531. // TRASNFER
  532. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  533. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  534. cell.accessoryType = UITableViewCell.AccessoryType.none
  535. cell.file.image = nil
  536. cell.status.image = nil
  537. cell.user.image = nil
  538. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  539. cell.labelTitle.text = metadata.fileNameView
  540. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  541. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  542. cell.labelTitle.isEnabled = true
  543. cell.labelInfoFile.isEnabled = true
  544. var progress: CGFloat = 0.0
  545. var totalBytes: Double = 0.0
  546. //var totalBytesExpected : Double = 0
  547. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  548. if progressArray != nil && progressArray?.count == 3 {
  549. progress = progressArray?.object(at: 0) as! CGFloat
  550. totalBytes = progressArray?.object(at: 1) as! Double
  551. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  552. }
  553. // Write status on Label Info
  554. switch metadata.status {
  555. case Int(k_metadataStatusWaitDownload):
  556. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  557. progress = 0.0
  558. break
  559. case Int(k_metadataStatusInDownload):
  560. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  561. progress = 0.0
  562. break
  563. case Int(k_metadataStatusDownloading):
  564. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  565. break
  566. case Int(k_metadataStatusWaitUpload):
  567. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  568. progress = 0.0
  569. break
  570. case Int(k_metadataStatusInUpload):
  571. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  572. progress = 0.0
  573. break
  574. case Int(k_metadataStatusUploading):
  575. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  576. break
  577. default:
  578. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  579. progress = 0.0
  580. }
  581. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  582. if iconFileExists {
  583. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  584. } else {
  585. if metadata.iconName.count > 0 {
  586. cell.file.image = UIImage.init(named: metadata.iconName)
  587. } else {
  588. cell.file.image = UIImage.init(named: "file")
  589. }
  590. }
  591. // uploadFile
  592. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  593. if (!iconFileExists) {
  594. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  595. }
  596. cell.labelTitle.isEnabled = false
  597. }
  598. // uploadFileError
  599. if metadata.status == k_metadataStatusUploadError {
  600. cell.labelTitle.isEnabled = false
  601. cell.status.image = UIImage.init(named: "statuserror")
  602. if !iconFileExists {
  603. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  604. }
  605. if metadata.sessionError.count == 0 {
  606. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  607. } else {
  608. cell.labelInfoFile.text = metadata.sessionError
  609. }
  610. }
  611. // Progress
  612. cell.transferButton.progress = progress
  613. // User
  614. if metadata.account != appDelegate.activeAccount {
  615. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  616. if tableAccount != nil {
  617. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  618. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  619. if avatar != nil {
  620. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  621. let imageSize = avatarImageView?.bounds.size
  622. UIGraphicsBeginImageContext(imageSize!)
  623. let context = UIGraphicsGetCurrentContext()
  624. avatarImageView?.layer.render(in: context!)
  625. avatar = UIGraphicsGetImageFromCurrentImageContext()
  626. UIGraphicsEndImageContext()
  627. cell.user.image = avatar
  628. }
  629. }
  630. }
  631. return cell
  632. }
  633. }
  634. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  635. guard let indexPath = indexPath else {
  636. return nil
  637. }
  638. guard let sectionDataSource = sectionDataSource else {
  639. return nil
  640. }
  641. let section = indexPath.section + 1
  642. let row = indexPath.row + 1
  643. let totSections = sectionDataSource.sections.count
  644. if totSections < section || section > totSections {
  645. return nil
  646. }
  647. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  648. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  649. return nil
  650. }
  651. let totRows = filesID.count
  652. if totRows < row || row > totRows {
  653. return nil
  654. }
  655. let ocId = filesID.object(at: indexPath.row)
  656. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  657. return metadata
  658. }
  659. @objc func reloadDatasource(ServerUrl: String?, ocId: String?, action: Int32) {
  660. if operationQueueReloadDatasource.operationCount > 0 {
  661. return
  662. }
  663. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  664. self.operationQueueReloadDatasource.addOperation {
  665. DispatchQueue.main.async {
  666. self.appDelegate.activeMain.reloadDatasource(ServerUrl, ocId: ocId, action: Int(action))
  667. }
  668. }
  669. }
  670. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  671. self.operationQueueReloadDatasource.addOperation {
  672. DispatchQueue.main.async {
  673. self.appDelegate.activeFavorites.reloadDatasource(ocId, action: Int(action))
  674. }
  675. }
  676. }
  677. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  678. self.operationQueueReloadDatasource.addOperation {
  679. DispatchQueue.main.async {
  680. self.appDelegate.activeTransfers.reloadDatasource(ocId, action: Int(action))
  681. }
  682. }
  683. }
  684. }
  685. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  686. if view is UICollectionView {
  687. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  688. }
  689. if view is UITableView {
  690. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  691. }
  692. return true
  693. }
  694. //MARK: - download Open Selector
  695. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  696. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  697. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_downloadedFile), object: nil, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  698. } else {
  699. NCNetworking.shared.download(metadata: metadata, selector: selector)
  700. }
  701. }
  702. //MARK: - OpenIn
  703. func openIn(metadata: tableMetadata, selector: String) {
  704. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  705. docController?.delegate = self
  706. if selector == selectorOpenInDetail {
  707. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  708. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  709. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  710. } else {
  711. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  712. return }
  713. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  714. }
  715. }
  716. //MARK: - OpenShare
  717. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  718. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  719. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  720. shareViewController.metadata = metadata
  721. shareViewController.indexPage = indexPage
  722. shareNavigationController.modalPresentationStyle = .formSheet
  723. ViewController.present(shareNavigationController, animated: true, completion: nil)
  724. }
  725. //MARK: - NCAudioRecorder
  726. func startAudioRecorder() {
  727. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  728. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  729. viewController.delegate = self
  730. viewController.createRecorder(fileName: fileName)
  731. viewController.modalTransitionStyle = .crossDissolve
  732. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  733. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  734. }
  735. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  736. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  737. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  738. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  739. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  740. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  741. }
  742. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  743. }
  744. }
  745. //MARK: - Main TabBarController
  746. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  747. override func viewDidLoad() {
  748. super.viewDidLoad()
  749. delegate = self
  750. }
  751. //Delegate methods
  752. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  753. let tabViewControllers = tabBarController.viewControllers!
  754. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  755. if let vc = viewController as? UINavigationController {
  756. vc.popToRootViewController(animated: true);
  757. }
  758. return false
  759. }
  760. animateToTab(toIndex: toIndex)
  761. return true
  762. }
  763. func animateToTab(toIndex: Int) {
  764. let tabViewControllers = viewControllers!
  765. let fromView = selectedViewController!.view!
  766. let toView = tabViewControllers[toIndex].view!
  767. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  768. guard fromIndex != toIndex else {return}
  769. // Add the toView to the tab bar view
  770. fromView.superview?.addSubview(toView)
  771. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  772. // Position toView off screen (to the left/right of fromView)
  773. let screenWidth = UIScreen.main.bounds.size.width;
  774. let scrollRight = toIndex > fromIndex!;
  775. let offset = (scrollRight ? screenWidth : -screenWidth)
  776. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  777. // Disable interaction during animation
  778. view.isUserInteractionEnabled = false
  779. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  780. // Slide the views by -offset
  781. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  782. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  783. }, completion: { finished in
  784. // Remove the old view from the tabbar view.
  785. fromView.removeFromSuperview()
  786. self.selectedIndex = toIndex
  787. self.view.isUserInteractionEnabled = true
  788. })
  789. }
  790. }
  791. //MARK: - Networking Main
  792. class NCNetworkingMain: NSObject, IMImagemeterViewerDelegate {
  793. @objc static let sharedInstance: NCNetworkingMain = {
  794. let instance = NCNetworkingMain()
  795. return instance
  796. }()
  797. lazy var operationQueueNetworkingMain: OperationQueue = {
  798. let queue = OperationQueue()
  799. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  800. queue.maxConcurrentOperationCount = 1
  801. return queue
  802. }()
  803. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  804. #if HC
  805. // IMImagemeterViewerDelegate
  806. func closeImagemeterViewer(metadata: tableMetadata?, bundleDirectory: String) {
  807. guard let metadata = metadata else { return }
  808. let ocIdTemp = NSUUID().uuidString.lowercased()
  809. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName)!
  810. let bundleDirectoryURL = URL(fileURLWithPath: bundleDirectory)
  811. let fileNameZipUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName))
  812. // Create IMI
  813. try? FileManager.default.removeItem(at: fileNameZipUrl)
  814. do {
  815. try FileManager().zipItem(at: bundleDirectoryURL, to:fileNameZipUrl)
  816. } catch {
  817. NCContentPresenter.shared.messageNotification("_error_", description: "Creation of IMI archive failed with error", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  818. return
  819. }
  820. // Verify if is changed
  821. if IMUtility.shared.IMIsChange(metadata: metadata, fileNameZipUrl: fileNameZipUrl) {
  822. let com = IMCommunication.init()
  823. _ = com.uploadFileIMI(serverUrl: metadata.serverUrl, fileName: metadata.fileName, fileNameLocalPath: fileNameLocalPath, ocId: ocIdTemp)
  824. }
  825. // Remove bundle directory
  826. try? FileManager.default.removeItem(atPath: bundleDirectory)
  827. }
  828. #endif
  829. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  830. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  831. }
  832. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  833. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  834. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  835. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  836. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview)) { (account, data, errorCode, errorMessage) in
  837. if errorCode == 0 && data != nil {
  838. if let image = UIImage.init(data: data!) {
  839. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  840. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  841. if cell is NCListCell {
  842. (cell as! NCListCell).imageItem.image = image
  843. } else if cell is NCGridCell {
  844. (cell as! NCGridCell).imageItem.image = image
  845. } else if cell is NCGridMediaCell {
  846. (cell as! NCGridMediaCell).imageItem.image = image
  847. }
  848. }
  849. }
  850. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  851. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  852. if cell is CCCellMainTransfer {
  853. (cell as! CCCellMainTransfer).file.image = image
  854. } else if cell is CCCellMain {
  855. (cell as! CCCellMain).file.image = image
  856. }
  857. }
  858. }
  859. }
  860. }
  861. return closure()
  862. }
  863. }
  864. return closure()
  865. }
  866. }
  867. //MARK: - Operation Networking Main
  868. class NCOperationNetworkingMain: Operation {
  869. private var _executing : Bool = false
  870. override var isExecuting : Bool {
  871. get { return _executing }
  872. set {
  873. guard _executing != newValue else { return }
  874. willChangeValue(forKey: "isExecuting")
  875. _executing = newValue
  876. didChangeValue(forKey: "isExecuting")
  877. }
  878. }
  879. private var _finished : Bool = false
  880. override var isFinished : Bool {
  881. get { return _finished }
  882. set {
  883. guard _finished != newValue else { return }
  884. willChangeValue(forKey: "isFinished")
  885. _finished = newValue
  886. didChangeValue(forKey: "isFinished")
  887. }
  888. }
  889. private var metadata: tableMetadata?
  890. private var view: Any?
  891. private var indexPath: IndexPath?
  892. private var networkingFunc: String = ""
  893. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  894. super.init()
  895. if metadata != nil { self.metadata = metadata! }
  896. if view != nil { self.view = view! }
  897. if indexPath != nil { self.indexPath = indexPath! }
  898. self.networkingFunc = networkingFunc
  899. }
  900. override func start() {
  901. if !Thread.isMainThread {
  902. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  903. } else {
  904. isExecuting = true
  905. if isCancelled {
  906. finish()
  907. } else {
  908. poolNetworking()
  909. }
  910. }
  911. }
  912. func finish() {
  913. isExecuting = false
  914. isFinished = true
  915. }
  916. override func cancel() {
  917. super.cancel()
  918. if isExecuting {
  919. complete()
  920. }
  921. }
  922. func complete() {
  923. finish()
  924. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  925. }
  926. func poolNetworking() {
  927. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  928. switch networkingFunc {
  929. case "downloadThumbnail":
  930. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  931. self.complete()
  932. }
  933. default:
  934. print("error")
  935. }
  936. }
  937. }
  938. //MARK: - Function Main
  939. class NCFunctionMain: NSObject {
  940. @objc static let sharedInstance: NCFunctionMain = {
  941. let instance = NCFunctionMain()
  942. return instance
  943. }()
  944. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  945. @objc func synchronizeOffline() {
  946. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  947. if (directories != nil) {
  948. for directory: tableDirectory in directories! {
  949. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  950. }
  951. }
  952. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  953. if (files != nil) {
  954. for file: tableLocalFile in files! {
  955. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  956. continue
  957. }
  958. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  959. }
  960. }
  961. }
  962. }