mpd_add_to_queue.c (3279B)
1 #include <mpd/client.h> 2 #include <stdbool.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <unistd.h> 7 8 // #define DEBUG 9 #ifdef DEBUG 10 #define D(x) \ 11 do { \ 12 x; \ 13 } while (0) 14 #else 15 #define D(x) \ 16 do { \ 17 } while (0) 18 #endif 19 20 #define DEFAULT_HOST "localhost" 21 #define DEFAULT_PORT 6600 22 23 struct mpd_connection *conn() { 24 const char *host = getenv("MPD_HOST"); 25 if (host == NULL || strlen(host) == 0) { 26 host = DEFAULT_HOST; 27 } 28 29 unsigned port = DEFAULT_PORT; 30 const char *port_str = getenv("MPD_PORT"); 31 if (port_str != NULL && strlen(port_str) > 0) { 32 port = (unsigned)atoi(port_str); 33 } 34 35 struct mpd_connection *c = mpd_connection_new(host, port, 0); 36 if (c == NULL) { 37 fprintf(stderr, "Failed to create MPD connection object\n"); 38 return NULL; 39 } 40 41 enum mpd_error err = mpd_connection_get_error(c); 42 if (err != 0) { 43 fprintf(stderr, "Error connecting to MPD (%s:%u): %s (code: %u)\n", host, 44 port, mpd_connection_get_error_message(c), err); 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, "MPD authentication failed: %s\n", 52 mpd_connection_get_error_message(c)); 53 mpd_connection_free(c); 54 return NULL; 55 } 56 #endif 57 return c; 58 } 59 60 int main(int argc, char *argv[]) { 61 FILE *input = stdin; 62 63 if (argc > 1) { 64 input = fopen(argv[1], "r"); 65 if (input == NULL) { 66 perror("Error opening file"); 67 return 1; 68 } 69 } else if (isatty(STDIN_FILENO)) { 70 fprintf(stderr, "Reading from stdin... (Press Ctrl+D to finish, or provide " 71 "a filename as argument)\n"); 72 } 73 74 struct mpd_connection *c = conn(); 75 if (c == NULL) { 76 if (input != stdin) 77 fclose(input); 78 return -1; 79 } 80 81 char *line = NULL; 82 size_t len = 0; 83 ssize_t read_bytes; 84 int added_count = 0; 85 int failed_count = 0; 86 87 while ((read_bytes = getline(&line, &len, input)) != -1) { 88 if (read_bytes > 0 && line[read_bytes - 1] == '\n') { 89 line[read_bytes - 1] = '\0'; 90 read_bytes--; 91 } 92 if (read_bytes > 0 && line[read_bytes - 1] == '\r') { 93 line[read_bytes - 1] = '\0'; 94 read_bytes--; 95 } 96 97 if (read_bytes == 0) 98 continue; 99 if (line[0] == '#') 100 continue; 101 102 if (!mpd_run_add(c, line)) { 103 fprintf(stderr, "Failed to add track: %s (Error: %s)\n", line, 104 mpd_connection_get_error_message(c)); 105 failed_count++; 106 if (!mpd_connection_clear_error(c)) 107 break; 108 } else { 109 printf("Added: %s\n", line); 110 added_count++; 111 } 112 } 113 114 printf("\nSummary: Added %d tracks, failed to add %d tracks.\n", added_count, 115 failed_count); 116 117 free(line); 118 if (input != stdin) 119 fclose(input); 120 mpd_connection_free(c); 121 122 return 0; 123 }