From 972aed7ef98fce3e6dd3576744b496a52cc54692 Mon Sep 17 00:00:00 2001 From: Andrzej Rybczak Date: Fri, 31 Oct 2008 17:44:43 +0100 Subject: [PATCH] initial commit --- AUTHORS | 1 + COPYING | 340 ++++++++ Makefile.am | 5 + autogen.sh | 163 ++++ configure.in | 37 + doc/Makefile.am | 3 + doc/scrobby.conf.example | 37 + src/Makefile.am | 11 + src/callback.cpp | 169 ++++ src/callback.h | 31 + src/configuration.cpp | 172 ++++ src/configuration.h | 48 ++ src/libmpdclient.c | 2025 ++++++++++++++++++++++++++++++++++++++++++++++ src/libmpdclient.h | 670 +++++++++++++++ src/misc.cpp | 143 ++++ src/misc.h | 55 ++ src/mpdpp.cpp | 185 +++++ src/mpdpp.h | 103 +++ src/scrobby.cpp | 467 +++++++++++ src/scrobby.h | 64 ++ 20 files changed, 4729 insertions(+) create mode 100644 AUTHORS create mode 100644 COPYING create mode 100644 Makefile.am create mode 100755 autogen.sh create mode 100644 configure.in create mode 100644 doc/Makefile.am create mode 100644 doc/scrobby.conf.example create mode 100644 src/Makefile.am create mode 100644 src/callback.cpp create mode 100644 src/callback.h create mode 100644 src/configuration.cpp create mode 100644 src/configuration.h create mode 100644 src/libmpdclient.c create mode 100644 src/libmpdclient.h create mode 100644 src/misc.cpp create mode 100644 src/misc.h create mode 100644 src/mpdpp.cpp create mode 100644 src/mpdpp.h create mode 100644 src/scrobby.cpp create mode 100644 src/scrobby.h diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..5f78f88 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Andrzej Rybczak diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..5b6e7c6 --- /dev/null +++ b/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..d030409 --- /dev/null +++ b/Makefile.am @@ -0,0 +1,5 @@ +# not a GNU package. You can remove this line, if +# have all needed files, that a GNU package needs +AUTOMAKE_OPTIONS = foreign 1.4 + +SUBDIRS = src doc diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..8c901ac --- /dev/null +++ b/autogen.sh @@ -0,0 +1,163 @@ +#!/bin/sh +# Run this to set up the build system: configure, makefiles, etc. +# (at one point this was based on the version in enlightenment's cvs) + +package="scrobby" + +olddir="`pwd`" +srcdir="`dirname $0`" +test -z "$srcdir" && srcdir=. +cd "$srcdir" +DIE= +AM_VERSIONGREP="sed -e s/.*[^0-9\.]\([0-9]\.[0-9]\).*/\1/" +AC_VERSIONGREP="sed -e s/.*[^0-9\.]\([0-9]\.[0-9][0-9]\).*/\1/" +VERSIONMKINT="sed -e s/[^0-9]//" +if test -n "$AM_FORCE_VERSION" +then + AM_VERSIONS="$AM_FORCE_VERSION" +else + AM_VERSIONS='1.6 1.7 1.8 1.9' +fi +if test -n "$AC_FORCE_VERSION" +then + AC_VERSIONS="$AC_FORCE_VERSION" +else + AC_VERSIONS='2.58 2.59' +fi + +versioned_bins () +{ + bin="$1" + needed_int=`echo $VERNEEDED | $VERSIONMKINT` + for i in $VERSIONS + do + i_int=`echo $i | $VERSIONMKINT` + if test $i_int -ge $needed_int + then + echo $bin-$i $bin$i $bin-$i_int $bin$i_int + fi + done + echo $bin +} + +for c in autoconf autoheader automake aclocal +do + uc=`echo $c | tr a-z A-Z` + eval "val=`echo '$'$uc`" + if test -n "$val" + then + echo "$uc=$val in environment, will not attempt to auto-detect" + continue + fi + + case "$c" in + autoconf|autoheader) + VERNEEDED=`fgrep AC_PREREQ configure.in | $AC_VERSIONGREP` + VERSIONS="$AC_VERSIONS" + pkg=autoconf + ;; + automake|aclocal) + VERNEEDED=`fgrep AUTOMAKE_OPTIONS Makefile.am | $AM_VERSIONGREP` + VERSIONS="$AM_VERSIONS" + pkg=automake + ;; + esac + printf "checking for $c ... " + for x in `versioned_bins $c`; do + ($x --version < /dev/null > /dev/null 2>&1) > /dev/null 2>&1 + if test $? -eq 0 + then + echo $x + eval $uc=$x + break + fi + done + eval "val=`echo '$'$uc`" + if test -z "$val" + then + if test $c = $pkg + then + DIE="$DIE $c=$VERNEEDED" + else + DIE="$DIE $c($pkg)=$VERNEEDED" + fi + fi +done + +if test -n "$LIBTOOLIZE" +then + echo "LIBTOOLIZE=$LIBTOOLIZE in environment," \ + "will not attempt to auto-detect" +else + printf "checking for libtoolize ... " + for x in libtoolize glibtoolize + do + ($x --version < /dev/null > /dev/null 2>&1) > /dev/null 2>&1 + if test $? -eq 0 + then + echo $x + LIBTOOLIZE=$x + break + fi + done +fi + +if test -z "$LIBTOOLIZE" +then + DIE="$DIE libtoolize(libtool)" +fi + +if test -n "$DIE" +then + echo "You must have the following installed to compile $package:" + for i in $DIE + do + printf ' ' + echo $i | sed -e 's/(/ (from /' -e 's/=\(.*\)/ (>= \1)/' + done + echo "Download the appropriate package(s) for your system," + echo "or get the source from one of the GNU ftp sites" + echo "listed in http://www.gnu.org/order/ftp.html" + exit 1 +fi + +echo "Generating configuration files for $package, please wait...." + +ACLOCAL_FLAGS="$ACLOCAL_FLAGS" + +# /usr/share/aclocal is most likely included by default, already... +ac_local_paths=' +/usr/local/share/aclocal +/sw/share/aclocal +/usr/pkg/share/aclocal +/opt/share/aclocal +/usr/gnu/share/aclocal +' + +for i in $ac_local_paths; do + if test -d "$i"; then + ACLOCAL_FLAGS="$ACLOCAL_FLAGS -I $i" + # we probably only want one of these... + break + fi +done + +echo " $ACLOCAL $ACLOCAL_FLAGS" +$ACLOCAL $ACLOCAL_FLAGS || exit 1 + +echo " $AUTOHEADER" +$AUTOHEADER || exit 1 + +echo " $LIBTOOLIZE --automake" +$LIBTOOLIZE --automake || exit 1 + +echo " $AUTOMAKE --add-missing $AUTOMAKE_FLAGS" +$AUTOMAKE --add-missing $AUTOMAKE_FLAGS || exit 1 + +echo " $AUTOCONF" +$AUTOCONF || exit 1 + +cd "$olddir" +if test x$NOCONFIGURE = x; then + "$srcdir"/configure "$@" || exit 1 +fi diff --git a/configure.in b/configure.in new file mode 100644 index 0000000..b05ff7c --- /dev/null +++ b/configure.in @@ -0,0 +1,37 @@ +AC_INIT(configure.in) + +AM_CONFIG_HEADER(config.h) +AM_INIT_AUTOMAKE(scrobby, 0.0.98) + +AC_PREREQ(2.59) + +AC_LANG_CPLUSPLUS +AC_PROG_CXX +AM_PROG_LIBTOOL + +dnl ======================== +dnl = checking for openssl = +dnl ======================== +PKG_CHECK_MODULES([libssl], libssl, , AC_MSG_ERROR([libssl library is required])) +AC_SUBST(libssl_CFLAGS) +AC_SUBST(libssl_LIBS) +CPPFLAGS="$CPPFLAGS $libssl_CFLAGS" +LDFLAGS="$LDFLAGS $libssl_LDFLAGS" +AC_CHECK_HEADERS([openssl/evp.h], , AC_MSG_ERROR([missing openssl/evp.h header])) + +dnl ================================= +dnl = checking for curl and pthread = +dnl ================================= +AC_CHECK_LIB(pthread, pthread_create, LDFLAGS="$LDFLAGS -pthread", AC_MSG_ERROR([pthread library is required])) +AC_CHECK_HEADERS([pthread.h], , AC_MSG_ERROR([missing pthread.h header])) +AC_PATH_PROG(CURL_CONFIG, curl-config) +if test "$CURL_CONFIG" != "" ; then + CPPFLAGS="$CPPFLAGS `$CURL_CONFIG --cflags`" + AC_CHECK_LIB(curl, curl_easy_init, LDFLAGS="$LDFLAGS `$CURL_CONFIG --libs`", AC_MSG_ERROR([curl library is required])) + AC_CHECK_HEADERS([curl/curl.h], , AC_MSG_ERROR([missing curl.h header])) +else + AC_MSG_ERROR([curl-config executable is missing]) +fi + +AC_CONFIG_FILES([Makefile doc/Makefile src/Makefile]) +AC_OUTPUT diff --git a/doc/Makefile.am b/doc/Makefile.am new file mode 100644 index 0000000..2092c82 --- /dev/null +++ b/doc/Makefile.am @@ -0,0 +1,3 @@ +docdir = $(prefix)/share/doc/$(PACKAGE) +doc_DATA = scrobby.conf.example +EXTRA_DIST = $(doc_DATA) diff --git a/doc/scrobby.conf.example b/doc/scrobby.conf.example new file mode 100644 index 0000000..c321fa8 --- /dev/null +++ b/doc/scrobby.conf.example @@ -0,0 +1,37 @@ +####################################### +## scrobby sample configuration file ## +## (copy it to /etc/scrobby.conf) ## +####################################### +# +## +## Note: you can specify a password +## in clear text or hashed with an +## md5 algorithm. +## +# +### files settings +# +#log_file = "/var/log/scrobby.log" +# +#pid_file = "/var/run/scrobby.pid" +# +#cache_file = "/var/cache/scrobby/scrobby.cache" +# +### mpd settings +# +#mpd_host = "localhost" +# +#mpd_port = "6600" +# +#mpd_password = "" +# +#mpd_timeout = "15" +# +### last.fm settings +# +#lastfm_user = "" +# +#lastfm_password = "" +# +#lastfm_md5_password = "" +# diff --git a/src/Makefile.am b/src/Makefile.am new file mode 100644 index 0000000..35ced94 --- /dev/null +++ b/src/Makefile.am @@ -0,0 +1,11 @@ +bin_PROGRAMS = scrobby +scrobby_SOURCES = callback.cpp configuration.cpp libmpdclient.c misc.cpp \ + mpdpp.cpp scrobby.cpp + +# set the include path found by configure +INCLUDES= $(all_includes) + +# the library search path. +scrobby_LDFLAGS = $(all_libraries) +noinst_HEADERS = callback.h configuration.h libmpdclient.h misc.h mpdpp.h \ + scrobby.h diff --git a/src/callback.cpp b/src/callback.cpp new file mode 100644 index 0000000..1904ed0 --- /dev/null +++ b/src/callback.cpp @@ -0,0 +1,169 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include + +#include "callback.h" +#include "misc.h" +#include "scrobby.h" + +using std::string; + +MPD::State old_state = MPD::psUnknown; +MPD::State current_state = MPD::psUnknown; + +extern HandshakeResult hr; +extern SubmissionCandidate sc; + +extern pthread_mutex_t curl; +extern pthread_mutex_t hr_lock; + +extern bool notify_about_now_playing; + +void ScrobbyErrorCallback(MPD::Connection *, int, string errormessage, void *) +{ + Log("MPD sent error message: " + errormessage); +} + +void ScrobbyStatusChanged(MPD::Connection *Mpd, MPD::StatusChanges changed, void *) +{ + if (changed.State) + { + old_state = current_state; + current_state = Mpd->GetState(); + if (old_state == MPD::psStop && current_state == MPD::psPlay) + changed.SongID = 1; + } + if (changed.ElapsedTime) + { + if (!Mpd->GetElapsedTime()) + changed.SongID = 1; + sc.noticed_playback++; + } + if (changed.SongID || (old_state == MPD::psPlay && current_state == MPD::psStop)) + { + if (sc.song) + SubmitSong(sc); + + // in this case allow entering only once + if (old_state == MPD::psPlay && current_state == MPD::psStop) + old_state = MPD::psUnknown; + + sc.Clear(); + if (Mpd->GetElapsedTime() < 5) // 5 seconds of playing for song to define this, should be enough + sc.started_time = time(NULL); + + if (current_state == MPD::psPlay || current_state == MPD::psPause) + { + sc.song = Mpd->CurrentSong(); + notify_about_now_playing = 1; + } + } + if (notify_about_now_playing) + { + if (sc.song && (!sc.song->artist || !sc.song->title)) + { + Log("Playing song with missing tags detected."); + } + else if (sc.song && sc.song->artist && sc.song->title) + { + if (hr.status == "OK" && !hr.nowplaying_url.empty()) + { + Log("Playing song detected, sending notification..."); + } + else + { + Log("Playing song detected, notification not sent due to problem with connection."); + goto NOTIFICATION_FAILED; + } + + string result, postdata; + CURLcode code; + + pthread_mutex_lock(&curl); + CURL *np_notification = curl_easy_init(); + + char *c_artist = curl_easy_escape(np_notification, sc.song->artist, 0); + char *c_title = curl_easy_escape(np_notification, sc.song->title, 0); + char *c_album = sc.song->album ? curl_easy_escape(np_notification, sc.song->album, 0) : NULL; + char *c_track = sc.song->track ? curl_easy_escape(np_notification, sc.song->track, 0) : NULL; + + postdata = "s="; + postdata += hr.session_id; + postdata += "&a="; + postdata += c_artist; + postdata += "&t="; + postdata += c_title; + postdata += "&b="; + if (c_album) + postdata += c_album; + postdata += "&l="; + postdata += IntoStr(sc.song->time); + postdata += "&n="; + if (c_track) + postdata += c_track; + postdata += "&m="; + + curl_free(c_artist); + curl_free(c_title); + curl_free(c_album); + curl_free(c_track); + + Log("URL: " + hr.nowplaying_url); + Log("Post data: " + postdata); + + curl_easy_setopt(np_notification, CURLOPT_URL, hr.nowplaying_url.c_str()); + curl_easy_setopt(np_notification, CURLOPT_POST, 1); + curl_easy_setopt(np_notification, CURLOPT_POSTFIELDS, postdata.c_str()); + curl_easy_setopt(np_notification, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(np_notification, CURLOPT_WRITEDATA, &result); + curl_easy_setopt(np_notification, CURLOPT_CONNECTTIMEOUT, 5); + code = curl_easy_perform(np_notification); + curl_easy_cleanup(np_notification); + pthread_mutex_unlock(&curl); + + ignore_newlines(result); + + if (code != CURLE_OK) + { + Log("Error while sending notification: " + string(curl_easy_strerror(code))); + } + else if (result == "OK") + { + Log("Notification about currently playing song sent."); + } + else + { + Log("Audioscrobbler returned status " + result); + } + } + if (0) + { + NOTIFICATION_FAILED: + + pthread_mutex_lock(&hr_lock); + hr.Clear(); // handshake probably failed if we are here, so reset it + Log("Handshake status reset"); + pthread_mutex_unlock(&hr_lock); + } + notify_about_now_playing = 0; + } +} + diff --git a/src/callback.h b/src/callback.h new file mode 100644 index 0000000..c863dd2 --- /dev/null +++ b/src/callback.h @@ -0,0 +1,31 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef _CALLBACK_H +#define _CALLBACK_H + +#include +#include "mpdpp.h" + +void ScrobbyErrorCallback(MPD::Connection *, int, std::string, void *); +void ScrobbyStatusChanged(MPD::Connection *, MPD::StatusChanges, void *); + +#endif + diff --git a/src/configuration.cpp b/src/configuration.cpp new file mode 100644 index 0000000..7000694 --- /dev/null +++ b/src/configuration.cpp @@ -0,0 +1,172 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include +#include + +#include "configuration.h" +#include "misc.h" + +using std::string; + +namespace +{ + std::string GetLineValue(const string &line, char a = '"', char b = '"') + { + int i = 0; + int begin = -1, end = -1; + for (string::const_iterator it = line.begin(); it != line.end(); i++, it++) + { + if (*it == a || *it == b) + { + if (begin < 0) + begin = i+1; + else + end = i; + } + } + if (begin >= 0 && end >= 0) + return line.substr(begin, end-begin); + else + return ""; + } +} + +bool CheckFiles(ScrobbyConfig &conf) +{ + std::ofstream f; + + f.open(conf.file_log.c_str(), std::ios_base::app); + if (!f.is_open()) + { + std::cerr << "Cannot create/open log file: " << conf.file_log << std::endl; + return false; + } + f.close(); + + f.open(conf.file_cache.c_str(), std::ios_base::app); + if (!f.is_open()) + { + std::cerr << "Cannot create/open cache file: " << conf.file_cache << std::endl; + return false; + } + f.close(); + + std::ifstream g(conf.file_pid.c_str()); + if (g.is_open()) + { + string pid; + getline(g, pid); + std::cerr << "scrobby is already running with PID " << pid << "!\n"; + return false; + } + f.open(conf.file_pid.c_str(), std::ios_base::app); + if (!f.is_open()) + { + std::cerr << "Cannot create/open pid file: " << conf.file_pid << std::endl; + return false; + } + f.close(); + + return true; +} + +void DefaultConfiguration(ScrobbyConfig &conf) +{ + conf.mpd_host = "localhost"; + conf.mpd_port = 6600; + conf.mpd_timeout = 15; + + conf.file_log = "/var/log/scrobby.log"; + conf.file_pid = "/var/run/scrobby.pid"; + conf.file_cache = "/var/cache/scrobby/scrobby.cache"; +} + +bool ReadConfiguration(ScrobbyConfig &conf, const string &file) +{ + string line, v; + std::ifstream f(file.c_str()); + + if (!f.is_open()) + return false; + + while (!f.eof()) + { + getline(f, line); + if (!line.empty() && line[0] != '#') + { + v = GetLineValue(line); + + if (line.find("mpd_host") != string::npos) + { + if (!line.empty()) + conf.mpd_host = v; + } + else if (line.find("mpd_password") != string::npos) + { + if (!v.empty()) + conf.mpd_password = v; + } + else if (line.find("mpd_port") != string::npos) + { + if (!v.empty()) + conf.mpd_port = StrToInt(v); + } + else if (line.find("mpd_timeout") != string::npos) + { + if (!v.empty()) + conf.mpd_timeout = StrToInt(v); + } + else if (line.find("log_file") != string::npos) + { + if (!v.empty()) + conf.file_log = v; + } + else if (line.find("pid_file") != string::npos) + { + if (!v.empty()) + conf.file_pid = v; + } + else if (line.find("cache_file") != string::npos) + { + if (!v.empty()) + conf.file_cache = v; + } + else if (line.find("lastfm_user") != string::npos) + { + if (!v.empty()) + conf.lastfm_user = v; + } + else if (line.find("lastfm_password") != string::npos) + { + if (!v.empty()) + conf.lastfm_password = v; + } + else if (line.find("lastfm_md5_password") != string::npos) + { + if (!v.empty()) + conf.lastfm_md5_password = v; + } + } + } + f.close(); + return true; +} + diff --git a/src/configuration.h b/src/configuration.h new file mode 100644 index 0000000..a065291 --- /dev/null +++ b/src/configuration.h @@ -0,0 +1,48 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef _CONFIGURATION_H +#define _CONFIGURATION_H + +#include + +struct ScrobbyConfig +{ + std::string mpd_host; + std::string mpd_password; + int mpd_port; + int mpd_timeout; + + std::string file_log; + std::string file_pid; + std::string file_cache; + + std::string lastfm_user; + std::string lastfm_password; + std::string lastfm_md5_password; +}; + +bool CheckFiles(ScrobbyConfig &); +void DefaultConfiguration(ScrobbyConfig &); +bool ReadConfiguration(ScrobbyConfig &, const std::string &file); + + +#endif + diff --git a/src/libmpdclient.c b/src/libmpdclient.c new file mode 100644 index 0000000..576f3dc --- /dev/null +++ b/src/libmpdclient.c @@ -0,0 +1,2025 @@ +/* libmpdclient + (c)2003-2006 by Warren Dukes (warren.dukes@gmail.com) + This project's homepage is: http://www.musicpd.org + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Music Player Daemon nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "libmpdclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WIN32 +# include +# include +#else +# include +# include +# include +# include +#endif + +/* (bits+1)/3 (plus the sign character) */ +#define INTLEN ((sizeof(int) * CHAR_BIT + 1) / 3 + 1) +#define LONGLONGLEN ((sizeof(long long) * CHAR_BIT + 1) / 3 + 1) + +#define COMMAND_LIST 1 +#define COMMAND_LIST_OK 2 + +#ifndef MPD_NO_GAI +# ifdef AI_ADDRCONFIG +# define MPD_HAVE_GAI +# endif +#endif + +#ifndef WIN32 +#include +#endif + +#ifndef MSG_DONTWAIT +# define MSG_DONTWAIT 0 +#endif + +#ifdef WIN32 +# define SELECT_ERRNO_IGNORE (errno == WSAEINTR || errno == WSAEINPROGRESS) +# define SENDRECV_ERRNO_IGNORE SELECT_ERRNO_IGNORE +#else +# define SELECT_ERRNO_IGNORE (errno == EINTR) +# define SENDRECV_ERRNO_IGNORE (errno == EINTR || errno == EAGAIN) +# define winsock_dll_error(c) 0 +# define closesocket(s) close(s) +# define WSACleanup() do { /* nothing */ } while (0) +#endif + +#ifdef WIN32 +static int winsock_dll_error(mpd_Connection *connection) +{ + WSADATA wsaData; + if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0 || + LOBYTE(wsaData.wVersion) != 2 || + HIBYTE(wsaData.wVersion) != 2 ) { + strcpy(connection->errorStr, + "Could not find usable WinSock DLL."); + connection->error = MPD_ERROR_SYSTEM; + return 1; + } + return 0; +} + +static int do_connect_fail(mpd_Connection *connection, + const struct sockaddr *serv_addr, int addrlen) +{ + int iMode = 1; /* 0 = blocking, else non-blocking */ + if (connect(connection->sock, serv_addr, addrlen) == SOCKET_ERROR) + return 1; + ioctlsocket(connection->sock, FIONBIO, (u_long FAR*) &iMode); + return 0; +} +#else /* !WIN32 (sane operating systems) */ +static int do_connect_fail(mpd_Connection *connection, + const struct sockaddr *serv_addr, int addrlen) +{ + int flags; + if (connect(connection->sock, serv_addr, addrlen) < 0) + return 1; + flags = fcntl(connection->sock, F_GETFL, 0); + fcntl(connection->sock, F_SETFL, flags | O_NONBLOCK); + return 0; +} +#endif /* !WIN32 */ + +#ifdef MPD_HAVE_GAI +static int mpd_connect(mpd_Connection * connection, const char * host, int port, + float timeout) +{ + int error; + char service[INTLEN+1]; + struct addrinfo hints; + struct addrinfo *res = NULL; + struct addrinfo *addrinfo = NULL; + + /** + * Setup hints + */ + hints.ai_flags = AI_ADDRCONFIG; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + hints.ai_addrlen = 0; + hints.ai_addr = NULL; + hints.ai_canonname = NULL; + hints.ai_next = NULL; + + snprintf(service, sizeof(service), "%i", port); + + error = getaddrinfo(host, service, &hints, &addrinfo); + + if (error) { + snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, + "host \"%s\" not found: %s", + host, gai_strerror(error)); + connection->error = MPD_ERROR_UNKHOST; + return -1; + } + + for (res = addrinfo; res; res = res->ai_next) { + /* create socket */ + if (connection->sock >= 0) + closesocket(connection->sock); + connection->sock = socket(res->ai_family, SOCK_STREAM, + res->ai_protocol); + if (connection->sock < 0) { + snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, + "problems creating socket: %s", + strerror(errno)); + connection->error = MPD_ERROR_SYSTEM; + freeaddrinfo(addrinfo); + return -1; + } + + mpd_setConnectionTimeout(connection, timeout); + + /* connect stuff */ + if (do_connect_fail(connection, + res->ai_addr, res->ai_addrlen)) { + /* try the next address */ + closesocket(connection->sock); + connection->sock = -1; + continue; + } + + break; + } + + freeaddrinfo(addrinfo); + + if (connection->sock < 0) { + snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, + "problems connecting to \"%s\" on port %i: %s", + host, port, strerror(errno)); + connection->error = MPD_ERROR_CONNPORT; + + return -1; + } + + return 0; +} +#else /* !MPD_HAVE_GAI */ +static int mpd_connect(mpd_Connection * connection, const char * host, int port, + float timeout) +{ + struct hostent * he; + struct sockaddr * dest; + int destlen; + struct sockaddr_in sin; + + if(!(he=gethostbyname(host))) { + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "host \"%s\" not found",host); + connection->error = MPD_ERROR_UNKHOST; + return -1; + } + + memset(&sin,0,sizeof(struct sockaddr_in)); + /*dest.sin_family = he->h_addrtype;*/ + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + + switch(he->h_addrtype) { + case AF_INET: + memcpy((char *)&sin.sin_addr.s_addr,(char *)he->h_addr, + he->h_length); + dest = (struct sockaddr *)&sin; + destlen = sizeof(struct sockaddr_in); + break; + default: + strcpy(connection->errorStr,"address type is not IPv4"); + connection->error = MPD_ERROR_SYSTEM; + return -1; + break; + } + + if (connection->sock >= 0) + closesocket(connection->sock); + if((connection->sock = socket(dest->sa_family,SOCK_STREAM,0))<0) { + strcpy(connection->errorStr,"problems creating socket"); + connection->error = MPD_ERROR_SYSTEM; + return -1; + } + + mpd_setConnectionTimeout(connection,timeout); + + /* connect stuff */ + if (do_connect_fail(connection, dest, destlen)) { + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "problems connecting to \"%s\" on port" + " %i",host,port); + connection->error = MPD_ERROR_CONNPORT; + return -1; + } + + return 0; +} +#endif /* !MPD_HAVE_GAI */ + +char * mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES] = +{ + "Artist", + "Album", + "Title", + "Track", + "Name", + "Genre", + "Date", + "Composer", + "Performer", + "Comment", + "Disc", + "Filename", + "Any" +}; + +static char * mpd_sanitizeArg(const char * arg) { + size_t i; + char * ret; + register const char *c; + register char *rc; + + /* instead of counting in that loop above, just + * use a bit more memory and half running time + */ + ret = malloc(strlen(arg) * 2 + 1); + + c = arg; + rc = ret; + for(i = strlen(arg)+1; i != 0; --i) { + if(*c=='"' || *c=='\\') + *rc++ = '\\'; + *(rc++) = *(c++); + } + + return ret; +} + +static mpd_ReturnElement * mpd_newReturnElement(const char * name, const char * value) +{ + mpd_ReturnElement * ret = malloc(sizeof(mpd_ReturnElement)); + + ret->name = strdup(name); + ret->value = strdup(value); + + return ret; +} + +static void mpd_freeReturnElement(mpd_ReturnElement * re) { + free(re->name); + free(re->value); + free(re); +} + +void mpd_setConnectionTimeout(mpd_Connection * connection, float timeout) { + connection->timeout.tv_sec = (int)timeout; + connection->timeout.tv_usec = (int)(timeout*1e6 - + connection->timeout.tv_sec*1000000 + + 0.5); +} + +static int mpd_parseWelcome(mpd_Connection * connection, const char * host, int port, + char * output) { + char * tmp; + char * test; + int i; + + if(strncmp(output,MPD_WELCOME_MESSAGE,strlen(MPD_WELCOME_MESSAGE))) { + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "mpd not running on port %i on host \"%s\"", + port,host); + connection->error = MPD_ERROR_NOTMPD; + return 1; + } + + tmp = &output[strlen(MPD_WELCOME_MESSAGE)]; + + for(i=0;i<3;i++) { + if(tmp) connection->version[i] = strtol(tmp,&test,10); + + if (!tmp || (test[0] != '.' && test[0] != '\0')) { + snprintf(connection->errorStr, + MPD_ERRORSTR_MAX_LENGTH, + "error parsing version number at " + "\"%s\"", + &output[strlen(MPD_WELCOME_MESSAGE)]); + connection->error = MPD_ERROR_NOTMPD; + return 1; + } + tmp = ++test; + } + + return 0; +} + +#ifndef WIN32 +static int mpd_connect_un(mpd_Connection * connection, + const char * host, float timeout) +{ + int error, flags; + size_t path_length; + struct sockaddr_un sun; + + path_length = strlen(host); + if (path_length >= sizeof(sun.sun_path)) { + strcpy(connection->errorStr, "unix socket path is too long"); + connection->error = MPD_ERROR_UNKHOST; + return -1; + } + + sun.sun_family = AF_UNIX; + memcpy(sun.sun_path, host, path_length + 1); + + connection->sock = socket(AF_UNIX, SOCK_STREAM, 0); + if (connection->sock < 0) { + strcpy(connection->errorStr, "problems creating socket"); + connection->error = MPD_ERROR_SYSTEM; + return -1; + } + + mpd_setConnectionTimeout(connection, timeout); + + flags = fcntl(connection->sock, F_GETFL, 0); + fcntl(connection->sock, F_SETFL, flags | O_NONBLOCK); + + error = connect(connection->sock, (struct sockaddr*)&sun, sizeof(sun)); + if (error < 0) { + /* try the next address family */ + close(connection->sock); + connection->sock = 0; + + snprintf(connection->errorStr,MPD_BUFFER_MAX_LENGTH, + "problems connecting to \"%s\": %s", + host, strerror(errno)); + connection->error = MPD_ERROR_CONNPORT; + return -1; + } + + return 0; +} +#endif /* WIN32 */ + +mpd_Connection * mpd_newConnection(const char * host, int port, float timeout) { + int err; + char * rt; + char * output = NULL; + mpd_Connection * connection = malloc(sizeof(mpd_Connection)); + struct timeval tv; + fd_set fds; + strcpy(connection->buffer,""); + connection->sock = -1; + connection->buflen = 0; + connection->bufstart = 0; + strcpy(connection->errorStr,""); + connection->error = 0; + connection->doneProcessing = 0; + connection->commandList = 0; + connection->listOks = 0; + connection->doneListOk = 0; + connection->returnElement = NULL; + connection->request = NULL; + + if (winsock_dll_error(connection)) + return connection; + +#ifndef WIN32 + if (host[0] == '/') + err = mpd_connect_un(connection, host, timeout); + else +#endif + err = mpd_connect(connection, host, port, timeout); + if (err < 0) + return connection; + + while(!(rt = strstr(connection->buffer,"\n"))) { + tv.tv_sec = connection->timeout.tv_sec; + tv.tv_usec = connection->timeout.tv_usec; + FD_ZERO(&fds); + FD_SET(connection->sock,&fds); + if((err = select(connection->sock+1,&fds,NULL,NULL,&tv)) == 1) { + int readed; + readed = recv(connection->sock, + &(connection->buffer[connection->buflen]), + MPD_BUFFER_MAX_LENGTH-connection->buflen,0); + if(readed<=0) { + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "problems getting a response from" + " \"%s\" on port %i : %s",host, + port, strerror(errno)); + connection->error = MPD_ERROR_NORESPONSE; + return connection; + } + connection->buflen+=readed; + connection->buffer[connection->buflen] = '\0'; + } + else if(err<0) { + if (SELECT_ERRNO_IGNORE) + continue; + snprintf(connection->errorStr, + MPD_ERRORSTR_MAX_LENGTH, + "problems connecting to \"%s\" on port" + " %i",host,port); + connection->error = MPD_ERROR_CONNPORT; + return connection; + } + else { + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "timeout in attempting to get a response from" + " \"%s\" on port %i",host,port); + connection->error = MPD_ERROR_NORESPONSE; + return connection; + } + } + + *rt = '\0'; + output = strdup(connection->buffer); + strcpy(connection->buffer,rt+1); + connection->buflen = strlen(connection->buffer); + + if(mpd_parseWelcome(connection,host,port,output) == 0) connection->doneProcessing = 1; + + free(output); + + return connection; +} + +void mpd_clearError(mpd_Connection * connection) { + connection->error = 0; + connection->errorStr[0] = '\0'; +} + +void mpd_closeConnection(mpd_Connection * connection) { + closesocket(connection->sock); + if(connection->returnElement) free(connection->returnElement); + if(connection->request) free(connection->request); + free(connection); + WSACleanup(); +} + +static void mpd_executeCommand(mpd_Connection * connection, char * command) { + int ret; + struct timeval tv; + fd_set fds; + char * commandPtr = command; + int commandLen = strlen(command); + + if(!connection->doneProcessing && !connection->commandList) { + strcpy(connection->errorStr,"not done processing current command"); + connection->error = 1; + return; + } + + mpd_clearError(connection); + + FD_ZERO(&fds); + FD_SET(connection->sock,&fds); + tv.tv_sec = connection->timeout.tv_sec; + tv.tv_usec = connection->timeout.tv_usec; + + while((ret = select(connection->sock+1,NULL,&fds,NULL,&tv)==1) || + (ret==-1 && SELECT_ERRNO_IGNORE)) { + ret = send(connection->sock,commandPtr,commandLen,MSG_DONTWAIT); + if(ret<=0) + { + if (SENDRECV_ERRNO_IGNORE) continue; + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "problems giving command \"%s\"",command); + connection->error = MPD_ERROR_SENDING; + return; + } + else { + commandPtr+=ret; + commandLen-=ret; + } + + if(commandLen<=0) break; + } + + if(commandLen>0) { + perror(""); + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "timeout sending command \"%s\"",command); + connection->error = MPD_ERROR_TIMEOUT; + return; + } + + if(!connection->commandList) connection->doneProcessing = 0; + else if(connection->commandList == COMMAND_LIST_OK) { + connection->listOks++; + } +} + +static void mpd_getNextReturnElement(mpd_Connection * connection) { + char * output = NULL; + char * rt = NULL; + char * name = NULL; + char * value = NULL; + fd_set fds; + struct timeval tv; + char * tok = NULL; + int readed; + char * bufferCheck = NULL; + int err; + int pos; + + if(connection->returnElement) mpd_freeReturnElement(connection->returnElement); + connection->returnElement = NULL; + + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) + { + strcpy(connection->errorStr,"already done processing current command"); + connection->error = 1; + return; + } + + bufferCheck = connection->buffer+connection->bufstart; + while(connection->bufstart>=connection->buflen || + !(rt = strchr(bufferCheck,'\n'))) { + if(connection->buflen>=MPD_BUFFER_MAX_LENGTH) { + memmove(connection->buffer, + connection->buffer+ + connection->bufstart, + connection->buflen- + connection->bufstart+1); + connection->buflen-=connection->bufstart; + connection->bufstart = 0; + } + if(connection->buflen>=MPD_BUFFER_MAX_LENGTH) { + strcpy(connection->errorStr,"buffer overrun"); + connection->error = MPD_ERROR_BUFFEROVERRUN; + connection->doneProcessing = 1; + connection->doneListOk = 0; + return; + } + bufferCheck = connection->buffer+connection->buflen; + tv.tv_sec = connection->timeout.tv_sec; + tv.tv_usec = connection->timeout.tv_usec; + FD_ZERO(&fds); + FD_SET(connection->sock,&fds); + if((err = select(connection->sock+1,&fds,NULL,NULL,&tv) == 1)) { + readed = recv(connection->sock, + connection->buffer+connection->buflen, + MPD_BUFFER_MAX_LENGTH-connection->buflen, + MSG_DONTWAIT); + if(readed<0 && SENDRECV_ERRNO_IGNORE) { + continue; + } + if(readed<=0) { + strcpy(connection->errorStr,"connection" + " closed"); + connection->error = MPD_ERROR_CONNCLOSED; + connection->doneProcessing = 1; + connection->doneListOk = 0; + return; + } + connection->buflen+=readed; + connection->buffer[connection->buflen] = '\0'; + } + else if(err<0 && SELECT_ERRNO_IGNORE) continue; + else { + strcpy(connection->errorStr,"connection timeout"); + connection->error = MPD_ERROR_TIMEOUT; + connection->doneProcessing = 1; + connection->doneListOk = 0; + return; + } + } + + *rt = '\0'; + output = connection->buffer+connection->bufstart; + connection->bufstart = rt - connection->buffer + 1; + + if(strcmp(output,"OK")==0) { + if(connection->listOks > 0) { + strcpy(connection->errorStr, "expected more list_OK's"); + connection->error = 1; + } + connection->listOks = 0; + connection->doneProcessing = 1; + connection->doneListOk = 0; + return; + } + + if(strcmp(output, "list_OK") == 0) { + if(!connection->listOks) { + strcpy(connection->errorStr, + "got an unexpected list_OK"); + connection->error = 1; + } + else { + connection->doneListOk = 1; + connection->listOks--; + } + return; + } + + if(strncmp(output,"ACK",strlen("ACK"))==0) { + char * test; + char * needle; + int val; + + strcpy(connection->errorStr, output); + connection->error = MPD_ERROR_ACK; + connection->errorCode = MPD_ACK_ERROR_UNK; + connection->errorAt = MPD_ERROR_AT_UNK; + connection->doneProcessing = 1; + connection->doneListOk = 0; + + needle = strchr(output, '['); + if(!needle) return; + val = strtol(needle+1, &test, 10); + if(*test != '@') return; + connection->errorCode = val; + val = strtol(test+1, &test, 10); + if(*test != ']') return; + connection->errorAt = val; + return; + } + + tok = strchr(output, ':'); + if (!tok) return; + pos = tok - output; + value = ++tok; + name = output; + name[pos] = '\0'; + + if(value[0]==' ') { + connection->returnElement = mpd_newReturnElement(name,&(value[1])); + } + else { + snprintf(connection->errorStr,MPD_ERRORSTR_MAX_LENGTH, + "error parsing: %s:%s",name,value); + connection->error = 1; + } +} + +void mpd_finishCommand(mpd_Connection * connection) { + while(!connection->doneProcessing) { + if(connection->doneListOk) connection->doneListOk = 0; + mpd_getNextReturnElement(connection); + } +} + +static void mpd_finishListOkCommand(mpd_Connection * connection) { + while(!connection->doneProcessing && connection->listOks && + !connection->doneListOk) + { + mpd_getNextReturnElement(connection); + } +} + +int mpd_nextListOkCommand(mpd_Connection * connection) { + mpd_finishListOkCommand(connection); + if(!connection->doneProcessing) connection->doneListOk = 0; + if(connection->listOks == 0 || connection->doneProcessing) return -1; + return 0; +} + +void mpd_sendStatusCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"status\n"); +} + +mpd_Status * mpd_getStatus(mpd_Connection * connection) { + mpd_Status * status; + + /*mpd_executeCommand(connection,"status\n"); + + if(connection->error) return NULL;*/ + + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) + { + return NULL; + } + + if(!connection->returnElement) mpd_getNextReturnElement(connection); + + status = malloc(sizeof(mpd_Status)); + status->volume = -1; + status->repeat = 0; + status->random = 0; + status->playlist = -1; + status->playlistLength = -1; + status->state = -1; + status->song = 0; + status->songid = -1; + status->elapsedTime = 0; + status->totalTime = 0; + status->bitRate = 0; + status->sampleRate = 0; + status->bits = 0; + status->channels = 0; + status->crossfade = -1; + status->error = NULL; + status->updatingDb = 0; + + if(connection->error) { + free(status); + return NULL; + } + while(connection->returnElement) { + mpd_ReturnElement * re = connection->returnElement; + if(strcmp(re->name,"volume")==0) { + status->volume = atoi(re->value); + } + else if(strcmp(re->name,"repeat")==0) { + status->repeat = atoi(re->value); + } + else if(strcmp(re->name,"random")==0) { + status->random = atoi(re->value); + } + else if(strcmp(re->name,"playlist")==0) { + status->playlist = strtol(re->value,NULL,10); + } + else if(strcmp(re->name,"playlistlength")==0) { + status->playlistLength = atoi(re->value); + } + else if(strcmp(re->name,"bitrate")==0) { + status->bitRate = atoi(re->value); + } + else if(strcmp(re->name,"state")==0) { + if(strcmp(re->value,"play")==0) { + status->state = MPD_STATUS_STATE_PLAY; + } + else if(strcmp(re->value,"stop")==0) { + status->state = MPD_STATUS_STATE_STOP; + } + else if(strcmp(re->value,"pause")==0) { + status->state = MPD_STATUS_STATE_PAUSE; + } + else { + status->state = MPD_STATUS_STATE_UNKNOWN; + } + } + else if(strcmp(re->name,"song")==0) { + status->song = atoi(re->value); + } + else if(strcmp(re->name,"songid")==0) { + status->songid = atoi(re->value); + } + else if(strcmp(re->name,"time")==0) { + char * tok = strchr(re->value,':'); + /* the second strchr below is a safety check */ + if (tok && (strchr(tok,0) > (tok+1))) { + /* atoi stops at the first non-[0-9] char: */ + status->elapsedTime = atoi(re->value); + status->totalTime = atoi(tok+1); + } + } + else if(strcmp(re->name,"error")==0) { + status->error = strdup(re->value); + } + else if(strcmp(re->name,"xfade")==0) { + status->crossfade = atoi(re->value); + } + else if(strcmp(re->name,"updating_db")==0) { + status->updatingDb = atoi(re->value); + } + else if(strcmp(re->name,"audio")==0) { + char * tok = strchr(re->value,':'); + if (tok && (strchr(tok,0) > (tok+1))) { + status->sampleRate = atoi(re->value); + status->bits = atoi(++tok); + tok = strchr(tok,':'); + if (tok && (strchr(tok,0) > (tok+1))) + status->channels = atoi(tok+1); + } + } + + mpd_getNextReturnElement(connection); + if(connection->error) { + free(status); + return NULL; + } + } + + if(connection->error) { + free(status); + return NULL; + } + else if(status->state<0) { + strcpy(connection->errorStr,"state not found"); + connection->error = 1; + free(status); + return NULL; + } + + return status; +} + +void mpd_freeStatus(mpd_Status * status) { + if(status->error) free(status->error); + free(status); +} + +void mpd_sendStatsCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"stats\n"); +} + +mpd_Stats * mpd_getStats(mpd_Connection * connection) { + mpd_Stats * stats; + + /*mpd_executeCommand(connection,"stats\n"); + + if(connection->error) return NULL;*/ + + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) + { + return NULL; + } + + if(!connection->returnElement) mpd_getNextReturnElement(connection); + + stats = malloc(sizeof(mpd_Stats)); + stats->numberOfArtists = 0; + stats->numberOfAlbums = 0; + stats->numberOfSongs = 0; + stats->uptime = 0; + stats->dbUpdateTime = 0; + stats->playTime = 0; + stats->dbPlayTime = 0; + + if(connection->error) { + free(stats); + return NULL; + } + while(connection->returnElement) { + mpd_ReturnElement * re = connection->returnElement; + if(strcmp(re->name,"artists")==0) { + stats->numberOfArtists = atoi(re->value); + } + else if(strcmp(re->name,"albums")==0) { + stats->numberOfAlbums = atoi(re->value); + } + else if(strcmp(re->name,"songs")==0) { + stats->numberOfSongs = atoi(re->value); + } + else if(strcmp(re->name,"uptime")==0) { + stats->uptime = strtol(re->value,NULL,10); + } + else if(strcmp(re->name,"db_update")==0) { + stats->dbUpdateTime = strtol(re->value,NULL,10); + } + else if(strcmp(re->name,"playtime")==0) { + stats->playTime = strtol(re->value,NULL,10); + } + else if(strcmp(re->name,"db_playtime")==0) { + stats->dbPlayTime = strtol(re->value,NULL,10); + } + + mpd_getNextReturnElement(connection); + if(connection->error) { + free(stats); + return NULL; + } + } + + if(connection->error) { + free(stats); + return NULL; + } + + return stats; +} + +void mpd_freeStats(mpd_Stats * stats) { + free(stats); +} + +mpd_SearchStats * mpd_getSearchStats(mpd_Connection * connection) +{ + mpd_SearchStats * stats; + mpd_ReturnElement * re; + + if (connection->doneProcessing || + (connection->listOks && connection->doneListOk)) { + return NULL; + } + + if (!connection->returnElement) mpd_getNextReturnElement(connection); + + if (connection->error) + return NULL; + + stats = malloc(sizeof(mpd_SearchStats)); + stats->numberOfSongs = 0; + stats->playTime = 0; + + while (connection->returnElement) { + re = connection->returnElement; + + if (strcmp(re->name, "songs") == 0) { + stats->numberOfSongs = atoi(re->value); + } else if (strcmp(re->name, "playtime") == 0) { + stats->playTime = strtol(re->value, NULL, 10); + } + + mpd_getNextReturnElement(connection); + if (connection->error) { + free(stats); + return NULL; + } + } + + if (connection->error) { + free(stats); + return NULL; + } + + return stats; +} + +void mpd_freeSearchStats(mpd_SearchStats * stats) +{ + free(stats); +} + +static void mpd_initSong(mpd_Song * song) { + song->file = NULL; + song->artist = NULL; + song->album = NULL; + song->track = NULL; + song->title = NULL; + song->name = NULL; + song->date = NULL; + /* added by Qball */ + song->genre = NULL; + song->composer = NULL; + song->performer = NULL; + song->disc = NULL; + song->comment = NULL; + + song->time = MPD_SONG_NO_TIME; + song->pos = MPD_SONG_NO_NUM; + song->id = MPD_SONG_NO_ID; +} + +static void mpd_finishSong(mpd_Song * song) { + if(song->file) free(song->file); + if(song->artist) free(song->artist); + if(song->album) free(song->album); + if(song->title) free(song->title); + if(song->track) free(song->track); + if(song->name) free(song->name); + if(song->date) free(song->date); + if(song->genre) free(song->genre); + if(song->composer) free(song->composer); + if(song->performer) free(song->performer); + if(song->disc) free(song->disc); + if(song->comment) free(song->comment); +} + +mpd_Song * mpd_newSong(void) { + mpd_Song * ret = malloc(sizeof(mpd_Song)); + + mpd_initSong(ret); + + return ret; +} + +void mpd_freeSong(mpd_Song * song) { + if (song) + mpd_finishSong(song); + free(song); +} + +mpd_Song * mpd_songDup(mpd_Song * song) { + mpd_Song * ret = mpd_newSong(); + + if(song->file) ret->file = strdup(song->file); + if(song->artist) ret->artist = strdup(song->artist); + if(song->album) ret->album = strdup(song->album); + if(song->title) ret->title = strdup(song->title); + if(song->track) ret->track = strdup(song->track); + if(song->name) ret->name = strdup(song->name); + if(song->date) ret->date = strdup(song->date); + if(song->genre) ret->genre= strdup(song->genre); + if(song->composer) ret->composer= strdup(song->composer); + if(song->performer) ret->performer = strdup(song->performer); + if(song->disc) ret->disc = strdup(song->disc); + if(song->comment) ret->comment = strdup(song->comment); + ret->time = song->time; + ret->pos = song->pos; + ret->id = song->id; + + return ret; +} + +static void mpd_initDirectory(mpd_Directory * directory) { + directory->path = NULL; +} + +static void mpd_finishDirectory(mpd_Directory * directory) { + if(directory->path) free(directory->path); +} + +mpd_Directory * mpd_newDirectory(void) { + mpd_Directory * directory = malloc(sizeof(mpd_Directory));; + + mpd_initDirectory(directory); + + return directory; +} + +void mpd_freeDirectory(mpd_Directory * directory) { + mpd_finishDirectory(directory); + + free(directory); +} + +mpd_Directory * mpd_directoryDup(mpd_Directory * directory) { + mpd_Directory * ret = mpd_newDirectory(); + + if(directory->path) ret->path = strdup(directory->path); + + return ret; +} + +static void mpd_initPlaylistFile(mpd_PlaylistFile * playlist) { + playlist->path = NULL; +} + +static void mpd_finishPlaylistFile(mpd_PlaylistFile * playlist) { + if(playlist->path) free(playlist->path); +} + +mpd_PlaylistFile * mpd_newPlaylistFile(void) { + mpd_PlaylistFile * playlist = malloc(sizeof(mpd_PlaylistFile)); + + mpd_initPlaylistFile(playlist); + + return playlist; +} + +void mpd_freePlaylistFile(mpd_PlaylistFile * playlist) { + mpd_finishPlaylistFile(playlist); + free(playlist); +} + +mpd_PlaylistFile * mpd_playlistFileDup(mpd_PlaylistFile * playlist) { + mpd_PlaylistFile * ret = mpd_newPlaylistFile(); + + if(playlist->path) ret->path = strdup(playlist->path); + + return ret; +} + +static void mpd_initInfoEntity(mpd_InfoEntity * entity) { + entity->info.directory = NULL; +} + +static void mpd_finishInfoEntity(mpd_InfoEntity * entity) { + if(entity->info.directory) { + if(entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) { + mpd_freeDirectory(entity->info.directory); + } + else if(entity->type == MPD_INFO_ENTITY_TYPE_SONG) { + mpd_freeSong(entity->info.song); + } + else if(entity->type == MPD_INFO_ENTITY_TYPE_PLAYLISTFILE) { + mpd_freePlaylistFile(entity->info.playlistFile); + } + } +} + +mpd_InfoEntity * mpd_newInfoEntity(void) { + mpd_InfoEntity * entity = malloc(sizeof(mpd_InfoEntity)); + + mpd_initInfoEntity(entity); + + return entity; +} + +void mpd_freeInfoEntity(mpd_InfoEntity * entity) { + mpd_finishInfoEntity(entity); + free(entity); +} + +static void mpd_sendInfoCommand(mpd_Connection * connection, char * command) { + mpd_executeCommand(connection,command); +} + +mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection) { + mpd_InfoEntity * entity = NULL; + + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) + { + return NULL; + } + + if(!connection->returnElement) mpd_getNextReturnElement(connection); + + if(connection->returnElement) { + if(strcmp(connection->returnElement->name,"file")==0) { + entity = mpd_newInfoEntity(); + entity->type = MPD_INFO_ENTITY_TYPE_SONG; + entity->info.song = mpd_newSong(); + entity->info.song->file = + strdup(connection->returnElement->value); + } + else if(strcmp(connection->returnElement->name, + "directory")==0) { + entity = mpd_newInfoEntity(); + entity->type = MPD_INFO_ENTITY_TYPE_DIRECTORY; + entity->info.directory = mpd_newDirectory(); + entity->info.directory->path = + strdup(connection->returnElement->value); + } + else if(strcmp(connection->returnElement->name,"playlist")==0) { + entity = mpd_newInfoEntity(); + entity->type = MPD_INFO_ENTITY_TYPE_PLAYLISTFILE; + entity->info.playlistFile = mpd_newPlaylistFile(); + entity->info.playlistFile->path = + strdup(connection->returnElement->value); + } + else if(strcmp(connection->returnElement->name, "cpos") == 0){ + entity = mpd_newInfoEntity(); + entity->type = MPD_INFO_ENTITY_TYPE_SONG; + entity->info.song = mpd_newSong(); + entity->info.song->pos = atoi(connection->returnElement->value); + } + else { + connection->error = 1; + strcpy(connection->errorStr,"problem parsing song info"); + return NULL; + } + } + else return NULL; + + mpd_getNextReturnElement(connection); + while(connection->returnElement) { + mpd_ReturnElement * re = connection->returnElement; + + if(strcmp(re->name,"file")==0) return entity; + else if(strcmp(re->name,"directory")==0) return entity; + else if(strcmp(re->name,"playlist")==0) return entity; + else if(strcmp(re->name,"cpos")==0) return entity; + + if(entity->type == MPD_INFO_ENTITY_TYPE_SONG && + strlen(re->value)) { + if(!entity->info.song->artist && + strcmp(re->name,"Artist")==0) { + entity->info.song->artist = strdup(re->value); + } + else if(!entity->info.song->album && + strcmp(re->name,"Album")==0) { + entity->info.song->album = strdup(re->value); + } + else if(!entity->info.song->title && + strcmp(re->name,"Title")==0) { + entity->info.song->title = strdup(re->value); + } + else if(!entity->info.song->track && + strcmp(re->name,"Track")==0) { + entity->info.song->track = strdup(re->value); + } + else if(!entity->info.song->name && + strcmp(re->name,"Name")==0) { + entity->info.song->name = strdup(re->value); + } + else if(entity->info.song->time==MPD_SONG_NO_TIME && + strcmp(re->name,"Time")==0) { + entity->info.song->time = atoi(re->value); + } + else if(entity->info.song->pos==MPD_SONG_NO_NUM && + strcmp(re->name,"Pos")==0) { + entity->info.song->pos = atoi(re->value); + } + else if(entity->info.song->id==MPD_SONG_NO_ID && + strcmp(re->name,"Id")==0) { + entity->info.song->id = atoi(re->value); + } + else if(!entity->info.song->date && + strcmp(re->name, "Date") == 0) { + entity->info.song->date = strdup(re->value); + } + else if(!entity->info.song->genre && + strcmp(re->name, "Genre") == 0) { + entity->info.song->genre = strdup(re->value); + } + else if(!entity->info.song->composer && + strcmp(re->name, "Composer") == 0) { + entity->info.song->composer = strdup(re->value); + } + else if(!entity->info.song->performer && + strcmp(re->name, "Performer") == 0) { + entity->info.song->performer = strdup(re->value); + } + else if(!entity->info.song->disc && + strcmp(re->name, "Disc") == 0) { + entity->info.song->disc = strdup(re->value); + } + else if(!entity->info.song->comment && + strcmp(re->name, "Comment") == 0) { + entity->info.song->comment = strdup(re->value); + } + } + else if(entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) { + } + else if(entity->type == MPD_INFO_ENTITY_TYPE_PLAYLISTFILE) { + } + + mpd_getNextReturnElement(connection); + } + + return entity; +} + +static char * mpd_getNextReturnElementNamed(mpd_Connection * connection, + const char * name) +{ + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) + { + return NULL; + } + + mpd_getNextReturnElement(connection); + while(connection->returnElement) { + mpd_ReturnElement * re = connection->returnElement; + + if(strcmp(re->name,name)==0) return strdup(re->value); + mpd_getNextReturnElement(connection); + } + + return NULL; +} + +char *mpd_getNextTag(mpd_Connection *connection, int type) +{ + if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES || + type == MPD_TAG_ITEM_ANY) + return NULL; + if (type == MPD_TAG_ITEM_FILENAME) + return mpd_getNextReturnElementNamed(connection, "file"); + return mpd_getNextReturnElementNamed(connection, mpdTagItemKeys[type]); +} + +char * mpd_getNextArtist(mpd_Connection * connection) { + return mpd_getNextReturnElementNamed(connection,"Artist"); +} + +char * mpd_getNextAlbum(mpd_Connection * connection) { + return mpd_getNextReturnElementNamed(connection,"Album"); +} + +void mpd_sendPlaylistInfoCommand(mpd_Connection * connection, int songPos) { + int len = strlen("playlistinfo")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "playlistinfo \"%i\"\n", songPos); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendPlaylistIdCommand(mpd_Connection * connection, int id) { + int len = strlen("playlistid")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "playlistid \"%i\"\n", id); + mpd_sendInfoCommand(connection, string); + free(string); +} + +void mpd_sendPlChangesCommand(mpd_Connection * connection, long long playlist) { + int len = strlen("plchanges")+2+LONGLONGLEN+3; + char *string = malloc(len); + snprintf(string, len, "plchanges \"%lld\"\n", playlist); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendPlChangesPosIdCommand(mpd_Connection * connection, long long playlist) { + int len = strlen("plchangesposid")+2+LONGLONGLEN+3; + char *string = malloc(len); + snprintf(string, len, "plchangesposid \"%lld\"\n", playlist); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendListallCommand(mpd_Connection * connection, const char * dir) { + char * sDir = mpd_sanitizeArg(dir); + int len = strlen("listall")+2+strlen(sDir)+3; + char *string = malloc(len); + snprintf(string, len, "listall \"%s\"\n", sDir); + mpd_sendInfoCommand(connection,string); + free(string); + free(sDir); +} + +void mpd_sendListallInfoCommand(mpd_Connection * connection, const char * dir) { + char * sDir = mpd_sanitizeArg(dir); + int len = strlen("listallinfo")+2+strlen(sDir)+3; + char *string = malloc(len); + snprintf(string, len, "listallinfo \"%s\"\n", sDir); + mpd_sendInfoCommand(connection,string); + free(string); + free(sDir); +} + +void mpd_sendLsInfoCommand(mpd_Connection * connection, const char * dir) { + char * sDir = mpd_sanitizeArg(dir); + int len = strlen("lsinfo")+2+strlen(sDir)+3; + char *string = malloc(len); + snprintf(string, len, "lsinfo \"%s\"\n", sDir); + mpd_sendInfoCommand(connection,string); + free(string); + free(sDir); +} + +void mpd_sendCurrentSongCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"currentsong\n"); +} + +void mpd_sendSearchCommand(mpd_Connection * connection, int table, + const char * str) +{ + mpd_startSearch(connection, 0); + mpd_addConstraintSearch(connection, table, str); + mpd_commitSearch(connection); +} + +void mpd_sendFindCommand(mpd_Connection * connection, int table, + const char * str) +{ + mpd_startSearch(connection, 1); + mpd_addConstraintSearch(connection, table, str); + mpd_commitSearch(connection); +} + +void mpd_sendListCommand(mpd_Connection * connection, int table, + const char * arg1) +{ + char st[10]; + int len; + char *string; + if(table == MPD_TABLE_ARTIST) strcpy(st,"artist"); + else if(table == MPD_TABLE_ALBUM) strcpy(st,"album"); + else { + connection->error = 1; + strcpy(connection->errorStr,"unknown table for list"); + return; + } + if(arg1) { + char * sanitArg1 = mpd_sanitizeArg(arg1); + len = strlen("list")+1+strlen(sanitArg1)+2+strlen(st)+3; + string = malloc(len); + snprintf(string, len, "list %s \"%s\"\n", st, sanitArg1); + free(sanitArg1); + } + else { + len = strlen("list")+1+strlen(st)+2; + string = malloc(len); + snprintf(string, len, "list %s\n", st); + } + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendAddCommand(mpd_Connection * connection, const char * file) { + char * sFile = mpd_sanitizeArg(file); + int len = strlen("add")+2+strlen(sFile)+3; + char *string = malloc(len); + snprintf(string, len, "add \"%s\"\n", sFile); + mpd_executeCommand(connection,string); + free(string); + free(sFile); +} + +int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file) +{ + int retval = -1; + char *sFile = mpd_sanitizeArg(file); + int len = strlen("addid")+2+strlen(sFile)+3; + char *string = malloc(len); + + snprintf(string, len, "addid \"%s\"\n", sFile); + mpd_sendInfoCommand(connection, string); + free(string); + free(sFile); + + string = mpd_getNextReturnElementNamed(connection, "Id"); + if (string) { + retval = atoi(string); + free(string); + } + + return retval; +} + +void mpd_sendDeleteCommand(mpd_Connection * connection, int songPos) { + int len = strlen("delete")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "delete \"%i\"\n", songPos); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendDeleteIdCommand(mpd_Connection * connection, int id) { + int len = strlen("deleteid")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "deleteid \"%i\"\n", id); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendSaveCommand(mpd_Connection * connection, const char * name) { + char * sName = mpd_sanitizeArg(name); + int len = strlen("save")+2+strlen(sName)+3; + char *string = malloc(len); + snprintf(string, len, "save \"%s\"\n", sName); + mpd_executeCommand(connection,string); + free(string); + free(sName); +} + +void mpd_sendLoadCommand(mpd_Connection * connection, const char * name) { + char * sName = mpd_sanitizeArg(name); + int len = strlen("load")+2+strlen(sName)+3; + char *string = malloc(len); + snprintf(string, len, "load \"%s\"\n", sName); + mpd_executeCommand(connection,string); + free(string); + free(sName); +} + +void mpd_sendRmCommand(mpd_Connection * connection, const char * name) { + char * sName = mpd_sanitizeArg(name); + int len = strlen("rm")+2+strlen(sName)+3; + char *string = malloc(len); + snprintf(string, len, "rm \"%s\"\n", sName); + mpd_executeCommand(connection,string); + free(string); + free(sName); +} + +void mpd_sendRenameCommand(mpd_Connection *connection, const char *from, + const char *to) +{ + char *sFrom = mpd_sanitizeArg(from); + char *sTo = mpd_sanitizeArg(to); + int len = strlen("rename")+2+strlen(sFrom)+3+strlen(sTo)+3; + char *string = malloc(len); + snprintf(string, len, "rename \"%s\" \"%s\"\n", sFrom, sTo); + mpd_executeCommand(connection, string); + free(string); + free(sFrom); + free(sTo); +} + +void mpd_sendShuffleCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"shuffle\n"); +} + +void mpd_sendClearCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"clear\n"); +} + +void mpd_sendPlayCommand(mpd_Connection * connection, int songPos) { + int len = strlen("play")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "play \"%i\"\n", songPos); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendPlayIdCommand(mpd_Connection * connection, int id) { + int len = strlen("playid")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "playid \"%i\"\n", id); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendStopCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"stop\n"); +} + +void mpd_sendPauseCommand(mpd_Connection * connection, int pauseMode) { + int len = strlen("pause")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "pause \"%i\"\n", pauseMode); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendNextCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"next\n"); +} + +void mpd_sendMoveCommand(mpd_Connection * connection, int from, int to) { + int len = strlen("move")+2+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "move \"%i\" \"%i\"\n", from, to); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendMoveIdCommand(mpd_Connection * connection, int id, int to) { + int len = strlen("moveid")+2+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "moveid \"%i\" \"%i\"\n", id, to); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendSwapCommand(mpd_Connection * connection, int song1, int song2) { + int len = strlen("swap")+2+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "swap \"%i\" \"%i\"\n", song1, song2); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendSwapIdCommand(mpd_Connection * connection, int id1, int id2) { + int len = strlen("swapid")+2+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "swapid \"%i\" \"%i\"\n", id1, id2); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendSeekCommand(mpd_Connection * connection, int song, int time) { + int len = strlen("seek")+2+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "seek \"%i\" \"%i\"\n", song, time); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendSeekIdCommand(mpd_Connection * connection, int id, int time) { + int len = strlen("seekid")+2+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "seekid \"%i\" \"%i\"\n", id, time); + mpd_sendInfoCommand(connection,string); + free(string); +} + +void mpd_sendUpdateCommand(mpd_Connection * connection, char * path) { + char * sPath = mpd_sanitizeArg(path); + int len = strlen("update")+2+strlen(sPath)+3; + char *string = malloc(len); + snprintf(string, len, "update \"%s\"\n", sPath); + mpd_sendInfoCommand(connection,string); + free(string); + free(sPath); +} + +int mpd_getUpdateId(mpd_Connection * connection) { + char * jobid; + int ret = 0; + + jobid = mpd_getNextReturnElementNamed(connection,"updating_db"); + if(jobid) { + ret = atoi(jobid); + free(jobid); + } + + return ret; +} + +void mpd_sendPrevCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"previous\n"); +} + +void mpd_sendRepeatCommand(mpd_Connection * connection, int repeatMode) { + int len = strlen("repeat")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "repeat \"%i\"\n", repeatMode); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendRandomCommand(mpd_Connection * connection, int randomMode) { + int len = strlen("random")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "random \"%i\"\n", randomMode); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendSetvolCommand(mpd_Connection * connection, int volumeChange) { + int len = strlen("setvol")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "setvol \"%i\"\n", volumeChange); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendVolumeCommand(mpd_Connection * connection, int volumeChange) { + int len = strlen("volume")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "volume \"%i\"\n", volumeChange); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendCrossfadeCommand(mpd_Connection * connection, int seconds) { + int len = strlen("crossfade")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "crossfade \"%i\"\n", seconds); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendPasswordCommand(mpd_Connection * connection, const char * pass) { + char * sPass = mpd_sanitizeArg(pass); + int len = strlen("password")+2+strlen(sPass)+3; + char *string = malloc(len); + snprintf(string, len, "password \"%s\"\n", sPass); + mpd_executeCommand(connection,string); + free(string); + free(sPass); +} + +void mpd_sendCommandListBegin(mpd_Connection * connection) { + if(connection->commandList) { + strcpy(connection->errorStr,"already in command list mode"); + connection->error = 1; + return; + } + connection->commandList = COMMAND_LIST; + mpd_executeCommand(connection,"command_list_begin\n"); +} + +void mpd_sendCommandListOkBegin(mpd_Connection * connection) { + if(connection->commandList) { + strcpy(connection->errorStr,"already in command list mode"); + connection->error = 1; + return; + } + connection->commandList = COMMAND_LIST_OK; + mpd_executeCommand(connection,"command_list_ok_begin\n"); + connection->listOks = 0; +} + +void mpd_sendCommandListEnd(mpd_Connection * connection) { + if(!connection->commandList) { + strcpy(connection->errorStr,"not in command list mode"); + connection->error = 1; + return; + } + connection->commandList = 0; + mpd_executeCommand(connection,"command_list_end\n"); +} + +void mpd_sendOutputsCommand(mpd_Connection * connection) { + mpd_executeCommand(connection,"outputs\n"); +} + +mpd_OutputEntity * mpd_getNextOutput(mpd_Connection * connection) { + mpd_OutputEntity * output = NULL; + + if(connection->doneProcessing || (connection->listOks && + connection->doneListOk)) + { + return NULL; + } + + if(connection->error) return NULL; + + output = malloc(sizeof(mpd_OutputEntity)); + output->id = -10; + output->name = NULL; + output->enabled = 0; + + if(!connection->returnElement) mpd_getNextReturnElement(connection); + + while(connection->returnElement) { + mpd_ReturnElement * re = connection->returnElement; + if(strcmp(re->name,"outputid")==0) { + if(output!=NULL && output->id>=0) return output; + output->id = atoi(re->value); + } + else if(strcmp(re->name,"outputname")==0) { + output->name = strdup(re->value); + } + else if(strcmp(re->name,"outputenabled")==0) { + output->enabled = atoi(re->value); + } + + mpd_getNextReturnElement(connection); + if(connection->error) { + free(output); + return NULL; + } + + } + + return output; +} + +void mpd_sendEnableOutputCommand(mpd_Connection * connection, int outputId) { + int len = strlen("enableoutput")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "enableoutput \"%i\"\n", outputId); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_sendDisableOutputCommand(mpd_Connection * connection, int outputId) { + int len = strlen("disableoutput")+2+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "disableoutput \"%i\"\n", outputId); + mpd_executeCommand(connection,string); + free(string); +} + +void mpd_freeOutputElement(mpd_OutputEntity * output) { + free(output->name); + free(output); +} + +/** + * mpd_sendNotCommandsCommand + * odd naming, but it gets the not allowed commands + */ + +void mpd_sendNotCommandsCommand(mpd_Connection * connection) +{ + mpd_executeCommand(connection, "notcommands\n"); +} + +/** + * mpd_sendCommandsCommand + * odd naming, but it gets the allowed commands + */ +void mpd_sendCommandsCommand(mpd_Connection * connection) +{ + mpd_executeCommand(connection, "commands\n"); +} + +/** + * Get the next returned command + */ +char * mpd_getNextCommand(mpd_Connection * connection) +{ + return mpd_getNextReturnElementNamed(connection, "command"); +} + +void mpd_sendUrlHandlersCommand(mpd_Connection * connection) +{ + mpd_executeCommand(connection, "urlhandlers\n"); +} + +char * mpd_getNextHandler(mpd_Connection * connection) +{ + return mpd_getNextReturnElementNamed(connection, "handler"); +} + +void mpd_sendTagTypesCommand(mpd_Connection * connection) +{ + mpd_executeCommand(connection, "tagtypes\n"); +} + +char * mpd_getNextTagType(mpd_Connection * connection) +{ + return mpd_getNextReturnElementNamed(connection, "tagtype"); +} + +void mpd_startSearch(mpd_Connection *connection, int exact) +{ + if (connection->request) { + strcpy(connection->errorStr, "search already in progress"); + connection->error = 1; + return; + } + + if (exact) connection->request = strdup("find"); + else connection->request = strdup("search"); +} + +void mpd_startStatsSearch(mpd_Connection *connection) +{ + if (connection->request) { + strcpy(connection->errorStr, "search already in progress"); + connection->error = 1; + return; + } + + connection->request = strdup("count"); +} + +void mpd_startPlaylistSearch(mpd_Connection *connection, int exact) +{ + if (connection->request) { + strcpy(connection->errorStr, "search already in progress"); + connection->error = 1; + return; + } + + if (exact) connection->request = strdup("playlistfind"); + else connection->request = strdup("playlistsearch"); +} + +void mpd_startFieldSearch(mpd_Connection *connection, int type) +{ + char *strtype; + int len; + + if (connection->request) { + strcpy(connection->errorStr, "search already in progress"); + connection->error = 1; + return; + } + + if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES) { + strcpy(connection->errorStr, "invalid type specified"); + connection->error = 1; + return; + } + + strtype = mpdTagItemKeys[type]; + + len = 5+strlen(strtype)+1; + connection->request = malloc(len); + + snprintf(connection->request, len, "list %c%s", + tolower(strtype[0]), strtype+1); +} + +void mpd_addConstraintSearch(mpd_Connection *connection, int type, const char *name) +{ + char *strtype; + char *arg; + int len; + char *string; + + if (!connection->request) { + strcpy(connection->errorStr, "no search in progress"); + connection->error = 1; + return; + } + + if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES) { + strcpy(connection->errorStr, "invalid type specified"); + connection->error = 1; + return; + } + + if (name == NULL) { + strcpy(connection->errorStr, "no name specified"); + connection->error = 1; + return; + } + + string = strdup(connection->request); + strtype = mpdTagItemKeys[type]; + arg = mpd_sanitizeArg(name); + + len = strlen(string)+1+strlen(strtype)+2+strlen(arg)+2; + connection->request = realloc(connection->request, len); + snprintf(connection->request, len, "%s %c%s \"%s\"", + string, tolower(strtype[0]), strtype+1, arg); + + free(string); + free(arg); +} + +void mpd_commitSearch(mpd_Connection *connection) +{ + int len; + + if (!connection->request) { + strcpy(connection->errorStr, "no search in progress"); + connection->error = 1; + return; + } + + len = strlen(connection->request)+2; + connection->request = realloc(connection->request, len); + connection->request[len-2] = '\n'; + connection->request[len-1] = '\0'; + mpd_sendInfoCommand(connection, connection->request); + + free(connection->request); + connection->request = NULL; +} + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content, with full metadata, of a stored playlist. + * + */ +void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path) +{ + char *arg = mpd_sanitizeArg(path); + int len = strlen("listplaylistinfo")+2+strlen(arg)+3; + char *query = malloc(len); + snprintf(query, len, "listplaylistinfo \"%s\"\n", arg); + mpd_sendInfoCommand(connection, query); + free(arg); + free(query); +} + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content of a stored playlist. + * + */ +void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path) +{ + char *arg = mpd_sanitizeArg(path); + int len = strlen("listplaylist")+2+strlen(arg)+3; + char *query = malloc(len); + snprintf(query, len, "listplaylist \"%s\"\n", arg); + mpd_sendInfoCommand(connection, query); + free(arg); + free(query); +} + +void mpd_sendPlaylistClearCommand(mpd_Connection *connection, char *path) +{ + char *sPath = mpd_sanitizeArg(path); + int len = strlen("playlistclear")+2+strlen(sPath)+3; + char *string = malloc(len); + snprintf(string, len, "playlistclear \"%s\"\n", sPath); + mpd_executeCommand(connection, string); + free(sPath); + free(string); +} + +void mpd_sendPlaylistAddCommand(mpd_Connection *connection, + char *playlist, char *path) +{ + char *sPlaylist = mpd_sanitizeArg(playlist); + char *sPath = mpd_sanitizeArg(path); + int len = strlen("playlistadd")+2+strlen(sPlaylist)+3+strlen(sPath)+3; + char *string = malloc(len); + snprintf(string, len, "playlistadd \"%s\" \"%s\"\n", sPlaylist, sPath); + mpd_executeCommand(connection, string); + free(sPlaylist); + free(sPath); + free(string); +} + +void mpd_sendPlaylistMoveCommand(mpd_Connection *connection, + char *playlist, int from, int to) +{ + char *sPlaylist = mpd_sanitizeArg(playlist); + int len = strlen("playlistmove")+ + 2+strlen(sPlaylist)+3+INTLEN+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "playlistmove \"%s\" \"%i\" \"%i\"\n", + sPlaylist, from, to); + mpd_executeCommand(connection, string); + free(sPlaylist); + free(string); +} + +void mpd_sendPlaylistDeleteCommand(mpd_Connection *connection, + char *playlist, int pos) +{ + char *sPlaylist = mpd_sanitizeArg(playlist); + int len = strlen("playlistdelete")+2+strlen(sPlaylist)+3+INTLEN+3; + char *string = malloc(len); + snprintf(string, len, "playlistdelete \"%s\" \"%i\"\n", sPlaylist, pos); + mpd_executeCommand(connection, string); + free(sPlaylist); + free(string); +} diff --git a/src/libmpdclient.h b/src/libmpdclient.h new file mode 100644 index 0000000..111d52a --- /dev/null +++ b/src/libmpdclient.h @@ -0,0 +1,670 @@ +/* libmpdclient + (c)2003-2006 by Warren Dukes (warren.dukes@gmail.com) + This project's homepage is: http://www.musicpd.org + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Music Player Daemon nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef LIBMPDCLIENT_H +#define LIBMPDCLIENT_H + +#ifdef WIN32 +# define __W32API_USE_DLLIMPORT__ 1 +#endif + +#include +#include +#define MPD_BUFFER_MAX_LENGTH 50000 +#define MPD_ERRORSTR_MAX_LENGTH 1000 +#define MPD_WELCOME_MESSAGE "OK MPD " + +#define MPD_ERROR_TIMEOUT 10 /* timeout trying to talk to mpd */ +#define MPD_ERROR_SYSTEM 11 /* system error */ +#define MPD_ERROR_UNKHOST 12 /* unknown host */ +#define MPD_ERROR_CONNPORT 13 /* problems connecting to port on host */ +#define MPD_ERROR_NOTMPD 14 /* mpd not running on port at host */ +#define MPD_ERROR_NORESPONSE 15 /* no response on attempting to connect */ +#define MPD_ERROR_SENDING 16 /* error sending command */ +#define MPD_ERROR_CONNCLOSED 17 /* connection closed by mpd */ +#define MPD_ERROR_ACK 18 /* ACK returned! */ +#define MPD_ERROR_BUFFEROVERRUN 19 /* Buffer was overrun! */ + +#define MPD_ACK_ERROR_UNK -1 +#define MPD_ERROR_AT_UNK -1 + +#define MPD_ACK_ERROR_NOT_LIST 1 +#define MPD_ACK_ERROR_ARG 2 +#define MPD_ACK_ERROR_PASSWORD 3 +#define MPD_ACK_ERROR_PERMISSION 4 +#define MPD_ACK_ERROR_UNKNOWN_CMD 5 + +#define MPD_ACK_ERROR_NO_EXIST 50 +#define MPD_ACK_ERROR_PLAYLIST_MAX 51 +#define MPD_ACK_ERROR_SYSTEM 52 +#define MPD_ACK_ERROR_PLAYLIST_LOAD 53 +#define MPD_ACK_ERROR_UPDATE_ALREADY 54 +#define MPD_ACK_ERROR_PLAYER_SYNC 55 +#define MPD_ACK_ERROR_EXIST 56 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum mpd_TagItems +{ + MPD_TAG_ITEM_ARTIST, + MPD_TAG_ITEM_ALBUM, + MPD_TAG_ITEM_TITLE, + MPD_TAG_ITEM_TRACK, + MPD_TAG_ITEM_NAME, + MPD_TAG_ITEM_GENRE, + MPD_TAG_ITEM_DATE, + MPD_TAG_ITEM_COMPOSER, + MPD_TAG_ITEM_PERFORMER, + MPD_TAG_ITEM_COMMENT, + MPD_TAG_ITEM_DISC, + MPD_TAG_ITEM_FILENAME, + MPD_TAG_ITEM_ANY, + MPD_TAG_NUM_OF_ITEM_TYPES +} mpd_TagItems; + +extern char * mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES]; + +/* internal stuff don't touch this struct */ +typedef struct _mpd_ReturnElement { + char * name; + char * value; +} mpd_ReturnElement; + +/* mpd_Connection + * holds info about connection to mpd + * use error, and errorStr to detect errors + */ +typedef struct _mpd_Connection { + /* use this to check the version of mpd */ + int version[3]; + /* IMPORTANT, you want to get the error messages from here */ + char errorStr[MPD_ERRORSTR_MAX_LENGTH+1]; + int errorCode; + int errorAt; + /* this will be set to MPD_ERROR_* if there is an error, 0 if not */ + int error; + /* DON'T TOUCH any of the rest of this stuff */ + int sock; + char buffer[MPD_BUFFER_MAX_LENGTH+1]; + int buflen; + int bufstart; + int doneProcessing; + int listOks; + int doneListOk; + int commandList; + mpd_ReturnElement * returnElement; + struct timeval timeout; + char *request; +} mpd_Connection; + +/* mpd_newConnection + * use this to open a new connection + * you should use mpd_closeConnection, when your done with the connection, + * even if an error has occurred + * _timeout_ is the connection timeout period in seconds + */ +mpd_Connection * mpd_newConnection(const char * host, int port, float timeout); + +void mpd_setConnectionTimeout(mpd_Connection * connection, float timeout); + +/* mpd_closeConnection + * use this to close a connection and free'ing subsequent memory + */ +void mpd_closeConnection(mpd_Connection * connection); + +/* mpd_clearError + * clears error + */ +void mpd_clearError(mpd_Connection * connection); + +/* STATUS STUFF */ + +/* use these with status.state to determine what state the player is in */ +#define MPD_STATUS_STATE_UNKNOWN 0 +#define MPD_STATUS_STATE_STOP 1 +#define MPD_STATUS_STATE_PLAY 2 +#define MPD_STATUS_STATE_PAUSE 3 + +/* us this with status.volume to determine if mpd has volume support */ +#define MPD_STATUS_NO_VOLUME -1 + +/* mpd_Status + * holds info return from status command + */ +typedef struct mpd_Status { + /* 0-100, or MPD_STATUS_NO_VOLUME when there is no volume support */ + int volume; + /* 1 if repeat is on, 0 otherwise */ + int repeat; + /* 1 if random is on, 0 otherwise */ + int random; + /* playlist length */ + int playlistLength; + /* playlist, use this to determine when the playlist has changed */ + long long playlist; + /* use with MPD_STATUS_STATE_* to determine state of player */ + int state; + /* crossfade setting in seconds */ + int crossfade; + /* if a song is currently selected (always the case when state is + * PLAY or PAUSE), this is the position of the currently + * playing song in the playlist, beginning with 0 + */ + int song; + /* Song ID of the currently selected song */ + int songid; + /* time in seconds that have elapsed in the currently playing/paused + * song + */ + int elapsedTime; + /* length in seconds of the currently playing/paused song */ + int totalTime; + /* current bit rate in kbs */ + int bitRate; + /* audio sample rate */ + unsigned int sampleRate; + /* audio bits */ + int bits; + /* audio channels */ + int channels; + /* 1 if mpd is updating, 0 otherwise */ + int updatingDb; + /* error */ + char * error; +} mpd_Status; + +void mpd_sendStatusCommand(mpd_Connection * connection); + +/* mpd_getStatus + * returns status info, be sure to free it with mpd_freeStatus() + * call this after mpd_sendStatusCommand() + */ +mpd_Status * mpd_getStatus(mpd_Connection * connection); + +/* mpd_freeStatus + * free's status info malloc'd and returned by mpd_getStatus + */ +void mpd_freeStatus(mpd_Status * status); + +typedef struct _mpd_Stats { + int numberOfArtists; + int numberOfAlbums; + int numberOfSongs; + unsigned long uptime; + unsigned long dbUpdateTime; + unsigned long playTime; + unsigned long dbPlayTime; +} mpd_Stats; + +typedef struct _mpd_SearchStats { + int numberOfSongs; + unsigned long playTime; +} mpd_SearchStats; + +void mpd_sendStatsCommand(mpd_Connection * connection); + +mpd_Stats * mpd_getStats(mpd_Connection * connection); + +void mpd_freeStats(mpd_Stats * stats); + +mpd_SearchStats * mpd_getSearchStats(mpd_Connection * connection); + +void mpd_freeSearchStats(mpd_SearchStats * stats); + +/* SONG STUFF */ + +#define MPD_SONG_NO_TIME -1 +#define MPD_SONG_NO_NUM -1 +#define MPD_SONG_NO_ID -1 + +/* mpd_Song + * for storing song info returned by mpd + */ +typedef struct _mpd_Song { + /* filename of song */ + char * file; + /* artist, maybe NULL if there is no tag */ + char * artist; + /* title, maybe NULL if there is no tag */ + char * title; + /* album, maybe NULL if there is no tag */ + char * album; + /* track, maybe NULL if there is no tag */ + char * track; + /* name, maybe NULL if there is no tag; it's the name of the current + * song, f.e. the icyName of the stream */ + char * name; + /* date */ + char *date; + + /* added by qball */ + /* Genre */ + char *genre; + /* Composer */ + char *composer; + /* Performer */ + char *performer; + /* Disc */ + char *disc; + /* Comment */ + char *comment; + + /* length of song in seconds, check that it is not MPD_SONG_NO_TIME */ + int time; + /* if plchanges/playlistinfo/playlistid used, is the position of the + * song in the playlist */ + int pos; + /* song id for a song in the playlist */ + int id; +} mpd_Song; + +/* mpd_newSong + * use to allocate memory for a new mpd_Song + * file, artist, etc all initialized to NULL + * if your going to assign values to file, artist, etc + * be sure to malloc or strdup the memory + * use mpd_freeSong to free the memory for the mpd_Song, it will also + * free memory for file, artist, etc, so don't do it yourself + */ +mpd_Song * mpd_newSong(void); + +/* mpd_freeSong + * use to free memory allocated by mpd_newSong + * also it will free memory pointed to by file, artist, etc, so be careful + */ +void mpd_freeSong(mpd_Song * song); + +/* mpd_songDup + * works like strDup, but for a mpd_Song + */ +mpd_Song * mpd_songDup(mpd_Song * song); + +/* DIRECTORY STUFF */ + +/* mpd_Directory + * used to store info fro directory (right now that just the path) + */ +typedef struct _mpd_Directory { + char * path; +} mpd_Directory; + +/* mpd_newDirectory + * allocates memory for a new directory + * use mpd_freeDirectory to free this memory + */ +mpd_Directory * mpd_newDirectory(void); + +/* mpd_freeDirectory + * used to free memory allocated with mpd_newDirectory, and it frees + * path of mpd_Directory, so be careful + */ +void mpd_freeDirectory(mpd_Directory * directory); + +/* mpd_directoryDup + * works like strdup, but for mpd_Directory + */ +mpd_Directory * mpd_directoryDup(mpd_Directory * directory); + +/* PLAYLISTFILE STUFF */ + +/* mpd_PlaylistFile + * stores info about playlist file returned by lsinfo + */ +typedef struct _mpd_PlaylistFile { + char * path; +} mpd_PlaylistFile; + +/* mpd_newPlaylistFile + * allocates memory for new mpd_PlaylistFile, path is set to NULL + * free this memory with mpd_freePlaylistFile + */ +mpd_PlaylistFile * mpd_newPlaylistFile(void); + +/* mpd_freePlaylist + * free memory allocated for freePlaylistFile, will also free + * path, so be careful + */ +void mpd_freePlaylistFile(mpd_PlaylistFile * playlist); + +/* mpd_playlistFileDup + * works like strdup, but for mpd_PlaylistFile + */ +mpd_PlaylistFile * mpd_playlistFileDup(mpd_PlaylistFile * playlist); + +/* INFO ENTITY STUFF */ + +/* the type of entity returned from one of the commands that generates info + * use in conjunction with mpd_InfoEntity.type + */ +#define MPD_INFO_ENTITY_TYPE_DIRECTORY 0 +#define MPD_INFO_ENTITY_TYPE_SONG 1 +#define MPD_INFO_ENTITY_TYPE_PLAYLISTFILE 2 + +/* mpd_InfoEntity + * stores info on stuff returned info commands + */ +typedef struct mpd_InfoEntity { + /* the type of entity, use with MPD_INFO_ENTITY_TYPE_* to determine + * what this entity is (song, directory, etc...) + */ + int type; + /* the actual data you want, mpd_Song, mpd_Directory, etc */ + union { + mpd_Directory * directory; + mpd_Song * song; + mpd_PlaylistFile * playlistFile; + } info; +} mpd_InfoEntity; + +mpd_InfoEntity * mpd_newInfoEntity(void); + +void mpd_freeInfoEntity(mpd_InfoEntity * entity); + +/* INFO COMMANDS AND STUFF */ + +/* use this function to loop over after calling Info/Listall functions */ +mpd_InfoEntity * mpd_getNextInfoEntity(mpd_Connection * connection); + +/* fetches the currently seeletect song (the song referenced by status->song + * and status->songid*/ +void mpd_sendCurrentSongCommand(mpd_Connection * connection); + +/* songNum of -1, means to display the whole list */ +void mpd_sendPlaylistInfoCommand(mpd_Connection * connection, int songNum); + +/* songId of -1, means to display the whole list */ +void mpd_sendPlaylistIdCommand(mpd_Connection * connection, int songId); + +/* use this to get the changes in the playlist since version _playlist_ */ +void mpd_sendPlChangesCommand(mpd_Connection * connection, long long playlist); + +/** + * @param connection: A valid and connected mpd_Connection. + * @param playlist: The playlist version you want the diff with. + * A more bandwidth efficient version of the mpd_sendPlChangesCommand. + * It only returns the pos+id of the changes song. + */ +void mpd_sendPlChangesPosIdCommand(mpd_Connection * connection, long long playlist); + +/* recursivel fetches all songs/dir/playlists in "dir* (no metadata is + * returned) */ +void mpd_sendListallCommand(mpd_Connection * connection, const char * dir); + +/* same as sendListallCommand, but also metadata is returned */ +void mpd_sendListallInfoCommand(mpd_Connection * connection, const char * dir); + +/* non-recursive version of ListallInfo */ +void mpd_sendLsInfoCommand(mpd_Connection * connection, const char * dir); + +#define MPD_TABLE_ARTIST MPD_TAG_ITEM_ARTIST +#define MPD_TABLE_ALBUM MPD_TAG_ITEM_ALBUM +#define MPD_TABLE_TITLE MPD_TAG_ITEM_TITLE +#define MPD_TABLE_FILENAME MPD_TAG_ITEM_FILENAME + +void mpd_sendSearchCommand(mpd_Connection * connection, int table, + const char * str); + +void mpd_sendFindCommand(mpd_Connection * connection, int table, + const char * str); + +/* LIST TAG COMMANDS */ + +/* use this function fetch next artist entry, be sure to free the returned + * string. NULL means there are no more. Best used with sendListArtists + */ +char * mpd_getNextArtist(mpd_Connection * connection); + +char * mpd_getNextAlbum(mpd_Connection * connection); + +char * mpd_getNextTag(mpd_Connection *connection, int type); + +/* list artist or albums by artist, arg1 should be set to the artist if + * listing albums by a artist, otherwise NULL for listing all artists or albums + */ +void mpd_sendListCommand(mpd_Connection * connection, int table, + const char * arg1); + +/* SIMPLE COMMANDS */ + +void mpd_sendAddCommand(mpd_Connection * connection, const char * file); + +int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file); + +void mpd_sendDeleteCommand(mpd_Connection * connection, int songNum); + +void mpd_sendDeleteIdCommand(mpd_Connection * connection, int songNum); + +void mpd_sendSaveCommand(mpd_Connection * connection, const char * name); + +void mpd_sendLoadCommand(mpd_Connection * connection, const char * name); + +void mpd_sendRmCommand(mpd_Connection * connection, const char * name); + +void mpd_sendRenameCommand(mpd_Connection *connection, const char *from, + const char *to); + +void mpd_sendShuffleCommand(mpd_Connection * connection); + +void mpd_sendClearCommand(mpd_Connection * connection); + +/* use this to start playing at the beginning, useful when in random mode */ +#define MPD_PLAY_AT_BEGINNING -1 + +void mpd_sendPlayCommand(mpd_Connection * connection, int songNum); + +void mpd_sendPlayIdCommand(mpd_Connection * connection, int songNum); + +void mpd_sendStopCommand(mpd_Connection * connection); + +void mpd_sendPauseCommand(mpd_Connection * connection, int pauseMode); + +void mpd_sendNextCommand(mpd_Connection * connection); + +void mpd_sendPrevCommand(mpd_Connection * connection); + +void mpd_sendMoveCommand(mpd_Connection * connection, int from, int to); + +void mpd_sendMoveIdCommand(mpd_Connection * connection, int from, int to); + +void mpd_sendSwapCommand(mpd_Connection * connection, int song1, int song2); + +void mpd_sendSwapIdCommand(mpd_Connection * connection, int song1, int song2); + +void mpd_sendSeekCommand(mpd_Connection * connection, int song, int time); + +void mpd_sendSeekIdCommand(mpd_Connection * connection, int song, int time); + +void mpd_sendRepeatCommand(mpd_Connection * connection, int repeatMode); + +void mpd_sendRandomCommand(mpd_Connection * connection, int randomMode); + +void mpd_sendSetvolCommand(mpd_Connection * connection, int volumeChange); + +/* WARNING: don't use volume command, its depreacted */ +void mpd_sendVolumeCommand(mpd_Connection * connection, int volumeChange); + +void mpd_sendCrossfadeCommand(mpd_Connection * connection, int seconds); + +void mpd_sendUpdateCommand(mpd_Connection * connection, char * path); + +/* returns the update job id, call this after a update command*/ +int mpd_getUpdateId(mpd_Connection * connection); + +void mpd_sendPasswordCommand(mpd_Connection * connection, const char * pass); + +/* after executing a command, when your done with it to get its status + * (you want to check connection->error for an error) + */ +void mpd_finishCommand(mpd_Connection * connection); + +/* command list stuff, use this to do things like add files very quickly */ +void mpd_sendCommandListBegin(mpd_Connection * connection); + +void mpd_sendCommandListOkBegin(mpd_Connection * connection); + +void mpd_sendCommandListEnd(mpd_Connection * connection); + +/* advance to the next listOk + * returns 0 if advanced to the next list_OK, + * returns -1 if it advanced to an OK or ACK */ +int mpd_nextListOkCommand(mpd_Connection * connection); + +typedef struct _mpd_OutputEntity { + int id; + char * name; + int enabled; +} mpd_OutputEntity; + +void mpd_sendOutputsCommand(mpd_Connection * connection); + +mpd_OutputEntity * mpd_getNextOutput(mpd_Connection * connection); + +void mpd_sendEnableOutputCommand(mpd_Connection * connection, int outputId); + +void mpd_sendDisableOutputCommand(mpd_Connection * connection, int outputId); + +void mpd_freeOutputElement(mpd_OutputEntity * output); + +/** + * @param connection a #mpd_Connection + * + * Queries mpd for the allowed commands + */ +void mpd_sendCommandsCommand(mpd_Connection * connection); + +/** + * @param connection a #mpd_Connection + * + * Queries mpd for the not allowed commands + */ +void mpd_sendNotCommandsCommand(mpd_Connection * connection); + +/** + * @param connection a #mpd_Connection + * + * returns the next supported command. + * + * @returns a string, needs to be free'ed + */ +char *mpd_getNextCommand(mpd_Connection *connection); + +void mpd_sendUrlHandlersCommand(mpd_Connection * connection); + +char *mpd_getNextHandler(mpd_Connection * connection); + +void mpd_sendTagTypesCommand(mpd_Connection * connection); + +char *mpd_getNextTagType(mpd_Connection * connection); + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content, with full metadata, of a stored playlist. + * + */ +void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path); + +/** + * @param connection a MpdConnection + * @param path the path to the playlist. + * + * List the content of a stored playlist. + * + */ +void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path); + +/** + * @param connection a #mpd_Connection + * @param exact if to match exact + * + * starts a search, use mpd_addConstraintSearch to add + * a constraint to the search, and mpd_commitSearch to do the actual search + */ +void mpd_startSearch(mpd_Connection *connection, int exact); + +/** + * @param connection a #mpd_Connection + * @param type + * @param name + */ +void mpd_addConstraintSearch(mpd_Connection *connection, int type, const char *name); + +/** + * @param connection a #mpd_Connection + */ +void mpd_commitSearch(mpd_Connection *connection); + +/** + * @param connection a #mpd_Connection + * @param type The type to search for + * + * starts a search for fields... f.e. get a list of artists would be: + * @code + * mpd_startFieldSearch(connection, MPD_TAG_ITEM_ARTIST); + * mpd_commitSearch(connection); + * @endcode + * + * or get a list of artist in genre "jazz" would be: + * @code + * mpd_startFieldSearch(connection, MPD_TAG_ITEM_ARTIST); + * mpd_addConstraintSearch(connection, MPD_TAG_ITEM_GENRE, "jazz") + * mpd_commitSearch(connection); + * @endcode + * + * mpd_startSearch will return a list of songs (and you need mpd_getNextInfoEntity) + * this one will return a list of only one field (the one specified with type) and you need + * mpd_getNextTag to get the results + */ +void mpd_startFieldSearch(mpd_Connection *connection, int type); + +void mpd_startPlaylistSearch(mpd_Connection *connection, int exact); + +void mpd_startStatsSearch(mpd_Connection *connection); + +void mpd_sendPlaylistClearCommand(mpd_Connection *connection, char *path); + +void mpd_sendPlaylistAddCommand(mpd_Connection *connection, + char *playlist, char *path); + +void mpd_sendPlaylistMoveCommand(mpd_Connection *connection, + char *playlist, int from, int to); + +void mpd_sendPlaylistDeleteCommand(mpd_Connection *connection, + char *playlist, int pos); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/misc.cpp b/src/misc.cpp new file mode 100644 index 0000000..74bf3c7 --- /dev/null +++ b/src/misc.cpp @@ -0,0 +1,143 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include +#include +#include +#include + +#include "configuration.h" +#include "misc.h" + +extern ScrobbyConfig config; + +pthread_mutex_t log_file = PTHREAD_MUTEX_INITIALIZER; + +size_t write_data(char *buffer, size_t size, size_t nmemb, std::string data) +{ + int result = 0; + if (buffer) + { + data += buffer; + result = size*nmemb; + } + return result; +} + +bool Daemonize() +{ + if (daemon(0, 0) < 0) + return false; + + std::ofstream f(config.file_pid.c_str(), std::ios_base::app); + if (f.is_open()) + { + pid_t pid = getpid(); + f << pid; + f.close(); + return true; + } + else + return false; +} + +void ClearCache() +{ + std::ofstream f(config.file_cache.c_str(), std::ios::trunc); + f.close(); +} + +void GetCachedSongs(std::vector &v) +{ + std::ifstream f(config.file_cache.c_str()); + if (f.is_open()) + { + std::string line; + while (!f.eof()) + { + getline(f, line); + if (!line.empty()) + v.push_back(line); + } + } +} + +void Cache(const std::string &s) +{ + std::ofstream f(config.file_cache.c_str(), std::ios::app); + if (f.is_open()) + { + f << s << std::endl; + f.close(); + } +} + +void Log(const std::string &s) +{ + pthread_mutex_lock(&log_file); + std::ofstream f(config.file_log.c_str(), std::ios::app); + if (f.is_open()) + { + f << "[" << DateTime() << "] " << s << std::endl; + f.close(); + } + pthread_mutex_unlock(&log_file); +} + +void ignore_newlines(std::string &s) +{ + for (unsigned i = s.find("\n"); i != std::string::npos; i = s.find("\n")) + s.replace(i, 1, ""); +} + +std::string md5sum(const std::string &s) +{ + char result[32]; + unsigned char md_value[EVP_MAX_MD_SIZE]; + unsigned int md_len; + + EVP_MD_CTX mdctx; + EVP_DigestInit(&mdctx, EVP_md5()); + EVP_DigestUpdate(&mdctx, s.c_str(), s.length()); + EVP_DigestFinal_ex(&mdctx, md_value, &md_len); + EVP_MD_CTX_cleanup(&mdctx); + + for (unsigned i = 0; i < md_len; i++) + sprintf(&result[i*2], "%02x", md_value[i]); + + return result; +} + +std::string DateTime() +{ + char result[32]; + time_t raw; + tm *t; + time(&raw); + t = localtime(&raw); + result[strftime(result, 31, "%Y/%m/%d %X", t)] = 0; + return result; +} + +int StrToInt(const std::string &s) +{ + return atoi(s.c_str()); +} + diff --git a/src/misc.h b/src/misc.h new file mode 100644 index 0000000..1534965 --- /dev/null +++ b/src/misc.h @@ -0,0 +1,55 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef _MISC_H +#define _MISC_H + +#include +#include +#include + +size_t write_data(char *, size_t, size_t, std::string); + +bool Daemonize(); + +void ClearCache(); +void GetCachedSongs(std::vector &); + +void Cache(const std::string &); +void Log(const std::string &); + +void ignore_newlines(std::string &); + +std::string md5sum(const std::string &); + +std::string DateTime(); + +int StrToInt(const std::string &); + +template +std::string IntoStr(T t) +{ + std::stringstream ss; + ss << t; + return ss.str(); +} + +#endif + diff --git a/src/mpdpp.cpp b/src/mpdpp.cpp new file mode 100644 index 0000000..c1a3348 --- /dev/null +++ b/src/mpdpp.cpp @@ -0,0 +1,185 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "mpdpp.h" + +using std::string; + +MPD::Connection::Connection() : isConnected(0), + itsErrorCode(0), + itsHost("localhost"), + itsPort(6600), + itsTimeout(15), + itsUpdater(0), + itsErrorHandler(0) +{ + itsConnection = 0; + itsCurrentStatus = 0; + itsOldStatus = 0; +} + +MPD::Connection::~Connection() +{ + if (itsConnection) + mpd_closeConnection(itsConnection); + if (itsOldStatus) + mpd_freeStatus(itsOldStatus); + if (itsCurrentStatus) + mpd_freeStatus(itsCurrentStatus); +} + +bool MPD::Connection::Connect() +{ + if (!isConnected && !itsConnection) + { + itsConnection = mpd_newConnection(itsHost.c_str(), itsPort, itsTimeout); + isConnected = 1; + if (CheckForErrors()) + return false; + if (!itsPassword.empty()) + SendPassword(); + return !CheckForErrors(); + } + else + return true; +} + +bool MPD::Connection::Connected() const +{ + return isConnected; +} + +void MPD::Connection::Disconnect() +{ + if (itsConnection) + mpd_closeConnection(itsConnection); + if (itsOldStatus) + mpd_freeStatus(itsOldStatus); + if (itsCurrentStatus) + mpd_freeStatus(itsCurrentStatus); + itsConnection = 0; + itsCurrentStatus = 0; + itsOldStatus = 0; + isConnected = 0; +} + +void MPD::Connection::SetHostname(const string &host) +{ + unsigned at = host.find("@"); + if (at != string::npos) + { + itsPassword = host.substr(0, at); + itsHost = host.substr(at+1); + } + else + itsHost = host; +} + +void MPD::Connection::SendPassword() const +{ + mpd_sendPasswordCommand(itsConnection, itsPassword.c_str()); + mpd_finishCommand(itsConnection); +} + +void MPD::Connection::SetStatusUpdater(StatusUpdater updater, void *data) +{ + itsUpdater = updater; + itsStatusUpdaterUserdata = data; +} + +void MPD::Connection::SetErrorHandler(ErrorHandler handler, void *data) +{ + itsErrorHandler = handler; + itsErrorHandlerUserdata = data; +} + +void MPD::Connection::UpdateStatus() +{ + CheckForErrors(); + + if (itsOldStatus) + mpd_freeStatus(itsOldStatus); + itsOldStatus = itsCurrentStatus; + mpd_sendStatusCommand(itsConnection); + itsCurrentStatus = mpd_getStatus(itsConnection); + + if (CheckForErrors()) + return; + + if (itsCurrentStatus && itsUpdater) + { + if (itsOldStatus == NULL) + { + itsChanges.SongID = 1; + itsChanges.ElapsedTime = 1; + itsChanges.State = 1; + } + else + { + itsChanges.SongID = itsOldStatus->songid != itsCurrentStatus->songid; + itsChanges.ElapsedTime = itsOldStatus->elapsedTime != itsCurrentStatus->elapsedTime; + itsChanges.State = itsOldStatus->state != itsCurrentStatus->state; + } + itsUpdater(this, itsChanges, itsErrorHandlerUserdata); + } +} + +mpd_Song * MPD::Connection::CurrentSong() const +{ + if (isConnected && (GetState() == psPlay || GetState() == psPause)) + { + mpd_sendCurrentSongCommand(itsConnection); + mpd_InfoEntity *item = NULL; + item = mpd_getNextInfoEntity(itsConnection); + if (item) + { + mpd_Song *result = item->info.song; + item->info.song = 0; + mpd_freeInfoEntity(item); + return result; + } + mpd_finishCommand(itsConnection); + } + return NULL; +} + +int MPD::Connection::CheckForErrors() +{ + itsErrorCode = 0; + if (itsConnection->error) + { + if (itsConnection->error == MPD_ERROR_ACK) + { + if (itsErrorHandler) + itsErrorHandler(this, itsConnection->errorCode, itsConnection->errorStr, itsErrorHandlerUserdata); + itsErrorCode = itsConnection->errorCode; + } + else + { + isConnected = 0; // the rest of errors are fatal to connection + if (itsErrorHandler) + itsErrorHandler(this, itsConnection->error, itsConnection->errorStr, itsErrorHandlerUserdata); + itsErrorCode = itsConnection->error; + } + itsErrorMessage = itsConnection->errorStr; + mpd_clearError(itsConnection); + } + return itsErrorCode; +} diff --git a/src/mpdpp.h b/src/mpdpp.h new file mode 100644 index 0000000..d7035bc --- /dev/null +++ b/src/mpdpp.h @@ -0,0 +1,103 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef _MPDPP_H +#define _MPDPP_H + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include "libmpdclient.h" + +namespace MPD +{ + enum State { psUnknown, psStop, psPlay, psPause }; + + struct StatusChanges + { + bool SongID; + bool ElapsedTime; + bool State; + }; + + class Connection + { + typedef void (*StatusUpdater) (Connection *, StatusChanges, void *); + typedef void (*ErrorHandler) (Connection *, int, std::string, void *); + + public: + Connection(); + ~Connection(); + + bool Connect(); + bool Connected() const; + void Disconnect(); + + const std::string & GetHostname() { return itsHost; } + int GetPort() { return itsPort; } + + void SetHostname(const std::string &); + void SetPort(int port) { itsPort = port; } + void SetTimeout(int timeout) { itsTimeout = timeout; } + void SetPassword(const std::string &password) { itsPassword = password; } + void SendPassword() const; + + void SetStatusUpdater(StatusUpdater, void *); + void SetErrorHandler(ErrorHandler, void *); + void UpdateStatus(); + + State GetState() const { return isConnected && itsCurrentStatus ? (State)itsCurrentStatus->state : psUnknown; } + int GetElapsedTime() const { return isConnected && itsCurrentStatus ? itsCurrentStatus->elapsedTime : -1; } + + const std::string & GetErrorMessage() const { return itsErrorMessage; } + int GetErrorCode() const { return itsErrorCode; } + + mpd_Song * CurrentSong() const; + + private: + int CheckForErrors(); + + StatusChanges itsChanges; + + mpd_Connection *itsConnection; + bool isConnected; + + std::string itsErrorMessage; + int itsErrorCode; + + std::string itsHost; + std::string itsPassword; + int itsPort; + int itsTimeout; + + mpd_Status *itsCurrentStatus; + mpd_Status *itsOldStatus; + + StatusUpdater itsUpdater; + void *itsStatusUpdaterUserdata; + ErrorHandler itsErrorHandler; + void *itsErrorHandlerUserdata; + }; +} + +#endif + diff --git a/src/scrobby.cpp b/src/scrobby.cpp new file mode 100644 index 0000000..4251581 --- /dev/null +++ b/src/scrobby.cpp @@ -0,0 +1,467 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include +#include +#include +#include +#include + +#include "callback.h" +#include "configuration.h" +#include "misc.h" +#include "scrobby.h" +#include "mpdpp.h" + +using std::string; + +ScrobbyConfig config; + +HandshakeResult hr; +SubmissionCandidate sc; + +pthread_t mpdconnection_th; +pthread_t handshake_th; + +pthread_mutex_t curl = PTHREAD_MUTEX_INITIALIZER; +pthread_mutex_t hr_lock = PTHREAD_MUTEX_INITIALIZER; + +std::vector queue; + +bool exit = 0; +bool notify_about_now_playing = 0; + +namespace +{ + void signal_handler(int); + bool send_handshake(); + + void *mpdconnection_handler(void *data); + void *handshake_handler(void *); +} + +int main(/*int argc, char **argv*/) +{ + DefaultConfiguration(config); + + if (!ReadConfiguration(config, "/etc/scrobby.conf")) + { + std::cerr << "cannot read configuration file!"; + return 1; + } + if (config.lastfm_user.empty() || (config.lastfm_md5_password.empty() && config.lastfm_password.empty())) + { + std::cerr << "last.fm user/password is not set.\n"; + return 1; + } + if (!CheckFiles(config)) + { + return 1; + } + if (!Daemonize()) + std::cerr << "couldn't daemonize!\n"; + + GetCachedSongs(queue); + + MPD::Connection *Mpd = new MPD::Connection; + + if (config.mpd_host != "localhost") + Mpd->SetHostname(config.mpd_host); + if (config.mpd_port != 6600) + Mpd->SetPort(config.mpd_port); + if (!config.mpd_password.empty()) + Mpd->SetPassword(config.mpd_password); + + Mpd->SetTimeout(config.mpd_timeout); + Mpd->SetStatusUpdater(ScrobbyStatusChanged, NULL); + Mpd->SetErrorHandler(ScrobbyErrorCallback, NULL); + + signal(SIGHUP, signal_handler); + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); + signal(SIGPIPE, SIG_IGN); + + pthread_create(&mpdconnection_th, NULL, mpdconnection_handler, Mpd); + pthread_create(&handshake_th, NULL, handshake_handler, NULL); + pthread_detach(mpdconnection_th); + pthread_detach(handshake_th); + + sleep(1); + + while (!exit && !usleep(500000)) + { + if (Mpd->Connected()) + Mpd->UpdateStatus(); + } + + if (sc.song) + SubmitSong(sc); + Log("Shutting down..."); + if (remove(config.file_pid.c_str()) != 0) + Log("Couldn't remove pid file!"); + delete Mpd; + + return 0; +} + +void SubmissionCandidate::Clear() +{ + if (song) + mpd_freeSong(song); + song = 0; + started_time = 0; + noticed_playback = 0; +} + +bool SubmissionCandidate::canBeSubmitted() +{ + if (!started_time || song->time < 30 || !song->artist || !song->title) + { + if (!started_time) + { + Log("Song's start time isn't known, not submitting."); + } + else if (song->time < 30) + { + Log("Song's length is too short, not submitting."); + } + else if (!song->artist || !song->title) + { + Log("Song has missing tags, not submitting."); + } + return false; + } + else if (noticed_playback < 4*60 && noticed_playback < song->time/2) + { + Log("Noticed playback was too short, not submitting."); + return false; + } + return true; +} + +void SubmitSong(SubmissionCandidate &sc) +{ + if (sc.canBeSubmitted()) + { + if (hr.status != "OK" || hr.submission_url.empty()) + { + Log("Problems with handshake status, queue song at position " + IntoStr(queue.size()) + "..."); + goto SUBMISSION_FAILED; + } + + Log("Submitting song..."); + + string result, postdata; + CURLcode code; + + pthread_mutex_lock(&curl); + CURL *submission = curl_easy_init(); + + char *c_artist = curl_easy_escape(submission, sc.song->artist, 0); + char *c_title = curl_easy_escape(submission, sc.song->title, 0); + char *c_album = sc.song->album ? curl_easy_escape(submission, sc.song->album, 0) : NULL; + char *c_track = sc.song->track ? curl_easy_escape(submission, sc.song->track, 0) : NULL; + + postdata = "s="; + postdata += hr.session_id; + postdata += "&a[0]="; + postdata += c_artist; + postdata += "&t[0]="; + postdata += c_title; + postdata += "&i[0]="; + postdata += IntoStr(sc.started_time); + postdata += "&o[0]=P"; + postdata += "&r[0]="; + postdata += "&l[0]="; + postdata += IntoStr(sc.song->time); + postdata += "&b[0]="; + if (c_album) + postdata += c_album; + postdata += "&n[0]="; + if (c_track) + postdata += c_track; + postdata += "&m[0]="; + + curl_free(c_artist); + curl_free(c_title); + curl_free(c_album); + curl_free(c_track); + + Log("URL: " + hr.submission_url); + Log("Post data: " + postdata); + + curl_easy_setopt(submission, CURLOPT_URL, hr.submission_url.c_str()); + curl_easy_setopt(submission, CURLOPT_POST, 1); + curl_easy_setopt(submission, CURLOPT_POSTFIELDS, postdata.c_str()); + curl_easy_setopt(submission, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(submission, CURLOPT_WRITEDATA, &result); + curl_easy_setopt(submission, CURLOPT_CONNECTTIMEOUT, 5); + code = curl_easy_perform(submission); + curl_easy_cleanup(submission); + pthread_mutex_unlock(&curl); + + ignore_newlines(result); + + if (result == "OK") + { + Log("Song submitted."); + } + else + { + if (result.empty()) + { + Log("Error while submitting song: " + string(curl_easy_strerror(code))); + } + else + { + Log("Audioscrobbler returned status " + result); + } + goto SUBMISSION_FAILED; + } + } + if (0) + { + SUBMISSION_FAILED: // so we cache not submitted song + + pthread_mutex_lock(&hr_lock); + hr.Clear(); // handshake probably failed if we are here, so reset it + Log("Handshake status reset"); + + string cache; + string offset = IntoStr(queue.size()); + + char *c_artist = curl_easy_escape(0, sc.song->artist, 0); + char *c_title = curl_easy_escape(0, sc.song->title, 0); + char *c_album = sc.song->album ? curl_easy_escape(0, sc.song->album, 0) : NULL; + char *c_track = sc.song->track ? curl_easy_escape(0, sc.song->track, 0) : NULL; + + cache = "&a["; + cache += offset; + cache += "]="; + cache += c_artist; + cache += "&t["; + cache += offset; + cache += "]="; + cache += c_title; + cache += "&i["; + cache += offset; + cache += "]="; + cache += IntoStr(sc.started_time); + cache += "&o["; + cache += offset; + cache += "]=P"; + cache += "&r["; + cache += offset; + cache += "]="; + cache += "&l["; + cache += offset; + cache += "]="; + cache += IntoStr(sc.song->time); + cache += "&b["; + cache += offset; + cache += "]="; + if (c_album) + cache += c_album; + cache += "&n["; + cache += offset; + cache += "]="; + if (c_track) + cache += c_track; + cache += "&m["; + cache += offset; + cache += "]="; + + Log("Metadata: " + cache); + + curl_free(c_artist); + curl_free(c_title); + curl_free(c_album); + curl_free(c_track); + + Cache(cache); + queue.push_back(cache); + Log("Song cached."); + pthread_mutex_unlock(&hr_lock); + } +} + +namespace +{ + void signal_handler(int) + { + exit = 1; + } + + bool send_handshake() + { + CURLcode code; + string handshake_url; + string result; + string timestamp = IntoStr(time(NULL)); + + handshake_url = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=mpc&v="VERSION"&u="; + handshake_url += config.lastfm_user; + handshake_url += "&t="; + handshake_url += timestamp; + handshake_url += "&a="; + handshake_url += md5sum((config.lastfm_md5_password.empty() ? md5sum(config.lastfm_password) : config.lastfm_md5_password) + timestamp); + + pthread_mutex_lock(&curl); + CURL *handshake = curl_easy_init(); + curl_easy_setopt(handshake, CURLOPT_URL, handshake_url.c_str()); + curl_easy_setopt(handshake, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(handshake, CURLOPT_WRITEDATA, &result); + curl_easy_setopt(handshake, CURLOPT_CONNECTTIMEOUT, 5); + code = curl_easy_perform(handshake); + curl_easy_cleanup(handshake); + pthread_mutex_unlock(&curl); + + if (code != CURLE_OK) + { + Log("Error while sending handshake: " + string(curl_easy_strerror(code))); + return false; + } + + int i = result.find("\n"); + hr.status = result.substr(0, i); + if (hr.status != "OK") + return false; + result = result.substr(i+1); + i = result.find("\n"); + hr.session_id = result.substr(0, i); + result = result.substr(i+1); + i = result.find("\n"); + hr.nowplaying_url = result.substr(0, i); + result = result.substr(i+1); + ignore_newlines(result); + hr.submission_url = result; + return true; + } + + void *mpdconnection_handler(void *data) + { + MPD::Connection *Mpd = static_cast(data); + while (!exit) + { + int x = 0; + while (!Mpd->Connected()) + { + Log("Connecting to MPD..."); + Mpd->Disconnect(); + if (Mpd->Connect()) + { + Log("Connected to " + config.mpd_host + "!"); + x = 0; + } + else + { + x++; + Log("MPD: " + Mpd->GetErrorMessage()); + Log("Cannot connect, retrieving in " + IntoStr(10*x) + " seconds..."); + sleep(10*x); + } + } + sleep(1); + } + pthread_exit(NULL); + } + + void *handshake_handler(void *) + { + int x = 0; + while (!exit) + { + if (hr.status != "OK") + { + pthread_mutex_lock(&hr_lock); + hr.Clear(); + if (send_handshake() && !hr.status.empty()) + { + Log("Handshake returned " + hr.status); + } + if (hr.status == "OK") + { + Log("Connected to Audioscrobbler!"); + if (!queue.empty()) + { + Log("Queue's not empty, submitting songs..."); + + string result, postdata; + CURLcode code; + + pthread_mutex_lock(&curl); + CURL *submission = curl_easy_init(); + + postdata = "s="; + postdata += hr.session_id; + + for (std::vector::const_iterator it = queue.begin(); it != queue.end(); it++) + postdata += *it; + + Log("URL: " + hr.submission_url); + Log("Post data: " + postdata); + + curl_easy_setopt(submission, CURLOPT_URL, hr.submission_url.c_str()); + curl_easy_setopt(submission, CURLOPT_POST, 1); + curl_easy_setopt(submission, CURLOPT_POSTFIELDS, postdata.c_str()); + curl_easy_setopt(submission, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(submission, CURLOPT_WRITEDATA, &result); + curl_easy_setopt(submission, CURLOPT_CONNECTTIMEOUT, 5); + code = curl_easy_perform(submission); + curl_easy_cleanup(submission); + pthread_mutex_unlock(&curl); + + ignore_newlines(result); + + if (result == "OK") + { + Log("Number of submitted songs: " + IntoStr(queue.size())); + queue.clear(); + ClearCache(); + x = 0; + } + else + { + if (result.empty()) + { + Log("Error while submitting songs: " + string(curl_easy_strerror(code))); + } + else + { + Log("Audioscrobbler returned status " + result); + } + } + } + notify_about_now_playing = 1; + } + else + { + x++; + Log("Connection refused, retrieving in " + IntoStr(10*x) + " seconds..."); + sleep(10*x); + } + pthread_mutex_unlock(&hr_lock); + } + sleep(1); + } + pthread_exit(NULL); + } +} + diff --git a/src/scrobby.h b/src/scrobby.h new file mode 100644 index 0000000..3e970bc --- /dev/null +++ b/src/scrobby.h @@ -0,0 +1,64 @@ +/*************************************************************************** + * Copyright (C) 2008 by Andrzej Rybczak * + * electricityispower@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#ifndef _SCROBBY_H +#define _SCROBBY_H + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include + +#include "libmpdclient.h" + +struct HandshakeResult +{ + void Clear() + { + status.clear(); + session_id.clear(); + nowplaying_url.clear(); + submission_url.clear(); + } + + std::string status; + std::string session_id; + std::string nowplaying_url; + std::string submission_url; +}; + +struct SubmissionCandidate +{ + SubmissionCandidate() : song(0), started_time(0), noticed_playback(0) { } + ~SubmissionCandidate() { if (song) mpd_freeSong(song); } + + void Clear(); + bool canBeSubmitted(); + + mpd_Song *song; + time_t started_time; + int noticed_playback; +}; + +void SubmitSong(SubmissionCandidate &); + +#endif + -- 2.11.4.GIT