123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455 |
- //
- // NCNetworking+Task.swift
- // Nextcloud
- //
- // Created by Marino Faggiana on 24/08/24.
- // Copyright © 2024 Marino Faggiana. All rights reserved.
- //
- // Author Marino Faggiana <marino.faggiana@nextcloud.com>
- //
- // This program is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
- //
- import Foundation
- import UIKit
- import NextcloudKit
- import Alamofire
- import RealmSwift
- extension NCNetworking {
- func cancelAllTask() {
- cancelAllQueue()
- cancelAllDataTask()
- cancelAllWaitTask()
- cancelAllDownloadUploadTask()
- }
- func cancelAllDownloadTask() {
- cancelDownloadTasks()
- cancelDownloadBackgroundTask()
- }
- func cancelAllUploadTask() {
- cancelUploadTasks()
- cancelUploadBackgroundTask()
- }
- func cancelAllDownloadUploadTask() {
- cancelAllDownloadTask()
- cancelAllUploadTask()
- }
- // MARK: -
- func cancelTask(metadata: tableMetadata) {
- /// FAVORITE
- ///
- if metadata.status == global.metadataStatusWaitFavorite {
- let favorite = (metadata.storeFlag as? NSString)?.boolValue ?? false
- database.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite, saveOldFavorite: nil, status: global.metadataStatusNormal)
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// COPY
- ///
- if metadata.status == global.metadataStatusWaitCopy {
- database.setMetadataCopyMove(ocId: metadata.ocId, serverUrlTo: "", overwrite: nil, status: global.metadataStatusNormal)
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// MOVE
- ///
- if metadata.status == global.metadataStatusWaitMove {
- database.setMetadataCopyMove(ocId: metadata.ocId, serverUrlTo: "", overwrite: nil, status: global.metadataStatusNormal)
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// DELETE
- ///
- if metadata.status == global.metadataStatusWaitDelete {
- database.setMetadataStatus(ocId: metadata.ocId, status: global.metadataStatusNormal)
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// RENAME
- ///
- if metadata.status == global.metadataStatusWaitRename {
- database.restoreMetadataFileName(ocId: metadata.ocId)
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// CREATE FOLDER
- ///
- if metadata.status == global.metadataStatusWaitCreateFolder {
- let metadatas = database.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND status != 0", metadata.account, metadata.serverUrl))
- for metadata in metadatas {
- database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- }
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// NO SESSION
- ///
- if metadata.session.isEmpty {
- self.database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- return
- }
- /// DOWNLOAD
- ///
- if metadata.session.contains("download") {
- if metadata.session == sessionDownload {
- cancelDownloadTasks(metadata: metadata)
- } else if metadata.session == sessionDownloadBackground {
- cancelDownloadBackgroundTask(metadata: metadata)
- }
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterDownloadCancelFile,
- object: nil,
- userInfo: ["ocId": metadata.ocId,
- "ocIdTransfer": metadata.ocIdTransfer,
- "session": metadata.session,
- "serverUrl": metadata.serverUrl,
- "account": metadata.account],
- second: 0.5)
- }
- /// UPLOAD
- ///
- if metadata.session.contains("upload") {
- if metadata.session == NextcloudKit.shared.nkCommonInstance.identifierSessionUpload {
- cancelUploadTasks(metadata: metadata)
- } else {
- cancelUploadBackgroundTask(metadata: metadata)
- }
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterUploadCancelFile,
- object: nil,
- userInfo: ["ocId": metadata.ocId,
- "ocIdTransfer": metadata.ocIdTransfer,
- "session": metadata.session,
- "serverUrl": metadata.serverUrl,
- "account": metadata.account],
- second: 0.5)
- }
- }
- func cancelAllWaitTask() {
- let metadatas = database.getMetadatas(predicate: NSPredicate(format: "status IN %@", global.metadataStatusWaitWebDav))
- for metadata in metadatas {
- cancelTask(metadata: metadata)
- }
- NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource)
- }
- func cancelAllDataTask() {
- NextcloudKit.shared.nkCommonInstance.nksessions.forEach { session in
- session.sessionData.session.getTasksWithCompletionHandler { dataTasks, _, _ in
- dataTasks.forEach { task in
- task.cancel()
- }
- }
- }
- }
- // MARK: -
- func cancelDownloadTasks(metadata: tableMetadata? = nil) {
- NextcloudKit.shared.nkCommonInstance.nksessions.forEach { session in
- session.sessionData.session.getTasksWithCompletionHandler { _, _, downloadTasks in
- downloadTasks.forEach { task in
- if metadata == nil || (task.taskIdentifier == metadata?.sessionTaskIdentifier) {
- task.cancel()
- }
- }
- }
- }
- if let metadata {
- self.database.clearMetadataSession(metadata: metadata)
- } else if let results = self.database.getResultsMetadatas(predicate: NSPredicate(format: "(status == %d || status == %d || status == %d) AND session == %@",
- self.global.metadataStatusWaitDownload,
- self.global.metadataStatusDownloading,
- self.global.metadataStatusDownloadError,
- sessionDownload)) {
- self.database.clearMetadataSession(metadatas: Array(results))
- }
- }
- func cancelDownloadBackgroundTask(metadata: tableMetadata? = nil) {
- NextcloudKit.shared.nkCommonInstance.nksessions.forEach { session in
- Task {
- let tasksBackground = await session.sessionDownloadBackground.tasks
- for task in tasksBackground.2 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
- if metadata == nil || (task.taskIdentifier == metadata?.sessionTaskIdentifier) {
- task.cancel()
- }
- }
- if let metadata {
- self.database.clearMetadataSession(metadata: metadata)
- } else if let results = self.database.getResultsMetadatas(predicate: NSPredicate(format: "(status == %d || status == %d || status == %d) AND session == %@",
- self.global.metadataStatusWaitDownload,
- self.global.metadataStatusDownloading,
- self.global.metadataStatusDownloadError,
- sessionDownloadBackground)) {
- self.database.clearMetadataSession(metadatas: Array(results))
- }
- }
- }
- }
- // MARK: -
- func cancelUploadTasks(metadata: tableMetadata? = nil) {
- NextcloudKit.shared.nkCommonInstance.nksessions.forEach { nkSession in
- nkSession.sessionData.session.getTasksWithCompletionHandler { _, uploadTasks, _ in
- uploadTasks.forEach { task in
- if metadata == nil || (metadata?.account == nkSession.account && metadata?.sessionTaskIdentifier == task.taskIdentifier) {
- task.cancel()
- }
- }
- }
- }
- if let metadata {
- self.database.deleteMetadataOcId(metadata.ocId)
- } else if let results = self.database.getResultsMetadatas(predicate: NSPredicate(format: "(status == %d || status == %d || status == %d) AND session == %@",
- self.global.metadataStatusWaitUpload,
- self.global.metadataStatusUploading,
- self.global.metadataStatusUploadError,
- sessionUpload)) {
- self.database.deleteMetadatas(Array(results))
- }
- }
- func cancelUploadBackgroundTask(metadata: tableMetadata? = nil) {
- NextcloudKit.shared.nkCommonInstance.nksessions.forEach { nkSession in
- Task {
- let tasksBackground = await nkSession.sessionUploadBackground.tasks
- for task in tasksBackground.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
- if metadata == nil || (metadata?.account == nkSession.account &&
- metadata?.session == sessionUploadBackground &&
- metadata?.sessionTaskIdentifier == task.taskIdentifier) {
- task.cancel()
- }
- }
- let tasksBackgroundWWan = await nkSession.sessionUploadBackgroundWWan.tasks
- for task in tasksBackgroundWWan.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
- if metadata == nil || (metadata?.account == nkSession.account &&
- metadata?.session == sessionUploadBackgroundWWan &&
- metadata?.sessionTaskIdentifier == task.taskIdentifier) {
- task.cancel()
- }
- }
- let tasksBackgroundExt = await nkSession.sessionUploadBackgroundExt.tasks
- for task in tasksBackgroundExt.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
- if metadata == nil || (metadata?.account == nkSession.account &&
- metadata?.session == sessionUploadBackgroundExt &&
- metadata?.sessionTaskIdentifier == task.taskIdentifier) {
- task.cancel()
- }
- }
- if let metadata {
- self.database.deleteMetadataOcId(metadata.ocId)
- } else if let results = self.database.getResultsMetadatas(predicate: NSPredicate(format: "(status == %d || status == %d || status == %d) AND (session == %@ || session == %@ || session == %@)",
- self.global.metadataStatusWaitUpload,
- self.global.metadataStatusUploading,
- self.global.metadataStatusUploadError,
- sessionUploadBackground,
- sessionUploadBackgroundWWan,
- sessionUploadBackgroundExt
- )) {
- self.database.deleteMetadatas(Array(results))
- }
- }
- }
- }
- // MARK: -
- func getAllDataTask() async -> [URLSessionDataTask] {
- guard let nkSessions = NextcloudKit.shared.nkCommonInstance.nksessions.getArray() else { return [] }
- var taskArray: [URLSessionDataTask] = []
- for nkSession in nkSessions {
- let tasks = await nkSession.sessionData.session.tasks
- for task in tasks.0 {
- taskArray.append(task)
- }
- }
- return taskArray
- }
- // MARK: -
- func verifyZombie() async {
- var metadatas: [tableMetadata] = []
- /// UPLOADING-FOREGROUND
- ///
- metadatas = self.database.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d",
- sessionUpload,
- self.global.metadataStatusUploading))
- for metadata in metadatas {
- guard let nkSession = NextcloudKit.shared.getSession(account: metadata.account) else {
- self.database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- continue
- }
- var foundTask = false
- let tasks = await nkSession.sessionData.session.tasks
- for task in tasks.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
- if metadata.sessionTaskIdentifier == task.taskIdentifier {
- foundTask = true
- }
- }
- if !foundTask {
- if NCUtilityFileSystem().fileProviderStorageExists(metadata) {
- self.database.setMetadataSession(ocId: metadata.ocId,
- sessionError: "",
- status: self.global.metadataStatusWaitUpload)
- } else {
- self.database.deleteMetadataOcId(metadata.ocId)
- }
- }
- }
- /// UPLOADING-BACKGROUND
- ///
- metadatas = self.database.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d",
- sessionUploadBackground,
- sessionUploadBackgroundWWan,
- sessionUploadBackgroundExt,
- self.global.metadataStatusUploading))
- for metadata in metadatas {
- guard let nkSession = NextcloudKit.shared.getSession(account: metadata.account) else {
- self.database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- continue
- }
- var session: URLSession?
- if metadata.session == sessionUploadBackground {
- session = nkSession.sessionUploadBackground
- } else if metadata.session == sessionUploadBackgroundWWan {
- session = nkSession.sessionUploadBackgroundWWan
- } else if metadata.session == sessionUploadBackgroundExt {
- session = nkSession.sessionUploadBackgroundExt
- }
- var foundTask = false
- guard let tasks = await session?.allTasks else {
- self.database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- continue
- }
- for task in tasks {
- if metadata.sessionTaskIdentifier == task.taskIdentifier {
- foundTask = true
- }
- }
- if !foundTask {
- if NCUtilityFileSystem().fileProviderStorageExists(metadata) {
- self.database.setMetadataSession(ocId: metadata.ocId,
- sessionError: "",
- status: self.global.metadataStatusWaitUpload)
- } else {
- self.database.deleteMetadataOcId(metadata.ocId)
- }
- }
- }
- /// DOWNLOADING-FOREGROUND
- ///
- metadatas = self.database.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d",
- sessionDownload,
- self.global.metadataStatusDownloading))
- for metadata in metadatas {
- guard let nkSession = NextcloudKit.shared.getSession(account: metadata.account) else {
- self.database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- continue
- }
- var foundTask = false
- let tasks = await nkSession.sessionData.session.tasks
- for task in tasks.2 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask])
- if metadata.sessionTaskIdentifier == task.taskIdentifier {
- foundTask = true
- }
- }
- if !foundTask {
- self.database.setMetadataSession(ocId: metadata.ocId,
- session: "",
- sessionError: "",
- selector: "",
- status: self.global.metadataStatusNormal)
- }
- }
- /// DOWNLOADING-BACKGROUND
- ///
- metadatas = self.database.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d",
- sessionDownloadBackground,
- self.global.metadataStatusDownloading))
- for metadata in metadatas {
- guard let nkSession = NextcloudKit.shared.getSession(account: metadata.account) else {
- self.database.deleteMetadataOcId(metadata.ocId)
- utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
- continue
- }
- var foundTask = false
- let tasks = await nkSession.sessionDownloadBackground.allTasks
- for task in tasks {
- if metadata.sessionTaskIdentifier == task.taskIdentifier {
- foundTask = true
- }
- }
- if !foundTask {
- self.database.setMetadataSession(ocId: metadata.ocId,
- session: "",
- sessionError: "",
- selector: "",
- status: self.global.metadataStatusNormal)
- }
- }
- }
- }
|