Files
baytransitclis/bt.nim
2022-06-30 18:06:11 -07:00

92 lines
2.5 KiB
Nim

import std/[json, httpclient, sequtils, strutils, times]
import strformat
import os
import terminal
let client = newHttpClient()
proc getDepartures(station: string): JSONNode =
let response = client.get(&"http://api.bart.gov/api/etd.aspx?cmd=etd&orig={station}&key=MW9S-E7SL-26DU-VV8V&json=y")
parseJson(response.body)
proc formatEstimateMinutes(minutes: string): string =
case minutes:
of "Leaving":
"leaving"
of "1":
"1 min"
else:
&"{minutes} mins"
proc lineColor(color: string): ForegroundColor =
case color.toLowerAscii():
of "blue": fgBlue
of "green": fgGreen
of "red": fgRed
of "yellow": fgYellow
of "orange": fgMagenta
else: fgDefault
# try to guess which station abbreviation I meant to type
proc parseStation(station: string): string =
case station:
of "ashby": "ashb"
of "antioch": "antioch"
of "balboa": "balb"
of "berkeley", "berkly": "dtbrk"
of "civic", "cvc": "civc"
of "uptown": "19th"
of "emb", "embark": "embr"
of "fmt", "fremont": "frmt"
of "mcaurthur", "mcaurther": "mcar"
of "montgomery": "mont"
of "walnut": "wcrk"
of "hwd", "hayward": "hayw"
of "sfo": "sfia"
of "oak": "oakl"
of "orinda": "orin"
of "millbrae", "mil": "mlbr"
of "powell", "powel": "powl"
of "rockridge": "rock"
of "west": "woak"
else: station
proc formatDepartures(etd: JSONNode): string =
if not etd["root"].hasKey("station"):
echo "No departures for this station"
return
let name = etd["root"]["station"][0]["name"].getStr
let lines = etd["root"]["station"][0]["etd"]
styledEcho styleBright, name & " - " & now().format("H:mm")
let maxDestLength = lines.getElems.map(proc (line: JSONNode): int = line["destination"].getStr.len).foldl(max(a,b), 1)
for line in lines:
let dest = line["destination"].getStr
let color = line["estimate"][0]["color"].getStr
var estimate = formatEstimateMinutes(line["estimate"][0]["minutes"].getStr)
if len(line["estimate"]) > 1:
estimate = estimate & ", " & formatEstimateMinutes(line["estimate"][1]["minutes"].getStr)
styledEcho lineColor(color), dest & indent(estimate, max(maxDestLength + 3 - len(dest), 0))
proc usage() =
echo """bt - bart times cli
usage: bt station [direction n or s]
"""
proc main =
let params = commandLineParams()
if len(params) == 0:
usage()
elif len(params) == 1:
let station = parseStation(params[0])
echo formatDepartures(getDepartures(station))
main()