nitter/src/apiutils.nim

116 lines
3.3 KiB
Nim
Raw Normal View History

2021-12-27 02:37:38 +01:00
# SPDX-License-Identifier: AGPL-3.0-only
2022-01-16 06:00:11 +01:00
import httpclient, asyncdispatch, options, sequtils, strutils, uri
import jsony, packedjson, zippy
import types, tokens, consts, parserutils, http_pool
2022-01-16 06:00:11 +01:00
from experimental/types/common import Errors, ErrorObj
2022-01-05 22:48:45 +01:00
const
rlRemaining = "x-rate-limit-remaining"
rlReset = "x-rate-limit-reset"
2020-06-01 02:16:24 +02:00
2022-01-02 11:21:03 +01:00
var pool: HttpPool
2022-01-06 03:57:14 +01:00
proc genParams*(pars: openArray[(string, string)] = @[]; cursor="";
2020-06-17 00:20:34 +02:00
count="20"; ext=true): seq[(string, string)] =
2020-06-01 02:16:24 +02:00
result = timelineParams
for p in pars:
result &= p
2020-06-17 00:20:34 +02:00
if ext:
result &= ("ext", "mediaStats")
if count.len > 0:
result &= ("count", count)
2021-12-28 08:07:15 +01:00
if cursor.len > 0:
# The raw cursor often has plus signs, which sometimes get turned into spaces,
# so we need to them back into a plus
if " " in cursor:
result &= ("cursor", cursor.replace(" ", "+"))
else:
result &= ("cursor", cursor)
2020-06-01 02:16:24 +02:00
proc genHeaders*(token: Token = nil): HttpHeaders =
2020-06-01 02:16:24 +02:00
result = newHttpHeaders({
"connection": "keep-alive",
2020-06-01 02:16:24 +02:00
"authorization": auth,
"content-type": "application/json",
"x-guest-token": if token == nil: "" else: token.tok,
"x-twitter-active-user": "yes",
"authority": "api.twitter.com",
"accept-encoding": "gzip",
2020-06-01 02:16:24 +02:00
"accept-language": "en-US,en;q=0.9",
"accept": "*/*",
"DNT": "1"
2020-06-01 02:16:24 +02:00
})
2022-01-16 06:00:11 +01:00
template updateToken() =
if api != Api.search and resp.headers.hasKey(rlRemaining):
let
remaining = parseInt(resp.headers[rlRemaining])
reset = parseInt(resp.headers[rlReset])
token.setRateLimit(api, remaining, reset)
template fetchImpl(result, fetchBody) {.dirty.} =
once:
pool = HttpPool()
2022-01-05 22:48:45 +01:00
var token = await getToken(api)
2020-07-09 09:18:14 +02:00
if token.tok.len == 0:
2021-01-07 22:31:29 +01:00
raise rateLimitError()
2020-06-01 02:16:24 +02:00
try:
var resp: AsyncResponse
2022-01-16 06:00:11 +01:00
result = pool.use(genHeaders(token)):
resp = await c.get($url)
2021-12-30 01:39:00 +01:00
await resp.body
2022-01-16 06:00:11 +01:00
if result.len > 0:
2021-12-30 01:39:00 +01:00
if resp.headers.getOrDefault("content-encoding") == "gzip":
2022-01-16 06:00:11 +01:00
result = uncompress(result, dfGzip)
2021-12-30 01:39:00 +01:00
else:
2022-01-16 06:00:11 +01:00
echo "non-gzip body, url: ", url, ", body: ", result
2022-01-16 06:00:11 +01:00
fetchBody
2020-06-01 02:16:24 +02:00
2022-01-16 06:00:11 +01:00
release(token, used=true)
2021-12-28 05:41:41 +01:00
if resp.status == $Http400:
raise newException(InternalError, $url)
except InternalError as e:
raise e
except Exception as e:
2021-12-28 05:41:41 +01:00
echo "error: ", e.name, ", msg: ", e.msg, ", token: ", token[], ", url: ", url
if "length" notin e.msg and "descriptor" notin e.msg:
release(token, invalid=true)
2021-01-07 22:31:29 +01:00
raise rateLimitError()
2022-01-16 06:00:11 +01:00
proc fetch*(url: Uri; api: Api): Future[JsonNode] {.async.} =
var body: string
fetchImpl body:
if body.startsWith('{') or body.startsWith('['):
result = parseJson(body)
else:
echo resp.status, ": ", body
result = newJNull()
updateToken()
let error = result.getError
if error in {invalidToken, forbidden, badToken}:
echo "fetch error: ", result.getError
release(token, invalid=true)
raise rateLimitError()
proc fetchRaw*(url: Uri; api: Api): Future[string] {.async.} =
fetchImpl result:
if not (result.startsWith('{') or result.startsWith('[')):
echo resp.status, ": ", result
result.setLen(0)
updateToken()
if result.startsWith("{\"errors"):
let errors = result.fromJson(Errors).errors
if errors.anyIt(it.code in {invalidToken, forbidden, badToken}):
echo "fetch error: ", errors
release(token, invalid=true)
raise rateLimitError()