NCMainCommon.swift 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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 <m.faggiana@twsweb.it>
  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. class NCMainCommon: NSObject {
  25. @objc static let sharedInstance: NCMainCommon = {
  26. let instance = NCMainCommon()
  27. return instance
  28. }()
  29. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. //MARK: -
  31. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView) {
  32. guard let dic = notification.userInfo else {
  33. return
  34. }
  35. let fileID = dic["fileID"] as! NSString
  36. _ = dic["serverUrl"] as! NSString
  37. let status = dic["status"] as! Int
  38. let progress = dic["progress"] as! CGFloat
  39. let totalBytes = dic["totalBytes"] as! Double
  40. let totalBytesExpected = dic["totalBytesExpected"] as! Double
  41. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  42. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  43. return
  44. }
  45. if isValidIndexPath(indexPath as! IndexPath, tableView: tableView) {
  46. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  47. var image = ""
  48. if status == k_metadataStatusInDownload {
  49. image = "↓"
  50. } else if status == k_metadataStatusInUpload {
  51. image = "↑"
  52. }
  53. cell.labelInfoFile.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  54. cell.transferButton.progress = progress
  55. }
  56. }
  57. }
  58. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool) {
  59. var actionReloadDatasource = k_action_NULL
  60. if metadata.session.count == 0 {
  61. return
  62. }
  63. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  64. return
  65. }
  66. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  67. return
  68. }
  69. // SESSION EXTENSION
  70. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  71. if (metadata.session == k_upload_session_extension) {
  72. do {
  73. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  74. } catch { }
  75. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  76. actionReloadDatasource = k_action_DEL
  77. } else {
  78. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  79. actionReloadDatasource = k_action_MOD
  80. }
  81. self.reloadDatasource(ServerUrl: serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  82. return
  83. }
  84. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  85. var cancel = false
  86. // DOWNLOAD
  87. if metadata.session.count > 0 && metadata.session.contains("download") {
  88. for task in downloadTasks {
  89. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  90. task.cancel()
  91. cancel = true
  92. }
  93. }
  94. if cancel == false {
  95. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  96. }
  97. actionReloadDatasource = k_action_MOD
  98. }
  99. // UPLOAD
  100. if metadata.session.count > 0 && metadata.session.contains("upload") {
  101. for task in uploadTasks {
  102. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  103. task.cancel()
  104. cancel = true
  105. }
  106. }
  107. if cancel == false {
  108. do {
  109. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  110. }
  111. catch { }
  112. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  113. }
  114. actionReloadDatasource = k_action_DEL
  115. }
  116. if cancel == false {
  117. self.reloadDatasource(ServerUrl: serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  118. }
  119. }
  120. }
  121. @objc func cancelAllTransfer() {
  122. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  123. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND (status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError), clearDateReadDirectoryID: nil)
  124. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status != %d AND status != %d", appDelegate.activeAccount, k_metadataStatusNormal, k_metadataStatusHide), sorted: "fileName", ascending: true) {
  125. for metadata in metadatas {
  126. // Modify
  127. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  128. metadata.session = ""
  129. metadata.sessionSelector = ""
  130. metadata.status = Int(k_metadataStatusNormal)
  131. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  132. }
  133. // Cancel Task
  134. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  135. cancelTransferMetadata(metadata, reloadDatasource: false)
  136. }
  137. }
  138. }
  139. self.reloadDatasource(ServerUrl: nil, fileID: nil, action: k_action_NULL)
  140. }
  141. //MARK: -
  142. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, typeLayout: String, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectFileID: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, source: UIViewController) -> UICollectionViewCell {
  143. var image: UIImage?
  144. var imagePreview = false
  145. if metadata.iconName.count > 0 {
  146. image = UIImage.init(named: metadata.iconName)
  147. } else {
  148. image = UIImage.init(named: "file")
  149. }
  150. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName)) {
  151. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName))
  152. imagePreview = true
  153. } else {
  154. if metadata.hasPreview == 1 && !CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  155. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, serverUrl: serverUrl, collectionView: collectionView, indexPath: indexPath)
  156. }
  157. }
  158. // Share
  159. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  160. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  161. var isShare = false
  162. var isMounted = false
  163. if metadataFolder != nil {
  164. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  165. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  166. }
  167. if typeLayout == k_layout_list {
  168. // LIST
  169. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  170. cell.delegate = source as? NCListCellDelegate
  171. cell.fileID = metadata.fileID
  172. cell.indexPath = indexPath
  173. cell.labelTitle.text = metadata.fileNameView
  174. cell.imageStatus.image = nil
  175. cell.imageLocal.image = nil
  176. cell.imageFavorite.image = nil
  177. cell.imageShare.image = nil
  178. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  179. if metadata.directory {
  180. if metadata.e2eEncrypted {
  181. image = UIImage.init(named: "folderEncrypted")
  182. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  183. image = UIImage.init(named: "folderAutomaticUpload")
  184. } else if isShare {
  185. image = UIImage.init(named: "folder_shared_with_me")
  186. } else if isMounted {
  187. image = UIImage.init(named: "folder_external")
  188. } else if (sharesUserAndGroup != nil) {
  189. image = UIImage.init(named: "folder_shared_with_me")
  190. } else if (sharesLink != nil) {
  191. image = UIImage.init(named: "folder_public")
  192. } else {
  193. image = UIImage.init(named: "folder")
  194. }
  195. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  196. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  197. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  198. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  199. // Status image: passcode
  200. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  201. cell.imageStatus.image = UIImage.init(named: "passcode")
  202. }
  203. // Local image: offline
  204. if tableDirectory != nil && tableDirectory!.offline {
  205. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  206. }
  207. } else {
  208. cell.imageItem.image = image
  209. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  210. // image Local
  211. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  212. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  213. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  214. else { cell.imageLocal.image = UIImage.init(named: "local") }
  215. }
  216. // Share
  217. if (isShare) {
  218. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  219. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  220. } else if (isMounted) {
  221. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  222. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  223. } else if (sharesLink != nil) {
  224. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  225. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  226. } else if (sharesUserAndGroup != nil) {
  227. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  228. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  229. }
  230. }
  231. // image Favorite
  232. if metadata.favorite {
  233. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  234. }
  235. if isEditMode {
  236. cell.imageItemLeftConstraint.constant = 45
  237. cell.imageSelect.isHidden = false
  238. if selectFileID.contains(metadata.fileID) {
  239. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  240. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  241. } else {
  242. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  243. cell.backgroundView = nil
  244. }
  245. } else {
  246. cell.imageItemLeftConstraint.constant = 10
  247. cell.imageSelect.isHidden = true
  248. cell.backgroundView = nil
  249. }
  250. // Remove last separator
  251. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  252. cell.separator.isHidden = true
  253. } else {
  254. cell.separator.isHidden = false
  255. }
  256. return cell
  257. } else {
  258. // GRID
  259. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  260. cell.delegate = source as? NCGridCellDelegate
  261. cell.fileID = metadata.fileID
  262. cell.indexPath = indexPath
  263. cell.labelTitle.text = metadata.fileNameView
  264. cell.imageStatus.image = nil
  265. cell.imageLocal.image = nil
  266. cell.imageFavorite.image = nil
  267. cell.imageShare.image = nil
  268. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  269. if metadata.directory {
  270. if metadata.e2eEncrypted {
  271. image = UIImage.init(named: "folderEncrypted")
  272. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  273. image = UIImage.init(named: "folderAutomaticUpload")
  274. } else if isShare {
  275. image = UIImage.init(named: "folder_shared_with_me")
  276. } else if isMounted {
  277. image = UIImage.init(named: "folder_external")
  278. } else if (sharesUserAndGroup != nil) {
  279. image = UIImage.init(named: "folder_shared_with_me")
  280. } else if (sharesLink != nil) {
  281. image = UIImage.init(named: "folder_public")
  282. } else {
  283. image = UIImage.init(named: "folder")
  284. }
  285. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*6, height: image!.size.height*6, scale: 3.0, color: NCBrandColor.sharedInstance.brandElement)
  286. cell.imageItem.contentMode = .center
  287. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  288. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  289. // Status image: passcode
  290. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  291. cell.imageStatus.image = UIImage.init(named: "passcode")
  292. }
  293. // Local image: offline
  294. if tableDirectory != nil && tableDirectory!.offline {
  295. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  296. }
  297. } else {
  298. cell.imageItem.image = image
  299. if imagePreview == false {
  300. let width = cell.imageItem.image!.size.width * 2
  301. //let scale = UIScreen.main.scale
  302. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  303. cell.imageItem.contentMode = .center
  304. }
  305. // image Local
  306. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  307. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  308. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  309. else { cell.imageLocal.image = UIImage.init(named: "local") }
  310. }
  311. // Share
  312. if (isShare) {
  313. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  314. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  315. } else if (isMounted) {
  316. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  317. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  318. } else if (sharesLink != nil) {
  319. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  320. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  321. } else if (sharesUserAndGroup != nil) {
  322. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  323. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  324. }
  325. }
  326. // image Favorite
  327. if metadata.favorite {
  328. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  329. }
  330. if isEditMode {
  331. cell.imageSelect.isHidden = false
  332. if selectFileID.contains(metadata.fileID) {
  333. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: UIColor.white)
  334. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  335. } else {
  336. cell.imageSelect.isHidden = true
  337. cell.backgroundView = nil
  338. }
  339. } else {
  340. cell.imageSelect.isHidden = true
  341. cell.backgroundView = nil
  342. }
  343. return cell
  344. }
  345. }
  346. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String) -> UITableViewCell {
  347. // Create File System
  348. if metadata.directory {
  349. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  350. } else {
  351. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  352. }
  353. // CCCell
  354. if metadata.status == k_metadataStatusNormal {
  355. // NORMAL
  356. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  357. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  358. cell.accessoryType = UITableViewCell.AccessoryType.none
  359. cell.file.image = nil
  360. cell.status.image = nil
  361. cell.favorite.image = nil
  362. cell.shared.image = nil
  363. cell.local.image = nil
  364. cell.imageTitleSegue = nil
  365. cell.shared.isUserInteractionEnabled = false
  366. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  367. // change color selection
  368. let selectionColor = UIView()
  369. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  370. cell.selectedBackgroundView = selectionColor
  371. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  372. cell.labelTitle.textColor = UIColor.black
  373. cell.labelTitle.text = metadata.fileNameView
  374. // Share
  375. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  376. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  377. var isShare = false
  378. var isMounted = false
  379. if metadataFolder != nil {
  380. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  381. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  382. }
  383. if metadata.directory {
  384. // lable Info
  385. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  386. // File Image & Image Title Segue
  387. if metadata.e2eEncrypted {
  388. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  389. cell.imageTitleSegue = UIImage.init(named: "lock")
  390. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  391. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  392. cell.imageTitleSegue = UIImage.init(named: "media")
  393. } else if isShare {
  394. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  395. cell.imageTitleSegue = UIImage.init(named: "share")
  396. } else if isMounted {
  397. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  398. cell.imageTitleSegue = UIImage.init(named: "shareMounted")
  399. } else if (sharesUserAndGroup != nil) {
  400. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  401. cell.imageTitleSegue = UIImage.init(named: "share")
  402. } else if (sharesLink != nil) {
  403. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  404. cell.imageTitleSegue = UIImage.init(named: "sharebylink")
  405. } else {
  406. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  407. }
  408. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  409. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  410. // Local image: offline
  411. if tableDirectory != nil && tableDirectory!.offline {
  412. cell.local.image = UIImage.init(named: "offlineFlag")
  413. }
  414. // Status image: passcode
  415. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  416. cell.status.image = UIImage.init(named: "passcode")
  417. }
  418. } else {
  419. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  420. // Lable Info
  421. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  422. // File Image
  423. if iconFileExists {
  424. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  425. } else {
  426. if metadata.iconName.count > 0 {
  427. cell.file.image = UIImage.init(named: metadata.iconName)
  428. } else {
  429. cell.file.image = UIImage.init(named: "file")
  430. }
  431. }
  432. // Local Image - Offline
  433. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  434. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  435. if tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  436. else { cell.local.image = UIImage.init(named: "local") }
  437. }
  438. // Status image: encrypted
  439. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  440. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  441. cell.status.image = UIImage.init(named: "encrypted")
  442. }
  443. // Share
  444. if (isShare) {
  445. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  446. } else if (isMounted) {
  447. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  448. } else if (sharesLink != nil) {
  449. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  450. } else if (sharesUserAndGroup != nil) {
  451. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  452. }
  453. }
  454. //
  455. // File & Directory
  456. //
  457. // Favorite
  458. if metadata.favorite {
  459. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  460. }
  461. // More Image
  462. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  463. return cell
  464. } else {
  465. // TRASNFER
  466. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  467. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  468. cell.accessoryType = UITableViewCell.AccessoryType.none
  469. cell.file.image = nil
  470. cell.status.image = nil
  471. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  472. cell.labelTitle.textColor = UIColor.black
  473. cell.labelTitle.text = metadata.fileNameView
  474. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  475. var progress: CGFloat = 0.0
  476. var totalBytes: Double = 0.0
  477. //var totalBytesExpected : Double = 0
  478. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  479. if progressArray != nil && progressArray?.count == 3 {
  480. progress = progressArray?.object(at: 0) as! CGFloat
  481. totalBytes = progressArray?.object(at: 1) as! Double
  482. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  483. }
  484. // Write status on Label Info
  485. switch metadata.status {
  486. case Int(k_metadataStatusWaitDownload):
  487. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  488. progress = 0.0
  489. break
  490. case Int(k_metadataStatusInDownload):
  491. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  492. progress = 0.0
  493. break
  494. case Int(k_metadataStatusDownloading):
  495. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  496. break
  497. case Int(k_metadataStatusWaitUpload):
  498. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  499. progress = 0.0
  500. break
  501. case Int(k_metadataStatusInUpload):
  502. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  503. progress = 0.0
  504. break
  505. case Int(k_metadataStatusUploading):
  506. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  507. break
  508. default:
  509. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  510. progress = 0.0
  511. }
  512. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  513. if iconFileExists {
  514. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  515. } else {
  516. if metadata.iconName.count > 0 {
  517. cell.file.image = UIImage.init(named: metadata.iconName)
  518. } else {
  519. cell.file.image = UIImage.init(named: "file")
  520. }
  521. }
  522. // Session Upload Extension
  523. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  524. cell.labelTitle.isEnabled = false
  525. cell.labelInfoFile.isEnabled = false
  526. } else {
  527. cell.labelTitle.isEnabled = true
  528. cell.labelInfoFile.isEnabled = true
  529. }
  530. // downloadFile
  531. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  532. //
  533. }
  534. // downloadFile Error
  535. if metadata.status == k_metadataStatusDownloadError {
  536. cell.status.image = UIImage.init(named: "statuserror")
  537. if metadata.sessionError.count == 0 {
  538. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  539. } else {
  540. cell.labelInfoFile.text = metadata.sessionError
  541. }
  542. }
  543. // uploadFile
  544. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  545. if (!iconFileExists) {
  546. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  547. }
  548. cell.labelTitle.isEnabled = false
  549. }
  550. // uploadFileError
  551. if metadata.status == k_metadataStatusUploadError {
  552. cell.labelTitle.isEnabled = false
  553. cell.status.image = UIImage.init(named: "statuserror")
  554. if !iconFileExists {
  555. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  556. }
  557. if metadata.sessionError.count == 0 {
  558. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  559. } else {
  560. cell.labelInfoFile.text = metadata.sessionError
  561. }
  562. }
  563. // Progress
  564. cell.transferButton.progress = progress
  565. return cell
  566. }
  567. }
  568. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  569. guard let indexPath = indexPath else {
  570. return nil
  571. }
  572. guard let sectionDataSource = sectionDataSource else {
  573. return nil
  574. }
  575. let section = indexPath.section + 1
  576. let row = indexPath.row + 1
  577. let totSections = sectionDataSource.sections.count
  578. if totSections < section || section > totSections {
  579. return nil
  580. }
  581. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  582. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  583. return nil
  584. }
  585. let totRows = filesID.count
  586. if totRows < row || row > totRows {
  587. return nil
  588. }
  589. let fileID = filesID.object(at: indexPath.row)
  590. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  591. return metadata
  592. }
  593. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  594. DispatchQueue.main.async {
  595. if self.appDelegate.activeMain != nil {
  596. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  597. }
  598. if self.appDelegate.activeFavorites != nil {
  599. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  600. }
  601. if self.appDelegate.activeTransfers != nil {
  602. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  603. }
  604. }
  605. }
  606. @objc func isValidIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> Bool {
  607. return indexPath.section < tableView.numberOfSections && indexPath.row < tableView.numberOfRows(inSection: indexPath.section)
  608. }
  609. //MARK: -
  610. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  611. var copyMetadatas = [tableMetadata]()
  612. for metadata in metadatas {
  613. copyMetadatas.append(tableMetadata.init(value: metadata))
  614. }
  615. if e2ee {
  616. DispatchQueue.global().async {
  617. 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)
  618. DispatchQueue.main.async {
  619. if error == nil {
  620. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  621. } else {
  622. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  623. return
  624. }
  625. }
  626. }
  627. } else {
  628. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  629. }
  630. }
  631. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  632. var count: Int = 0
  633. var completionErrorCode: Int = 0
  634. var completionMessage = ""
  635. let ocNetworking = OCnetworking.init(delegate: nil, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  636. for metadata in metadatas {
  637. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  638. continue
  639. }
  640. self.appDelegate.filterFileID.add(metadata.fileID)
  641. let path = serverUrl + "/" + metadata.fileName
  642. ocNetworking?.deleteFileOrFolder(path, completion: { (message, errorCode) in
  643. count += 1
  644. if errorCode == 0 || errorCode == 404 {
  645. do {
  646. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  647. } catch { }
  648. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  649. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  650. NCManageDatabase.sharedInstance.deletePhotos(fileID: metadata.fileID)
  651. if metadata.directory {
  652. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName))
  653. }
  654. if (e2ee) {
  655. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  656. }
  657. self.appDelegate.filterFileID.remove(metadata.fileID)
  658. } else {
  659. completionErrorCode = errorCode
  660. completionMessage = ""
  661. if message != nil {
  662. completionMessage = message!
  663. }
  664. self.appDelegate.filterFileID.remove(metadata.fileID)
  665. }
  666. if count == metadatas.count {
  667. if e2ee {
  668. DispatchQueue.global().async {
  669. 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)
  670. DispatchQueue.main.async {
  671. completion(completionErrorCode, completionMessage)
  672. }
  673. }
  674. } else {
  675. completion(completionErrorCode, completionMessage)
  676. }
  677. }
  678. })
  679. }
  680. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  681. self.appDelegate.activeMedia.reloadDatasource(nil, action: Int(k_action_NULL))
  682. }
  683. @objc func openPhotosPickerViewController(_ sourceViewController: UIViewController, phAssets: @escaping () -> ()) {
  684. var selectedAssets = [TLPHAsset]()
  685. var configure = TLPhotosPickerConfigure()
  686. configure.cancelTitle = NSLocalizedString("_cancel_", comment: "")
  687. configure.defaultCameraRollTitle = NSLocalizedString("_camera_roll_", comment: "")
  688. configure.doneTitle = NSLocalizedString("_done_", comment: "")
  689. configure.emptyMessage = NSLocalizedString("_no_albums_", comment: "")
  690. configure.tapHereToChange = NSLocalizedString("_tap_here_to_change_", comment: "")
  691. let viewController = TLPhotosPickerViewController(withTLPHAssets: { [weak self] (assets) in // TLAssets
  692. selectedAssets = assets
  693. phAssets()
  694. }, didCancel: nil)
  695. viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
  696. //exceed max selection
  697. }
  698. viewController.handleNoAlbumPermissions = { [weak self] (picker) in
  699. // handle denied albums permissions case
  700. }
  701. viewController.handleNoCameraPermissions = { [weak self] (picker) in
  702. // handle denied camera permissions case
  703. }
  704. viewController.selectedAssets = selectedAssets
  705. viewController.configure = configure
  706. sourceViewController.present(viewController, animated: true, completion: nil)
  707. }
  708. }
  709. //MARK: -
  710. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  711. override func viewDidLoad() {
  712. super.viewDidLoad()
  713. delegate = self
  714. }
  715. //Delegate methods
  716. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  717. let tabViewControllers = tabBarController.viewControllers!
  718. guard let toIndex = tabViewControllers.index(of: viewController) else {
  719. if let vc = viewController as? UINavigationController {
  720. vc.popToRootViewController(animated: true);
  721. }
  722. return false
  723. }
  724. animateToTab(toIndex: toIndex)
  725. return true
  726. }
  727. func animateToTab(toIndex: Int) {
  728. let tabViewControllers = viewControllers!
  729. let fromView = selectedViewController!.view!
  730. let toView = tabViewControllers[toIndex].view!
  731. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  732. guard fromIndex != toIndex else {return}
  733. // Add the toView to the tab bar view
  734. fromView.superview?.addSubview(toView)
  735. fromView.superview?.backgroundColor = UIColor.white
  736. // Position toView off screen (to the left/right of fromView)
  737. let screenWidth = UIScreen.main.bounds.size.width;
  738. let scrollRight = toIndex > fromIndex!;
  739. let offset = (scrollRight ? screenWidth : -screenWidth)
  740. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  741. // Disable interaction during animation
  742. view.isUserInteractionEnabled = false
  743. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  744. // Slide the views by -offset
  745. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  746. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  747. }, completion: { finished in
  748. // Remove the old view from the tabbar view.
  749. fromView.removeFromSuperview()
  750. self.selectedIndex = toIndex
  751. self.view.isUserInteractionEnabled = true
  752. })
  753. }
  754. }
  755. //
  756. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  757. //
  758. extension UITabBar {
  759. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  760. // the Master view controller shows the UITabBarItem icon next to the text
  761. override open var traitCollection: UITraitCollection {
  762. if UIDevice.current.userInterfaceIdiom == .pad {
  763. return UITraitCollection(horizontalSizeClass: .compact)
  764. }
  765. return super.traitCollection
  766. }
  767. }
  768. //MARK: -
  769. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  770. @objc static let sharedInstance: NCNetworkingMain = {
  771. let instance = NCNetworkingMain()
  772. return instance
  773. }()
  774. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  775. // DOWNLOAD
  776. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  777. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  778. appDelegate.updateApplicationIconBadgeNumber()
  779. }
  780. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  781. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  782. return
  783. }
  784. if errorCode == 0 {
  785. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  786. // Synchronized
  787. if selector == selectorDownloadSynchronize {
  788. //
  789. }
  790. // open View File
  791. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  792. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  793. if appDelegate.activeMain.view.window != nil {
  794. appDelegate.activeMain.open(in: metadata)
  795. }
  796. if appDelegate.activeFavorites.view.window != nil {
  797. appDelegate.activeFavorites.open(in: metadata)
  798. }
  799. } else {
  800. if appDelegate.activeMain.view.window != nil {
  801. appDelegate.activeMain.metadata = metadata;
  802. appDelegate.activeMain.shouldPerformSegue()
  803. }
  804. if appDelegate.activeFavorites.view.window != nil {
  805. appDelegate.activeFavorites.metadata = metadata;
  806. appDelegate.activeFavorites.shouldPerformSegue()
  807. }
  808. }
  809. }
  810. // Open in...
  811. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  812. if appDelegate.activeMain.view.window != nil {
  813. appDelegate.activeMain.open(in: metadata)
  814. }
  815. if appDelegate.activeFavorites.view.window != nil {
  816. appDelegate.activeFavorites.open(in: metadata)
  817. }
  818. }
  819. // Save to Photo Album
  820. if selector == selectorSave {
  821. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  822. }
  823. // Copy File
  824. if selector == selectorLoadCopy {
  825. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  826. }
  827. // Set as available offline
  828. if selector == selectorLoadOffline {
  829. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  830. }
  831. //selectorLoadViewImage
  832. if selector == selectorLoadViewImage {
  833. if appDelegate.activeDetail != nil {
  834. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  835. }
  836. if appDelegate.activeMedia != nil {
  837. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  838. }
  839. }
  840. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  841. } else {
  842. // File do not exists on server, remove in local
  843. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  844. do {
  845. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  846. } catch { }
  847. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  848. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  849. NCManageDatabase.sharedInstance.deletePhotos(fileID: fileID)
  850. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  851. }
  852. if selector == selectorLoadViewImage {
  853. if appDelegate.activeDetail.view.window != nil {
  854. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  855. }
  856. if appDelegate.activeMedia.view.window != nil {
  857. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  858. }
  859. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  860. }
  861. }
  862. }
  863. // UPLOAD
  864. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  865. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  866. appDelegate.updateApplicationIconBadgeNumber()
  867. }
  868. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  869. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  870. if errorCode == 0 {
  871. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  872. } else {
  873. NCManageDatabase.sharedInstance.addActivityClient(fileName, fileID: assetLocalIdentifier, action: k_activityDebugActionUpload, selector: selector, note: errorMessage, type: k_activityTypeFailure, verbose: false, activeUrl: appDelegate.activeUrl)
  874. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  875. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  876. }
  877. }
  878. }
  879. func downloadThumbnail(with metadata: tableMetadata, serverUrl: String, collectionView: UICollectionView, indexPath: IndexPath) {
  880. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  881. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  882. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  883. ocNetworking?.downloadPreview(with: metadata, serverUrl: serverUrl, withWidth: width, andHeight: height, completion: { (message, errorCode) in
  884. if errorCode == 0 && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  885. collectionView.reloadItems(at: [indexPath])
  886. }
  887. })
  888. }
  889. }
  890. //MARK: -
  891. class NCFunctionMain: NSObject {
  892. @objc static let sharedInstance: NCFunctionMain = {
  893. let instance = NCFunctionMain()
  894. return instance
  895. }()
  896. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  897. @objc func synchronizeOffline() {
  898. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  899. if (directories != nil) {
  900. for directory: tableDirectory in directories! {
  901. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload)
  902. }
  903. }
  904. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  905. if (files != nil) {
  906. for file: tableLocalFile in files! {
  907. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  908. continue
  909. }
  910. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  911. continue
  912. }
  913. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: serverUrl, selector: selectorReadFileWithDownload)
  914. }
  915. }
  916. }
  917. }