NCMainCommon.swift 67 KB

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