2019-10-26 15:34:30 +02:00
|
|
|
import httpclient, asyncdispatch, htmlparser, options
|
2019-09-06 03:37:12 +02:00
|
|
|
import strutils, json, xmltree, uri
|
|
|
|
|
2019-10-23 08:34:03 +02:00
|
|
|
import ../types
|
2019-10-02 10:13:17 +02:00
|
|
|
import consts
|
|
|
|
|
|
|
|
proc genHeaders*(headers: openArray[tuple[key: string, val: string]];
|
|
|
|
agent: string; referer: Uri; lang=true;
|
|
|
|
auth=false; xml=false): HttpHeaders =
|
|
|
|
result = newHttpHeaders({
|
|
|
|
"referer": $referer,
|
|
|
|
"user-agent": agent,
|
|
|
|
"x-twitter-active-user": "yes",
|
|
|
|
})
|
|
|
|
|
|
|
|
if auth: result["authority"] = "twitter.com"
|
|
|
|
if lang: result["accept-language"] = consts.lang
|
|
|
|
if xml: result["x-requested-with"] = "XMLHttpRequest"
|
|
|
|
|
|
|
|
for (key, val) in headers:
|
|
|
|
result[key] = val
|
|
|
|
|
|
|
|
proc genHeaders*(agent: string; referer: Uri; lang=true;
|
|
|
|
auth=false; xml=false): HttpHeaders =
|
|
|
|
genHeaders([], agent, referer, lang, auth, xml)
|
|
|
|
|
2019-09-06 03:37:12 +02:00
|
|
|
template newClient*() {.dirty.} =
|
|
|
|
var client = newAsyncHttpClient()
|
2020-01-01 17:24:24 +01:00
|
|
|
defer:
|
|
|
|
try: client.close()
|
|
|
|
except: discard
|
2019-09-06 03:37:12 +02:00
|
|
|
client.headers = headers
|
|
|
|
|
|
|
|
proc fetchHtml*(url: Uri; headers: HttpHeaders; jsonKey = ""): Future[XmlNode] {.async.} =
|
2019-10-02 10:13:17 +02:00
|
|
|
headers["accept"] = htmlAccept
|
2019-09-06 03:37:12 +02:00
|
|
|
newClient()
|
|
|
|
|
|
|
|
var resp = ""
|
|
|
|
try:
|
|
|
|
resp = await client.getContent($url)
|
|
|
|
except:
|
|
|
|
return nil
|
|
|
|
|
|
|
|
if jsonKey.len > 0:
|
2019-10-02 10:13:17 +02:00
|
|
|
resp = parseJson(resp)[jsonKey].str
|
|
|
|
return parseHtml(resp)
|
2019-09-06 03:37:12 +02:00
|
|
|
|
|
|
|
proc fetchJson*(url: Uri; headers: HttpHeaders): Future[JsonNode] {.async.} =
|
2019-10-02 10:13:17 +02:00
|
|
|
headers["accept"] = jsonAccept
|
2019-09-06 03:37:12 +02:00
|
|
|
newClient()
|
|
|
|
|
|
|
|
try:
|
2019-12-22 01:45:07 +01:00
|
|
|
let resp = await client.getContent($url)
|
2019-09-06 03:37:12 +02:00
|
|
|
result = parseJson(resp)
|
|
|
|
except:
|
|
|
|
return nil
|
2019-10-23 08:34:03 +02:00
|
|
|
|
|
|
|
proc getLastId*(tweets: Result[Tweet]): string =
|
|
|
|
if tweets.content.len == 0: return
|
|
|
|
let last = tweets.content[^1]
|
|
|
|
if last.retweet.isNone:
|
|
|
|
$last.id
|
|
|
|
else:
|
|
|
|
$(get(last.retweet).id)
|