summaryrefslogtreecommitdiff
path: root/ar/.local/bin/statusbar/sb-price
blob: 5323ef1a7bb99075b983246e81654523c54436db (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/sh

# Usage:
#	price <currency-base currency> <name of currency> <icon> <signal>
#	price bat-btc "Basic Attention Token" 🦁 21
#	This will give the price of BAT denominated in BTC and will update on
#	signal 21.
# When the name of the currency is multi-word, put it in quotes.

[ -z "$1" ] && exit 1

url="${CRYPTOURL:-rate.sx}"
target="${1%%-*}"
denom="${1##*-}"
name="${2:-$1}"
icon="${3:-💰}"
case "$denom" in
"$target" | usd)
  denom="usd"
  symb="$"
  ;;
gbp) symb="£" ;;
eur) symb="€" ;;
btc) symb="" ;;
esac
interval="@14d" # History contained in chart preceded by '@' (7d = 7 days)
dir="${XDG_CACHE_HOME:-$HOME/.cache}/crypto-prices"
pricefile="$dir/$target-$denom"
chartfile="$dir/$target-$denom-chart"

[ -d "$dir" ] || mkdir -p "$dir"

checkprice() {
  [ "$(stat -c %y "$pricefile" 2>/dev/null |
    cut -d' ' -f1)" = "$(date '+%Y-%m-%d')" ]
}

updateprice() {
  { grep -q -m1 '^up$' /sys/class/net/w*/operstate || grep -q -m1 '^up$' /sys/class/net/e*/operstate; } &&
    curl -sf \
      --fail-early "${denom}.${url}/1${target}" "${denom}.${url}/${target}${interval}" \
      --output "$pricefile" --output "$chartfile" &&
    touch "$pricefile" "$chartfile"
}

checkprice || updateme="1"

case $BLOCK_BUTTON in
1) setsid "$TERMINAL" -e less -Srf "$chartfile" ;;
2)
  notify-send -u low "$icon Updating..." "Updating $name price..."
  updateme="1"
  showupdate="1"
  ;;
3)
  uptime="$(date -d "$(stat -c %x "$pricefile" 2>/dev/null)" '+%D at %T' | sed "s|$(date '+%D')|Today|")"
  notify-send "$icon $name module" "\- <b>Exact price: \$$(cat "$pricefile")</b>
- Left click for chart of changes.
- Middle click to update.
- Shows 🔃 if updating prices.
- <b>Last updated:
	$uptime</b>"
  ;;
6) setsid -f "$TERMINAL" -e "$EDITOR" "$0" ;;
esac

[ -n "$updateme" ] &&
  if [ -n "$showupdate" ]; then
    updateprice && notify-send "$icon Update complete." "$name price is now \$$(cat "$pricefile")"
  else
    # shellcheck disable=SC2015
    [ -n "$4" ] &&
      (
        flock -n 9 &&
          (
            tries=0
            while [ $tries -ne 100 ]; do
              updateprice && break ||
                {
                  tries=$((tries + 1))
                  sleep .1
                }
            done
            ! checkprice &&
              until updateprice; do sleep 60; done
            pkill -RTMIN+"$4" "${STATUSBAR:-dwmblocks}"
          ) &
        echo
        exit
      ) 9>"${XDG_RUNTIME_DIR}/sb-price.lock" ||
      updateprice
  fi

[ -f "$pricefile" ] && printf "%s%s%0.2f" "$icon" "$symb" "$(cat "$pricefile")"