ctucx.git: nimhafas

[nimlang] hafas-client library

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
import httpclient
import asyncdispatch
import md5
import json
import strutils
import errors

proc slug*(s: string): string =
  for c in s:
    if c.isAlphaNumeric():
      result &= c.toLowerAscii()
    else:
      result &= '-'

proc request*(req: JsonNode): Future[JsonNode] {.async.} =
  let client = newAsyncHttpClient()

  let body = %*{
    "lang": "de",
    "svcReqL": [req]
  }

  # TODO: move to profile
  body["svcReqL"][0]["cfg"]["rtMode"] = %* "HYBRID"
  body["client"] = %* {
    "id": "DB",
    "v": "16040000",
    "type": "IPH",
    "name": "DB Navigator"
  }
  body["ext"] = %* "DB.R19.04.a"
  body["ver"] = %* "1.16"
  body["auth"] = %* {
    "type": "AID",
    "aid": "n91dB8Z77MLdoR0K"
  }
  let salt = "bdI8UVj40K5fvxwf"
  let bodytext = $body
  let checksum = $toMD5(bodytext & salt)
  let url = "https://reiseauskunft.bahn.de/bin/mgate.exe?checksum=" & checksum

  client.headers = newHttpHeaders({
    "Content-Type": "application/json",
    "Accept": "application/json",
    "user-agent": "my-awesome-e5f276d8fe6cprogram",
  })

  #echo pretty body
  let req = await client.request(url, httpMethod = HttpPost, body = $body)
  let resp = await req.body
  let data = parseJson(resp)
  client.close

  let error = data{"svcResL"}{0}{"err"}.getStr()
  if error != "OK":
    raise parseError(error)

  return data{"svcResL"}{0}