nitter/src/tokens.nim

123 lines
3.2 KiB
Nim
Raw Normal View History

2021-12-27 01:37:38 +00:00
# SPDX-License-Identifier: AGPL-3.0-only
2022-01-05 21:48:45 +00:00
import asyncdispatch, httpclient, times, sequtils, json, random
import strutils, tables
import zippy
import types, agents, consts, http_pool
2020-06-01 00:16:24 +00:00
const
2022-01-05 21:48:45 +00:00
maxAge = 3.hours # tokens expire after 3 hours
maxLastUse = 1.hours # if a token is unused for 60 minutes, it expires
failDelay = initDuration(minutes=30)
2020-07-09 07:18:14 +00:00
var
2022-01-02 10:21:03 +00:00
clientPool: HttpPool
tokenPool: seq[Token]
2020-07-09 07:18:14 +00:00
lastFailed: Time
proc getPoolJson*: string =
let list = newJObject()
for token in tokenPool:
list[token.tok] = %*{
"apis": newJObject(),
"init": $token.init,
"lastUse": $token.lastUse
}
for api in token.apis.keys:
list[token.tok]["apis"][$api] = %*{
"remaining": token.apis[api].remaining,
"reset": $token.apis[api].reset
}
return $list
proc rateLimitError*(): ref RateLimitError =
2022-01-05 21:48:45 +00:00
newException(RateLimitError, "rate limited")
2020-06-01 00:16:24 +00:00
proc fetchToken(): Future[Token] {.async.} =
if getTime() - lastFailed < failDelay:
raise rateLimitError()
2020-07-09 07:18:14 +00:00
let headers = newHttpHeaders({
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"accept-encoding": "gzip",
"accept-language": "en-US,en;q=0.5",
"connection": "keep-alive",
"user-agent": getAgent(),
"authorization": auth
})
2020-06-01 00:16:24 +00:00
2020-06-02 18:37:55 +00:00
try:
2022-01-05 21:48:45 +00:00
let
resp = clientPool.use(headers): await c.postContent(activate)
tokNode = parseJson(uncompress(resp))["guest_token"]
tok = tokNode.getStr($(tokNode.getInt))
time = getTime()
2020-06-01 00:16:24 +00:00
2022-01-05 21:48:45 +00:00
return Token(tok: tok, init: time, lastUse: time)
2020-06-24 13:02:34 +00:00
except Exception as e:
2020-07-09 07:18:14 +00:00
lastFailed = getTime()
2021-01-07 21:31:29 +00:00
echo "fetching token failed: ", e.msg
2020-06-01 00:16:24 +00:00
2022-01-05 21:48:45 +00:00
proc expired(token: Token): bool =
let time = getTime()
2022-01-05 21:48:45 +00:00
token.init < time - maxAge or token.lastUse < time - maxLastUse
2020-06-01 00:16:24 +00:00
2022-01-05 21:48:45 +00:00
proc isLimited(token: Token; api: Api): bool =
if token.isNil or token.expired:
return true
if api in token.apis:
let limit = token.apis[api]
return (limit.remaining <= 5 and limit.reset > getTime())
else:
return false
2020-06-01 00:16:24 +00:00
proc release*(token: Token; invalid=false) =
2022-01-05 21:48:45 +00:00
if not token.isNil and (invalid or token.expired):
let idx = tokenPool.find(token)
if idx > -1: tokenPool.delete(idx)
2020-06-01 00:16:24 +00:00
2022-01-05 21:48:45 +00:00
proc getToken*(api: Api): Future[Token] {.async.} =
2020-06-01 00:16:24 +00:00
for i in 0 ..< tokenPool.len:
2022-01-05 21:48:45 +00:00
if not (result.isNil or result.isLimited(api)):
break
release(result)
result = tokenPool.sample()
2020-06-01 00:16:24 +00:00
2022-01-05 21:48:45 +00:00
if result.isNil or result.isLimited(api):
release(result)
2020-06-01 00:16:24 +00:00
result = await fetchToken()
tokenPool.add result
2022-01-05 21:48:45 +00:00
if result.isNil:
raise rateLimitError()
2022-01-05 21:48:45 +00:00
proc setRateLimit*(token: Token; api: Api; remaining, reset: int) =
token.apis[api] = RateLimit(
remaining: remaining,
reset: fromUnix(reset)
)
2020-06-01 00:16:24 +00:00
proc poolTokens*(amount: int) {.async.} =
var futs: seq[Future[Token]]
for i in 0 ..< amount:
futs.add fetchToken()
for token in futs:
var newToken: Token
try: newToken = await token
except: discard
2022-01-05 21:48:45 +00:00
if not newToken.isNil:
tokenPool.add newToken
2020-06-01 00:16:24 +00:00
proc initTokenPool*(cfg: Config) {.async.} =
clientPool = HttpPool()
2020-06-01 00:16:24 +00:00
while true:
2022-01-05 21:48:45 +00:00
if tokenPool.countIt(not it.isLimited(Api.timeline)) < cfg.minTokens:
await poolTokens(min(4, cfg.minTokens - tokenPool.len))
await sleepAsync(2000)