NCMainCommon.swift 61 KB

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