apiutils.nim 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # SPDX-License-Identifier: AGPL-3.0-only
  2. import httpclient, asyncdispatch, options, times, strutils, uri
  3. import packedjson, zippy
  4. import types, tokens, consts, parserutils, http_pool
  5. const
  6. rlRemaining = "x-rate-limit-remaining"
  7. rlReset = "x-rate-limit-reset"
  8. var pool: HttpPool
  9. proc genParams*(pars: openarray[(string, string)] = @[]; cursor="";
  10. count="20"; ext=true): seq[(string, string)] =
  11. result = timelineParams
  12. for p in pars:
  13. result &= p
  14. if ext:
  15. result &= ("ext", "mediaStats")
  16. if count.len > 0:
  17. result &= ("count", count)
  18. if cursor.len > 0:
  19. # The raw cursor often has plus signs, which sometimes get turned into spaces,
  20. # so we need to them back into a plus
  21. if " " in cursor:
  22. result &= ("cursor", cursor.replace(" ", "+"))
  23. else:
  24. result &= ("cursor", cursor)
  25. proc genHeaders*(token: Token = nil): HttpHeaders =
  26. result = newHttpHeaders({
  27. "connection": "keep-alive",
  28. "authorization": auth,
  29. "content-type": "application/json",
  30. "x-guest-token": if token == nil: "" else: token.tok,
  31. "x-twitter-active-user": "yes",
  32. "authority": "api.twitter.com",
  33. "accept-encoding": "gzip",
  34. "accept-language": "en-US,en;q=0.9",
  35. "accept": "*/*",
  36. "DNT": "1"
  37. })
  38. proc fetch*(url: Uri; api: Api): Future[JsonNode] {.async.} =
  39. once:
  40. pool = HttpPool()
  41. var token = await getToken(api)
  42. if token.tok.len == 0:
  43. raise rateLimitError()
  44. let headers = genHeaders(token)
  45. try:
  46. var resp: AsyncResponse
  47. var body = pool.use(headers):
  48. resp = await c.get($url)
  49. await resp.body
  50. if body.len > 0:
  51. if resp.headers.getOrDefault("content-encoding") == "gzip":
  52. body = uncompress(body, dfGzip)
  53. else:
  54. echo "non-gzip body, url: ", url, ", body: ", body
  55. if body.startsWith('{') or body.startsWith('['):
  56. result = parseJson(body)
  57. else:
  58. echo resp.status, ": ", body
  59. result = newJNull()
  60. if api != Api.search and resp.headers.hasKey(rlRemaining):
  61. let
  62. remaining = parseInt(resp.headers[rlRemaining])
  63. reset = parseInt(resp.headers[rlReset])
  64. token.setRateLimit(api, remaining, reset)
  65. if result.getError notin {invalidToken, forbidden, badToken}:
  66. release(token, used=true)
  67. else:
  68. echo "fetch error: ", result.getError
  69. release(token, invalid=true)
  70. raise rateLimitError()
  71. if resp.status == $Http400:
  72. raise newException(InternalError, $url)
  73. except InternalError as e:
  74. raise e
  75. except Exception as e:
  76. echo "error: ", e.name, ", msg: ", e.msg, ", token: ", token[], ", url: ", url
  77. if "length" notin e.msg and "descriptor" notin e.msg:
  78. release(token, invalid=true)
  79. raise rateLimitError()