slstatus/components/mpd.c
2024-03-18 23:55:03 +01:00

80 lines
2.1 KiB
C

#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpd/client.h>
#include "../util.h"
/* add to config.mk :
# mpd
+ MPDLIB = -lmpdclient
+ MPDFLAG = -DMPD
- LIBS = -L/usr/lib -lc -L${X11LIB} -lX11
+ LIBS = -L/usr/lib -lc -L${X11LIB} -lX11 ${MPDLIB}
- CPPFLAGS = -DVERSION=\"${VERSION}\"
+ CPPFLAGS = ${MPDFLAG} -DVERSION=\"${VERSION}\"
*/
/* simple function to retrieve mpd status */
const char *
mpd_song() {
const int titlethres = 79;
int ret = -1;
struct mpd_song * song = NULL;
const char *title;
const char *artist;
char *uri;
struct mpd_connection * conn ;
if (!(conn = mpd_connection_new("localhost", 0, 30000)) ||
mpd_connection_get_error(conn)){
return NULL;
}
mpd_command_list_begin(conn, true);
mpd_send_status(conn);
mpd_send_current_song(conn);
mpd_command_list_end(conn);
struct mpd_status* theStatus = mpd_recv_status(conn);
if ((theStatus) && (mpd_status_get_state(theStatus) == MPD_STATE_PLAY)) {
mpd_response_next(conn);
song = mpd_recv_song(conn);
title = mpd_song_get_tag(song, MPD_TAG_TITLE, 0);
artist = mpd_song_get_tag(song, MPD_TAG_ARTIST, 0);
if (!title) {
uri = strdup(mpd_song_get_uri(song));
/* Don't apply basename() to URLs */
if (!strncmp(uri, "https://", strlen("https://"))) {
ret = esnprintf(buf, sizeof(buf), "%s", uri);
} else {
ret = esnprintf(buf, sizeof(buf), "%s", basename(uri));
}
free(uri);
} else if (!artist) {
ret = esnprintf(buf, sizeof(buf), "%s", title);
} else {
ret = esnprintf(buf, sizeof(buf), "%s - %s", artist, title);
}
/*
artist = smprintf("%s",mpd_song_get_tag(song, MPD_TAG_ARTIST, 0));
elapsed = mpd_status_get_elapsed_time(theStatus);
total = mpd_status_get_total_time(theStatus);
*/
mpd_song_free(song);
}
mpd_response_finish(conn);
mpd_connection_free(conn);
if (ret < 0) {
ret = esnprintf(buf, sizeof(buf), "▮▮");
} else if (ret >= titlethres && titlethres + 3 < sizeof(buf)) {
/* Crop overly long titles */
buf[titlethres] = buf[titlethres+1] = buf[titlethres+2] = '.';
buf[titlethres+3] = '\0';
}
return (ret < 0) ? NULL : buf;
}