NCMainCommon.swift 66 KB

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