oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2
3public struct ShareResponse: Sendable {
4 public let status: Int
5 public let data: Data
6 public init(status: Int, data: Data) { self.status = status; self.data = data }
7}
8public protocol ShareTransport: Sendable {
9 func send(_ request: URLRequest, file: URL?, progress: @escaping @Sendable (Double) -> Void) async throws -> ShareResponse
10}
11public struct ShareHTTP: ShareTransport {
12 public init() {}
13 public func send(_ request: URLRequest, file: URL? = nil, progress: @escaping @Sendable (Double) -> Void = { _ in }) async throws -> ShareResponse {
14 let operation = Operation(progress: progress)
15 return try await withTaskCancellationHandler {
16 try await withCheckedThrowingContinuation { operation.start(request, file: file, continuation: $0) }
17 } onCancel: { operation.cancel() }
18 }
19 private final class Operation: NSObject, URLSessionDataDelegate, @unchecked Sendable {
20 let lock = NSLock()
21 var continuation: CheckedContinuation<ShareResponse, Error>?
22 var session: URLSession?
23 var task: URLSessionTask?
24 var cancelled = false
25 var data = Data()
26 var failure: Error?
27 let progress: @Sendable (Double) -> Void
28 init(progress: @escaping @Sendable (Double) -> Void) { self.progress = progress }
29 func start(_ request: URLRequest, file: URL?, continuation: CheckedContinuation<ShareResponse, Error>) {
30 lock.lock(); defer { lock.unlock() }
31 if cancelled { continuation.resume(throwing: CancellationError()); return }
32 self.continuation = continuation
33 let config = URLSessionConfiguration.ephemeral
34 config.httpCookieStorage = nil; config.httpShouldSetCookies = false; config.urlCache = nil
35 config.timeoutIntervalForResource = 120
36 let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
37 self.session = session
38 let task = file.map { session.uploadTask(with: request, fromFile: $0) } ?? session.dataTask(with: request)
39 self.task = task; task.resume()
40 }
41 func cancel() { lock.withLock { cancelled = true; task?.cancel() } }
42 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { nil }
43 func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) {
44 guard data.count + chunk.count <= 128 * 1024 else { failure = ShareFailure.tooLarge; dataTask.cancel(); return }
45 data.append(chunk)
46 }
47 func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
48 if totalBytesExpectedToSend > 0 { progress(min(1, Double(totalBytesSent) / Double(totalBytesExpectedToSend))) }
49 }
50 func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
51 let continuation = lock.withLock { let c = self.continuation; self.continuation = nil; self.task = nil; self.session = nil; return c }
52 defer { session.finishTasksAndInvalidate() }
53 if let failure = failure ?? error { continuation?.resume(throwing: failure) }
54 else if let response = task.response as? HTTPURLResponse { continuation?.resume(returning: ShareResponse(status: response.statusCode, data: data)) }
55 else { continuation?.resume(throwing: ShareFailure.unconfirmed) }
56 }
57 }
58}
59