| 1 | #! /usr/bin/awk -f |
| 2 | |
| 3 | BEGIN { |
| 4 | OFS = msg_fs ? msg_fs : "|" |
| 5 | Kfs = key_fs ? key_fs : ":" |
| 6 | } |
| 7 | |
| 8 | # Msg separator |
| 9 | /^OK/ {msg_count++; next} |
| 10 | |
| 11 | # Msg content |
| 12 | /^[a-zA-Z-]+: / { |
| 13 | key = $1 |
| 14 | val = $0 |
| 15 | sub(".*" key " *", "", val) |
| 16 | sub(":$", "", key) |
| 17 | key = tolower(key) |
| 18 | # Note that we expect a particular order of response messages (also |
| 19 | # reflected in the name of this script file): "status" THEN "currentsong" |
| 20 | if (msg_count == 1) {status[key] = val} |
| 21 | else if (msg_count == 2) {currentsong[key] = val} |
| 22 | else { |
| 23 | printf("Unexpected msg_count in mpd response: %d\n", msg_count) \ |
| 24 | > "/dev/stderr" |
| 25 | exit 1 |
| 26 | } |
| 27 | next |
| 28 | } |
| 29 | |
| 30 | END { |
| 31 | name = currentsong["name"] |
| 32 | title = currentsong["title"] |
| 33 | file = currentsong["file"] |
| 34 | |
| 35 | if (name) { |
| 36 | song = name |
| 37 | } else if (title) { |
| 38 | song = title |
| 39 | } else if (file) { |
| 40 | last = split(file, parts, "/") |
| 41 | song = parts[last] |
| 42 | } else { |
| 43 | song = "?" |
| 44 | } |
| 45 | |
| 46 | format_time(status["time"], time) |
| 47 | output["play_time_minimal_units"] = time["minimal_units"] |
| 48 | output["play_time_percentage"] = time["percentage"] |
| 49 | output["state"] = status["state"] |
| 50 | output["song"] = song |
| 51 | for (key in output) { |
| 52 | print(key, output[key]) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | function format_time(time_str, time_arr, \ |
| 57 | \ |
| 58 | time_str_parts, |
| 59 | seconds_current, |
| 60 | seconds_total, |
| 61 | hours, |
| 62 | secs_beyond_hours, |
| 63 | mins, |
| 64 | secs, |
| 65 | time_percentage \ |
| 66 | ) { |
| 67 | split(time_str, time_str_parts, ":") |
| 68 | seconds_current = time_str_parts[1] |
| 69 | seconds_total = time_str_parts[2] |
| 70 | |
| 71 | hours = int(seconds_current / 60 / 60); |
| 72 | secs_beyond_hours = seconds_current - (hours * 60 * 60); |
| 73 | mins = int(secs_beyond_hours / 60); |
| 74 | secs = secs_beyond_hours - (mins * 60); |
| 75 | |
| 76 | if (hours > 0) { |
| 77 | time_arr["minimal_units"] = sprintf("%d:%.2d:%.2d", hours, mins, secs) |
| 78 | } else { |
| 79 | time_arr["minimal_units"] = sprintf("%.2d:%.2d", mins, secs) |
| 80 | } |
| 81 | |
| 82 | if (seconds_total > 0) { |
| 83 | time_percentage = (seconds_current / seconds_total) * 100 |
| 84 | time_arr["percentage"] = sprintf("%d%%", time_percentage) |
| 85 | } else { |
| 86 | time_arr["percentage"] = "~" |
| 87 | } |
| 88 | } |