nitter/src/apiutils.nim

141 lines
4.3 KiB
Nim
Raw Normal View History

2021-12-27 01:37:38 +00:00
# SPDX-License-Identifier: AGPL-3.0-only
import httpclient, asyncdispatch, options, strutils, uri, times, math, tables
import jsony, packedjson, zippy, oauth1
import types, auth, consts, parserutils, http_pool
2022-01-16 17:28:40 +00:00
import experimental/types/common
2022-01-05 21:48:45 +00:00
const
rlRemaining = "x-rate-limit-remaining"
rlReset = "x-rate-limit-reset"
2020-06-01 00:16:24 +00:00
2022-01-02 10:21:03 +00:00
var pool: HttpPool
proc getOauthHeader(url, oauthToken, oauthTokenSecret: string): string =
let
encodedUrl = url.replace(",", "%2C").replace("+", "%20")
params = OAuth1Parameters(
consumerKey: consumerKey,
signatureMethod: "HMAC-SHA1",
timestamp: $int(round(epochTime())),
nonce: "0",
isIncludeVersionToHeader: true,
token: oauthToken
)
signature = getSignature(HttpGet, encodedUrl, "", params, consumerSecret, oauthTokenSecret)
params.signature = percentEncode(signature)
return getOauth1RequestHeader(params)["authorization"]
proc genHeaders*(url, oauthToken, oauthTokenSecret: string): HttpHeaders =
let header = getOauthHeader(url, oauthToken, oauthTokenSecret)
2020-06-01 00:16:24 +00:00
result = newHttpHeaders({
"connection": "keep-alive",
"authorization": header,
2020-06-01 00:16:24 +00:00
"content-type": "application/json",
"x-twitter-active-user": "yes",
2025-02-04 23:40:19 +00:00
"authority": "api.x.com",
"accept-encoding": "gzip",
2020-06-01 00:16:24 +00:00
"accept-language": "en-US,en;q=0.9",
"accept": "*/*",
"DNT": "1"
2020-06-01 00:16:24 +00:00
})
2022-01-16 05:00:11 +00:00
template fetchImpl(result, fetchBody) {.dirty.} =
once:
pool = HttpPool()
var session = await getSession(api)
if session.oauthToken.len == 0:
echo "[sessions] Empty oauth token, session: ", session.id
2021-01-07 21:31:29 +00:00
raise rateLimitError()
2020-06-01 00:16:24 +00:00
try:
2022-01-23 01:29:03 +00:00
var resp: AsyncResponse
pool.use(genHeaders($url, session.oauthToken, session.oauthSecret)):
template getContent =
resp = await c.get($url)
result = await resp.body
getContent()
if resp.status == $Http503:
badClient = true
raise newException(BadClientError, "Bad client")
2021-12-30 00:39:00 +00:00
if resp.headers.hasKey(rlRemaining):
let
remaining = parseInt(resp.headers[rlRemaining])
reset = parseInt(resp.headers[rlReset])
session.setRateLimit(api, remaining, reset)
2022-01-16 05:00:11 +00:00
if result.len > 0:
2021-12-30 00:39:00 +00:00
if resp.headers.getOrDefault("content-encoding") == "gzip":
2022-01-16 05:00:11 +00:00
result = uncompress(result, dfGzip)
if result.startsWith("{\"errors"):
let errors = result.fromJson(Errors)
2025-02-04 23:35:39 +00:00
echo "Fetch error, API: ", api, ", errors: ", errors
if errors in {expiredToken, badToken, locked}:
invalidate(session)
raise rateLimitError()
elif errors in {rateLimited}:
# rate limit hit, resets after 24 hours
setLimited(session, api)
raise rateLimitError()
elif result.startsWith("429 Too Many Requests"):
echo "[sessions] 429 error, API: ", api, ", session: ", session.id
session.apis[api].remaining = 0
# rate limit hit, resets after the 15 minute window
raise rateLimitError()
2020-06-01 00:16:24 +00:00
fetchBody
2021-12-28 04:41:41 +00:00
if resp.status == $Http400:
2025-02-04 23:35:39 +00:00
echo "ERROR 400, ", api, ": ", result
2021-12-28 04:41:41 +00:00
raise newException(InternalError, $url)
except InternalError as e:
raise e
except BadClientError as e:
raise e
except OSError as e:
raise e
except Exception as e:
let id = if session.isNil: "null" else: $session.id
echo "error: ", e.name, ", msg: ", e.msg, ", sessionId: ", id, ", url: ", url
2021-01-07 21:31:29 +00:00
raise rateLimitError()
finally:
release(session)
2022-01-16 05:00:11 +00:00
template retry(bod) =
try:
bod
except RateLimitError:
echo "[sessions] Rate limited, retrying ", api, " request..."
bod
2022-01-16 05:00:11 +00:00
proc fetch*(url: Uri; api: Api): Future[JsonNode] {.async.} =
retry:
var body: string
fetchImpl body:
if body.startsWith('{') or body.startsWith('['):
result = parseJson(body)
else:
echo resp.status, ": ", body, " --- url: ", url
result = newJNull()
let error = result.getError
2025-02-05 02:49:17 +00:00
if error != null:
echo "Fetch error, API: ", api, ", error: ", error
if error in {expiredToken, badToken, locked}:
invalidate(session)
2025-02-05 02:49:17 +00:00
raise rateLimitError()
2022-01-16 05:00:11 +00:00
proc fetchRaw*(url: Uri; api: Api): Future[string] {.async.} =
retry:
fetchImpl result:
if not (result.startsWith('{') or result.startsWith('[')):
echo resp.status, ": ", result, " --- url: ", url
result.setLen(0)