NCMainCommon.swift 69 KB

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