NCMainCommon.swift 57 KB

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