NCMainCommon.swift 59 KB

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