NCMainCommon.swift 63 KB

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