NCMainCommon.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 shared: NCMainCommon = {
  30. let instance = NCMainCommon()
  31. instance.createImagesThemingColor()
  32. return instance
  33. }()
  34. var metadataEditPhoto: tableMetadata?
  35. var docController: UIDocumentInteractionController?
  36. //MARK: -
  37. struct NCMainCommonImages {
  38. static var cellSharedImage = UIImage()
  39. static var cellCanShareImage = UIImage()
  40. static var cellShareByLinkImage = UIImage()
  41. static var cellFavouriteImage = UIImage()
  42. static var cellMoreImage = UIImage()
  43. static var cellCommentImage = UIImage()
  44. static var cellLivePhotoImage = UIImage()
  45. static var cellFolderEncryptedImage = UIImage()
  46. static var cellFolderSharedWithMeImage = UIImage()
  47. static var cellFolderPublicImage = UIImage()
  48. static var cellFolderGroupImage = UIImage()
  49. static var cellFolderExternalImage = UIImage()
  50. static var cellFolderAutomaticUploadImage = UIImage()
  51. static var cellFolderImage = UIImage()
  52. static var cellPlayImage = UIImage()
  53. }
  54. @objc func createImagesThemingColor() {
  55. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  56. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  57. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  58. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  59. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  60. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  61. NCMainCommonImages.cellLivePhotoImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  62. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  63. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  64. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  65. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  66. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  67. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  68. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  69. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  70. }
  71. //MARK: -
  72. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  73. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  74. if viewController.viewIfLoaded?.window == nil {
  75. return
  76. }
  77. guard let dic = notification.userInfo else {
  78. return
  79. }
  80. let account = dic["account"] as? NSString ?? ""
  81. let ocId = dic["ocId"] as? NSString ?? ""
  82. let serverUrl = dic["serverUrl"] as? String ?? ""
  83. let status = dic["status"] as? Int ?? Int(k_metadataStatusNormal)
  84. let progress = dic["progress"] as? CGFloat ?? 0
  85. let totalBytes = dic["totalBytes"] as? Double ?? 0
  86. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  87. if (account != appDelegate.account! as NSString) && !(viewController is CCTransfers) {
  88. return
  89. }
  90. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  91. return
  92. }
  93. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  94. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  95. return
  96. }
  97. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  98. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  99. var image = ""
  100. if status == k_metadataStatusInDownload {
  101. image = "↓"
  102. } else if status == k_metadataStatusInUpload {
  103. image = "↑"
  104. }
  105. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  106. cell.transferButton?.progress = progress
  107. }
  108. }
  109. }
  110. @objc func cancelTransferMetadata(_ metadata: tableMetadata, uploadStatusForcedStart: Bool) {
  111. if metadata.session.count == 0 {
  112. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  113. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  114. return
  115. }
  116. let metadata = tableMetadata.init(value: metadata)
  117. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  118. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  119. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  120. NCNetworking.shared.cancelUpload(ocId: metadata.ocId)
  121. } else {
  122. var session: URLSession?
  123. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  124. session = NCNetworking.shared.sessionManagerBackground
  125. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  126. session = NCNetworking.shared.sessionManagerBackgroundWWan
  127. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundExtension {
  128. session = NCNetworking.shared.sessionManagerBackgroundExtension
  129. }
  130. session!.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  131. var cancel = false
  132. if metadata.session.count > 0 && metadata.session.contains("upload") {
  133. for task in uploadTasks {
  134. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  135. if uploadStatusForcedStart {
  136. metadata.status = Int(k_metadataStatusUploadForcedStart)
  137. NCManageDatabase.sharedInstance.addMetadata(metadata)
  138. }
  139. task.cancel()
  140. cancel = true
  141. }
  142. }
  143. if cancel == false {
  144. do {
  145. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  146. }
  147. catch { }
  148. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  149. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  150. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  151. }
  152. }
  153. }
  154. }
  155. }
  156. }
  157. @objc func cancelAllTransfer() {
  158. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  159. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  160. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.account, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  161. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  162. let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d", k_metadataStatusNormal), sorted: "fileName", ascending: true)
  163. for metadata in metadatas {
  164. // Modify
  165. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  166. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  167. }
  168. // Cancel Task
  169. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  170. self.cancelTransferMetadata(metadata, uploadStatusForcedStart: false)
  171. }
  172. }
  173. }
  174. NCOperationQueue.shared.downloadCancelAll()
  175. }
  176. //MARK: -
  177. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectocId: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController) {
  178. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  179. var tableShare: tableShare?
  180. // Share
  181. if shares != nil {
  182. for share in shares! {
  183. if share.fileName == metadata.fileName {
  184. tableShare = share
  185. break
  186. }
  187. }
  188. }
  189. // Download preview
  190. if downloadThumbnail {
  191. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  192. }
  193. var isShare = false
  194. var isMounted = false
  195. if metadataFolder != nil {
  196. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  197. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  198. }
  199. if cell is NCListCell {
  200. let cell = cell as! NCListCell
  201. cell.delegate = source as? NCListCellDelegate
  202. cell.objectId = metadata.ocId
  203. cell.indexPath = indexPath
  204. cell.labelTitle.text = metadata.fileNameView
  205. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  206. cell.imageStatus.image = nil
  207. cell.imageLocal.image = nil
  208. cell.imageFavorite.image = nil
  209. cell.imageShared.image = nil
  210. if metadata.directory {
  211. if metadata.e2eEncrypted {
  212. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  213. } else if isShare {
  214. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  215. } else if (tableShare != nil && tableShare!.shareType != 3) {
  216. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  217. } else if (tableShare != nil && tableShare!.shareType == 3) {
  218. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  219. } else if metadata.mountType == "group" {
  220. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  221. } else if isMounted {
  222. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  223. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  224. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  225. } else {
  226. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  227. }
  228. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  229. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  230. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  231. // Local image: offline
  232. if tableDirectory != nil && tableDirectory!.offline {
  233. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  234. }
  235. } else {
  236. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  237. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  238. } else if(!metadata.hasPreview) {
  239. if metadata.iconName.count > 0 {
  240. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  241. } else {
  242. cell.imageItem.image = UIImage.init(named: "file")
  243. }
  244. }
  245. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  246. // image local
  247. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  248. if size > 0 {
  249. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  250. if tableLocalFile == nil && size == metadata.size {
  251. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  252. }
  253. if tableLocalFile?.offline ?? false {
  254. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  255. } else{
  256. cell.imageLocal.image = UIImage.init(named: "local")
  257. }
  258. }
  259. }
  260. // image Favorite
  261. if metadata.favorite {
  262. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  263. }
  264. // Share image
  265. if (isShare) {
  266. cell.imageShared.image = NCMainCommonImages.cellSharedImage
  267. } else if (tableShare != nil && tableShare!.shareType == 3) {
  268. cell.imageShared.image = NCMainCommonImages.cellShareByLinkImage
  269. } else if (tableShare != nil && tableShare!.shareType != 3) {
  270. cell.imageShared.image = NCMainCommonImages.cellSharedImage
  271. } else {
  272. cell.imageShared.image = NCMainCommonImages.cellCanShareImage
  273. }
  274. if metadata.ownerId != appDelegate.userID {
  275. // Load avatar
  276. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  277. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  278. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  279. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  280. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  281. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  282. } else {
  283. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  284. if errorCode == 0 && account == appDelegate.account {
  285. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  286. }
  287. }
  288. }
  289. }
  290. if isEditMode {
  291. cell.imageItemLeftConstraint.constant = 45
  292. cell.imageSelect.isHidden = false
  293. if selectocId.contains(metadata.ocId) {
  294. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  295. cell.backgroundView = NCUtility.shared.cellBlurEffect(with: cell.bounds)
  296. } else {
  297. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  298. cell.backgroundView = nil
  299. }
  300. } else {
  301. cell.imageItemLeftConstraint.constant = 10
  302. cell.imageSelect.isHidden = true
  303. cell.backgroundView = nil
  304. }
  305. // Transfer
  306. if metadata.status == k_metadataStatusInDownload || metadata.status >= k_metadataStatusTypeUpload {
  307. cell.progressView.isHidden = false
  308. cell.setButtonMore(named: "stop")
  309. } else {
  310. cell.progressView.isHidden = true
  311. cell.progressView.progress = 0.0
  312. cell.setButtonMore(named: "more")
  313. }
  314. // Remove last separator
  315. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  316. cell.separator.isHidden = true
  317. } else {
  318. cell.separator.isHidden = false
  319. }
  320. } else if cell is NCGridCell {
  321. let cell = cell as! NCGridCell
  322. cell.delegate = source as? NCGridCellDelegate
  323. cell.objectId = metadata.ocId
  324. cell.indexPath = indexPath
  325. cell.labelTitle.text = metadata.fileNameView
  326. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  327. cell.imageStatus.image = nil
  328. cell.imageLocal.image = nil
  329. cell.imageFavorite.image = nil
  330. if metadata.directory {
  331. if metadata.e2eEncrypted {
  332. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  333. } else if isShare {
  334. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  335. } else if (tableShare != nil && tableShare!.shareType != 3) {
  336. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  337. } else if (tableShare != nil && tableShare!.shareType == 3) {
  338. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  339. } else if metadata.mountType == "group" {
  340. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  341. } else if isMounted {
  342. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  343. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  344. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  345. } else {
  346. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  347. }
  348. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  349. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  350. // Local image: offline
  351. if tableDirectory != nil && tableDirectory!.offline {
  352. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  353. }
  354. } else {
  355. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  356. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  357. } else if(!metadata.hasPreview) {
  358. if metadata.iconName.count > 0 {
  359. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  360. } else {
  361. cell.imageItem.image = UIImage.init(named: "file")
  362. }
  363. }
  364. // image Local
  365. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  366. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  367. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  368. else { cell.imageLocal.image = UIImage.init(named: "local") }
  369. }
  370. }
  371. // image Favorite
  372. if metadata.favorite {
  373. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  374. }
  375. if isEditMode {
  376. cell.imageSelect.isHidden = false
  377. if selectocId.contains(metadata.ocId) {
  378. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  379. cell.backgroundView = NCUtility.shared.cellBlurEffect(with: cell.bounds)
  380. } else {
  381. cell.imageSelect.isHidden = true
  382. cell.backgroundView = nil
  383. }
  384. } else {
  385. cell.imageSelect.isHidden = true
  386. cell.backgroundView = nil
  387. }
  388. // Transfer
  389. if metadata.status == k_metadataStatusInDownload || metadata.status >= k_metadataStatusTypeUpload {
  390. cell.progressView.isHidden = false
  391. cell.setButtonMore(named: "stop")
  392. } else {
  393. cell.progressView.isHidden = true
  394. cell.progressView.progress = 0.0
  395. cell.setButtonMore(named: "more")
  396. }
  397. }
  398. }
  399. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?, livePhoto: Bool) -> UITableViewCell {
  400. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  401. // Create File System
  402. if metadata.directory {
  403. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  404. } else {
  405. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  406. }
  407. // CCCell
  408. if metadata.status == k_metadataStatusNormal || metadata.status == k_metadataStatusDownloadError {
  409. // NORMAL
  410. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  411. cell.labelTitle.text = metadata.fileNameView
  412. cell.filePreviewImageView.image = nil
  413. cell.filePreviewImageView.backgroundColor = UIColor.lightGray
  414. // Download preview
  415. if !(metadataFolder?.e2eEncrypted ?? false) {
  416. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: tableView, indexPath: indexPath)
  417. }
  418. // Share
  419. var isShare = false
  420. var isMounted = false
  421. if metadataFolder != nil {
  422. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  423. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  424. }
  425. if metadata.directory {
  426. // lable Info
  427. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  428. cell.file.backgroundColor = nil
  429. // File Image & Image Title Segue
  430. if metadata.e2eEncrypted {
  431. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  432. } else if isShare {
  433. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  434. } else if (tableShare != nil && tableShare!.shareType != 3) {
  435. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  436. } else if (tableShare != nil && tableShare!.shareType == 3) {
  437. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  438. } else if metadata.mountType == "group" {
  439. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  440. } else if isMounted {
  441. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  442. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  443. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  444. } else {
  445. cell.file.image = NCMainCommonImages.cellFolderImage
  446. }
  447. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  448. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  449. // Local image: offline
  450. if tableDirectory != nil && tableDirectory!.offline {
  451. cell.local.image = UIImage.init(named: "offlineFlag")
  452. }
  453. } else {
  454. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  455. // Lable Info
  456. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  457. // File Image
  458. if iconFileExists {
  459. cell.file.backgroundColor = nil
  460. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  461. } else if(!metadata.hasPreview){
  462. cell.file.backgroundColor = nil
  463. if metadata.iconName.count > 0 {
  464. cell.file.image = UIImage.init(named: metadata.iconName)
  465. } else {
  466. cell.file.image = UIImage.init(named: "file")
  467. }
  468. }
  469. // Local Image - Offline
  470. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  471. if size > 0 {
  472. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  473. if tableLocalFile == nil && size == metadata.size {
  474. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  475. }
  476. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  477. else { cell.local.image = UIImage.init(named: "local") }
  478. }
  479. // Status image: encrypted
  480. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.account, metadata.fileName))
  481. if tableE2eEncryption != nil && NCUtility.shared.isEncryptedMetadata(metadata) {
  482. cell.status.image = UIImage.init(named: "encrypted")
  483. }
  484. // Live Photo
  485. if metadata.livePhoto && livePhoto {
  486. cell.status.image = NCMainCommonImages.cellLivePhotoImage
  487. }
  488. }
  489. //
  490. // File & Directory
  491. //
  492. // Favorite
  493. if metadata.favorite {
  494. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  495. }
  496. // Share image
  497. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  498. if (isShare) {
  499. cell.shared.image = NCMainCommonImages.cellSharedImage
  500. } else if (tableShare != nil && tableShare!.shareType == 3) {
  501. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  502. } else if (tableShare != nil && tableShare!.shareType != 3) {
  503. cell.shared.image = NCMainCommonImages.cellSharedImage
  504. } else {
  505. cell.shared.image = NCMainCommonImages.cellCanShareImage
  506. }
  507. if metadata.ownerId != appDelegate.userID {
  508. // Load avatar
  509. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  510. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  511. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  512. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  513. cell.shared.image = avatar
  514. }
  515. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  516. if let avatar = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  517. cell.shared.image = avatar
  518. }
  519. } else {
  520. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  521. if errorCode == 0 && account == appDelegate.account {
  522. cell.shared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  523. }
  524. }
  525. }
  526. }
  527. }
  528. // Comment
  529. if metadata.commentsUnread {
  530. cell.comment.image = NCMainCommonImages.cellCommentImage
  531. cell.labelTitleTrailingConstraint.constant = 160
  532. } else {
  533. cell.labelTitleTrailingConstraint.constant = 110
  534. }
  535. // More Image
  536. cell.more.image = NCMainCommonImages.cellMoreImage
  537. // downloadFile Error
  538. if metadata.status == k_metadataStatusDownloadError {
  539. cell.status.image = UIImage.init(named: "statuserror")
  540. if metadata.sessionError.count == 0 {
  541. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  542. } else {
  543. cell.labelInfoFile.text = metadata.sessionError
  544. }
  545. }
  546. return cell
  547. } else {
  548. // TRASNFER
  549. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  550. cell.labelTitle.text = metadata.fileNameView
  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, etag: metadata.etag))
  589. if iconFileExists {
  590. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  591. } else {
  592. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  593. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudUpload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  594. } else {
  595. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudDownload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  596. }
  597. }
  598. // uploadFileError
  599. if metadata.status == k_metadataStatusUploadError {
  600. cell.status.image = UIImage.init(named: "statuserror")
  601. if metadata.sessionError.count == 0 {
  602. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  603. } else {
  604. cell.labelInfoFile.text = metadata.sessionError
  605. }
  606. }
  607. // Progress
  608. cell.transferButton.progress = progress
  609. // User
  610. if metadata.account != appDelegate.account {
  611. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  612. if tableAccount != nil {
  613. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, urlBase: tableAccount!.urlBase) + "-" + tableAccount!.user + ".png"
  614. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  615. if avatar != nil {
  616. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  617. let imageSize = avatarImageView?.bounds.size
  618. UIGraphicsBeginImageContext(imageSize!)
  619. let context = UIGraphicsGetCurrentContext()
  620. avatarImageView?.layer.render(in: context!)
  621. avatar = UIGraphicsGetImageFromCurrentImageContext()
  622. UIGraphicsEndImageContext()
  623. cell.user.image = avatar
  624. }
  625. }
  626. }
  627. return cell
  628. }
  629. }
  630. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  631. guard let indexPath = indexPath else {
  632. return nil
  633. }
  634. guard let sectionDataSource = sectionDataSource else {
  635. return nil
  636. }
  637. let section = indexPath.section + 1
  638. let row = indexPath.row + 1
  639. let totSections = sectionDataSource.sections.count
  640. if totSections < section || section > totSections {
  641. return nil
  642. }
  643. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  644. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  645. return nil
  646. }
  647. let totRows = filesID.count
  648. if totRows < row || row > totRows {
  649. return nil
  650. }
  651. let ocId = filesID.object(at: indexPath.row)
  652. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  653. return metadata
  654. }
  655. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  656. if view is UICollectionView {
  657. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  658. }
  659. if view is UITableView {
  660. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  661. }
  662. return true
  663. }
  664. //MARK: - download Open Selector
  665. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  666. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  667. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  668. } else {
  669. NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
  670. }
  671. }
  672. //MARK: - OpenIn
  673. func openIn(fileURL: URL, selector: String?) {
  674. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  675. docController = UIDocumentInteractionController(url: fileURL)
  676. docController?.delegate = self
  677. if selector == selectorOpenInDetail {
  678. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  679. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  680. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  681. } else {
  682. guard let splitViewController = appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  683. return }
  684. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  685. }
  686. }
  687. //MARK: - OpenShare
  688. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  689. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  690. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  691. shareViewController.metadata = metadata
  692. shareViewController.indexPage = indexPage
  693. shareNavigationController.modalPresentationStyle = .formSheet
  694. ViewController.present(shareNavigationController, animated: true, completion: nil)
  695. }
  696. //MARK: - NCAudioRecorder
  697. func startAudioRecorder() {
  698. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  699. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  700. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  701. viewController.delegate = self
  702. viewController.createRecorder(fileName: fileName)
  703. viewController.modalTransitionStyle = .crossDissolve
  704. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  705. appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  706. }
  707. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  708. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  709. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  710. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  711. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  712. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  713. appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  714. }
  715. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  716. }
  717. }
  718. //MARK: - Main TabBarController
  719. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  720. override func viewDidLoad() {
  721. super.viewDidLoad()
  722. delegate = self
  723. }
  724. //Delegate methods
  725. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  726. let tabViewControllers = tabBarController.viewControllers!
  727. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  728. if let vc = viewController as? UINavigationController {
  729. vc.popToRootViewController(animated: true);
  730. }
  731. return false
  732. }
  733. animateToTab(toIndex: toIndex)
  734. return true
  735. }
  736. func animateToTab(toIndex: Int) {
  737. let tabViewControllers = viewControllers!
  738. let fromView = selectedViewController!.view!
  739. let toView = tabViewControllers[toIndex].view!
  740. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  741. guard fromIndex != toIndex else {return}
  742. // Add the toView to the tab bar view
  743. fromView.superview?.addSubview(toView)
  744. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  745. // Position toView off screen (to the left/right of fromView)
  746. let screenWidth = UIScreen.main.bounds.size.width;
  747. let scrollRight = toIndex > fromIndex!;
  748. let offset = (scrollRight ? screenWidth : -screenWidth)
  749. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  750. // Disable interaction during animation
  751. view.isUserInteractionEnabled = false
  752. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  753. // Slide the views by -offset
  754. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  755. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  756. }, completion: { finished in
  757. // Remove the old view from the tabbar view.
  758. fromView.removeFromSuperview()
  759. self.selectedIndex = toIndex
  760. self.view.isUserInteractionEnabled = true
  761. })
  762. }
  763. }