52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package radarfetch
|
|
|
|
import (
|
|
"bytes"
|
|
)
|
|
|
|
// ExtractFirstImageAndTime tries to extract data-img and data-time from NMC HTML.
|
|
// It first searches for an element with class "time" that carries data-img/time;
|
|
// falls back to the first occurrence of data-img / data-time attributes in the HTML.
|
|
func ExtractFirstImageAndTime(html []byte) (img string, timeStr string, ok bool) {
|
|
// naive scan for data-img and data-time on the same segment first
|
|
// Search for class="time" anchor to bias to the right element
|
|
idx := bytes.Index(html, []byte("class=\"time\""))
|
|
start := 0
|
|
if idx >= 0 {
|
|
// back up a bit to include attributes on same tag
|
|
if idx > 200 {
|
|
start = idx - 200
|
|
} else {
|
|
start = 0
|
|
}
|
|
}
|
|
seg := html[start:]
|
|
img = findAttr(seg, "data-img")
|
|
timeStr = findAttr(seg, "data-time")
|
|
if img != "" {
|
|
return img, timeStr, true
|
|
}
|
|
// fallback: first data-img anywhere
|
|
img = findAttr(html, "data-img")
|
|
timeStr = findAttr(html, "data-time")
|
|
if img != "" {
|
|
return img, timeStr, true
|
|
}
|
|
return "", "", false
|
|
}
|
|
|
|
func findAttr(b []byte, key string) string {
|
|
// look for key="..."
|
|
pat := []byte(key + "=\"")
|
|
i := bytes.Index(b, pat)
|
|
if i < 0 {
|
|
return ""
|
|
}
|
|
i += len(pat)
|
|
j := bytes.IndexByte(b[i:], '"')
|
|
if j < 0 {
|
|
return ""
|
|
}
|
|
return string(b[i : i+j])
|
|
}
|