NCMainCommon.swift 58 KB

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