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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
|
/* --------------------------------------------------------------------------
MusicBrainz -- The Internet music metadatabase
Copyright (C) 2000 Robert Kaye
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
$Id: musicbrainz.cpp,v 1.42 2001/12/10 21:41:27 robert Exp $
----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#ifdef WIN32
#include <winsock.h>
#include "config_win32.h"
#endif
#include "musicbrainz.h"
#include "http.h"
#include "errors.h"
#include "diskid.h"
extern "C"
{
#include "sha1.h"
#include "base64.h"
#include "bitcollider.h"
}
const char *scriptUrl = "/cgi-bin/mq.pl";
const char *localCDInfo = "@CDINFO@";
const char *localTOCInfo = "@LOCALCDINFO@";
const char *localAssociateCD = "@CDINFOASSOCIATECD@";
const char *defaultServer = "mm.musicbrainz.org";
const short defaultPort = 80;
const char *rdfUTF8Encoding = "<?xml version=\"1.0\"?>\n";
const char *rdfISOEncoding =
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n";
const char *rdfHeader =
"<rdf:RDF xmlns:rdf = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
" xmlns:dc = \"http://purl.org/dc/elements/1.1/\"\n"
" xmlns:mq = \"http://musicbrainz.org/mm/mq-1.0#\"\n"
" xmlns:mm = \"http://musicbrainz.org/mm/mm-2.0#\">\n";
const char *rdfFooter =
"</rdf:RDF>\n";
#define DB printf("%s:%d\n", __FILE__, __LINE__);
MusicBrainz::MusicBrainz(void)
{
m_rdf = NULL;
m_server = string(defaultServer);
m_serverPort = defaultPort;
m_proxy = "";
m_useUTF8 = true;
m_depth = 2;
m_debug = false;
}
MusicBrainz::~MusicBrainz(void)
{
delete m_rdf;
}
// Get the version of the library
void MusicBrainz::GetVersion(int &major, int &minor, int &rev)
{
sscanf(VERSION, "%d.%d.%d", &major, &minor, &rev);
}
// Set the URL and port of the musicbrainz server to use.
bool MusicBrainz::SetServer(const string &serverAddr, short serverPort)
{
m_server = serverAddr;
m_serverPort = serverPort;
return true;
}
// Set the HTTP proxy server address and port if needed.
bool MusicBrainz::SetProxy(const string &proxyAddr, short proxyPort)
{
m_proxy = proxyAddr;
m_proxyPort = proxyPort;
return true;
}
// Set the cdrom device used for cd lookups. In windows, this would
// be a drive specification.
bool MusicBrainz::SetDevice(const string &device)
{
m_device = device;
return true;
}
// Set the debug option -- if enabled debug output will be printed to stdout
void MusicBrainz::SetDebug(bool debug)
{
m_debug = debug;
}
// Start the authentication process. Contact the server and send the
// username to the server. The server will respond with authChallenge
// data and a sessionId. The authChallenge will need to get hashed into
// an authorization key, and that key and the session id will need to
// be sent to the server to get credit for a submission.
bool MusicBrainz::Authenticate(const string &userName, const string &password)
{
bool ret;
vector<string> args;
string authChallenge;
SHA_INFO context;
unsigned char digest[20];
char sessionKey[41];
m_sessionId = string("");
m_sessionKey = string("");
args.push_back(userName);
ret = Query(string(MBQ_Authenticate), &args);
if (!ret)
{
string error;
GetQueryError(error);
printf("Authenticate: query failed: %s\n", error.c_str());
return false;
}
m_sessionId = Data(MBE_AuthGetSessionId);
authChallenge = Data(MBE_AuthGetChallenge);
if (m_sessionId.length() == 0 || authChallenge.length() == 0)
{
m_sessionId = string("");
m_sessionKey = string("");
m_error = "The server did not return a session id an auth challenge."
"Make sure the username is valid.";
return false;
}
sha_init(&context);
sha_update(&context, (SHA_BYTE *)authChallenge.c_str(),
authChallenge.length());
sha_update(&context, (SHA_BYTE *)userName.c_str(),
userName.length());
sha_update(&context, (SHA_BYTE *)password.c_str(),
password.length());
sha_final((unsigned char *)&digest, &context);
for(int i = 0; i < 20; i++)
sprintf(sessionKey + (i * sizeof(char) * 2), "%02x", digest[i] & 0xFF);
m_sessionKey = string(sessionKey);
return true;
}
// Set the depth for the queries. The depth of a query determines the
// number of levels of information are returned from the server.
bool MusicBrainz::SetDepth(int depth)
{
m_depth = depth;
return true;
}
// Stoopid windows helper functions to init the winsock layer.
#ifdef WIN32
void MusicBrainz::WSAInit(void)
{
WSADATA sGawdIHateMicrosoft;
WSAStartup(0x0002, &sGawdIHateMicrosoft);
}
void MusicBrainz::WSAStop(void)
{
WSACleanup();
}
#endif
// This function generates the URL needed to access the web cd submission
// pages on MusicBrainz.
bool MusicBrainz::GetWebSubmitURL(string &url)
{
DiskId id;
string args;
Error ret;
ret = id.GetWebSubmitURLArgs(m_device, args);
if (ret != kError_NoErr)
return false;
url = string("http://") + string(m_server);
if (m_serverPort != defaultPort)
{
char port[10];
sprintf(port, ":%d", m_serverPort);
url += string(port);
}
url += string("/bare/cdlookup.html") + args;
return true;
}
// A helper function to glue the necessary RDF headers and footers to make
// a valid RDF query
void MusicBrainz::MakeRDFQuery(string &rdf)
{
rdf = (m_useUTF8 ? string(rdfUTF8Encoding) : string(rdfISOEncoding)) +
string(rdfHeader) +
rdf +
string(rdfFooter);
}
// The main Query function. This query builds a valid RDF query,
// sends it to the server using http and then creates an RDF parser
// to parse the returned RDF from the server.
bool MusicBrainz::Query(const string &rdfObject, vector<string> *args)
{
MBHttp http;
char port[20];
string rdf = rdfObject, url, value;
Error ret;
// Is the given query a placeholder to perform a local query?
// A cd lookup/associate function requires to have the diskid
// module to generate an RDF query based on the values read
// from the current CD.
if (rdf == string(localCDInfo) ||
rdf == string(localAssociateCD))
{
DiskId id;
// Generate the local query and then keep trucking
ret = id.GenerateDiskIdQueryRDF(m_device, rdf,
rdf == string(localAssociateCD));
if (IsError(ret))
{
id.GetLastError(m_error);
return false;
}
if (m_debug)
printf("%s\n", rdf.c_str());
}
// If the query is a local TOC query, the client just wants to
// know about the table of contents of the CD, not about the
// server lookup metadata. In that case, generate the proper
// RDF from the CD, and then use that as the result of the query
// so the user can query it to extract the TOC from the CD.
if (rdf == string(localTOCInfo))
{
DiskId id;
// Generate the TOC query
ret = id.GenerateDiskIdRDF(m_device, m_response);
if (IsError(ret))
{
id.GetLastError(m_error);
return false;
}
// And now take the query and parse it so the user can query it
MakeRDFQuery(m_response);
m_rdf = new RDFExtract(m_response, m_useUTF8);
if (m_rdf->HasError())
{
m_error = string("Internal error.");
return false;
}
m_rdf->GetSubjectFromObject(string(MBE_QuerySubject), m_baseURI);
m_currentURI = m_baseURI;
// Return, because we don't want to actually query the server
return true;
}
// Substitute the passed in literal strings into the placeholders
// in the query.
SubstituteArgs(rdf, args);
// If there is a proxy, set up the proxy url now
if (m_proxy.length() > 0)
{
sprintf(port, ":%d", m_proxyPort);
http.SetProxyURL(string("http://") + m_proxy + string(port));
}
// Is this a GET or POST query? GET queries start with an http
// and will specify the URL to retrieve. If a query does not
// start with an http, then its assumed to be a POST query.
if (strncmp(rdf.c_str(), "http://", 7) == 0)
{
string::size_type pos = 0;
pos = rdf.find("@URL@", pos);
if (pos != string::npos)
{
sprintf(port, ":%d", m_serverPort);
rdf.replace(pos, 5, m_server + string(port));
}
pos = rdf.find("@DEPTH@", pos);
if (pos != string::npos)
{
sprintf(port, "%d", m_depth);
rdf.replace(pos, 7, string(port));
}
url = rdf;
rdf = string("");
}
else
{
MakeRDFQuery(rdf);
sprintf(port, ":%d", m_serverPort);
url = string("http://") + m_server + string(port) + string(scriptUrl);
}
if (m_debug)
{
printf(" url: %s\n", url.c_str());
printf("query: %s\n\n", rdf.c_str());
}
// Now use the http module to get/post the request and to download
// the result.
ret = http.DownloadToString(url, rdf, m_response);
if (IsError(ret))
{
SetError(ret);
return false;
}
if (m_debug)
printf("result: %s\n\n", m_response.c_str());
// Parse the returned RDF
m_rdf = new RDFExtract(m_response, m_useUTF8);
if (m_rdf->HasError())
{
string err;
m_rdf->GetError(err);
m_error = string("The server sent an invalid response. (") +
err + string(")");
return false;
}
// Determine the top level node by reverse looking up the mq:result node
if (!m_rdf->GetSubjectFromObject(string(MBE_QuerySubject), m_baseURI))
{
m_error = string("Cannot parse the server response (cannot find "
"mq:Result top level URI)");
return false;
}
// Use the baseURI as the starting point in the RDF graph.
m_currentURI = m_baseURI;
// See if an error occured. If so, extract the error message and return
value = m_rdf->Extract(m_currentURI, string(MBE_GetError));
if (value.length() != 0)
{
m_error = value;
return false;
}
// Extract the status of the query
value = m_rdf->Extract(m_currentURI, string(MBE_GetStatus));
if (value.length() == 0)
{
m_error = string("Could not determine the result of the query");
return false;
}
// Return if its not OK or fuzzy. OK means that the query ran successfully
// and if the query was a CD match query and the match was fuzzy,
// the status will be Fuzzy.
if (value != string("OK") && value != string("Fuzzy"))
{
m_error = string("Unknown query status: ") + value;
return false;
}
// We're done -- bail. The user can now use Select/Extract to retrieve
// data from the RDF
return true;
}
// returns a error string from the last query
void MusicBrainz::GetQueryError(string &ErrorText)
{
ErrorText = m_error;
}
// A shortcut function to retrieve a string value from the RDF result.
const string &MusicBrainz::Data(const string &resultName, int Index)
{
if (!m_rdf)
{
m_error = string("The server returned no valid data");
return m_empty;
}
return m_rdf->Extract(m_currentURI, resultName, Index);
}
// A shortcut function to retrieve an integer value from the RDF result.
int MusicBrainz::DataInt(const string &resultName, int Index)
{
if (!m_rdf)
{
m_error = string("The server returned no valid data");
return -1;
}
return atoi(m_rdf->Extract(m_currentURI, resultName, Index).c_str());
}
// This function calls the RDF extract function to retrieve one node
// from the RDF graph. Please see the docs for more details.
bool MusicBrainz::GetResultData(const string &resultName, int Index,
string &data)
{
if (!m_rdf)
{
m_error = string("The server returned no valid data");
return false;
}
data = m_rdf->Extract(m_currentURI, resultName, Index);
if (data.length() > 0)
return true;
m_error = "No data was returned.";
return false;
}
// Check to see if a given RDF node exists. This function takes the
// same args as the Extract and Select functions
bool MusicBrainz::DoesResultExist(const string &resultName, int Index)
{
string data;
string query;
if (!m_rdf)
return false;
data = m_rdf->Extract(m_currentURI, resultName, Index);
return data.length() > 0;
}
// This is a shorthand version of the Select, which allows passing
// one ordinal. The default value for the ordinal is 0. See
// the function below and the docs for more details on this function.
bool MusicBrainz::Select(const string &query, int ordinal)
{
list<int> ordinalList;
if (m_rdf == NULL)
return false;
ordinalList.push_back(ordinal);
return Select(query, &ordinalList);
}
// The Select function selects a new currentURI. Please check the
// docs for details on this important function.
bool MusicBrainz::Select(const string &queryArg, list<int> *ordinalList)
{
string newURI, query = queryArg;
if (m_rdf == NULL)
return false;
if (query == string(MBS_Rewind))
{
m_currentURI = m_baseURI;
return true;
}
if (query == string(MBS_Back))
{
if (m_contextHistory.size() == 0)
return false;
m_currentURI = *(m_contextHistory.end() - 1);
m_contextHistory.erase(m_contextHistory.end(), m_contextHistory.end());
return true;
}
newURI = m_rdf->Extract(m_currentURI, query, ordinalList);
if (newURI.length() == 0)
return false;
m_contextHistory.push_back(m_currentURI);
m_currentURI = newURI;
return true;
}
// Return the RDF document that the server returned to us.
bool MusicBrainz::GetResultRDF(string &RDFObject)
{
RDFObject = m_response;
return true;
}
// This function allows an outside user to set and RDF object and
// then query it using the Extract/Select functions.
bool MusicBrainz::SetResultRDF(string &rdf)
{
if (m_rdf)
delete m_rdf;
m_rdf = new RDFExtract(rdf, m_useUTF8);
if (!m_rdf->HasError())
{
m_response = rdf;
return true;
}
return false;
}
// some Get???ID queries return complete URLs that can be used
// to retrieve the related content from the MB server. To get just
// the id from the URL, use this function.
void MusicBrainz::GetIDFromURL(const string &url, string &id)
{
string::size_type pos;
id = url;
pos = id.rfind("/", string::npos);
if (pos != string::npos)
pos++;
id.erase(0, pos);
}
// Escape the & < and > in the passed rdf string and replace with
// the proper XML entities
const string MusicBrainz::EscapeArg(const string &arg)
{
string text;
string::size_type pos;
text = arg;
// Replace all the &
pos = text.find("&", 0);
for(;;)
{
pos = text.find("&", pos);
if (pos != string::npos)
text.replace(pos, 1, string("&"));
else
break;
pos++;
}
// Replace all the <
pos = text.find("<", 0);
for(;;)
{
pos = text.find("<", pos);
if (pos != string::npos)
text.replace(pos, 1, string("<"));
else
break;
}
// Replace all the >
pos = text.find(">", 0);
for(;;)
{
pos = text.find(">", pos);
if (pos != string::npos)
text.replace(pos, 1, string(">"));
else
break;
}
return text;
}
// This function replaces the @1@, @2@ argument place holders with
// literal values passed in the args vector.
void MusicBrainz::SubstituteArgs(string &rdf, vector<string> *args)
{
vector<string>::iterator i;
string::size_type pos;
char replace[100];
int j = 1;
string arg;
if (args)
{
// Replace all occurances of @##@ with the arguments passed in the
// args list
for(i = args->begin(), j = 1; i != args->end(); i++, j++)
{
arg = EscapeArg(*i);
sprintf(replace, "@%d@", j);
pos = rdf.find(string(replace), 0);
if (pos != string::npos)
{
if (arg.length() == 0)
rdf.replace(pos, strlen(replace), string("__NULL__"));
else
rdf.replace(pos, strlen(replace), arg);
}
}
}
// If there are fewer args passed than are in the rdf, then
// replace the remaining tokens with a NULL specifier.
for(;; j++)
{
sprintf(replace, "@%d@", j);
pos = rdf.find(string(replace), 0);
if (pos != string::npos)
{
rdf.replace(pos, strlen(replace), "__NULL__");
}
else
break;
}
ReplaceIntArg(rdf, "@DEPTH@", m_depth);
ReplaceArg(rdf, "@SESSID@", m_sessionId);
ReplaceArg(rdf, "@SESSKEY@", m_sessionKey);
}
void MusicBrainz::ReplaceArg(string &rdf, const string &from, const string &to)
{
string::size_type pos;
for(;;)
{
pos = rdf.find(from, 0);
if (pos != string::npos)
{
rdf.replace(pos, from.length(), to);
}
else
break;
}
}
void MusicBrainz::ReplaceIntArg(string &rdf, const string &from, int to)
{
char replace[10];
string::size_type pos;
for(;;)
{
pos = rdf.find(from, 0);
if (pos != string::npos)
{
sprintf(replace, "%d", to);
rdf.replace(pos, from.length(), string(replace));
}
else
break;
}
}
// Convert the internal error code to an error string
void MusicBrainz::SetError(Error ret)
{
switch(ret)
{
case kError_CantFindHost:
m_error = string("Cannot find server: ") + m_server;
break;
case kError_ConnectFailed:
m_error = string("Cannot connect to server: ") + m_server;
break;
case kError_IOError:
m_error = string("Cannot send/receive to/from server.");
break;
case kError_InvalidURL:
m_error = string("Proxy or server URL is invalid.");
break;
case kError_WriteFile:
m_error = string("Cannot write to disk. Disk full?");
break;
case kError_HTTPFileNotFound:
m_error = string("Cannot find musicbrainz pages on server. Check "
"your server name and port settings.");
break;
case kError_UnknownServerError:
m_error = string("The server encountered an error processing this "
"query.");
break;
default:
char num[10];
sprintf(num, "%d", ret);
m_error = string("Internal error: ") + string(num);
break;
}
}
// Calculate a sha1 hash for a given file. This sha1 value will be used
// in the MusicBrainz data acceptance process.
bool MusicBrainz::CalculateSha1(const string &fileName, string &sha1)
{
FILE *fp;
unsigned char digest[20];
SHA_INFO sha_info;
char temp[3];
fp = fopen(fileName.c_str(), "rb");
if (fp == NULL)
return false;
sha_stream(digest, &sha_info, fp);
fclose(fp);
sha1 = string("");
for(int i = 0; i < 20; i++)
{
sprintf(temp, "%02X", digest[i] & 0xFF);
sha1 += string(temp);
}
return true;
}
// Calculate a Bitzi bitprint given a file. The
// bitprint will be used in the musicbrainz metadata acceptance
// process. The completed bitzi bitprints will be submitted to the
// Bitizi community metadatabase.
bool MusicBrainz::CalculateBitprint(const string &fileName, BitprintInfo *info)
{
Bitcollider *bc;
BitcolliderSubmission *sub;
bc = bitcollider_init(0);
if (!bc)
return false;
sub = create_submission(bc);
if (sub == NULL)
return false;
if (!analyze_file(sub, fileName.c_str(), false))
return false;
strncpy(info->filename, fileName.c_str(), 255);
strncpy(info->bitprint, get_attribute(sub, "bitprint"), MB_BITPRINTSIZE);
strncpy(info->first20,
get_attribute(sub, "tag.file.first20"), MB_FIRST20SIZE);
info->length = atoi(get_attribute(sub, "tag.file.length"));
if (get_attribute(sub, "tag.mp3.audio_sha1"))
{
strncpy(info->audioSha1,
get_attribute(sub, "tag.mp3.audio_sha1"), MB_SHA1SIZE);
info->duration = atoi(get_attribute(sub, "tag.mp3.duration"));
info->samplerate = atoi(get_attribute(sub, "tag.mp3.samplerate"));
info->bitrate = atoi(get_attribute(sub, "tag.mp3.bitrate"));
info->stereo = strcmp(get_attribute(sub, "tag.mp3.stereo"), "y") == 0;
if (get_attribute(sub, "tag.mp3.vbr"))
info->vbr = strcmp(get_attribute(sub, "tag.mp3.vbr"), "y") == 0;
else
info->vbr = 0;
}
delete_submission(sub);
bitcollider_shutdown(bc);
return true;
}
|