2020-06-02 14:22:44 +00:00
|
|
|
import httpclient, asyncdispatch, options, times, strutils, uri
|
|
|
|
import packedjson
|
2020-06-15 14:40:27 +00:00
|
|
|
import types, tokens, consts, parserutils
|
|
|
|
|
|
|
|
const rl = "x-rate-limit-"
|
2020-06-01 00:16:24 +00:00
|
|
|
|
|
|
|
proc genParams*(pars: openarray[(string, string)] = @[];
|
|
|
|
cursor=""): seq[(string, string)] =
|
|
|
|
result = timelineParams
|
|
|
|
for p in pars:
|
|
|
|
result &= p
|
|
|
|
if cursor.len > 0:
|
|
|
|
result &= ("cursor", cursor)
|
|
|
|
|
2020-06-15 14:40:27 +00:00
|
|
|
proc genHeaders*(token: Token = nil): HttpHeaders =
|
2020-06-01 00:16:24 +00:00
|
|
|
result = newHttpHeaders({
|
|
|
|
"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-language": "en-US,en;q=0.9",
|
|
|
|
"accept": "*/*",
|
2020-06-15 14:40:27 +00:00
|
|
|
"DNT": "1"
|
2020-06-01 00:16:24 +00:00
|
|
|
})
|
|
|
|
|
2020-06-15 14:40:27 +00:00
|
|
|
proc fetch*(url: Uri; oldApi=false): Future[JsonNode] {.async.} =
|
2020-06-01 00:16:24 +00:00
|
|
|
var
|
2020-06-15 14:40:27 +00:00
|
|
|
token = if oldApi: nil else: await getToken()
|
|
|
|
client = newAsyncHttpClient(headers=genHeaders(token))
|
2020-06-01 00:16:24 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
let
|
|
|
|
resp = await client.get($url)
|
|
|
|
body = await resp.body
|
|
|
|
|
2020-06-15 14:40:27 +00:00
|
|
|
if not body.startsWith('{'):
|
|
|
|
echo resp.status, ": ", body
|
|
|
|
result = newJNull()
|
|
|
|
else:
|
|
|
|
result = parseJson(body)
|
|
|
|
|
2020-06-01 00:16:24 +00:00
|
|
|
if not oldApi and resp.headers.hasKey(rl & "limit"):
|
|
|
|
token.remaining = parseInt(resp.headers[rl & "remaining"])
|
|
|
|
token.reset = fromUnix(parseInt(resp.headers[rl & "reset"]))
|
|
|
|
|
2020-06-15 14:40:27 +00:00
|
|
|
if result.getError notin {invalidToken, forbidden, badToken}:
|
|
|
|
token.release()
|
|
|
|
except Exception:
|
2020-06-01 00:16:24 +00:00
|
|
|
echo "error: ", url
|
2020-06-02 14:22:44 +00:00
|
|
|
result = newJNull()
|
2020-06-01 00:16:24 +00:00
|
|
|
finally:
|
|
|
|
try: client.close()
|
|
|
|
except: discard
|