NCMainCommon.swift 61 KB

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