NCMainCommon.swift 60 KB

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