NCMainCommon.swift 72 KB

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