mpd.c (1567B)
1 /* See LICENSE for license details. */ 2 #include <mpd/client.h> 3 #include <mpd/tag.h> 4 5 struct mpd_arg { 6 const char *host; 7 const char *sep; 8 const enum mpd_tag_type *tags; 9 size_t ntags; 10 }; 11 12 static struct mpd_connection *conn; 13 14 static int 15 open_conn(const char *host) 16 { 17 conn = mpd_connection_new(host, 0, 0); 18 if (!mpd_connection_get_error(conn) 19 && mpd_connection_set_keepalive(conn, true)) { 20 mpd_send_idle(conn); 21 return 0; 22 } 23 mpd_connection_free(conn); 24 conn = NULL; 25 return -1; 26 } 27 28 static int 29 check_conn(const char *host) 30 { 31 if (!mpd_connection_get_error(conn)) 32 return 0; 33 34 mpd_connection_free(conn); 35 return open_conn(host); 36 } 37 38 static size_t 39 mpd_tag(struct Block *b) 40 { 41 struct mpd_song *song = NULL; 42 struct mpd_status *status = NULL; 43 struct mpd_arg *ma = b->arg; 44 size_t i, len = 0; 45 46 if ((!conn && open_conn(ma->host) != 0) || check_conn(ma->host) != 0) 47 return 0; 48 49 mpd_run_noidle(conn); 50 51 if ((status = mpd_run_status(conn))) { 52 switch (mpd_status_get_state(status)) { 53 case MPD_STATE_PAUSE: 54 case MPD_STATE_PLAY: 55 song = mpd_run_current_song(conn); 56 for (i = 0; i < ma->ntags; i++) { 57 if (len != 0) 58 len += snprintf(buf + len, 59 sizeof(buf) - len, "%s", 60 ma->sep ? ma->sep : ""); 61 len += snprintf( 62 buf + len, sizeof(buf) - len, "%s", 63 mpd_song_get_tag(song, ma->tags[i], 0)); 64 } 65 mpd_song_free(song); 66 case MPD_STATE_STOP: 67 default: 68 break; 69 } 70 mpd_status_free(status); 71 } 72 73 mpd_send_idle(conn); 74 75 return len? snprintf(b->curstr, LEN(b->curstr), b->fmt, buf) : 0; 76 }