NCMainCommon.swift 61 KB

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