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