NCMainCommon.swift 59 KB

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