2024-06-28 10:34:57 +00:00
|
|
|
{.push raises: [].}
|
2023-04-04 13:34:53 +00:00
|
|
|
|
2022-11-10 09:29:34 +00:00
|
|
|
import
|
2022-11-16 15:38:31 +00:00
|
|
|
std/json,
|
2024-07-09 11:14:28 +00:00
|
|
|
results,
|
2022-11-16 15:38:31 +00:00
|
|
|
stew/shims/net,
|
2022-11-10 09:29:34 +00:00
|
|
|
chronicles,
|
|
|
|
chronicles/topics_registry,
|
|
|
|
chronos,
|
2024-03-15 23:08:47 +00:00
|
|
|
presto/[client, common]
|
2022-11-10 09:29:34 +00:00
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
type NodeLocation* = object
|
|
|
|
country*: string
|
|
|
|
city*: string
|
|
|
|
lat*: string
|
|
|
|
long*: string
|
|
|
|
isp*: string
|
2022-11-10 09:29:34 +00:00
|
|
|
|
|
|
|
proc flatten*[T](a: seq[seq[T]]): seq[T] =
|
|
|
|
var aFlat = newSeq[T](0)
|
|
|
|
for subseq in a:
|
|
|
|
aFlat &= subseq
|
|
|
|
return aFlat
|
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
proc decodeBytes*(
|
|
|
|
t: typedesc[NodeLocation], value: openArray[byte], contentType: Opt[ContentTypeData]
|
|
|
|
): RestResult[NodeLocation] =
|
2022-11-16 15:38:31 +00:00
|
|
|
var res: string
|
|
|
|
if len(value) > 0:
|
|
|
|
res = newString(len(value))
|
|
|
|
copyMem(addr res[0], unsafeAddr value[0], len(value))
|
|
|
|
try:
|
|
|
|
let jsonContent = parseJson(res)
|
|
|
|
if $jsonContent["status"].getStr() != "success":
|
2024-03-15 23:08:47 +00:00
|
|
|
error "query failed", result = jsonContent
|
2022-11-16 15:38:31 +00:00
|
|
|
return err("query failed")
|
2024-03-15 23:08:47 +00:00
|
|
|
return ok(
|
|
|
|
NodeLocation(
|
|
|
|
country: jsonContent["country"].getStr(),
|
|
|
|
city: jsonContent["city"].getStr(),
|
|
|
|
lat: $jsonContent["lat"].getFloat(),
|
|
|
|
long: $jsonContent["lon"].getFloat(),
|
|
|
|
isp: jsonContent["isp"].getStr(),
|
|
|
|
)
|
|
|
|
)
|
2023-04-05 12:27:11 +00:00
|
|
|
except Exception:
|
2022-11-16 15:38:31 +00:00
|
|
|
return err("failed to get the location: " & getCurrentExceptionMsg())
|
2022-11-10 09:29:34 +00:00
|
|
|
|
2022-11-16 15:38:31 +00:00
|
|
|
proc encodeString*(value: string): RestResult[string] =
|
|
|
|
ok(value)
|
2022-11-10 09:29:34 +00:00
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
proc ipToLocation*(
|
|
|
|
ip: string
|
|
|
|
): RestResponse[NodeLocation] {.rest, endpoint: "json/{ip}", meth: MethodGet.}
|