NCMainCommon.swift 60 KB

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