NCMainCommon.swift 64 KB

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