wmtools/tides.nim

106 lines
2.8 KiB
Nim

#curl https://www.tidetimes.org.uk/exmouth-dock-tide-times-20190101 | grep -E -o ">((High|Low)|([0-9]+:[0-9]+)|([0-9]+\.[0-9]+m))"
import base
import std/[re,httpclient,times,osproc,sequtils]
# TODO:
# Pass location in as variable
const url* = "https://www.tidetimes.org.uk/%LOC-tide-times"
const loc* = "exmouth-dock"
const icon: string = "🌊 "
type
Tide = ref object
State: string
Time: string
Height: string
Tomorrow: bool
TideList = ref object
Tides: seq[Tide]
LastUpdated: DateTime
proc sortTides(tides: seq[Tide], is_tomorrow: bool = false): seq[Tide] =
let timenow = now()
var reltides: seq[Tide]
for tide in tides:
if timenow.format("HH:MM") <= tide.Time and not is_tomorrow:
reltides.add(tide)
elif is_tomorrow:
reltides.add(tide)
return reltides
proc getTideData(get_tomorrow: bool = false): seq[Tide] =
var tides: seq[Tide]
let fnd = re">((High|Low)|([0-9]+:[0-9]+)|([0-9]+\.[0-9]+m))"
var client = newHttpClient()
var link = replace(url,re"\%LOC",loc)
if get_tomorrow:
let tomdate = now() + initTimeInterval(days = 1)
link &= "-" & tomdate.format("yyyyMMdd")
try:
# Remember to compile with -d:ssl else this won't work
let data = client.getContent(link)
let times = findAll(data,fnd)
var tide: Tide
var column = 0
for idx,time in times:
if idx == 12:
break
let l = len(time) - 1
if time == ">High" or time == ">Low":
tide = Tide()
tide.State = time[1..l]
column = 1
continue
elif column == 1:
tide.Time = time[1..l]
column = 2
continue
elif column == 2:
tide.Height = time[1..l]
tides.add(tide)
column = 0
continue
except:
echo "Unable to get Tide Data : " & getCurrentExceptionMsg()
return tides
proc getDesign(tides: seq[Tide]): Info =
var my_tides: seq[string] = @[]
for tide in tides:
let str = icon & tide.State[0] & " " & tide.Time & " " & tide.Height
my_tides.add(str)
var data = newInfo("Tides")
data.border = black
data.args = my_tides
return data
proc getTides*(get_tomorrow: bool = false) =
var mytides = TideList()
mytides.Tides = getTideData(get_tomorrow)
mytides.Tides = sortTides(mytides.Tides, get_tomorrow)
if len(mytides.Tides) == 0:
getTides(true)
return
let data = getDesign(mytides.Tides)
var opt_tomorrow = "tomorrow"
if get_tomorrow:
opt_tomorrow = "back"
let args = concat(data.args,@["---",opt_tomorrow])
let output = outputData(data,args)
if output == "tomorrow":
getTides(true)
elif output == "back":
getTides()
elif output == "---":
return
elif output in args:
let url = replace(url,re"\%LOC",loc)
discard execCmd("xdg-open " & url)
proc main() =
getTides()
if isMainModule:
main()