NCMainCommon.swift 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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, bottom: false)
  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. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  638. self.operationQueueReloadDatasource.addOperation {
  639. DispatchQueue.main.async {
  640. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  641. }
  642. }
  643. }
  644. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  645. self.operationQueueReloadDatasource.addOperation {
  646. DispatchQueue.main.async {
  647. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  648. }
  649. }
  650. }
  651. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  652. self.operationQueueReloadDatasource.addOperation {
  653. DispatchQueue.main.async {
  654. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  655. }
  656. }
  657. }
  658. }
  659. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  660. if view is UICollectionView {
  661. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  662. }
  663. if view is UITableView {
  664. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  665. }
  666. return true
  667. }
  668. //MARK: -
  669. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  670. var copyMetadatas = [tableMetadata]()
  671. for metadata in metadatas {
  672. copyMetadatas.append(tableMetadata.init(value: metadata))
  673. }
  674. if e2ee {
  675. DispatchQueue.global().async {
  676. 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)
  677. DispatchQueue.main.async {
  678. if error == nil {
  679. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  680. } else {
  681. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  682. return
  683. }
  684. }
  685. }
  686. } else {
  687. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  688. }
  689. }
  690. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  691. var count: Int = 0
  692. var completionErrorCode: Int = 0
  693. var completionMessage = ""
  694. for metadata in metadatas {
  695. self.appDelegate.filterFileID.add(metadata.fileID)
  696. let path = metadata.serverUrl + "/" + metadata.fileName
  697. OCNetworking.sharedManager().deleteFileOrFolder(withAccount: appDelegate.activeAccount, path: path, completion: { (account, message, errorCode) in
  698. if account == self.appDelegate.activeAccount {
  699. count += 1
  700. if errorCode == 0 || errorCode == kOCErrorServerPathNotFound {
  701. do {
  702. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  703. } catch { }
  704. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  705. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  706. NCManageDatabase.sharedInstance.deletePhotos(fileID: metadata.fileID)
  707. if metadata.directory {
  708. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName), account: metadata.account)
  709. }
  710. if (e2ee) {
  711. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  712. }
  713. self.appDelegate.filterFileID.remove(metadata.fileID)
  714. } else {
  715. completionErrorCode = errorCode
  716. completionMessage = ""
  717. if message != nil {
  718. completionMessage = message!
  719. }
  720. self.appDelegate.filterFileID.remove(metadata.fileID)
  721. }
  722. if count == metadatas.count {
  723. if e2ee {
  724. DispatchQueue.global().async {
  725. 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)
  726. DispatchQueue.main.async {
  727. completion(completionErrorCode, completionMessage)
  728. }
  729. }
  730. } else {
  731. completion(completionErrorCode, completionMessage)
  732. }
  733. }
  734. }
  735. })
  736. }
  737. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  738. self.appDelegate.activeMedia.reloadDatasource(nil, action: Int(k_action_NULL))
  739. }
  740. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  741. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  742. return
  743. }
  744. guard let image = UIImage(contentsOfFile: path) else {
  745. return
  746. }
  747. self.metadata = metadata
  748. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  749. photoEditor.image = image
  750. photoEditor.photoEditorDelegate = self
  751. photoEditor.hiddenControls = [.save, .share, .sticker]
  752. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  753. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  754. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  755. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  756. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  757. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  758. viewController.present(photoEditor, animated: true, completion: nil)
  759. }
  760. func doneEditing(image: UIImage) {
  761. guard let metadata = self.metadata else {
  762. return
  763. }
  764. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  765. return
  766. }
  767. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  768. return
  769. }
  770. if filetype == "PNG" {
  771. do {
  772. try image.pngData()?.write(to: path.url, options: .atomic)
  773. } catch { return }
  774. } else if filetype == "JPG" {
  775. let imageData = image.jpegData(compressionQuality: 1)
  776. do {
  777. try imageData?.write(to: path.url)
  778. } catch { return }
  779. }
  780. // write icon
  781. CCGraphics.createNewImage(from: metadata.fileNameView, fileID: metadata.fileID, extension: filetype, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  782. // upload
  783. metadata.session = k_upload_session
  784. metadata.sessionSelector = selectorUploadFile
  785. metadata.status = Int(k_metadataStatusWaitUpload)
  786. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  787. }
  788. func canceledEditing() {
  789. print("Canceled")
  790. }
  791. }
  792. //MARK: -
  793. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  794. override func viewDidLoad() {
  795. super.viewDidLoad()
  796. delegate = self
  797. }
  798. //Delegate methods
  799. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  800. let tabViewControllers = tabBarController.viewControllers!
  801. guard let toIndex = tabViewControllers.index(of: viewController) else {
  802. if let vc = viewController as? UINavigationController {
  803. vc.popToRootViewController(animated: true);
  804. }
  805. return false
  806. }
  807. animateToTab(toIndex: toIndex)
  808. return true
  809. }
  810. func animateToTab(toIndex: Int) {
  811. let tabViewControllers = viewControllers!
  812. let fromView = selectedViewController!.view!
  813. let toView = tabViewControllers[toIndex].view!
  814. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  815. guard fromIndex != toIndex else {return}
  816. // Add the toView to the tab bar view
  817. fromView.superview?.addSubview(toView)
  818. fromView.superview?.backgroundColor = UIColor.white
  819. // Position toView off screen (to the left/right of fromView)
  820. let screenWidth = UIScreen.main.bounds.size.width;
  821. let scrollRight = toIndex > fromIndex!;
  822. let offset = (scrollRight ? screenWidth : -screenWidth)
  823. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  824. // Disable interaction during animation
  825. view.isUserInteractionEnabled = false
  826. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  827. // Slide the views by -offset
  828. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  829. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  830. }, completion: { finished in
  831. // Remove the old view from the tabbar view.
  832. fromView.removeFromSuperview()
  833. self.selectedIndex = toIndex
  834. self.view.isUserInteractionEnabled = true
  835. })
  836. }
  837. }
  838. //
  839. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  840. //
  841. extension UITabBar {
  842. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  843. // the Master view controller shows the UITabBarItem icon next to the text
  844. override open var traitCollection: UITraitCollection {
  845. if UIDevice.current.userInterfaceIdiom == .pad {
  846. return UITraitCollection(horizontalSizeClass: .compact)
  847. }
  848. return super.traitCollection
  849. }
  850. }
  851. //MARK: -
  852. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  853. @objc static let sharedInstance: NCNetworkingMain = {
  854. let instance = NCNetworkingMain()
  855. return instance
  856. }()
  857. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  858. // DOWNLOAD
  859. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  860. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  861. appDelegate.updateApplicationIconBadgeNumber()
  862. }
  863. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  864. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  865. return
  866. }
  867. if metadata.account != appDelegate.activeAccount {
  868. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  869. return
  870. }
  871. if errorCode == 0 {
  872. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  873. // Synchronized
  874. if selector == selectorDownloadSynchronize {
  875. appDelegate.updateApplicationIconBadgeNumber()
  876. return
  877. }
  878. // Modify Photo
  879. if selector == selectorDownloadEditPhoto {
  880. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  881. return
  882. }
  883. // open View File
  884. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  885. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  886. if uti == nil {
  887. uti = ""
  888. } else if uti!.contains("opendocument") && !NCViewerRichdocument.sharedInstance.isRichDocument(metadata) {
  889. metadata.typeFile = k_metadataTypeFile_unknown
  890. }
  891. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  892. if appDelegate.activeMain.view.window != nil {
  893. appDelegate.activeMain.open(in: metadata)
  894. }
  895. if appDelegate.activeFavorites.view.window != nil {
  896. appDelegate.activeFavorites.open(in: metadata)
  897. }
  898. } else {
  899. if appDelegate.activeMain.view.window != nil {
  900. appDelegate.activeMain.shouldPerformSegue(metadata)
  901. }
  902. if appDelegate.activeFavorites.view.window != nil {
  903. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  904. }
  905. }
  906. }
  907. // Open in...
  908. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  909. if appDelegate.activeMain.view.window != nil {
  910. appDelegate.activeMain.open(in: metadata)
  911. }
  912. if appDelegate.activeFavorites.view.window != nil {
  913. appDelegate.activeFavorites.open(in: metadata)
  914. }
  915. }
  916. // Save to Photo Album
  917. if selector == selectorSave {
  918. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  919. }
  920. // Copy File
  921. if selector == selectorLoadCopy {
  922. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  923. }
  924. // Set as available offline
  925. if selector == selectorLoadOffline {
  926. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  927. }
  928. //selectorLoadViewImage
  929. if selector == selectorLoadViewImage {
  930. if appDelegate.activeDetail != nil {
  931. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  932. }
  933. if appDelegate.activeMedia != nil {
  934. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  935. }
  936. }
  937. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  938. } else {
  939. // File do not exists on server, remove in local
  940. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  941. do {
  942. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  943. } catch { }
  944. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  945. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  946. NCManageDatabase.sharedInstance.deletePhotos(fileID: fileID)
  947. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  948. }
  949. if selector == selectorLoadViewImage {
  950. if appDelegate.activeDetail.view.window != nil {
  951. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  952. }
  953. if appDelegate.activeMedia.view.window != nil {
  954. appDelegate.activeMedia.downloadFileSuccessFailure(metadata.fileName, fileID: metadata.fileID, serverUrl: serverUrl, selector: selector, errorMessage: errorMessage, errorCode: errorCode)
  955. }
  956. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  957. }
  958. }
  959. }
  960. // UPLOAD
  961. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  962. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  963. appDelegate.updateApplicationIconBadgeNumber()
  964. }
  965. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  966. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  967. return
  968. }
  969. if metadata.account != appDelegate.activeAccount {
  970. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  971. return
  972. }
  973. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  974. if errorCode == 0 {
  975. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  976. } else {
  977. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  978. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  979. }
  980. }
  981. }
  982. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  983. if metadata.hasPreview == 1 && (!CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  984. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  985. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  986. OCNetworking.sharedManager().downloadPreview(withAccount: appDelegate.activeAccount, metadata: metadata, withWidth: width, andHeight: height, completion: { (account, image, message, errorCode) in
  987. if errorCode == 0 && account == self.appDelegate.activeAccount {
  988. if CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  989. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  990. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  991. if cell is NCListCell {
  992. (cell as! NCListCell).imageItem.image = image
  993. } else if cell is NCGridCell {
  994. (cell as! NCGridCell).imageItem.image = image
  995. }
  996. }
  997. }
  998. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  999. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1000. if cell is CCCellMainTransfer {
  1001. (cell as! CCCellMainTransfer).file.image = image
  1002. } else if cell is CCCellMain {
  1003. (cell as! CCCellMain).file.image = image
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. })
  1010. }
  1011. }
  1012. }
  1013. //MARK: -
  1014. class NCFunctionMain: NSObject {
  1015. @objc static let sharedInstance: NCFunctionMain = {
  1016. let instance = NCFunctionMain()
  1017. return instance
  1018. }()
  1019. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1020. @objc func synchronizeOffline() {
  1021. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1022. if (directories != nil) {
  1023. for directory: tableDirectory in directories! {
  1024. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload)
  1025. }
  1026. }
  1027. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1028. if (files != nil) {
  1029. for file: tableLocalFile in files! {
  1030. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  1031. continue
  1032. }
  1033. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload)
  1034. }
  1035. }
  1036. }
  1037. }