NCMainCommon.swift 63 KB

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