/
query_freedb.c
100 lines (85 loc) · 2.53 KB
/
query_freedb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <cddb/cddb.h>
cddb_conn_t *init_conn();
cddb_disc_t *init_disc();
void read_db(cddb_conn_t *conn, cddb_disc_t *disc);
int search_db(cddb_conn_t *conn, cddb_disc_t *disc, const char *str);
void lowercase(char *str);
int main(int argc, char *argv[]) {
/*initialize the connection to the freedb server */
cddb_conn_t *conn = NULL;
cddb_disc_t *disc;
cddb_track_t *track;
conn = init_conn();
/* set track info */
if (argc != 4) {
fprintf(stderr, "usage: cddb_query <discid> <category> <track number>\n");
return -1;
}
char *p;
unsigned long discid = strtoul(argv[1], &p, 16);
char *cat = argv[2];
lowercase(cat);
int tracknum = atoi(argv[3]);
/* initialize the disc */
disc = init_disc();
cddb_disc_set_discid(disc, discid);
cddb_disc_set_category_str(disc, cat);
/* query the database to populate the disc info */
read_db(conn, disc);
/* extract the track from the disc */
track = cddb_disc_get_track(disc, tracknum - 1);
/* format an output track info */
const char *title = cddb_track_get_title(track);
const char *artist = cddb_disc_get_artist(disc);
const char *album = cddb_disc_get_title(disc);
unsigned int date = cddb_disc_get_year(disc);
const char *label = "";
const char *genre = cddb_disc_get_genre(disc);
printf("%s\t%s\t%s\t%d\t%s\t%s\t", title, artist, album, date, label, genre);
return 0;
}
/* initialize connection to cddb server */
cddb_conn_t *init_conn() {
cddb_conn_t *conn;
if ((conn = cddb_new()) == NULL) {
fprintf(stderr, "out of memory, "
"unable to create connection structure");
}
/* HTTP settings */
cddb_http_enable(conn);
cddb_set_server_port(conn, 80);
cddb_set_server_name(conn, "freedb.org");
cddb_set_http_path_query(conn, "/~cddb/cddb.cgi");
cddb_set_http_path_submit(conn, "/~cddb/submit.cgi");
return conn;
}
/* initialize disc */
cddb_disc_t *init_disc() {
cddb_disc_t *disc;
if ((disc = cddb_disc_new()) == NULL) {
fprintf(stderr, "out of memory, unable to create disc");
exit(-1);
}
return disc;
}
/* read data from cddb database */
void read_db(cddb_conn_t *conn, cddb_disc_t *disc) {
int success = cddb_read(conn, disc);
if (!success) {
/* something went wrong, print error */
cddb_error_print(cddb_errno(conn));
exit(-1);
}
}
/* change all characters in a string to lowercase (for cddb_read call in main) */
void lowercase(char *str) {
for (int i = 0; str[i] != '\0'; i++) {
tolower(str[i]);
str[i] = tolower(str[i]);
}
}