NCMainCommon.swift 59 KB

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