1 /*****************************************************************************
2 * audioscrobbler.c : audioscrobbler submission plugin
3 *****************************************************************************
4 * Copyright © 2006-2011 the VideoLAN team
7 * Author: Rafaël Carré <funman at videolanorg>
8 * Ilkka Ollakka <ileoo at videolan org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /* audioscrobbler protocol version: 1.2
26 * http://www.audioscrobbler.net/development/protocol/
28 * TODO: "Now Playing" feature (not mandatory)
29 * Update to new API? http://www.lastfm.fr/api
31 /*****************************************************************************
33 *****************************************************************************/
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
43 #include <vlc_interface.h>
44 #include <vlc_dialog.h>
47 #include <vlc_stream.h>
49 #include <vlc_network.h>
50 #include <vlc_playlist.h>
52 /*****************************************************************************
54 *****************************************************************************/
58 /* Keeps track of metadata to be submitted */
59 typedef struct audioscrobbler_song_t
61 char *psz_a; /**< track artist */
62 char *psz_t; /**< track title */
63 char *psz_b; /**< track album */
64 char *psz_n; /**< track number */
65 int i_l; /**< track length */
66 char *psz_m; /**< musicbrainz id */
67 time_t date; /**< date since epoch */
68 mtime_t i_start; /**< playing start */
69 } audioscrobbler_song_t;
73 audioscrobbler_song_t p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
74 int i_songs; /**< number of songs */
76 vlc_mutex_t lock; /**< p_sys mutex */
77 vlc_cond_t wait; /**< song to submit event */
78 vlc_thread_t thread; /**< thread to submit song */
80 /* submission of played songs */
81 vlc_url_t p_submit_url; /**< where to submit data */
83 /* submission of playing song */
85 char *psz_nowp_host; /**< where to submit data */
86 int i_nowp_port; /**< port to which submit */
87 char *psz_nowp_file; /**< file to which submit */
89 char psz_auth_token[33]; /**< Authentication token */
91 /* data about song currently playing */
92 audioscrobbler_song_t p_current_song; /**< song being played */
94 mtime_t time_pause; /**< time when vlc paused */
95 mtime_t time_total_pauses; /**< total time in pause */
97 bool b_submit; /**< do we have to submit ? */
99 bool b_state_cb; /**< if we registered the
100 * "state" callback */
102 bool b_meta_read; /**< if we read the song's
103 * metadata already */
106 static int Open (vlc_object_t *);
107 static void Close (vlc_object_t *);
108 static void *Run (void *);
110 /*****************************************************************************
112 ****************************************************************************/
114 #define USERNAME_TEXT N_("Username")
115 #define USERNAME_LONGTEXT N_("The username of your last.fm account")
116 #define PASSWORD_TEXT N_("Password")
117 #define PASSWORD_LONGTEXT N_("The password of your last.fm account")
118 #define URL_TEXT N_("Scrobbler URL")
119 #define URL_LONGTEXT N_("The URL set for an alternative scrobbler engine")
121 /* This error value is used when last.fm plugin has to be unloaded. */
122 #define VLC_AUDIOSCROBBLER_EFATAL -69
124 /* last.fm client identifier */
125 #define CLIENT_NAME PACKAGE
126 #define CLIENT_VERSION VERSION
129 set_category(CAT_INTERFACE)
130 set_subcategory(SUBCAT_INTERFACE_CONTROL)
131 set_shortname(N_("Audioscrobbler"))
132 set_description(N_("Submission of played songs to last.fm"))
133 add_string("lastfm-username", "",
134 USERNAME_TEXT, USERNAME_LONGTEXT, false)
135 add_password("lastfm-password", "",
136 PASSWORD_TEXT, PASSWORD_LONGTEXT, false)
137 add_string("scrobbler-url", "post.audioscrobbler.com",
138 URL_TEXT, URL_LONGTEXT, false)
139 set_capability("interface", 0)
140 set_callbacks(Open, Close)
143 /*****************************************************************************
144 * DeleteSong : Delete the char pointers in a song
145 *****************************************************************************/
146 static void DeleteSong(audioscrobbler_song_t* p_song)
148 FREENULL(p_song->psz_a);
149 FREENULL(p_song->psz_b);
150 FREENULL(p_song->psz_t);
151 FREENULL(p_song->psz_m);
152 FREENULL(p_song->psz_n);
155 /*****************************************************************************
156 * ReadMetaData : Read meta data when parsed by vlc
157 *****************************************************************************/
158 static void ReadMetaData(intf_thread_t *p_this)
160 intf_sys_t *p_sys = p_this->p_sys;
162 input_thread_t *p_input = pl_CurrentInput(p_this);
166 input_item_t *p_item = input_GetItem(p_input);
169 vlc_object_release(p_input);
173 #define ALLOC_ITEM_META(a, b) do { \
174 char *psz_meta = input_item_Get##b(p_item); \
175 if (psz_meta && *psz_meta) \
176 a = encode_URI_component(psz_meta); \
180 vlc_mutex_lock(&p_sys->lock);
182 p_sys->b_meta_read = true;
184 ALLOC_ITEM_META(p_sys->p_current_song.psz_a, Artist);
185 if (!p_sys->p_current_song.psz_a)
187 msg_Dbg(p_this, "No artist..");
188 DeleteSong(&p_sys->p_current_song);
192 ALLOC_ITEM_META(p_sys->p_current_song.psz_t, Title);
193 if (!p_sys->p_current_song.psz_t)
195 msg_Dbg(p_this, "No track name..");
196 DeleteSong(&p_sys->p_current_song);
200 /* Now we have read the mandatory meta data, so we can submit that info */
201 p_sys->b_submit = true;
203 ALLOC_ITEM_META(p_sys->p_current_song.psz_b, Album);
204 if (!p_sys->p_current_song.psz_b)
205 p_sys->p_current_song.psz_b = calloc(1, 1);
207 ALLOC_ITEM_META(p_sys->p_current_song.psz_m, TrackID);
208 if (!p_sys->p_current_song.psz_m)
209 p_sys->p_current_song.psz_m = calloc(1, 1);
211 p_sys->p_current_song.i_l = input_item_GetDuration(p_item) / 1000000;
213 ALLOC_ITEM_META(p_sys->p_current_song.psz_n, TrackNum);
214 if (!p_sys->p_current_song.psz_n)
215 p_sys->p_current_song.psz_n = calloc(1, 1);
216 #undef ALLOC_ITEM_META
218 msg_Dbg(p_this, "Meta data registered");
221 vlc_mutex_unlock(&p_sys->lock);
222 vlc_object_release(p_input);
225 /*****************************************************************************
226 * AddToQueue: Add the played song to the queue to be submitted
227 *****************************************************************************/
228 static void AddToQueue (intf_thread_t *p_this)
231 intf_sys_t *p_sys = p_this->p_sys;
233 vlc_mutex_lock(&p_sys->lock);
234 if (!p_sys->b_submit)
237 /* wait for the user to listen enough before submitting */
238 played_time = mdate() - p_sys->p_current_song.i_start -
239 p_sys->time_total_pauses;
240 played_time /= 1000000; /* µs → s */
242 /*HACK: it seam that the preparsing sometime fail,
243 so use the playing time as the song length */
244 if (p_sys->p_current_song.i_l == 0)
245 p_sys->p_current_song.i_l = played_time;
247 /* Don't send song shorter than 30s */
248 if (p_sys->p_current_song.i_l < 30)
250 msg_Dbg(p_this, "Song too short (< 30s), not submitting");
254 /* Send if the user had listen more than 240s OR half the track length */
255 if ((played_time < 240) &&
256 (played_time < (p_sys->p_current_song.i_l / 2)))
258 msg_Dbg(p_this, "Song not listened long enough, not submitting");
262 /* Check that all meta are present */
263 if (!p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
264 !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t)
266 msg_Dbg(p_this, "Missing artist or title, not submitting");
270 if (p_sys->i_songs >= QUEUE_MAX)
272 msg_Warn(p_this, "Submission queue is full, not submitting");
276 msg_Dbg(p_this, "Song will be submitted.");
278 #define QUEUE_COPY(a) \
279 p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
281 #define QUEUE_COPY_NULL(a) \
283 p_sys->p_current_song.a = NULL
286 QUEUE_COPY_NULL(psz_n);
287 QUEUE_COPY_NULL(psz_a);
288 QUEUE_COPY_NULL(psz_t);
289 QUEUE_COPY_NULL(psz_b);
290 QUEUE_COPY_NULL(psz_m);
292 #undef QUEUE_COPY_NULL
297 /* signal the main loop we have something to submit */
298 vlc_cond_signal(&p_sys->wait);
301 DeleteSong(&p_sys->p_current_song);
302 p_sys->b_submit = false;
303 vlc_mutex_unlock(&p_sys->lock);
306 /*****************************************************************************
307 * PlayingChange: Playing status change callback
308 *****************************************************************************/
309 static int PlayingChange(vlc_object_t *p_this, const char *psz_var,
310 vlc_value_t oldval, vlc_value_t newval, void *p_data)
314 intf_thread_t *p_intf = (intf_thread_t*) p_data;
315 intf_sys_t *p_sys = p_intf->p_sys;
316 input_thread_t *p_input = (input_thread_t*)p_this;
321 if (newval.i_int != INPUT_EVENT_STATE) return VLC_SUCCESS;
323 if (var_CountChoices(p_input, "video-es"))
325 msg_Dbg(p_this, "Not an audio-only input, not submitting");
329 state = var_GetInteger(p_input, "state");
331 if (!p_sys->b_meta_read && state >= PLAYING_S)
333 ReadMetaData(p_intf);
340 else if (state == PAUSE_S)
341 p_sys->time_pause = mdate();
342 else if (p_sys->time_pause > 0 && state == PLAYING_S)
344 p_sys->time_total_pauses += (mdate() - p_sys->time_pause);
345 p_sys->time_pause = 0;
351 /*****************************************************************************
352 * ItemChange: Playlist item change callback
353 *****************************************************************************/
354 static int ItemChange(vlc_object_t *p_this, const char *psz_var,
355 vlc_value_t oldval, vlc_value_t newval, void *p_data)
357 intf_thread_t *p_intf = (intf_thread_t*) p_data;
358 intf_sys_t *p_sys = p_intf->p_sys;
360 VLC_UNUSED(p_this); VLC_UNUSED(psz_var);
361 VLC_UNUSED(oldval); VLC_UNUSED(newval);
363 p_sys->b_state_cb = false;
364 p_sys->b_meta_read = false;
365 p_sys->b_submit = false;
367 input_thread_t *p_input = pl_CurrentInput(p_intf);
368 if (!p_input || p_input->b_dead)
371 input_item_t *p_item = input_GetItem(p_input);
374 vlc_object_release(p_input);
378 if (var_CountChoices(p_input, "video-es"))
380 msg_Dbg(p_this, "Not an audio-only input, not submitting");
381 vlc_object_release(p_input);
385 p_sys->time_total_pauses = 0;
386 time(&p_sys->p_current_song.date); /* to be sent to last.fm */
387 p_sys->p_current_song.i_start = mdate(); /* only used locally */
389 var_AddCallback(p_input, "intf-event", PlayingChange, p_intf);
390 p_sys->b_state_cb = true;
392 if (input_item_IsPreparsed(p_item))
393 ReadMetaData(p_intf);
394 /* if the input item was not preparsed, we'll do it in PlayingChange()
395 * callback, when "state" == PLAYING_S */
397 vlc_object_release(p_input);
401 /*****************************************************************************
402 * Open: initialize and create stuff
403 *****************************************************************************/
404 static int Open(vlc_object_t *p_this)
406 intf_thread_t *p_intf = (intf_thread_t*) p_this;
407 intf_sys_t *p_sys = calloc(1, sizeof(intf_sys_t));
412 p_intf->p_sys = p_sys;
414 vlc_mutex_init(&p_sys->lock);
415 vlc_cond_init(&p_sys->wait);
417 if (vlc_clone(&p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW))
419 vlc_cond_destroy(&p_sys->wait);
420 vlc_mutex_destroy(&p_sys->lock);
425 var_AddCallback(pl_Get(p_intf), "activity", ItemChange, p_intf);
430 /*****************************************************************************
431 * Close: destroy interface stuff
432 *****************************************************************************/
433 static void Close(vlc_object_t *p_this)
435 intf_thread_t *p_intf = (intf_thread_t*) p_this;
436 intf_sys_t *p_sys = p_intf->p_sys;
438 var_DelCallback(pl_Get(p_intf), "activity", ItemChange, p_intf);
440 vlc_cancel(p_sys->thread);
441 vlc_join(p_sys->thread, NULL);
443 input_thread_t *p_input = pl_CurrentInput(p_intf);
446 if (p_sys->b_state_cb)
447 var_DelCallback(p_input, "intf-event", PlayingChange, p_intf);
448 vlc_object_release(p_input);
452 for (i = 0; i < p_sys->i_songs; i++)
453 DeleteSong(&p_sys->p_queue[i]);
454 vlc_UrlClean(&p_sys->p_submit_url);
456 free(p_sys->psz_nowp_host);
457 free(p_sys->psz_nowp_file);
459 vlc_cond_destroy(&p_sys->wait);
460 vlc_mutex_destroy(&p_sys->lock);
464 /*****************************************************************************
465 * Handshake : Init audioscrobbler connection
466 *****************************************************************************/
467 static int Handshake(intf_thread_t *p_this)
469 char *psz_username, *psz_password;
470 char *psz_scrobbler_url;
472 char psz_timestamp[21];
474 struct md5_s p_struct_md5;
477 char *psz_handshake_url;
478 uint8_t p_buffer[1024];
484 intf_thread_t *p_intf = (intf_thread_t*) p_this;
485 intf_sys_t *p_sys = p_this->p_sys;
487 psz_username = var_InheritString(p_this, "lastfm-username");
488 psz_password = var_InheritString(p_this, "lastfm-password");
490 /* username or password have not been setup */
491 if (EMPTY_STR(psz_username) || EMPTY_STR(psz_password))
500 /* generates a md5 hash of the password */
501 InitMD5(&p_struct_md5);
502 AddMD5(&p_struct_md5, (uint8_t*) psz_password, strlen(psz_password));
503 EndMD5(&p_struct_md5);
507 char *psz_password_md5 = psz_md5_hash(&p_struct_md5);
508 if (!psz_password_md5)
514 snprintf(psz_timestamp, sizeof(psz_timestamp), "%"PRIu64,
515 (uint64_t)timestamp);
517 /* generates a md5 hash of :
518 * - md5 hash of the password, plus
519 * - timestamp in clear text
521 InitMD5(&p_struct_md5);
522 AddMD5(&p_struct_md5, (uint8_t*) psz_password_md5, 32);
523 AddMD5(&p_struct_md5, (uint8_t*) psz_timestamp, strlen(psz_timestamp));
524 EndMD5(&p_struct_md5);
525 free(psz_password_md5);
527 char *psz_auth_token = psz_md5_hash(&p_struct_md5);
534 psz_scrobbler_url = var_InheritString(p_this, "scrobbler-url");
535 if (!psz_scrobbler_url)
537 free(psz_auth_token);
542 i_ret = asprintf(&psz_handshake_url,
543 "http://%s/?hs=true&p=1.2&c="CLIENT_NAME"&v="CLIENT_VERSION"&u=%s&t=%s&a=%s"
544 , psz_scrobbler_url, psz_username, psz_timestamp, psz_auth_token);
546 free(psz_auth_token);
547 free(psz_scrobbler_url);
552 /* send the http handshake request */
553 p_stream = stream_UrlNew(p_intf, psz_handshake_url);
554 free(psz_handshake_url);
560 i_ret = stream_Read(p_stream, p_buffer, sizeof(p_buffer) - 1);
563 stream_Delete(p_stream);
566 p_buffer[i_ret] = '\0';
567 stream_Delete(p_stream);
569 p_buffer_pos = strstr((char*) p_buffer, "FAILED ");
572 /* handshake request failed, sorry */
573 msg_Err(p_this, "last.fm handshake failed: %s", p_buffer_pos + 7);
577 if (strstr((char*) p_buffer, "BADAUTH"))
579 /* authentication failed, bad username/password combination */
581 _("last.fm: Authentication failed"),
582 "%s", _("last.fm username or password is incorrect. "
583 "Please verify your settings and relaunch VLC."));
584 return VLC_AUDIOSCROBBLER_EFATAL;
587 if (strstr((char*) p_buffer, "BANNED"))
589 /* oops, our version of vlc has been banned by last.fm servers */
590 msg_Err(p_intf, "This version of VLC has been banned by last.fm. "
591 "You should upgrade VLC, or disable the last.fm plugin.");
592 return VLC_AUDIOSCROBBLER_EFATAL;
595 if (strstr((char*) p_buffer, "BADTIME"))
597 /* The system clock isn't good */
598 msg_Err(p_intf, "last.fm handshake failed because your clock is too "
599 "much shifted. Please correct it, and relaunch VLC.");
600 return VLC_AUDIOSCROBBLER_EFATAL;
603 p_buffer_pos = strstr((char*) p_buffer, "OK");
607 p_buffer_pos = strstr(p_buffer_pos, "\n");
608 if (!p_buffer_pos || strlen(p_buffer_pos) < 33)
610 p_buffer_pos++; /* we skip the '\n' */
612 /* save the session ID */
613 memcpy(p_sys->psz_auth_token, p_buffer_pos, 32);
614 p_sys->psz_auth_token[32] = '\0';
616 p_buffer_pos = strstr(p_buffer_pos, "http://");
617 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
620 /* We need to read the nowplaying url */
621 p_buffer_pos += 7; /* we skip "http://" */
623 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
627 switch(ParseURL(psz_url, &p_sys->psz_nowp_host,
628 &p_sys->psz_nowp_file, &p_sys->i_nowp_port))
639 p_buffer_pos = strstr(p_buffer_pos, "http://");
640 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
643 /* We need to read the submission url */
644 p_buffer_pos += 7; /* we skip "http://" */
645 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
649 /* parse the submission url */
650 vlc_UrlParse(&p_sys->p_submit_url, psz_url, 0);
659 msg_Err(p_intf, "Handshake: can't recognize server protocol");
663 static void HandleInterval(mtime_t *next, unsigned int *i_interval)
665 if (*i_interval == 0)
667 /* first interval is 1 minute */
672 /* else we double the previous interval, up to 120 minutes */
674 if (*i_interval > 120)
677 *next = mdate() + (*i_interval * 1000000 * 60);
680 /*****************************************************************************
681 * Run : call Handshake() then submit songs
682 *****************************************************************************/
683 static void *Run(void *data)
685 intf_thread_t *p_intf = data;
686 uint8_t p_buffer[1024];
687 int canc = vlc_savecancel();
688 bool b_handshaked = false;
690 /* data about audioscrobbler session */
691 mtime_t next_exchange = -1; /**< when can we send data */
692 unsigned int i_interval = 0; /**< waiting interval (secs)*/
694 intf_sys_t *p_sys = p_intf->p_sys;
699 vlc_restorecancel(canc);
700 vlc_mutex_lock(&p_sys->lock);
701 mutex_cleanup_push(&p_sys->lock);
704 vlc_cond_wait(&p_sys->wait, &p_sys->lock);
705 while (mdate() < next_exchange);
708 canc = vlc_savecancel();
710 /* handshake if needed */
713 msg_Dbg(p_intf, "Handshaking with last.fm ...");
715 switch(Handshake(p_intf))
721 /* username not set */
723 _("Last.fm username not set"),
724 "%s", _("Please set a username or disable the "
725 "audioscrobbler plugin, and restart VLC.\n"
726 "Visit http://www.last.fm/join/ to get an account."));
730 msg_Dbg(p_intf, "Handshake successful :)");
733 next_exchange = mdate();
736 case VLC_AUDIOSCROBBLER_EFATAL:
737 msg_Warn(p_intf, "Exiting...");
742 /* protocol error : we'll try later */
743 HandleInterval(&next_exchange, &i_interval);
746 /* if handshake failed let's restart the loop */
751 msg_Dbg(p_intf, "Going to submit some data...");
753 if (asprintf(&psz_submit, "s=%s", p_sys->psz_auth_token) == -1)
756 /* forge the HTTP POST request */
757 vlc_mutex_lock(&p_sys->lock);
758 audioscrobbler_song_t *p_song;
759 for (int i_song = 0 ; i_song < p_sys->i_songs ; i_song++)
761 char *psz_submit_song, *psz_submit_tmp;
762 p_song = &p_sys->p_queue[i_song];
763 if (asprintf(&psz_submit_song,
773 i_song, p_song->psz_a,
774 i_song, p_song->psz_t,
775 i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
779 i_song, p_song->psz_b,
780 i_song, p_song->psz_n,
781 i_song, p_song->psz_m
783 { /* Out of memory */
784 vlc_mutex_unlock(&p_sys->lock);
787 psz_submit_tmp = psz_submit;
788 if (asprintf(&psz_submit, "%s%s",
789 psz_submit_tmp, psz_submit_song) == -1)
790 { /* Out of memory */
791 free(psz_submit_tmp);
792 free(psz_submit_song);
793 vlc_mutex_unlock(&p_sys->lock);
796 free(psz_submit_song);
797 free(psz_submit_tmp);
799 vlc_mutex_unlock(&p_sys->lock);
801 int i_post_socket = net_ConnectTCP(p_intf, p_sys->p_submit_url.psz_host,
802 p_sys->p_submit_url.i_port);
804 if (i_post_socket == -1)
806 /* If connection fails, we assume we must handshake again */
807 HandleInterval(&next_exchange, &i_interval);
808 b_handshaked = false;
813 /* we transmit the data */
814 int i_net_ret = net_Printf(p_intf, i_post_socket, NULL,
816 "Accept-Encoding: identity\n"
817 "Content-length: %zu\n"
818 "Connection: close\n"
819 "Content-type: application/x-www-form-urlencoded\n"
821 "User-agent: VLC media player/"VERSION"\r\n"
825 p_sys->p_submit_url.psz_path, strlen(psz_submit),
826 p_sys->p_submit_url.psz_host, psz_submit
832 /* If connection fails, we assume we must handshake again */
833 HandleInterval(&next_exchange, &i_interval);
834 b_handshaked = false;
838 i_net_ret = net_Read(p_intf, i_post_socket, NULL,
839 p_buffer, sizeof(p_buffer) - 1, false);
842 /* if we get no answer, something went wrong : try again */
846 net_Close(i_post_socket);
847 p_buffer[i_net_ret] = '\0';
849 char *failed = strstr((char *) p_buffer, "FAILED");
852 msg_Warn(p_intf, "%s", failed);
853 HandleInterval(&next_exchange, &i_interval);
857 if (strstr((char *) p_buffer, "BADSESSION"))
859 msg_Err(p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?");
860 b_handshaked = false;
861 HandleInterval(&next_exchange, &i_interval);
865 if (strstr((char *) p_buffer, "OK"))
867 for (int i = 0; i < p_sys->i_songs; i++)
868 DeleteSong(&p_sys->p_queue[i]);
871 next_exchange = mdate();
872 msg_Dbg(p_intf, "Submission successful!");
876 msg_Err(p_intf, "Authentication failed, handshaking again (%s)",
878 b_handshaked = false;
879 HandleInterval(&next_exchange, &i_interval);
883 vlc_restorecancel(canc);