~tardypad/dotfiles

ref: 00c0c349a1b8960152233f11caa9ea1a40e395a3 dotfiles/files/scripts/shell/somafm -rwxr-xr-x 2.0 KiB
00c0c349 — Damien Tardy-Panis Add presentation mode to mako to hide notifications 4 months ago
                                                                                
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
95
96
#!/bin/sh

init_variables() {
  COMMAND=${0##*/}

  CHANNELS_URL='https://api.somafm.com/channels.json'
  CACHE_CHANNELS_FILE="${XDG_CACHE_HOME:-$HOME/.cache}/somafm_channels.json"

  ACTION=
  CHANNEL_ID=
}

parse_command_line() {
  ACTION="$1"
  CHANNEL_ID="$2"
}

validate_command_line() {
  if [ -z "${ACTION}" ]; then
    exit_error "missing action argument"
  fi

  if [ "${ACTION}" != 'channels' ] && [ "${ACTION}" != 'playlist' ] \
     && [ "${ACTION}" != 'direct_url' ]; then
    exit_error "invalid action ${ACTION}"
  fi

  if { [ "${ACTION}" = 'playlist' ] || [ "${ACTION}" = 'direct_url' ]; } \
    && [ -z "${CHANNEL_ID}" ]; then
    exit_error 'missing channel argument'
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $1"
  exit 1
} >&2

should_build_cache() {
  [ -f "${CACHE_CHANNELS_FILE}" ] || return 0

  CACHE_LAST_MODIFIED=$( stat -c '%Y' "${CACHE_CHANNELS_FILE}" )
  CURRENT_TIME=$( date +%s )

  # keep cache for one week
  [ $(( CURRENT_TIME - CACHE_LAST_MODIFIED )) -gt 604800 ]
}

build_cache() {
  mkdir -p "$( dirname "${CACHE_CHANNELS_FILE}" )"

  echo "Fetching list of channels..." >&2
  curl -s "${CHANNELS_URL}" -o "${CACHE_CHANNELS_FILE}"
}

somafm_channels() {
  jq -r '.channels[]
         | [ .id, .title, .dj, .genre, .description ]
         | @tsv' \
    "${CACHE_CHANNELS_FILE}"
}

somafm_playlist() {
  # select highest quality stream preferably in AAC format
  jq -r ".channels[]
         | select(.id==\"${CHANNEL_ID}\")
         | .playlists[]
         | [ .quality, .format, .url ]
         | @tsv" \
    "${CACHE_CHANNELS_FILE}" \
    | sed '{
        s/^highest/1/
        s/^high/2/
        s/^low/3/
        s/\taacp/\t2/
        s/\taac/\t1/
        s/\tmp3/\t3/
      }' \
    | sort -k 1,2 \
    | head -n 1 \
    | cut -f 3
}

somafm_direct_url() {
  echo "Fetching channel..." >&2
  curl -s "$( somafm_playlist )" \
    | sed -n 's/^File1=\(.*\)/\1/p'
}

init_variables
parse_command_line "$@"
validate_command_line

should_build_cache && build_cache

"somafm_${ACTION}"