blob: aaa48e2c85690919023edac75fac35cb90949af8 (
plain)
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
|
#!/bin/bash
# Fetch current weather into a cache file. Run from conky's ${execi}, so it
# prints nothing on success and never blocks the dashboard: the widget only
# ever reads the cache.
#
# Exits non-zero with a message on stderr when it cannot fetch, and leaves any
# existing cache untouched rather than replacing good data with an error.
set -u
ENV_FILE="${WEATHER_ENV:-$HOME/.config/udt/weather.env}"
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/udt"
CACHE="$CACHE_DIR/weather.json"
if [ ! -r "$ENV_FILE" ]; then
echo "weather-fetch: no $ENV_FILE (copy weather.env.example)" >&2
exit 1
fi
# shellcheck source=/dev/null
set -a; . "$ENV_FILE"; set +a
if [ -z "${KEY:-}" ]; then
echo "weather-fetch: KEY is empty in $ENV_FILE" >&2
exit 1
fi
mkdir -p "$CACHE_DIR"
# The temp file sits in the same directory as the target, because rename is
# only atomic within a filesystem. The widget reads this cache on its own 2s
# cadence, so a fetch killed mid-write would otherwise hand it half a response.
TMP="$CACHE.tmp.$$"
trap 'rm -f "$TMP"' EXIT
URL="https://api.openweathermap.org/data/2.5/weather"
if ! curl -fsS --max-time 15 --get "$URL" \
--data-urlencode "appid=$KEY" \
--data-urlencode "units=${UNITS:-metric}" \
--data-urlencode "lang=${LANG_CODE:-en}" \
--data-urlencode "q=${CITY},${COUNTRY}" \
-o "$TMP" 2>/dev/null; then
echo "weather-fetch: request failed" >&2
exit 1
fi
# A bad key returns HTTP 200 with a JSON error body, so the status code alone
# proves nothing. This check is carried over from the polybar script, which
# learned it the same way.
if [ "$(jq -r '.cod // empty' "$TMP" 2>/dev/null)" != "200" ]; then
echo "weather-fetch: API error: $(jq -r '.message // "unknown"' "$TMP" 2>/dev/null)" >&2
exit 1
fi
mv -f "$TMP" "$CACHE"
|