NCMainCommon.swift 59 KB

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