about summary refs log tree commit diff stats
path: root/src/loader/response.nim
blob: a3b7e3e4cf77bc807ed46ec2bed4e860888c9b5e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import std/strutils
import std/tables

import chagashi/charset
import chagashi/decoder
import img/bitmap
import io/dynstream
import io/promise
import loader/headers
import loader/request
import monoucha/javascript
import monoucha/jserror
import monoucha/quickjs
import types/blob
import types/color
import types/opt
import types/url
import utils/mimeguess
import utils/twtstr

type
  ResponseType* = enum
    rtDefault = "default"
    rtBasic = "basic"
    rtCors = "cors"
    rtError = "error"
    rtOpaque = "opaque"
    rtOpaquedirect = "opaqueredirect"

  ResponseFlag* = enum
    rfAborted

  Response* = ref object
    responseType* {.jsget: "type".}: ResponseType
    res*: int
    body*: SocketStream
    bodyUsed* {.jsget.}: bool
    status* {.jsget.}: uint16
    headers* {.jsget.}: Headers
    url*: URL #TODO should be urllist?
    unregisterFun*: proc()
    resumeFun*: proc(outputId: int)
    bodyRead*: EmptyPromise
    internalMessage*: string # should NOT be exposed to JS!
    outputId*: int
    onRead*: proc(response: Response) {.nimcall.}
    opaque*: RootRef
    flags*: set[ResponseFlag]

jsDestructor(Response)

proc newResponse*(res: int; request: Request; stream: SocketStream;
    outputId: int; status: uint16): Response =
  return Response(
    res: res,
    url: request.url,
    body: stream,
    bodyRead: EmptyPromise(),
    outputId: outputId,
    status: status
  )

func makeNetworkError*(): Response {.jsstfunc: "Response.error".} =
  #TODO use "create" function
  return Response(
    res: 0,
    responseType: rtError,
    status: 0,
    headers: newHeaders(hgImmutable),
    bodyUsed: true
  )

func sok(response: Response): bool {.jsfget: "ok".} =
  return response.status in 200u16 .. 299u16

func surl*(response: Response): string {.jsfget: "url".} =
  if response.responseType == rtError or response.url == nil:
    return ""
  return $response.url

#TODO: this should be a property of body
proc close*(response: Response) {.jsfunc.} =
  response.bodyUsed = true
  if response.unregisterFun != nil:
    response.unregisterFun()
  if response.body != nil:
    response.body.sclose()

func getCharset*(this: Response; fallback: Charset): Charset =
  if "Content-Type" notin this.headers.table:
    return fallback
  let header = this.headers.table["Content-Type"][0].toLowerAscii()
  let cs = header.getContentTypeAttr("charset").getCharset()
  if cs == CHARSET_UNKNOWN:
    return fallback
  return cs

func getContentType*(this: Response; fallback = "application/octet-stream"):
    string =
  this.headers.table.withValue("Content-Type", p):
    return p[][0].untilLower(';').strip()
  # also use DefaultGuess for container, so that local mime.types cannot
  # override buffer mime.types
  return DefaultGuess.guessContentType(this.url.pathname, fallback)

type TextOpaque = ref object of RootObj
  buf: string

const BufferSize = 4096

proc onReadText(response: Response) =
  let opaque = TextOpaque(response.opaque)
  while true:
    let olen = opaque.buf.len
    try:
      opaque.buf.setLen(olen + BufferSize)
      let n = response.body.recvData(addr opaque.buf[olen], BufferSize)
      opaque.buf.setLen(olen + n)
      if n == 0:
        break
    except ErrorAgain:
      opaque.buf.setLen(olen)
      break

proc resume*(response: Response) =
  response.resumeFun(response.outputId)
  response.resumeFun = nil

proc text*(response: Response): Promise[JSResult[string]] {.jsfunc.} =
  if response.body == nil:
    let p = newPromise[JSResult[string]]()
    p.resolve(JSResult[string].ok(""))
    return p
  if response.bodyUsed:
    let p = newPromise[JSResult[string]]()
    let err = JSResult[string]
      .err(newTypeError("Body has already been consumed"))
    p.resolve(err)
    return p
  let opaque = TextOpaque()
  response.opaque = opaque
  response.onRead = onReadText
  response.bodyUsed = true
  response.resume()
  return response.bodyRead.then(proc(): JSResult[string] =
    let charset = response.getCharset(CHARSET_UTF_8)
    ok(opaque.buf.decodeAll(charset))
  )

type BlobOpaque = ref object of RootObj
  p: pointer
  len: int
  size: int

proc onReadBlob(response: Response) =
  let opaque = BlobOpaque(response.opaque)
  while true:
    try:
      let targetLen = opaque.len + BufferSize
      if targetLen > opaque.size:
        opaque.size = targetLen
        opaque.p = realloc(opaque.p, targetLen)
      let p = cast[ptr UncheckedArray[uint8]](opaque.p)
      let n = response.body.recvData(addr p[opaque.len], BufferSize)
      opaque.len += n
      if n == 0:
        break
    except ErrorAgain:
      break

proc blob*(response: Response): Promise[JSResult[Blob]] {.jsfunc.} =
  if response.bodyUsed:
    let p = newPromise[JSResult[Blob]]()
    let err = JSResult[Blob].err(newTypeError("Body has already been consumed"))
    p.resolve(err)
    return p
  let opaque = BlobOpaque()
  response.opaque = opaque
  response.onRead = onReadBlob
  response.bodyUsed = true
  response.resume()
  let contentType = response.getContentType()
  return response.bodyRead.then(proc(): JSResult[Blob] =
    let p = realloc(opaque.p, opaque.len)
    opaque.p = nil
    if p == nil:
      return ok(newBlob(nil, 0, contentType, nil))
    ok(newBlob(p, opaque.len, contentType, deallocBlob))
  )

type BitmapOpaque = ref object of RootObj
  bmp: Bitmap
  idx: int

proc onReadBitmap(response: Response) =
  let opaque = BitmapOpaque(response.opaque)
  let bmp = opaque.bmp
  while true:
    try:
      let p = cast[ptr UncheckedArray[uint8]](addr bmp.px[0])
      let L = bmp.px.len * 4 - opaque.idx
      let n = response.body.recvData(addr p[opaque.idx], L)
      opaque.idx += n
      if n == 0:
        break
    except ErrorAgain:
      break

proc saveToBitmap*(response: Response; bmp: Bitmap): EmptyPromise =
  assert not response.bodyUsed
  let opaque = BitmapOpaque(bmp: bmp, idx: 0)
  let size = bmp.width * bmp.height
  bmp.px = cast[seq[RGBAColorBE]](newSeqUninitialized[uint32](size))
  response.opaque = opaque
  if size > 0:
    response.onRead = onReadBitmap
  else:
    response.unregisterFun()
    response.body.sclose()
  response.bodyUsed = true
  response.resume()
  return response.bodyRead

proc json(ctx: JSContext; this: Response): Promise[JSResult[JSValue]]
    {.jsfunc.} =
  return this.text().then(proc(s: JSResult[string]): JSResult[JSValue] =
    let s = ?s
    return ok(JS_ParseJSON(ctx, cstring(s), csize_t(s.len), cstring"<input>"))
  )

proc addResponseModule*(ctx: JSContext) =
  ctx.registerType(Response)