NCMainCommon.swift 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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, PhotoEditorDelegate, NCAudioRecorderViewControllerDelegate, UIDocumentInteractionControllerDelegate {
  29. @objc static let sharedInstance: NCMainCommon = {
  30. let instance = NCMainCommon()
  31. instance.createImagesThemingColor()
  32. return instance
  33. }()
  34. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  35. var metadataEditPhoto: tableMetadata?
  36. var docController: UIDocumentInteractionController?
  37. lazy var operationQueueReloadDatasource: OperationQueue = {
  38. let queue = OperationQueue()
  39. queue.name = "Reload main datasource queue"
  40. queue.maxConcurrentOperationCount = 1
  41. return queue
  42. }()
  43. //MARK: -
  44. struct NCMainCommonImages {
  45. static var cellSharedImage = UIImage()
  46. static var cellCanShareImage = UIImage()
  47. static var cellShareByLinkImage = UIImage()
  48. static var cellFavouriteImage = UIImage()
  49. static var cellMoreImage = UIImage()
  50. static var cellCommentImage = UIImage()
  51. static var cellFolderEncryptedImage = UIImage()
  52. static var cellFolderSharedWithMeImage = UIImage()
  53. static var cellFolderPublicImage = UIImage()
  54. static var cellFolderGroupImage = UIImage()
  55. static var cellFolderExternalImage = UIImage()
  56. static var cellFolderAutomaticUploadImage = UIImage()
  57. static var cellFolderImage = UIImage()
  58. static var cellPlayImage = UIImage()
  59. }
  60. @objc func createImagesThemingColor() {
  61. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  62. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.graySoft)
  63. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  64. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  65. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  66. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  67. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  68. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  69. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  70. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  71. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  72. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  73. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  74. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  75. }
  76. //MARK: -
  77. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  78. if viewController.viewIfLoaded?.window == nil {
  79. return
  80. }
  81. guard let dic = notification.userInfo else {
  82. return
  83. }
  84. let account = dic["account"] as? NSString ?? ""
  85. let ocId = dic["ocId"] as? NSString ?? ""
  86. let serverUrl = dic["serverUrl"] as? String ?? ""
  87. let status = dic["status"] as? Int ?? Int(k_taskIdentifierDone)
  88. let progress = dic["progress"] as? CGFloat ?? 0
  89. let totalBytes = dic["totalBytes"] as? Double ?? 0
  90. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  91. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  92. return
  93. }
  94. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  95. return
  96. }
  97. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  98. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  99. return
  100. }
  101. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  102. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  103. var image = ""
  104. if status == k_metadataStatusInDownload {
  105. image = "↓"
  106. } else if status == k_metadataStatusInUpload {
  107. image = "↑"
  108. }
  109. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  110. cell.transferButton?.progress = progress
  111. }
  112. }
  113. }
  114. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  115. var actionReloadDatasource = k_action_NULL
  116. var metadata = metadata
  117. if metadata.session.count == 0 { return }
  118. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else { return }
  119. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  120. var cancel = false
  121. // DOWNLOAD
  122. if metadata.session.count > 0 && metadata.session.contains("download") {
  123. for task in downloadTasks {
  124. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  125. task.cancel()
  126. cancel = true
  127. }
  128. }
  129. if cancel == false {
  130. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  131. }
  132. actionReloadDatasource = k_action_MOD
  133. }
  134. // UPLOAD
  135. if metadata.session.count > 0 && metadata.session.contains("upload") {
  136. for task in uploadTasks {
  137. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  138. if uploadStatusForcedStart {
  139. metadata.status = Int(k_metadataStatusUploadForcedStart)
  140. metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) ?? metadata
  141. }
  142. task.cancel()
  143. cancel = true
  144. }
  145. }
  146. if cancel == false {
  147. do {
  148. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  149. }
  150. catch { }
  151. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  152. }
  153. actionReloadDatasource = k_action_DEL
  154. }
  155. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  156. self.reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: actionReloadDatasource)
  157. }
  158. }
  159. }
  160. @objc func cancelAllTransfer() {
  161. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  162. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  163. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  164. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d", k_metadataStatusNormal), sorted: "fileName", ascending: true) {
  165. for metadata in metadatas {
  166. // Modify
  167. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  168. metadata.session = ""
  169. metadata.sessionSelector = ""
  170. metadata.status = Int(k_metadataStatusNormal)
  171. NCManageDatabase.sharedInstance.addMetadata(metadata)
  172. }
  173. // Cancel Task
  174. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  175. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  176. }
  177. }
  178. }
  179. }
  180. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  181. return
  182. }
  183. }
  184. //MARK: -
  185. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectocId: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController) {
  186. var tableShare: tableShare?
  187. // Share
  188. if shares != nil {
  189. for share in shares! {
  190. if share.fileName == metadata.fileName {
  191. tableShare = share
  192. break
  193. }
  194. }
  195. }
  196. // Download preview
  197. if downloadThumbnail {
  198. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  199. }
  200. var isShare = false
  201. var isMounted = false
  202. if metadataFolder != nil {
  203. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  204. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  205. }
  206. if cell is NCListCell {
  207. let cell = cell as! NCListCell
  208. cell.delegate = source as? NCListCellDelegate
  209. cell.objectId = metadata.ocId
  210. cell.indexPath = indexPath
  211. cell.labelTitle.text = metadata.fileNameView
  212. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  213. cell.imageStatus.image = nil
  214. cell.imageLocal.image = nil
  215. cell.imageFavorite.image = nil
  216. cell.shared.image = nil
  217. if metadata.directory {
  218. if metadata.e2eEncrypted {
  219. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  220. } else if isShare {
  221. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  222. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  223. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  224. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  225. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  226. } else if metadata.mountType == "group" {
  227. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  228. } else if isMounted {
  229. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  230. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  231. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  232. } else {
  233. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  234. }
  235. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  236. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  237. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  238. // Status image: passcode
  239. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  240. cell.imageStatus.image = UIImage.init(named: "passcode")
  241. }
  242. // Local image: offline
  243. if tableDirectory != nil && tableDirectory!.offline {
  244. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  245. }
  246. } else {
  247. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileName)) {
  248. NCUtility.sharedInstance.loadImage(ocId: metadata.ocId, fileNameView: metadata.fileNameView) { (image) in
  249. cell.imageItem.image = image
  250. }
  251. } else {
  252. if metadata.iconName.count > 0 {
  253. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  254. } else {
  255. cell.imageItem.image = UIImage.init(named: "file")
  256. }
  257. }
  258. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  259. // image local
  260. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  261. if size > 0 {
  262. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  263. if tableLocalFile == nil && size == metadata.size {
  264. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  265. }
  266. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  267. else { cell.imageLocal.image = UIImage.init(named: "local") }
  268. }
  269. }
  270. // image Favorite
  271. if metadata.favorite {
  272. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  273. }
  274. // Share image
  275. if (isShare) {
  276. cell.shared.image = NCMainCommonImages.cellSharedImage
  277. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  278. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  279. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  280. cell.shared.image = NCMainCommonImages.cellSharedImage
  281. } else {
  282. cell.shared.image = NCMainCommonImages.cellCanShareImage
  283. }
  284. if metadata.ownerId != appDelegate.activeUserID {
  285. // Load avatar
  286. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  287. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  288. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  289. cell.shared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  290. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  291. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  292. } else {
  293. NCCommunication.sharedInstance.downloadAvatar(serverUrl: appDelegate.activeUrl, userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: appDelegate.activeAccount) { (account, data, errorCode, errorMessage) in
  294. if errorCode == 0 && account == self.appDelegate.activeAccount {
  295. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  296. }
  297. }
  298. }
  299. }
  300. if isEditMode {
  301. cell.imageItemLeftConstraint.constant = 45
  302. cell.imageSelect.isHidden = false
  303. if selectocId.contains(metadata.ocId) {
  304. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  305. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  306. } else {
  307. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  308. cell.backgroundView = nil
  309. }
  310. } else {
  311. cell.imageItemLeftConstraint.constant = 10
  312. cell.imageSelect.isHidden = true
  313. cell.backgroundView = nil
  314. }
  315. // Remove last separator
  316. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  317. cell.separator.isHidden = true
  318. } else {
  319. cell.separator.isHidden = false
  320. }
  321. } else if cell is NCGridCell {
  322. let cell = cell as! NCGridCell
  323. cell.delegate = source as? NCGridCellDelegate
  324. cell.objectId = metadata.ocId
  325. cell.indexPath = indexPath
  326. cell.labelTitle.text = metadata.fileNameView
  327. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  328. cell.imageStatus.image = nil
  329. cell.imageLocal.image = nil
  330. cell.imageFavorite.image = nil
  331. if metadata.directory {
  332. if metadata.e2eEncrypted {
  333. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  334. } else if isShare {
  335. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  336. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  337. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  338. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  339. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  340. } else if metadata.mountType == "group" {
  341. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  342. } else if isMounted {
  343. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  344. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  345. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  346. } else {
  347. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  348. }
  349. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  350. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  351. // Status image: passcode
  352. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  353. cell.imageStatus.image = UIImage.init(named: "passcode")
  354. }
  355. // Local image: offline
  356. if tableDirectory != nil && tableDirectory!.offline {
  357. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  358. }
  359. } else {
  360. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileName)) {
  361. NCUtility.sharedInstance.loadImage(ocId: metadata.ocId, fileNameView: metadata.fileNameView) { (image) in
  362. cell.imageItem.image = image
  363. }
  364. } else {
  365. if metadata.iconName.count > 0 {
  366. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  367. } else {
  368. cell.imageItem.image = UIImage.init(named: "file")
  369. }
  370. }
  371. // image Local
  372. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  373. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  374. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  375. else { cell.imageLocal.image = UIImage.init(named: "local") }
  376. }
  377. }
  378. // image Favorite
  379. if metadata.favorite {
  380. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  381. }
  382. if isEditMode {
  383. cell.imageSelect.isHidden = false
  384. if selectocId.contains(metadata.ocId) {
  385. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  386. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  387. } else {
  388. cell.imageSelect.isHidden = true
  389. cell.backgroundView = nil
  390. }
  391. } else {
  392. cell.imageSelect.isHidden = true
  393. cell.backgroundView = nil
  394. }
  395. }
  396. }
  397. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?) -> UITableViewCell {
  398. // Create File System
  399. if metadata.directory {
  400. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  401. } else {
  402. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  403. }
  404. // CCCell
  405. if metadata.status == k_metadataStatusNormal {
  406. // NORMAL
  407. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  408. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  409. cell.accessoryType = UITableViewCell.AccessoryType.none
  410. cell.file.image = nil
  411. cell.status.image = nil
  412. cell.favorite.image = nil
  413. cell.shared.image = nil
  414. cell.local.image = nil
  415. cell.comment.image = nil
  416. cell.shared.isUserInteractionEnabled = false
  417. cell.viewShared.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  418. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  419. // change color selection
  420. let selectionColor = UIView()
  421. selectionColor.backgroundColor = NCBrandColor.sharedInstance.select
  422. cell.selectedBackgroundView = selectionColor
  423. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  424. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  425. cell.labelTitle.text = metadata.fileNameView
  426. // Download preview
  427. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  428. // Share
  429. var isShare = false
  430. var isMounted = false
  431. if metadataFolder != nil {
  432. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  433. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  434. }
  435. if metadata.directory {
  436. // lable Info
  437. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  438. // File Image & Image Title Segue
  439. if metadata.e2eEncrypted {
  440. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  441. } else if isShare {
  442. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  443. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  444. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  445. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  446. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  447. } else if metadata.mountType == "group" {
  448. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  449. } else if isMounted {
  450. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  451. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  452. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  453. } else {
  454. cell.file.image = NCMainCommonImages.cellFolderImage
  455. }
  456. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  457. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  458. // Local image: offline
  459. if tableDirectory != nil && tableDirectory!.offline {
  460. cell.local.image = UIImage.init(named: "offlineFlag")
  461. }
  462. // Status image: passcode
  463. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  464. cell.status.image = UIImage.init(named: "passcode")
  465. }
  466. } else {
  467. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  468. // Lable Info
  469. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  470. // File Image
  471. if iconFileExists {
  472. NCUtility.sharedInstance.loadImage(ocId: metadata.ocId, fileNameView: metadata.fileNameView) { (image) in
  473. cell.file.image = image
  474. }
  475. } else {
  476. if metadata.iconName.count > 0 {
  477. cell.file.image = UIImage.init(named: metadata.iconName)
  478. } else {
  479. cell.file.image = UIImage.init(named: "file")
  480. }
  481. }
  482. // Local Image - Offline
  483. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  484. if size > 0 {
  485. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  486. if tableLocalFile == nil && size == metadata.size {
  487. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  488. }
  489. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  490. else { cell.local.image = UIImage.init(named: "local") }
  491. }
  492. // Status image: encrypted
  493. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  494. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  495. cell.status.image = UIImage.init(named: "encrypted")
  496. }
  497. }
  498. //
  499. // File & Directory
  500. //
  501. // Favorite
  502. if metadata.favorite {
  503. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  504. }
  505. // Share image
  506. if (isShare) {
  507. cell.shared.image = NCMainCommonImages.cellSharedImage
  508. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  509. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  510. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  511. cell.shared.image = NCMainCommonImages.cellSharedImage
  512. } else {
  513. cell.shared.image = NCMainCommonImages.cellCanShareImage
  514. }
  515. if metadata.ownerId != appDelegate.activeUserID {
  516. // Load avatar
  517. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  518. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  519. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  520. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  521. cell.shared.image = avatar
  522. }
  523. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  524. if let avatar = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  525. cell.shared.image = avatar
  526. }
  527. } else {
  528. NCCommunication.sharedInstance.downloadAvatar(serverUrl: appDelegate.activeUrl, userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: appDelegate.activeAccount) { (account, data, errorCode, errorMessage) in
  529. if errorCode == 0 && account == self.appDelegate.activeAccount {
  530. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  531. }
  532. }
  533. }
  534. }
  535. // Comment
  536. if metadata.commentsUnread {
  537. cell.comment.image = NCMainCommonImages.cellCommentImage
  538. cell.labelTitleTrailingConstraint.constant = 160
  539. } else {
  540. cell.labelTitleTrailingConstraint.constant = 110
  541. }
  542. // More Image
  543. cell.more.image = NCMainCommonImages.cellMoreImage
  544. return cell
  545. } else {
  546. // TRASNFER
  547. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  548. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  549. cell.accessoryType = UITableViewCell.AccessoryType.none
  550. cell.file.image = nil
  551. cell.status.image = nil
  552. cell.user.image = nil
  553. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  554. cell.labelTitle.text = metadata.fileNameView
  555. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  556. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  557. var progress: CGFloat = 0.0
  558. var totalBytes: Double = 0.0
  559. //var totalBytesExpected : Double = 0
  560. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  561. if progressArray != nil && progressArray?.count == 3 {
  562. progress = progressArray?.object(at: 0) as! CGFloat
  563. totalBytes = progressArray?.object(at: 1) as! Double
  564. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  565. }
  566. // Write status on Label Info
  567. switch metadata.status {
  568. case Int(k_metadataStatusWaitDownload):
  569. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  570. progress = 0.0
  571. break
  572. case Int(k_metadataStatusInDownload):
  573. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  574. progress = 0.0
  575. break
  576. case Int(k_metadataStatusDownloading):
  577. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  578. break
  579. case Int(k_metadataStatusWaitUpload):
  580. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  581. progress = 0.0
  582. break
  583. case Int(k_metadataStatusInUpload):
  584. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  585. progress = 0.0
  586. break
  587. case Int(k_metadataStatusUploading):
  588. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  589. break
  590. default:
  591. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  592. progress = 0.0
  593. }
  594. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  595. if iconFileExists {
  596. NCUtility.sharedInstance.loadImage(ocId: metadata.ocId, fileNameView: metadata.fileNameView) { (image) in
  597. cell.file.image = image
  598. }
  599. } else {
  600. if metadata.iconName.count > 0 {
  601. cell.file.image = UIImage.init(named: metadata.iconName)
  602. } else {
  603. cell.file.image = UIImage.init(named: "file")
  604. }
  605. }
  606. // Session Upload Extension
  607. if metadata.session == k_upload_session_extension {
  608. cell.labelTitle.isEnabled = false
  609. cell.labelInfoFile.isEnabled = false
  610. } else {
  611. cell.labelTitle.isEnabled = true
  612. cell.labelInfoFile.isEnabled = true
  613. }
  614. // downloadFile
  615. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  616. //
  617. }
  618. // downloadFile Error
  619. if metadata.status == k_metadataStatusDownloadError {
  620. cell.status.image = UIImage.init(named: "statuserror")
  621. if metadata.sessionError.count == 0 {
  622. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  623. } else {
  624. cell.labelInfoFile.text = metadata.sessionError
  625. }
  626. }
  627. // uploadFile
  628. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  629. if (!iconFileExists) {
  630. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  631. }
  632. cell.labelTitle.isEnabled = false
  633. }
  634. // uploadFileError
  635. if metadata.status == k_metadataStatusUploadError {
  636. cell.labelTitle.isEnabled = false
  637. cell.status.image = UIImage.init(named: "statuserror")
  638. if !iconFileExists {
  639. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  640. }
  641. if metadata.sessionError.count == 0 {
  642. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  643. } else {
  644. cell.labelInfoFile.text = metadata.sessionError
  645. }
  646. }
  647. // Progress
  648. cell.transferButton.progress = progress
  649. // User
  650. if metadata.account != appDelegate.activeAccount {
  651. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  652. if tableAccount != nil {
  653. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  654. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  655. if avatar != nil {
  656. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  657. let imageSize = avatarImageView?.bounds.size
  658. UIGraphicsBeginImageContext(imageSize!)
  659. let context = UIGraphicsGetCurrentContext()
  660. avatarImageView?.layer.render(in: context!)
  661. avatar = UIGraphicsGetImageFromCurrentImageContext()
  662. UIGraphicsEndImageContext()
  663. cell.user.image = avatar
  664. }
  665. }
  666. }
  667. return cell
  668. }
  669. }
  670. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  671. guard let indexPath = indexPath else {
  672. return nil
  673. }
  674. guard let sectionDataSource = sectionDataSource else {
  675. return nil
  676. }
  677. let section = indexPath.section + 1
  678. let row = indexPath.row + 1
  679. let totSections = sectionDataSource.sections.count
  680. if totSections < section || section > totSections {
  681. return nil
  682. }
  683. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  684. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  685. return nil
  686. }
  687. let totRows = filesID.count
  688. if totRows < row || row > totRows {
  689. return nil
  690. }
  691. let ocId = filesID.object(at: indexPath.row)
  692. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  693. return metadata
  694. }
  695. @objc func reloadDatasource(ServerUrl: String?, ocId: String?, action: Int32) {
  696. if operationQueueReloadDatasource.operationCount > 0 {
  697. return
  698. }
  699. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  700. self.operationQueueReloadDatasource.addOperation {
  701. DispatchQueue.main.async {
  702. self.appDelegate.activeMain.reloadDatasource(ServerUrl, ocId: ocId, action: Int(action))
  703. }
  704. }
  705. }
  706. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  707. self.operationQueueReloadDatasource.addOperation {
  708. DispatchQueue.main.async {
  709. self.appDelegate.activeFavorites.reloadDatasource(ocId, action: Int(action))
  710. }
  711. }
  712. }
  713. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  714. self.operationQueueReloadDatasource.addOperation {
  715. DispatchQueue.main.async {
  716. self.appDelegate.activeTransfers.reloadDatasource(ocId, action: Int(action))
  717. }
  718. }
  719. }
  720. }
  721. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  722. if view is UICollectionView {
  723. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  724. }
  725. if view is UITableView {
  726. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  727. }
  728. return true
  729. }
  730. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  731. guard let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  732. return
  733. }
  734. guard let image = UIImage(contentsOfFile: path) else {
  735. return
  736. }
  737. self.metadataEditPhoto = metadata
  738. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  739. photoEditor.image = image
  740. photoEditor.photoEditorDelegate = self
  741. photoEditor.hiddenControls = [.save, .share, .sticker]
  742. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  743. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  744. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  745. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  746. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  747. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  748. photoEditor.modalPresentationStyle = .fullScreen
  749. viewController.present(photoEditor, animated: true, completion: nil)
  750. }
  751. func doneEditing(image: UIImage) {
  752. guard let metadata = self.metadataEditPhoto else {
  753. return
  754. }
  755. guard let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  756. return
  757. }
  758. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  759. return
  760. }
  761. if filetype == "PNG" {
  762. do {
  763. try image.pngData()?.write(to: NSURL(fileURLWithPath:path) as URL, options: .atomic)
  764. } catch { return }
  765. } else if filetype == "JPG" {
  766. let imageData = image.jpegData(compressionQuality: 1)
  767. do {
  768. try imageData?.write(to: NSURL(fileURLWithPath:path) as URL)
  769. } catch { return }
  770. }
  771. // write icon
  772. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  773. // upload
  774. metadata.session = k_upload_session
  775. metadata.sessionSelector = selectorUploadFile
  776. metadata.status = Int(k_metadataStatusWaitUpload)
  777. NCManageDatabase.sharedInstance.addMetadata(metadata)
  778. }
  779. func canceledEditing() {
  780. print("Canceled")
  781. }
  782. //MARK: - download Open Selector
  783. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  784. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  785. NCNetworkingMain.sharedInstance.downloadFileSuccessFailure(metadata.fileName, ocId: metadata.ocId, serverUrl: metadata.serverUrl, selector: selector, errorMessage: "", errorCode: 0)
  786. } else {
  787. metadata.session = k_download_session
  788. metadata.sessionError = ""
  789. metadata.sessionSelector = selector //selectorOpenIn
  790. metadata.status = Int(k_metadataStatusWaitDownload)
  791. NCManageDatabase.sharedInstance.addMetadata(metadata)
  792. reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: k_action_MOD)
  793. }
  794. }
  795. //MARK: - OpenIn
  796. func openIn(metadata: tableMetadata, selector: String) {
  797. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  798. docController?.delegate = self
  799. if selector == selectorOpenInDetail {
  800. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  801. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  802. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  803. } else {
  804. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  805. return }
  806. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  807. }
  808. }
  809. //MARK: - OpenShare
  810. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  811. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  812. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  813. shareViewController.metadata = metadata
  814. shareViewController.indexPage = indexPage
  815. shareNavigationController.modalPresentationStyle = .formSheet
  816. ViewController.present(shareNavigationController, animated: true, completion: nil)
  817. }
  818. //MARK: - NCAudioRecorder
  819. func startAudioRecorder() {
  820. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  821. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  822. viewController.delegate = self
  823. viewController.createRecorder(fileName: fileName)
  824. viewController.modalTransitionStyle = .crossDissolve
  825. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  826. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  827. }
  828. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  829. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  830. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  831. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  832. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  833. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  834. }
  835. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  836. }
  837. }
  838. //MARK: - Main TabBarController
  839. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  840. override func viewDidLoad() {
  841. super.viewDidLoad()
  842. delegate = self
  843. }
  844. //Delegate methods
  845. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  846. let tabViewControllers = tabBarController.viewControllers!
  847. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  848. if let vc = viewController as? UINavigationController {
  849. vc.popToRootViewController(animated: true);
  850. }
  851. return false
  852. }
  853. animateToTab(toIndex: toIndex)
  854. return true
  855. }
  856. func animateToTab(toIndex: Int) {
  857. let tabViewControllers = viewControllers!
  858. let fromView = selectedViewController!.view!
  859. let toView = tabViewControllers[toIndex].view!
  860. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  861. guard fromIndex != toIndex else {return}
  862. // Add the toView to the tab bar view
  863. fromView.superview?.addSubview(toView)
  864. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  865. // Position toView off screen (to the left/right of fromView)
  866. let screenWidth = UIScreen.main.bounds.size.width;
  867. let scrollRight = toIndex > fromIndex!;
  868. let offset = (scrollRight ? screenWidth : -screenWidth)
  869. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  870. // Disable interaction during animation
  871. view.isUserInteractionEnabled = false
  872. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  873. // Slide the views by -offset
  874. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  875. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  876. }, completion: { finished in
  877. // Remove the old view from the tabbar view.
  878. fromView.removeFromSuperview()
  879. self.selectedIndex = toIndex
  880. self.view.isUserInteractionEnabled = true
  881. })
  882. }
  883. }
  884. //
  885. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  886. //
  887. extension UITabBar {
  888. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  889. // the Master view controller shows the UITabBarItem icon next to the text
  890. override open var traitCollection: UITraitCollection {
  891. if UIDevice.current.userInterfaceIdiom == .pad {
  892. return UITraitCollection(horizontalSizeClass: .compact)
  893. }
  894. return super.traitCollection
  895. }
  896. }
  897. //MARK: - Networking Main
  898. class NCNetworkingMain: NSObject, CCNetworkingDelegate, IMImagemeterViewerDelegate {
  899. @objc static let sharedInstance: NCNetworkingMain = {
  900. let instance = NCNetworkingMain()
  901. return instance
  902. }()
  903. lazy var operationQueueNetworkingMain: OperationQueue = {
  904. let queue = OperationQueue()
  905. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  906. queue.maxConcurrentOperationCount = 1
  907. return queue
  908. }()
  909. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  910. // DOWNLOAD
  911. func downloadStart(_ ocId: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  912. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  913. appDelegate.updateApplicationIconBadgeNumber()
  914. }
  915. func downloadFileSuccessFailure(_ fileName: String!, ocId: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  916. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else {
  917. return
  918. }
  919. if metadata.account != appDelegate.activeAccount {
  920. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  921. return
  922. }
  923. if errorCode == 0 {
  924. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  925. // Synchronized
  926. if selector == selectorDownloadSynchronize {
  927. appDelegate.updateApplicationIconBadgeNumber()
  928. appDelegate.startLoadAutoDownloadUpload()
  929. return
  930. }
  931. // Modify Photo
  932. if selector == selectorDownloadEditPhoto {
  933. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  934. return
  935. }
  936. // open View File
  937. if (selector == selectorLoadFileView || selector == selectorLoadFileViewFavorite || selector == selectorLoadFileInternalView) && UIApplication.shared.applicationState == UIApplication.State.active {
  938. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  939. if uti == nil {
  940. uti = ""
  941. } else if uti!.contains("opendocument") && !NCUtility.sharedInstance.isRichDocument(metadata) {
  942. metadata.typeFile = k_metadataTypeFile_unknown
  943. }
  944. #if HC
  945. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  946. if !IMUtility.shared.IMUnzip(metadata: metadata) {
  947. NCContentPresenter.shared.messageNotification("_error_", description: "Bundle imagemeter error. 🤷‍♂️", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: 0)
  948. return
  949. }
  950. let storyboard = UIStoryboard(name: "IMImagemeter", bundle: nil)
  951. let imagemeterViewer = storyboard.instantiateInitialViewController() as! IMImagemeterViewer
  952. imagemeterViewer.metadata = metadata
  953. imagemeterViewer.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  954. imagemeterViewer.imagemeterViewerDelegate = self
  955. self.appDelegate.window.rootViewController?.present(imagemeterViewer, animated: true, completion: nil)
  956. return
  957. }
  958. #else
  959. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  960. NCMainCommon.sharedInstance.openIn(metadata: metadata, selector: selector)
  961. return
  962. }
  963. #endif
  964. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  965. NCMainCommon.sharedInstance.openIn(metadata: metadata, selector: selector)
  966. } else {
  967. if appDelegate.activeMain.view.window != nil {
  968. appDelegate.activeMain.shouldPerformSegue(metadata, selector: selector)
  969. }
  970. if appDelegate.activeFavorites.view.window != nil {
  971. appDelegate.activeFavorites.shouldPerformSegue(metadata, selector: selector)
  972. }
  973. }
  974. }
  975. // Open in...
  976. if (selector == selectorOpenIn || selector == selectorOpenInDetail) && UIApplication.shared.applicationState == UIApplication.State.active {
  977. NCMainCommon.sharedInstance.openIn(metadata: metadata, selector: selector)
  978. }
  979. // Save to Photo Album
  980. if selector == selectorSave {
  981. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  982. }
  983. // Copy File
  984. if selector == selectorLoadCopy {
  985. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  986. }
  987. // Set as available offline
  988. if selector == selectorLoadOffline {
  989. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, offline: true)
  990. }
  991. appDelegate.startLoadAutoDownloadUpload()
  992. } else {
  993. // File do not exists on server, remove in local
  994. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  995. do {
  996. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  997. } catch { }
  998. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  999. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  1000. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_DEL))
  1001. }
  1002. }
  1003. appDelegate.startLoadAutoDownloadUpload()
  1004. }
  1005. #if HC
  1006. // IMImagemeterViewerDelegate
  1007. func closeImagemeterViewer(metadata: tableMetadata?, bundleDirectory: String) {
  1008. guard let metadata = metadata else { return }
  1009. let ocIdTemp = NSUUID().uuidString.lowercased()
  1010. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName)!
  1011. let bundleDirectoryURL = URL(fileURLWithPath: bundleDirectory)
  1012. let fileNameZipUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName))
  1013. // Create IMI
  1014. try? FileManager.default.removeItem(at: fileNameZipUrl)
  1015. do {
  1016. try FileManager().zipItem(at: bundleDirectoryURL, to:fileNameZipUrl)
  1017. } catch {
  1018. NCContentPresenter.shared.messageNotification("_error_", description: "Creation of IMI archive failed with error", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  1019. return
  1020. }
  1021. // Verify if is changed
  1022. if IMUtility.shared.IMIsChange(metadata: metadata, fileNameZipUrl: fileNameZipUrl) {
  1023. let com = IMCommunication.init()
  1024. _ = com.uploadFileIMI(serverUrl: metadata.serverUrl, fileName: metadata.fileName, fileNameLocalPath: fileNameLocalPath, ocId: ocIdTemp)
  1025. }
  1026. // Remove bundle directory
  1027. try? FileManager.default.removeItem(atPath: bundleDirectory)
  1028. }
  1029. #endif
  1030. // UPLOAD
  1031. func uploadStart(_ ocId: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  1032. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1033. appDelegate.updateApplicationIconBadgeNumber()
  1034. }
  1035. func uploadFileSuccessFailure(_ fileName: String!, ocId: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  1036. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else {
  1037. return
  1038. }
  1039. if metadata.account != appDelegate.activeAccount {
  1040. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1041. return
  1042. }
  1043. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, ocId: ocId, action: Int32(k_action_MOD))
  1044. if errorCode == 0 {
  1045. appDelegate.startLoadAutoDownloadUpload()
  1046. } else {
  1047. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1048. NCContentPresenter.shared.messageNotification("_upload_file_", description: errorMessage, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  1049. }
  1050. }
  1051. }
  1052. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1053. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  1054. }
  1055. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  1056. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1057. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  1058. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  1059. NCCommunication.sharedInstance.downloadPreview(serverUrl: appDelegate.activeUrl, fileNamePath: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview), customUserAgent: nil, addCustomHeaders: nil, account: metadata.account) { (account, data, errorCode, errorMessage) in
  1060. if errorCode == 0 && data != nil {
  1061. if let image = UIImage.init(data: data!) {
  1062. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1063. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1064. if cell is NCListCell {
  1065. (cell as! NCListCell).imageItem.image = image
  1066. } else if cell is NCGridCell {
  1067. (cell as! NCGridCell).imageItem.image = image
  1068. } else if cell is NCGridMediaCell {
  1069. (cell as! NCGridMediaCell).imageItem.image = image
  1070. }
  1071. }
  1072. }
  1073. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1074. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1075. if cell is CCCellMainTransfer {
  1076. (cell as! CCCellMainTransfer).file.image = image
  1077. } else if cell is CCCellMain {
  1078. (cell as! CCCellMain).file.image = image
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. return closure()
  1085. }
  1086. }
  1087. return closure()
  1088. }
  1089. }
  1090. //MARK: - Operation Networking Main
  1091. class NCOperationNetworkingMain: Operation {
  1092. private var _executing : Bool = false
  1093. override var isExecuting : Bool {
  1094. get { return _executing }
  1095. set {
  1096. guard _executing != newValue else { return }
  1097. willChangeValue(forKey: "isExecuting")
  1098. _executing = newValue
  1099. didChangeValue(forKey: "isExecuting")
  1100. }
  1101. }
  1102. private var _finished : Bool = false
  1103. override var isFinished : Bool {
  1104. get { return _finished }
  1105. set {
  1106. guard _finished != newValue else { return }
  1107. willChangeValue(forKey: "isFinished")
  1108. _finished = newValue
  1109. didChangeValue(forKey: "isFinished")
  1110. }
  1111. }
  1112. private var metadata: tableMetadata?
  1113. private var view: Any?
  1114. private var indexPath: IndexPath?
  1115. private var networkingFunc: String = ""
  1116. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  1117. super.init()
  1118. if metadata != nil { self.metadata = metadata! }
  1119. if view != nil { self.view = view! }
  1120. if indexPath != nil { self.indexPath = indexPath! }
  1121. self.networkingFunc = networkingFunc
  1122. }
  1123. override func start() {
  1124. if !Thread.isMainThread {
  1125. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  1126. } else {
  1127. isExecuting = true
  1128. if isCancelled {
  1129. finish()
  1130. } else {
  1131. poolNetworking()
  1132. }
  1133. }
  1134. }
  1135. func finish() {
  1136. isExecuting = false
  1137. isFinished = true
  1138. }
  1139. override func cancel() {
  1140. super.cancel()
  1141. if isExecuting {
  1142. complete()
  1143. }
  1144. }
  1145. func complete() {
  1146. finish()
  1147. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  1148. }
  1149. func poolNetworking() {
  1150. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  1151. switch networkingFunc {
  1152. case "downloadThumbnail":
  1153. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  1154. self.complete()
  1155. }
  1156. default:
  1157. print("error")
  1158. }
  1159. }
  1160. }
  1161. //MARK: - Function Main
  1162. class NCFunctionMain: NSObject {
  1163. @objc static let sharedInstance: NCFunctionMain = {
  1164. let instance = NCFunctionMain()
  1165. return instance
  1166. }()
  1167. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1168. @objc func synchronizeOffline() {
  1169. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1170. if (directories != nil) {
  1171. for directory: tableDirectory in directories! {
  1172. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1173. }
  1174. }
  1175. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1176. if (files != nil) {
  1177. for file: tableLocalFile in files! {
  1178. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  1179. continue
  1180. }
  1181. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1182. }
  1183. }
  1184. }
  1185. }