diff --git a/src/apiutils.nim b/src/apiutils.nim index 12a915e..41ae136 100644 --- a/src/apiutils.nim +++ b/src/apiutils.nim @@ -29,10 +29,11 @@ proc genHeaders*(token: Token = nil): HttpHeaders = }) proc fetch*(url: Uri; oldApi=false): Future[JsonNode] {.async.} = - var - token = await getToken() - client = newAsyncHttpClient(headers=genHeaders(token)) + var token = await getToken() + if token.tok.len == 0: + result = newJNull() + var client = newAsyncHttpClient(headers=genHeaders(token)) try: let resp = await client.get($url) @@ -54,5 +55,4 @@ proc fetch*(url: Uri; oldApi=false): Future[JsonNode] {.async.} = echo "error: ", url result = newJNull() finally: - try: client.close() - except: discard + client.close() diff --git a/src/tokens.nim b/src/tokens.nim index 44c2cb9..37b9e67 100644 --- a/src/tokens.nim +++ b/src/tokens.nim @@ -1,9 +1,15 @@ import asyncdispatch, httpclient, times, sequtils, strutils, json import types, agents, consts -var tokenPool {.threadvar.}: seq[Token] +var + tokenPool {.threadvar.}: seq[Token] + lastFailed: Time + minFail = initDuration(seconds=10) proc fetchToken(): Future[Token] {.async.} = + if getTime() - lastFailed < minFail: + return Token() + let headers = newHttpHeaders({ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", @@ -26,8 +32,9 @@ proc fetchToken(): Future[Token] {.async.} = result = Token(tok: tok, remaining: 187, reset: time + 15.minutes, init: time, lastUse: time) except Exception as e: + lastFailed = getTime() echo "fetching token failed: ", e.msg - return Token() + result = Token() finally: client.close()