NCMainCommon.swift 59 KB

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