NCMainCommon.swift 72 KB

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