NCMainCommon.swift 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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.graySoft)
  63. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  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.sharedInstance.downloadAvatar(serverUrl: appDelegate.activeUrl, userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: appDelegate.activeAccount) { (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 {
  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.sharedInstance.downloadAvatar(serverUrl: appDelegate.activeUrl, userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: appDelegate.activeAccount) { (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. return cell
  529. } else {
  530. // TRASNFER
  531. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  532. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  533. cell.accessoryType = UITableViewCell.AccessoryType.none
  534. cell.file.image = nil
  535. cell.status.image = nil
  536. cell.user.image = nil
  537. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  538. cell.labelTitle.text = metadata.fileNameView
  539. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  540. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  541. 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. // Session Upload Extension
  589. if metadata.session == k_upload_session_extension {
  590. cell.labelTitle.isEnabled = false
  591. cell.labelInfoFile.isEnabled = false
  592. } else {
  593. cell.labelTitle.isEnabled = true
  594. cell.labelInfoFile.isEnabled = true
  595. }
  596. // downloadFile
  597. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  598. //
  599. }
  600. // downloadFile Error
  601. if metadata.status == k_metadataStatusDownloadError {
  602. cell.status.image = UIImage.init(named: "statuserror")
  603. if metadata.sessionError.count == 0 {
  604. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  605. } else {
  606. cell.labelInfoFile.text = metadata.sessionError
  607. }
  608. }
  609. // uploadFile
  610. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  611. if (!iconFileExists) {
  612. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  613. }
  614. cell.labelTitle.isEnabled = false
  615. }
  616. // uploadFileError
  617. if metadata.status == k_metadataStatusUploadError {
  618. cell.labelTitle.isEnabled = false
  619. cell.status.image = UIImage.init(named: "statuserror")
  620. if !iconFileExists {
  621. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  622. }
  623. if metadata.sessionError.count == 0 {
  624. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  625. } else {
  626. cell.labelInfoFile.text = metadata.sessionError
  627. }
  628. }
  629. // Progress
  630. cell.transferButton.progress = progress
  631. // User
  632. if metadata.account != appDelegate.activeAccount {
  633. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  634. if tableAccount != nil {
  635. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  636. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  637. if avatar != nil {
  638. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  639. let imageSize = avatarImageView?.bounds.size
  640. UIGraphicsBeginImageContext(imageSize!)
  641. let context = UIGraphicsGetCurrentContext()
  642. avatarImageView?.layer.render(in: context!)
  643. avatar = UIGraphicsGetImageFromCurrentImageContext()
  644. UIGraphicsEndImageContext()
  645. cell.user.image = avatar
  646. }
  647. }
  648. }
  649. return cell
  650. }
  651. }
  652. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  653. guard let indexPath = indexPath else {
  654. return nil
  655. }
  656. guard let sectionDataSource = sectionDataSource else {
  657. return nil
  658. }
  659. let section = indexPath.section + 1
  660. let row = indexPath.row + 1
  661. let totSections = sectionDataSource.sections.count
  662. if totSections < section || section > totSections {
  663. return nil
  664. }
  665. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  666. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  667. return nil
  668. }
  669. let totRows = filesID.count
  670. if totRows < row || row > totRows {
  671. return nil
  672. }
  673. let ocId = filesID.object(at: indexPath.row)
  674. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  675. return metadata
  676. }
  677. @objc func reloadDatasource(ServerUrl: String?, ocId: String?, action: Int32) {
  678. if operationQueueReloadDatasource.operationCount > 0 {
  679. return
  680. }
  681. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  682. self.operationQueueReloadDatasource.addOperation {
  683. DispatchQueue.main.async {
  684. self.appDelegate.activeMain.reloadDatasource(ServerUrl, ocId: ocId, action: Int(action))
  685. }
  686. }
  687. }
  688. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  689. self.operationQueueReloadDatasource.addOperation {
  690. DispatchQueue.main.async {
  691. self.appDelegate.activeFavorites.reloadDatasource(ocId, action: Int(action))
  692. }
  693. }
  694. }
  695. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  696. self.operationQueueReloadDatasource.addOperation {
  697. DispatchQueue.main.async {
  698. self.appDelegate.activeTransfers.reloadDatasource(ocId, action: Int(action))
  699. }
  700. }
  701. }
  702. }
  703. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  704. if view is UICollectionView {
  705. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  706. }
  707. if view is UITableView {
  708. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  709. }
  710. return true
  711. }
  712. //MARK: - download Open Selector
  713. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  714. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  715. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_downloadedFile), object: nil, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  716. } else {
  717. metadata.session = k_download_session
  718. metadata.sessionError = ""
  719. metadata.sessionSelector = selector //selectorOpenIn
  720. metadata.status = Int(k_metadataStatusWaitDownload)
  721. NCManageDatabase.sharedInstance.addMetadata(metadata)
  722. reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: k_action_MOD)
  723. }
  724. }
  725. //MARK: - OpenIn
  726. func openIn(metadata: tableMetadata, selector: String) {
  727. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  728. docController?.delegate = self
  729. if selector == selectorOpenInDetail {
  730. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  731. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  732. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  733. } else {
  734. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  735. return }
  736. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  737. }
  738. }
  739. //MARK: - OpenShare
  740. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  741. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  742. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  743. shareViewController.metadata = metadata
  744. shareViewController.indexPage = indexPage
  745. shareNavigationController.modalPresentationStyle = .formSheet
  746. ViewController.present(shareNavigationController, animated: true, completion: nil)
  747. }
  748. //MARK: - NCAudioRecorder
  749. func startAudioRecorder() {
  750. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  751. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  752. viewController.delegate = self
  753. viewController.createRecorder(fileName: fileName)
  754. viewController.modalTransitionStyle = .crossDissolve
  755. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  756. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  757. }
  758. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  759. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  760. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  761. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  762. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  763. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  764. }
  765. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  766. }
  767. }
  768. //MARK: - Main TabBarController
  769. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  770. override func viewDidLoad() {
  771. super.viewDidLoad()
  772. delegate = self
  773. }
  774. //Delegate methods
  775. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  776. let tabViewControllers = tabBarController.viewControllers!
  777. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  778. if let vc = viewController as? UINavigationController {
  779. vc.popToRootViewController(animated: true);
  780. }
  781. return false
  782. }
  783. animateToTab(toIndex: toIndex)
  784. return true
  785. }
  786. func animateToTab(toIndex: Int) {
  787. let tabViewControllers = viewControllers!
  788. let fromView = selectedViewController!.view!
  789. let toView = tabViewControllers[toIndex].view!
  790. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  791. guard fromIndex != toIndex else {return}
  792. // Add the toView to the tab bar view
  793. fromView.superview?.addSubview(toView)
  794. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  795. // Position toView off screen (to the left/right of fromView)
  796. let screenWidth = UIScreen.main.bounds.size.width;
  797. let scrollRight = toIndex > fromIndex!;
  798. let offset = (scrollRight ? screenWidth : -screenWidth)
  799. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  800. // Disable interaction during animation
  801. view.isUserInteractionEnabled = false
  802. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  803. // Slide the views by -offset
  804. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  805. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  806. }, completion: { finished in
  807. // Remove the old view from the tabbar view.
  808. fromView.removeFromSuperview()
  809. self.selectedIndex = toIndex
  810. self.view.isUserInteractionEnabled = true
  811. })
  812. }
  813. }
  814. //
  815. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  816. //
  817. extension UITabBar {
  818. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  819. // the Master view controller shows the UITabBarItem icon next to the text
  820. override open var traitCollection: UITraitCollection {
  821. if UIDevice.current.userInterfaceIdiom == .pad {
  822. return UITraitCollection(horizontalSizeClass: .compact)
  823. }
  824. return super.traitCollection
  825. }
  826. }
  827. //MARK: - Networking Main
  828. class NCNetworkingMain: NSObject, IMImagemeterViewerDelegate {
  829. @objc static let sharedInstance: NCNetworkingMain = {
  830. let instance = NCNetworkingMain()
  831. return instance
  832. }()
  833. lazy var operationQueueNetworkingMain: OperationQueue = {
  834. let queue = OperationQueue()
  835. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  836. queue.maxConcurrentOperationCount = 1
  837. return queue
  838. }()
  839. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  840. #if HC
  841. // IMImagemeterViewerDelegate
  842. func closeImagemeterViewer(metadata: tableMetadata?, bundleDirectory: String) {
  843. guard let metadata = metadata else { return }
  844. let ocIdTemp = NSUUID().uuidString.lowercased()
  845. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName)!
  846. let bundleDirectoryURL = URL(fileURLWithPath: bundleDirectory)
  847. let fileNameZipUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName))
  848. // Create IMI
  849. try? FileManager.default.removeItem(at: fileNameZipUrl)
  850. do {
  851. try FileManager().zipItem(at: bundleDirectoryURL, to:fileNameZipUrl)
  852. } catch {
  853. NCContentPresenter.shared.messageNotification("_error_", description: "Creation of IMI archive failed with error", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  854. return
  855. }
  856. // Verify if is changed
  857. if IMUtility.shared.IMIsChange(metadata: metadata, fileNameZipUrl: fileNameZipUrl) {
  858. let com = IMCommunication.init()
  859. _ = com.uploadFileIMI(serverUrl: metadata.serverUrl, fileName: metadata.fileName, fileNameLocalPath: fileNameLocalPath, ocId: ocIdTemp)
  860. }
  861. // Remove bundle directory
  862. try? FileManager.default.removeItem(atPath: bundleDirectory)
  863. }
  864. #endif
  865. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  866. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  867. }
  868. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  869. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  870. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  871. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  872. NCCommunication.sharedInstance.downloadPreview(serverUrl: appDelegate.activeUrl, fileNamePath: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview), customUserAgent: nil, addCustomHeaders: nil, account: metadata.account) { (account, data, errorCode, errorMessage) in
  873. if errorCode == 0 && data != nil {
  874. if let image = UIImage.init(data: data!) {
  875. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  876. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  877. if cell is NCListCell {
  878. (cell as! NCListCell).imageItem.image = image
  879. } else if cell is NCGridCell {
  880. (cell as! NCGridCell).imageItem.image = image
  881. } else if cell is NCGridMediaCell {
  882. (cell as! NCGridMediaCell).imageItem.image = image
  883. }
  884. }
  885. }
  886. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  887. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  888. if cell is CCCellMainTransfer {
  889. (cell as! CCCellMainTransfer).file.image = image
  890. } else if cell is CCCellMain {
  891. (cell as! CCCellMain).file.image = image
  892. }
  893. }
  894. }
  895. }
  896. }
  897. return closure()
  898. }
  899. }
  900. return closure()
  901. }
  902. }
  903. //MARK: - Operation Networking Main
  904. class NCOperationNetworkingMain: Operation {
  905. private var _executing : Bool = false
  906. override var isExecuting : Bool {
  907. get { return _executing }
  908. set {
  909. guard _executing != newValue else { return }
  910. willChangeValue(forKey: "isExecuting")
  911. _executing = newValue
  912. didChangeValue(forKey: "isExecuting")
  913. }
  914. }
  915. private var _finished : Bool = false
  916. override var isFinished : Bool {
  917. get { return _finished }
  918. set {
  919. guard _finished != newValue else { return }
  920. willChangeValue(forKey: "isFinished")
  921. _finished = newValue
  922. didChangeValue(forKey: "isFinished")
  923. }
  924. }
  925. private var metadata: tableMetadata?
  926. private var view: Any?
  927. private var indexPath: IndexPath?
  928. private var networkingFunc: String = ""
  929. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  930. super.init()
  931. if metadata != nil { self.metadata = metadata! }
  932. if view != nil { self.view = view! }
  933. if indexPath != nil { self.indexPath = indexPath! }
  934. self.networkingFunc = networkingFunc
  935. }
  936. override func start() {
  937. if !Thread.isMainThread {
  938. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  939. } else {
  940. isExecuting = true
  941. if isCancelled {
  942. finish()
  943. } else {
  944. poolNetworking()
  945. }
  946. }
  947. }
  948. func finish() {
  949. isExecuting = false
  950. isFinished = true
  951. }
  952. override func cancel() {
  953. super.cancel()
  954. if isExecuting {
  955. complete()
  956. }
  957. }
  958. func complete() {
  959. finish()
  960. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  961. }
  962. func poolNetworking() {
  963. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  964. switch networkingFunc {
  965. case "downloadThumbnail":
  966. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  967. self.complete()
  968. }
  969. default:
  970. print("error")
  971. }
  972. }
  973. }
  974. //MARK: - Function Main
  975. class NCFunctionMain: NSObject {
  976. @objc static let sharedInstance: NCFunctionMain = {
  977. let instance = NCFunctionMain()
  978. return instance
  979. }()
  980. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  981. @objc func synchronizeOffline() {
  982. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  983. if (directories != nil) {
  984. for directory: tableDirectory in directories! {
  985. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  986. }
  987. }
  988. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  989. if (files != nil) {
  990. for file: tableLocalFile in files! {
  991. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  992. continue
  993. }
  994. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  995. }
  996. }
  997. }
  998. }