NCMainCommon.swift 73 KB

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