NCMainCommon.swift 57 KB

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