NCMainCommon.swift 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import TLPhotoPicker
  25. class NCMainCommon: NSObject {
  26. @objc static let sharedInstance: NCMainCommon = {
  27. let instance = NCMainCommon()
  28. return instance
  29. }()
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. let operationQueueReloadDatasource = OperationQueue.main
  32. //MARK: -
  33. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  34. if viewController.viewIfLoaded?.window == nil {
  35. return
  36. }
  37. guard let dic = notification.userInfo else {
  38. return
  39. }
  40. let fileID = dic["fileID"] as! NSString
  41. let serverUrl = dic["serverUrl"] as! String
  42. let status = dic["status"] as! Int
  43. let progress = dic["progress"] as! CGFloat
  44. let totalBytes = dic["totalBytes"] as! Double
  45. let totalBytesExpected = dic["totalBytesExpected"] as! Double
  46. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  47. return
  48. }
  49. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  50. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  51. return
  52. }
  53. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  54. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  55. var image = ""
  56. if status == k_metadataStatusInDownload {
  57. image = "↓"
  58. } else if status == k_metadataStatusInUpload {
  59. image = "↑"
  60. }
  61. cell.labelInfoFile.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  62. cell.transferButton.progress = progress
  63. }
  64. }
  65. }
  66. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool) {
  67. var actionReloadDatasource = k_action_NULL
  68. if metadata.session.count == 0 {
  69. return
  70. }
  71. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  72. return
  73. }
  74. 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. }
  713. //MARK: -
  714. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  715. override func viewDidLoad() {
  716. super.viewDidLoad()
  717. delegate = self
  718. }
  719. //Delegate methods
  720. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  721. let tabViewControllers = tabBarController.viewControllers!
  722. guard let toIndex = tabViewControllers.index(of: viewController) else {
  723. if let vc = viewController as? UINavigationController {
  724. vc.popToRootViewController(animated: true);
  725. }
  726. return false
  727. }
  728. animateToTab(toIndex: toIndex)
  729. return true
  730. }
  731. func animateToTab(toIndex: Int) {
  732. let tabViewControllers = viewControllers!
  733. let fromView = selectedViewController!.view!
  734. let toView = tabViewControllers[toIndex].view!
  735. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  736. guard fromIndex != toIndex else {return}
  737. // Add the toView to the tab bar view
  738. fromView.superview?.addSubview(toView)
  739. fromView.superview?.backgroundColor = UIColor.white
  740. // Position toView off screen (to the left/right of fromView)
  741. let screenWidth = UIScreen.main.bounds.size.width;
  742. let scrollRight = toIndex > fromIndex!;
  743. let offset = (scrollRight ? screenWidth : -screenWidth)
  744. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  745. // Disable interaction during animation
  746. view.isUserInteractionEnabled = false
  747. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  748. // Slide the views by -offset
  749. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  750. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  751. }, completion: { finished in
  752. // Remove the old view from the tabbar view.
  753. fromView.removeFromSuperview()
  754. self.selectedIndex = toIndex
  755. self.view.isUserInteractionEnabled = true
  756. })
  757. }
  758. }
  759. //
  760. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  761. //
  762. extension UITabBar {
  763. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  764. // the Master view controller shows the UITabBarItem icon next to the text
  765. override open var traitCollection: UITraitCollection {
  766. if UIDevice.current.userInterfaceIdiom == .pad {
  767. return UITraitCollection(horizontalSizeClass: .compact)
  768. }
  769. return super.traitCollection
  770. }
  771. }
  772. //MARK: -
  773. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  774. @objc static let sharedInstance: NCNetworkingMain = {
  775. let instance = NCNetworkingMain()
  776. return instance
  777. }()
  778. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  779. // DOWNLOAD
  780. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  781. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  782. appDelegate.updateApplicationIconBadgeNumber()
  783. }
  784. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  785. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  786. return
  787. }
  788. if errorCode == 0 {
  789. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  790. // Synchronized
  791. if selector == selectorDownloadSynchronize {
  792. appDelegate.updateApplicationIconBadgeNumber()
  793. return
  794. }
  795. // open View File
  796. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  797. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  798. if uti == nil {
  799. uti = ""
  800. } else if uti!.contains("opendocument") && !NCViewerRichdocument.sharedInstance.isRichDocument(metadata) {
  801. metadata.typeFile = k_metadataTypeFile_unknown
  802. }
  803. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  804. if appDelegate.activeMain.view.window != nil {
  805. appDelegate.activeMain.open(in: metadata)
  806. }
  807. if appDelegate.activeFavorites.view.window != nil {
  808. appDelegate.activeFavorites.open(in: metadata)
  809. }
  810. } else {
  811. if appDelegate.activeMain.view.window != nil {
  812. appDelegate.activeMain.shouldPerformSegue(metadata)
  813. }
  814. if appDelegate.activeFavorites.view.window != nil {
  815. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  816. }
  817. }
  818. }
  819. // Open in...
  820. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  821. if appDelegate.activeMain.view.window != nil {
  822. appDelegate.activeMain.open(in: metadata)
  823. }
  824. if appDelegate.activeFavorites.view.window != nil {
  825. appDelegate.activeFavorites.open(in: metadata)
  826. }
  827. }
  828. // Save to Photo Album
  829. if selector == selectorSave {
  830. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  831. }
  832. // Copy File
  833. if selector == selectorLoadCopy {
  834. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  835. }
  836. // Set as available offline
  837. if selector == selectorLoadOffline {
  838. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  839. }
  840. //selectorLoadViewImage
  841. if selector == selectorLoadViewImage {
  842. if appDelegate.activeDetail != nil {
  843. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  844. }
  845. if appDelegate.activeMedia != nil {
  846. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  847. }
  848. }
  849. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  850. } else {
  851. // File do not exists on server, remove in local
  852. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  853. do {
  854. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  855. } catch { }
  856. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID), clearDateReadDirectoryID: metadata.directoryID)
  857. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  858. NCManageDatabase.sharedInstance.deletePhotos(fileID: fileID)
  859. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  860. }
  861. if selector == selectorLoadViewImage {
  862. if appDelegate.activeDetail.view.window != nil {
  863. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  864. }
  865. if appDelegate.activeMedia.view.window != nil {
  866. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  867. }
  868. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  869. }
  870. }
  871. }
  872. // UPLOAD
  873. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  874. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  875. appDelegate.updateApplicationIconBadgeNumber()
  876. }
  877. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  878. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  879. if errorCode == 0 {
  880. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  881. } else {
  882. NCManageDatabase.sharedInstance.addActivityClient(fileName, fileID: assetLocalIdentifier, action: k_activityDebugActionUpload, selector: selector, note: errorMessage, type: k_activityTypeFailure, verbose: false, activeUrl: appDelegate.activeUrl)
  883. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  884. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  885. }
  886. }
  887. }
  888. @objc func downloadThumbnail(with metadata: tableMetadata, serverUrl: String, view: Any, indexPath: IndexPath, forceDownload: Bool) {
  889. if metadata.hasPreview == 1 && (!CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) || forceDownload) {
  890. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  891. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  892. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  893. ocNetworking?.downloadPreview(with: metadata, serverUrl: serverUrl, withWidth: width, andHeight: height, completion: { (message, errorCode) in
  894. if errorCode == 0 && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  895. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  896. (view as! UICollectionView).reloadItems(at: [indexPath])
  897. }
  898. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName){
  899. (view as! UITableView).reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
  900. }
  901. }
  902. })
  903. }
  904. }
  905. }
  906. //MARK: -
  907. class NCFunctionMain: NSObject {
  908. @objc static let sharedInstance: NCFunctionMain = {
  909. let instance = NCFunctionMain()
  910. return instance
  911. }()
  912. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  913. @objc func synchronizeOffline() {
  914. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  915. if (directories != nil) {
  916. for directory: tableDirectory in directories! {
  917. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload)
  918. }
  919. }
  920. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  921. if (files != nil) {
  922. for file: tableLocalFile in files! {
  923. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  924. continue
  925. }
  926. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  927. continue
  928. }
  929. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: serverUrl, selector: selectorReadFileWithDownload)
  930. }
  931. }
  932. }
  933. }