mpd_add_to_playlist.c (2751B)
1 #include <mpd/client.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 // #define DEBUG 6 #ifdef DEBUG 7 #define D(x) \ 8 do { \ 9 x; \ 10 } while (0) 11 #else 12 #define D(x) \ 13 do { \ 14 } while (0) 15 #endif 16 #define DEFAULT_HOST "localhost" 17 #define DEFAULT_PORT 6600 18 struct mpd_connection *conn() { 19 // Read host from environment variable, use default if not set 20 const char *host = getenv("MPD_HOST"); 21 if (host == NULL || strlen(host) == 0) { 22 host = DEFAULT_HOST; 23 } 24 D(printf("Using host: %s\n", host)); 25 26 // Read port from environment variable, use default if not set 27 unsigned port = DEFAULT_PORT; 28 const char *port_str = getenv("MPD_PORT"); 29 if (port_str != NULL && strlen(port_str) > 0) { 30 port = (unsigned)atoi(port_str); 31 } 32 D(printf("Using port: %u\n", port)); 33 34 D(printf("%s %s:%u\n", "Connecting to", host, port)); 35 36 struct mpd_connection *c = mpd_connection_new(host, port, 0); 37 if (c == NULL) { 38 fprintf(stderr, "Failed to create MPD connection object\n"); 39 return NULL; 40 } 41 42 if (mpd_connection_get_error(c) != MPD_ERROR_SUCCESS) { 43 fprintf(stderr, "Error connecting to MPD (%s:%u): %s\n", host, port, 44 mpd_connection_get_error_message(c)); 45 mpd_connection_free(c); 46 return NULL; 47 } 48 #ifdef PASS 49 const char *pass = PASS; 50 if (mpd_run_password(c, pass) == false) { 51 fprintf(stderr, "Bad password\n"); 52 mpd_connection_free(c); 53 return NULL; 54 } 55 #endif 56 D(printf("%s %s:%u\n", "Connected to", host, port)); 57 return c; 58 } 59 int main(int argc, char *argv[]) { 60 // Check for playlist name argument 61 if (argc < 2) { 62 printf("Usage: %s PLAYLIST_NAME\n", argv[0]); 63 return 1; 64 } 65 66 const char *playlist = argv[1]; 67 D(printf("Using playlist: %s\n", playlist)); 68 69 struct mpd_connection *c = conn(); 70 if (c == NULL) 71 return -1; 72 73 struct mpd_song *curr = mpd_run_current_song(c); 74 if (curr == NULL) { 75 printf("No song is currently playing\n"); 76 mpd_connection_free(c); 77 return -1; 78 } 79 80 const char *curr_uri = mpd_song_get_uri(curr); 81 D(printf("Currently playing: %s\n", curr_uri)); 82 83 if (mpd_run_playlist_add(c, playlist, curr_uri)) { 84 printf("%s %s %s %s\n", "Added", curr_uri, "to playlist", playlist); 85 } else { 86 printf("%s\n", "Some error"); 87 mpd_song_free(curr); 88 mpd_connection_free(c); 89 return -1; 90 } 91 // Free resources 92 mpd_song_free(curr); 93 mpd_connection_free(c); 94 95 return 0; 96 }