NCMainCommon.swift 61 KB

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