NCMainCommon.swift 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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.file.layer.cornerRadius = 6
  392. cell.file.layer.masksToBounds = true
  393. cell.status.image = nil
  394. cell.favorite.image = nil
  395. cell.shared.image = nil
  396. cell.local.image = nil
  397. cell.comment.image = nil
  398. cell.shared.isUserInteractionEnabled = false
  399. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  400. // change color selection
  401. let selectionColor = UIView()
  402. selectionColor.backgroundColor = NCBrandColor.sharedInstance.select
  403. cell.selectedBackgroundView = selectionColor
  404. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  405. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  406. cell.labelTitle.text = metadata.fileNameView
  407. // Download preview
  408. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  409. // Share
  410. var isShare = false
  411. var isMounted = false
  412. if metadataFolder != nil {
  413. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  414. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  415. }
  416. if metadata.directory {
  417. // lable Info
  418. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  419. // File Image & Image Title Segue
  420. if metadata.e2eEncrypted {
  421. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  422. } else if isShare {
  423. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  424. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  425. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  426. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  427. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  428. } else if metadata.mountType == "group" {
  429. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  430. } else if isMounted {
  431. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  432. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  433. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  434. } else {
  435. cell.file.image = NCMainCommonImages.cellFolderImage
  436. }
  437. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  438. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  439. // Local image: offline
  440. if tableDirectory != nil && tableDirectory!.offline {
  441. cell.local.image = UIImage.init(named: "offlineFlag")
  442. }
  443. } else {
  444. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  445. // Lable Info
  446. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  447. // File Image
  448. if iconFileExists {
  449. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  450. } else {
  451. if metadata.iconName.count > 0 {
  452. cell.file.image = UIImage.init(named: metadata.iconName)
  453. } else {
  454. cell.file.image = UIImage.init(named: "file")
  455. }
  456. }
  457. // Local Image - Offline
  458. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  459. if size > 0 {
  460. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  461. if tableLocalFile == nil && size == metadata.size {
  462. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  463. }
  464. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  465. else { cell.local.image = UIImage.init(named: "local") }
  466. }
  467. // Status image: encrypted
  468. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  469. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  470. cell.status.image = UIImage.init(named: "encrypted")
  471. }
  472. }
  473. //
  474. // File & Directory
  475. //
  476. // Favorite
  477. if metadata.favorite {
  478. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  479. }
  480. // Share image
  481. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  482. if (isShare) {
  483. cell.shared.image = NCMainCommonImages.cellSharedImage
  484. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  485. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  486. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  487. cell.shared.image = NCMainCommonImages.cellSharedImage
  488. } else {
  489. cell.shared.image = NCMainCommonImages.cellCanShareImage
  490. }
  491. if metadata.ownerId != appDelegate.activeUserID {
  492. // Load avatar
  493. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  494. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  495. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  496. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  497. cell.shared.image = avatar
  498. }
  499. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  500. if let avatar = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  501. cell.shared.image = avatar
  502. }
  503. } else {
  504. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  505. if errorCode == 0 && account == self.appDelegate.activeAccount {
  506. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  507. }
  508. }
  509. }
  510. }
  511. }
  512. // Comment
  513. if metadata.commentsUnread {
  514. cell.comment.image = NCMainCommonImages.cellCommentImage
  515. cell.labelTitleTrailingConstraint.constant = 160
  516. } else {
  517. cell.labelTitleTrailingConstraint.constant = 110
  518. }
  519. // More Image
  520. cell.more.image = NCMainCommonImages.cellMoreImage
  521. // downloadFile Error
  522. if metadata.status == k_metadataStatusDownloadError {
  523. cell.status.image = UIImage.init(named: "statuserror")
  524. if metadata.sessionError.count == 0 {
  525. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  526. } else {
  527. cell.labelInfoFile.text = metadata.sessionError
  528. }
  529. }
  530. return cell
  531. } else {
  532. // TRASNFER
  533. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  534. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  535. cell.accessoryType = UITableViewCell.AccessoryType.none
  536. cell.file.image = nil
  537. cell.file.layer.cornerRadius = 6
  538. cell.file.layer.masksToBounds = true
  539. cell.status.image = nil
  540. cell.user.image = nil
  541. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  542. cell.labelTitle.text = metadata.fileNameView
  543. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  544. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  545. cell.labelTitle.isEnabled = true
  546. cell.labelInfoFile.isEnabled = true
  547. var progress: CGFloat = 0.0
  548. var totalBytes: Double = 0.0
  549. //var totalBytesExpected : Double = 0
  550. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  551. if progressArray != nil && progressArray?.count == 3 {
  552. progress = progressArray?.object(at: 0) as! CGFloat
  553. totalBytes = progressArray?.object(at: 1) as! Double
  554. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  555. }
  556. // Write status on Label Info
  557. switch metadata.status {
  558. case Int(k_metadataStatusWaitDownload):
  559. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  560. progress = 0.0
  561. break
  562. case Int(k_metadataStatusInDownload):
  563. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  564. progress = 0.0
  565. break
  566. case Int(k_metadataStatusDownloading):
  567. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  568. break
  569. case Int(k_metadataStatusWaitUpload):
  570. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  571. progress = 0.0
  572. break
  573. case Int(k_metadataStatusInUpload):
  574. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  575. progress = 0.0
  576. break
  577. case Int(k_metadataStatusUploading):
  578. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  579. break
  580. default:
  581. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  582. progress = 0.0
  583. }
  584. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  585. if iconFileExists {
  586. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  587. } else {
  588. if metadata.iconName.count > 0 {
  589. cell.file.image = UIImage.init(named: metadata.iconName)
  590. } else {
  591. cell.file.image = UIImage.init(named: "file")
  592. }
  593. }
  594. // uploadFile
  595. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  596. if (!iconFileExists) {
  597. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  598. }
  599. cell.labelTitle.isEnabled = false
  600. }
  601. // uploadFileError
  602. if metadata.status == k_metadataStatusUploadError {
  603. cell.labelTitle.isEnabled = false
  604. cell.status.image = UIImage.init(named: "statuserror")
  605. if !iconFileExists {
  606. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  607. }
  608. if metadata.sessionError.count == 0 {
  609. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  610. } else {
  611. cell.labelInfoFile.text = metadata.sessionError
  612. }
  613. }
  614. // Progress
  615. cell.transferButton.progress = progress
  616. // User
  617. if metadata.account != appDelegate.activeAccount {
  618. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  619. if tableAccount != nil {
  620. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  621. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  622. if avatar != nil {
  623. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  624. let imageSize = avatarImageView?.bounds.size
  625. UIGraphicsBeginImageContext(imageSize!)
  626. let context = UIGraphicsGetCurrentContext()
  627. avatarImageView?.layer.render(in: context!)
  628. avatar = UIGraphicsGetImageFromCurrentImageContext()
  629. UIGraphicsEndImageContext()
  630. cell.user.image = avatar
  631. }
  632. }
  633. }
  634. return cell
  635. }
  636. }
  637. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  638. guard let indexPath = indexPath else {
  639. return nil
  640. }
  641. guard let sectionDataSource = sectionDataSource else {
  642. return nil
  643. }
  644. let section = indexPath.section + 1
  645. let row = indexPath.row + 1
  646. let totSections = sectionDataSource.sections.count
  647. if totSections < section || section > totSections {
  648. return nil
  649. }
  650. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  651. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  652. return nil
  653. }
  654. let totRows = filesID.count
  655. if totRows < row || row > totRows {
  656. return nil
  657. }
  658. let ocId = filesID.object(at: indexPath.row)
  659. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  660. return metadata
  661. }
  662. @objc func reloadDatasource(ServerUrl: String?, ocId: String?, action: Int32) {
  663. if operationQueueReloadDatasource.operationCount > 0 {
  664. return
  665. }
  666. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  667. self.operationQueueReloadDatasource.addOperation {
  668. DispatchQueue.main.async {
  669. self.appDelegate.activeMain.reloadDatasource(ServerUrl, ocId: ocId, action: Int(action))
  670. }
  671. }
  672. }
  673. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  674. self.operationQueueReloadDatasource.addOperation {
  675. DispatchQueue.main.async {
  676. self.appDelegate.activeFavorites.reloadDatasource(ocId, action: Int(action))
  677. }
  678. }
  679. }
  680. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  681. self.operationQueueReloadDatasource.addOperation {
  682. DispatchQueue.main.async {
  683. self.appDelegate.activeTransfers.reloadDatasource(ocId, action: Int(action))
  684. }
  685. }
  686. }
  687. }
  688. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  689. if view is UICollectionView {
  690. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  691. }
  692. if view is UITableView {
  693. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  694. }
  695. return true
  696. }
  697. //MARK: - download Open Selector
  698. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  699. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  700. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_downloadedFile), object: nil, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  701. } else {
  702. NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
  703. }
  704. }
  705. //MARK: - OpenIn
  706. func openIn(metadata: tableMetadata, selector: String) {
  707. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  708. docController?.delegate = self
  709. if selector == selectorOpenInDetail {
  710. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  711. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  712. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  713. } else {
  714. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  715. return }
  716. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  717. }
  718. }
  719. //MARK: - OpenShare
  720. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  721. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  722. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  723. shareViewController.metadata = metadata
  724. shareViewController.indexPage = indexPage
  725. shareNavigationController.modalPresentationStyle = .formSheet
  726. ViewController.present(shareNavigationController, animated: true, completion: nil)
  727. }
  728. //MARK: - NCAudioRecorder
  729. func startAudioRecorder() {
  730. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  731. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  732. viewController.delegate = self
  733. viewController.createRecorder(fileName: fileName)
  734. viewController.modalTransitionStyle = .crossDissolve
  735. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  736. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  737. }
  738. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  739. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  740. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  741. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  742. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  743. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  744. }
  745. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  746. }
  747. }
  748. //MARK: - Main TabBarController
  749. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  750. override func viewDidLoad() {
  751. super.viewDidLoad()
  752. delegate = self
  753. }
  754. //Delegate methods
  755. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  756. let tabViewControllers = tabBarController.viewControllers!
  757. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  758. if let vc = viewController as? UINavigationController {
  759. vc.popToRootViewController(animated: true);
  760. }
  761. return false
  762. }
  763. animateToTab(toIndex: toIndex)
  764. return true
  765. }
  766. func animateToTab(toIndex: Int) {
  767. let tabViewControllers = viewControllers!
  768. let fromView = selectedViewController!.view!
  769. let toView = tabViewControllers[toIndex].view!
  770. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  771. guard fromIndex != toIndex else {return}
  772. // Add the toView to the tab bar view
  773. fromView.superview?.addSubview(toView)
  774. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  775. // Position toView off screen (to the left/right of fromView)
  776. let screenWidth = UIScreen.main.bounds.size.width;
  777. let scrollRight = toIndex > fromIndex!;
  778. let offset = (scrollRight ? screenWidth : -screenWidth)
  779. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  780. // Disable interaction during animation
  781. view.isUserInteractionEnabled = false
  782. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  783. // Slide the views by -offset
  784. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  785. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  786. }, completion: { finished in
  787. // Remove the old view from the tabbar view.
  788. fromView.removeFromSuperview()
  789. self.selectedIndex = toIndex
  790. self.view.isUserInteractionEnabled = true
  791. })
  792. }
  793. }
  794. //MARK: - Networking Main
  795. class NCNetworkingMain: NSObject, IMImagemeterViewerDelegate {
  796. @objc static let sharedInstance: NCNetworkingMain = {
  797. let instance = NCNetworkingMain()
  798. return instance
  799. }()
  800. lazy var operationQueueNetworkingMain: OperationQueue = {
  801. let queue = OperationQueue()
  802. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  803. queue.maxConcurrentOperationCount = 1
  804. return queue
  805. }()
  806. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  807. #if HC
  808. // IMImagemeterViewerDelegate
  809. func closeImagemeterViewer(metadata: tableMetadata?, bundleDirectory: String) {
  810. guard let metadata = metadata else { return }
  811. let ocIdTemp = NSUUID().uuidString.lowercased()
  812. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName)!
  813. let bundleDirectoryURL = URL(fileURLWithPath: bundleDirectory)
  814. let fileNameZipUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName))
  815. // Create IMI
  816. try? FileManager.default.removeItem(at: fileNameZipUrl)
  817. do {
  818. try FileManager().zipItem(at: bundleDirectoryURL, to:fileNameZipUrl)
  819. } catch {
  820. NCContentPresenter.shared.messageNotification("_error_", description: "Creation of IMI archive failed with error", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  821. return
  822. }
  823. // Verify if is changed
  824. if IMUtility.shared.IMIsChange(metadata: metadata, fileNameZipUrl: fileNameZipUrl) {
  825. let com = IMCommunication.init()
  826. _ = com.uploadFileIMI(serverUrl: metadata.serverUrl, fileName: metadata.fileName, fileNameLocalPath: fileNameLocalPath, ocId: ocIdTemp)
  827. }
  828. // Remove bundle directory
  829. try? FileManager.default.removeItem(atPath: bundleDirectory)
  830. }
  831. #endif
  832. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  833. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  834. }
  835. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  836. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  837. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  838. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  839. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview)) { (account, data, errorCode, errorMessage) in
  840. if errorCode == 0 && data != nil {
  841. if let image = UIImage.init(data: data!) {
  842. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  843. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  844. if cell is NCListCell {
  845. (cell as! NCListCell).imageItem.image = image
  846. } else if cell is NCGridCell {
  847. (cell as! NCGridCell).imageItem.image = image
  848. } else if cell is NCGridMediaCell {
  849. (cell as! NCGridMediaCell).imageItem.image = image
  850. }
  851. }
  852. }
  853. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  854. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  855. if cell is CCCellMainTransfer {
  856. (cell as! CCCellMainTransfer).file.image = image
  857. } else if cell is CCCellMain {
  858. (cell as! CCCellMain).file.image = image
  859. }
  860. }
  861. }
  862. }
  863. }
  864. return closure()
  865. }
  866. }
  867. return closure()
  868. }
  869. }
  870. //MARK: - Operation Networking Main
  871. class NCOperationNetworkingMain: Operation {
  872. private var _executing : Bool = false
  873. override var isExecuting : Bool {
  874. get { return _executing }
  875. set {
  876. guard _executing != newValue else { return }
  877. willChangeValue(forKey: "isExecuting")
  878. _executing = newValue
  879. didChangeValue(forKey: "isExecuting")
  880. }
  881. }
  882. private var _finished : Bool = false
  883. override var isFinished : Bool {
  884. get { return _finished }
  885. set {
  886. guard _finished != newValue else { return }
  887. willChangeValue(forKey: "isFinished")
  888. _finished = newValue
  889. didChangeValue(forKey: "isFinished")
  890. }
  891. }
  892. private var metadata: tableMetadata?
  893. private var view: Any?
  894. private var indexPath: IndexPath?
  895. private var networkingFunc: String = ""
  896. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  897. super.init()
  898. if metadata != nil { self.metadata = metadata! }
  899. if view != nil { self.view = view! }
  900. if indexPath != nil { self.indexPath = indexPath! }
  901. self.networkingFunc = networkingFunc
  902. }
  903. override func start() {
  904. if !Thread.isMainThread {
  905. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  906. } else {
  907. isExecuting = true
  908. if isCancelled {
  909. finish()
  910. } else {
  911. poolNetworking()
  912. }
  913. }
  914. }
  915. func finish() {
  916. isExecuting = false
  917. isFinished = true
  918. }
  919. override func cancel() {
  920. super.cancel()
  921. if isExecuting {
  922. complete()
  923. }
  924. }
  925. func complete() {
  926. finish()
  927. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  928. }
  929. func poolNetworking() {
  930. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  931. switch networkingFunc {
  932. case "downloadThumbnail":
  933. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  934. self.complete()
  935. }
  936. default:
  937. print("error")
  938. }
  939. }
  940. }
  941. //MARK: - Function Main
  942. class NCFunctionMain: NSObject {
  943. @objc static let sharedInstance: NCFunctionMain = {
  944. let instance = NCFunctionMain()
  945. return instance
  946. }()
  947. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  948. @objc func synchronizeOffline() {
  949. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  950. if (directories != nil) {
  951. for directory: tableDirectory in directories! {
  952. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  953. }
  954. }
  955. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  956. if (files != nil) {
  957. for file: tableLocalFile in files! {
  958. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  959. continue
  960. }
  961. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  962. }
  963. }
  964. }
  965. }