NCMainCommon.swift 60 KB

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