NCMainCommon.swift 58 KB

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