NCMainCommon.swift 57 KB

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