Scoop API

scoop:scoop.http.client:0.1.0

src/download/file.scoop

Selected production source · src/download/file.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.platform.fs.Path
6internal suspend fun prepareClientDownload(
7 download: ClientDownload,
8 request: HttpRequest,
9 destination: Path,
10 options: HttpDownloadOptions
11): HttpDownloadResult {
12 val loop = download.client.loop
13 val response = executeClientSequence(download.client, request, download.sequence)
14 download.client.lock.withLock { download.responseCall = Some(response.call) }
15 return response.useAsync suspend {
16 value ->
17 value.requireSuccess()
18 val parent = destination.parent ?: Path.fromString(".")
19 val temporary = loop.createTempFile(Some(parent), "pending-http-download-")
20 val output = ClientDownloadFile(temporary.path, temporary.file, true)
21 download.output = Some(output)
22 output.useAsync suspend {
23 owned ->
24 val written =
25 copyClientDownload(
26 download,
27 value,
28 owned.file,
29 options,
30 0L,
31 value.body.contentLength
32 )
33 download.requireActive()
34 if (options.syncOnCommit)
35 owned.file.syncAll()
36 download.requireActive()
37 HttpDownloadResult(destination, value.url, value.head, value.trailers!!, written)
38 }
39 }
42internal suspend fun cleanupClientDownload(download: ClientDownload) {
43 val output = download.output ?: return
44 nonCancellableScope<Unit> {
45 var failure: Throwable? = None
46 try {
47 output.close()
48 } catch (error: Throwable) {
49 failure = Some(error)
50 }
51 try {
52 if (output.discardOnFailure)
53 deleteClientCacheFile(output.path)
54 }
55 catch (error: Throwable) {
56 failure = Some(clientCombined(failure, error))
57 }
58 val metadata = download.resumeMetadata
59 if (download.committed && clientPresent(metadata)) {
60 try {
61 deleteClientCacheFile(metadata!!)
62 }
63 catch (error: Throwable) {
64 failure = Some(clientCombined(failure, error))
65 }
66 }
67 if (clientPresent(failure))
68 throw failure!!
69 }