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 *****************************************************************************/
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_interface.h>
45 #include <vlc_input.h>
46 #include <vlc_dialog.h>
49 #include <vlc_stream.h>
51 #include <vlc_network.h>
52 #include <vlc_playlist.h>
54 /*****************************************************************************
56 *****************************************************************************/
60 /* Keeps track of metadata to be submitted */
61 typedef struct audioscrobbler_song_t
63 char *psz_a; /**< track artist */
64 char *psz_t; /**< track title */
65 char *psz_b; /**< track album */
66 char *psz_n; /**< track number */
67 int i_l; /**< track length */
68 char *psz_m; /**< musicbrainz id */
69 time_t date; /**< date since epoch */
70 mtime_t i_start; /**< playing start */
71 } audioscrobbler_song_t;
75 audioscrobbler_song_t p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
76 int i_songs; /**< number of songs */
78 input_thread_t *p_input; /**< current input thread */
79 vlc_mutex_t lock; /**< p_sys mutex */
80 vlc_cond_t wait; /**< song to submit event */
81 vlc_thread_t thread; /**< thread to submit song */
83 /* submission of played songs */
84 vlc_url_t p_submit_url; /**< where to submit data */
86 /* submission of playing song */
88 char *psz_nowp_host; /**< where to submit data */
89 int i_nowp_port; /**< port to which submit */
90 char *psz_nowp_file; /**< file to which submit */
92 char psz_auth_token[33]; /**< Authentication token */
94 /* data about song currently playing */
95 audioscrobbler_song_t p_current_song; /**< song being played */
97 mtime_t time_pause; /**< time when vlc paused */
98 mtime_t time_total_pauses; /**< total time in pause */
100 bool b_submit; /**< do we have to submit ? */
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, input_thread_t *p_input)
160 intf_sys_t *p_sys = p_this->p_sys;
162 assert(p_input != NULL);
164 input_item_t *p_item = input_GetItem(p_input);
168 #define ALLOC_ITEM_META(a, b) do { \
169 char *psz_meta = input_item_Get##b(p_item); \
170 if (psz_meta && *psz_meta) \
171 a = encode_URI_component(psz_meta); \
175 vlc_mutex_lock(&p_sys->lock);
177 p_sys->b_meta_read = true;
179 ALLOC_ITEM_META(p_sys->p_current_song.psz_a, Artist);
180 if (!p_sys->p_current_song.psz_a)
182 msg_Dbg(p_this, "No artist..");
183 DeleteSong(&p_sys->p_current_song);
187 ALLOC_ITEM_META(p_sys->p_current_song.psz_t, Title);
188 if (!p_sys->p_current_song.psz_t)
190 msg_Dbg(p_this, "No track name..");
191 DeleteSong(&p_sys->p_current_song);
195 /* Now we have read the mandatory meta data, so we can submit that info */
196 p_sys->b_submit = true;
198 ALLOC_ITEM_META(p_sys->p_current_song.psz_b, Album);
199 if (!p_sys->p_current_song.psz_b)
200 p_sys->p_current_song.psz_b = calloc(1, 1);
202 ALLOC_ITEM_META(p_sys->p_current_song.psz_m, TrackID);
203 if (!p_sys->p_current_song.psz_m)
204 p_sys->p_current_song.psz_m = calloc(1, 1);
206 p_sys->p_current_song.i_l = input_item_GetDuration(p_item) / 1000000;
208 ALLOC_ITEM_META(p_sys->p_current_song.psz_n, TrackNum);
209 if (!p_sys->p_current_song.psz_n)
210 p_sys->p_current_song.psz_n = calloc(1, 1);
211 #undef ALLOC_ITEM_META
213 msg_Dbg(p_this, "Meta data registered");
216 vlc_mutex_unlock(&p_sys->lock);
219 /*****************************************************************************
220 * AddToQueue: Add the played song to the queue to be submitted
221 *****************************************************************************/
222 static void AddToQueue (intf_thread_t *p_this)
225 intf_sys_t *p_sys = p_this->p_sys;
227 vlc_mutex_lock(&p_sys->lock);
228 if (!p_sys->b_submit)
231 /* wait for the user to listen enough before submitting */
232 played_time = mdate() - p_sys->p_current_song.i_start -
233 p_sys->time_total_pauses;
234 played_time /= 1000000; /* µs → s */
236 /*HACK: it seam that the preparsing sometime fail,
237 so use the playing time as the song length */
238 if (p_sys->p_current_song.i_l == 0)
239 p_sys->p_current_song.i_l = played_time;
241 /* Don't send song shorter than 30s */
242 if (p_sys->p_current_song.i_l < 30)
244 msg_Dbg(p_this, "Song too short (< 30s), not submitting");
248 /* Send if the user had listen more than 240s OR half the track length */
249 if ((played_time < 240) &&
250 (played_time < (p_sys->p_current_song.i_l / 2)))
252 msg_Dbg(p_this, "Song not listened long enough, not submitting");
256 /* Check that all meta are present */
257 if (!p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
258 !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t)
260 msg_Dbg(p_this, "Missing artist or title, not submitting");
264 if (p_sys->i_songs >= QUEUE_MAX)
266 msg_Warn(p_this, "Submission queue is full, not submitting");
270 msg_Dbg(p_this, "Song will be submitted.");
272 #define QUEUE_COPY(a) \
273 p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
275 #define QUEUE_COPY_NULL(a) \
277 p_sys->p_current_song.a = NULL
280 QUEUE_COPY_NULL(psz_n);
281 QUEUE_COPY_NULL(psz_a);
282 QUEUE_COPY_NULL(psz_t);
283 QUEUE_COPY_NULL(psz_b);
284 QUEUE_COPY_NULL(psz_m);
286 #undef QUEUE_COPY_NULL
291 /* signal the main loop we have something to submit */
292 vlc_cond_signal(&p_sys->wait);
295 DeleteSong(&p_sys->p_current_song);
296 p_sys->b_submit = false;
297 vlc_mutex_unlock(&p_sys->lock);
300 /*****************************************************************************
301 * PlayingChange: Playing status change callback
302 *****************************************************************************/
303 static int PlayingChange(vlc_object_t *p_this, const char *psz_var,
304 vlc_value_t oldval, vlc_value_t newval, void *p_data)
308 intf_thread_t *p_intf = (intf_thread_t*) p_data;
309 intf_sys_t *p_sys = p_intf->p_sys;
310 input_thread_t *p_input = (input_thread_t*)p_this;
315 if (newval.i_int != INPUT_EVENT_STATE) return VLC_SUCCESS;
317 if (var_CountChoices(p_input, "video-es"))
319 msg_Dbg(p_this, "Not an audio-only input, not submitting");
323 state = var_GetInteger(p_input, "state");
325 if (!p_sys->b_meta_read && state >= PLAYING_S)
327 ReadMetaData(p_intf, p_input);
334 else if (state == PAUSE_S)
335 p_sys->time_pause = mdate();
336 else if (p_sys->time_pause > 0 && state == PLAYING_S)
338 p_sys->time_total_pauses += (mdate() - p_sys->time_pause);
339 p_sys->time_pause = 0;
345 /*****************************************************************************
346 * ItemChange: Playlist item change callback
347 *****************************************************************************/
348 static int ItemChange(vlc_object_t *p_this, const char *psz_var,
349 vlc_value_t oldval, vlc_value_t newval, void *p_data)
351 intf_thread_t *p_intf = p_data;
352 intf_sys_t *p_sys = p_intf->p_sys;
353 input_thread_t *p_input = newval.p_address;
355 VLC_UNUSED(p_this); VLC_UNUSED(psz_var);
358 p_sys->b_meta_read = false;
359 p_sys->b_submit = false;
361 if (p_sys->p_input != NULL)
363 var_DelCallback(p_sys->p_input, "intf-event", PlayingChange, p_intf);
364 vlc_object_release(p_sys->p_input);
365 p_sys->p_input = NULL;
371 input_item_t *p_item = input_GetItem(p_input);
375 if (var_CountChoices(p_input, "video-es"))
377 msg_Dbg(p_this, "Not an audio-only input, not submitting");
381 p_sys->time_total_pauses = 0;
382 time(&p_sys->p_current_song.date); /* to be sent to last.fm */
383 p_sys->p_current_song.i_start = mdate(); /* only used locally */
385 p_sys->p_input = vlc_object_hold(p_input);
386 var_AddCallback(p_input, "intf-event", PlayingChange, p_intf);
388 if (input_item_IsPreparsed(p_item))
389 ReadMetaData(p_intf, p_input);
390 /* if the input item was not preparsed, we'll do it in PlayingChange()
391 * callback, when "state" == PLAYING_S */
396 /*****************************************************************************
397 * Open: initialize and create stuff
398 *****************************************************************************/
399 static int Open(vlc_object_t *p_this)
401 intf_thread_t *p_intf = (intf_thread_t*) p_this;
402 intf_sys_t *p_sys = calloc(1, sizeof(intf_sys_t));
407 p_intf->p_sys = p_sys;
409 vlc_mutex_init(&p_sys->lock);
410 vlc_cond_init(&p_sys->wait);
412 if (vlc_clone(&p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW))
414 vlc_cond_destroy(&p_sys->wait);
415 vlc_mutex_destroy(&p_sys->lock);
420 var_AddCallback(pl_Get(p_intf), "input-current", ItemChange, p_intf);
425 /*****************************************************************************
426 * Close: destroy interface stuff
427 *****************************************************************************/
428 static void Close(vlc_object_t *p_this)
430 intf_thread_t *p_intf = (intf_thread_t*) p_this;
431 intf_sys_t *p_sys = p_intf->p_sys;
433 vlc_cancel(p_sys->thread);
434 vlc_join(p_sys->thread, NULL);
436 var_DelCallback(pl_Get(p_intf), "input-current", ItemChange, p_intf);
438 if (p_sys->p_input != NULL)
440 var_DelCallback(p_sys->p_input, "intf-event", PlayingChange, p_intf);
441 vlc_object_release(p_sys->p_input);
445 for (i = 0; i < p_sys->i_songs; i++)
446 DeleteSong(&p_sys->p_queue[i]);
447 vlc_UrlClean(&p_sys->p_submit_url);
449 free(p_sys->psz_nowp_host);
450 free(p_sys->psz_nowp_file);
452 vlc_cond_destroy(&p_sys->wait);
453 vlc_mutex_destroy(&p_sys->lock);
457 /*****************************************************************************
458 * Handshake : Init audioscrobbler connection
459 *****************************************************************************/
460 static int Handshake(intf_thread_t *p_this)
462 char *psz_username, *psz_password;
463 char *psz_scrobbler_url;
465 char psz_timestamp[21];
467 struct md5_s p_struct_md5;
470 char *psz_handshake_url;
471 uint8_t p_buffer[1024];
477 intf_thread_t *p_intf = (intf_thread_t*) p_this;
478 intf_sys_t *p_sys = p_this->p_sys;
480 psz_username = var_InheritString(p_this, "lastfm-username");
481 psz_password = var_InheritString(p_this, "lastfm-password");
483 /* username or password have not been setup */
484 if (EMPTY_STR(psz_username) || EMPTY_STR(psz_password))
493 /* generates a md5 hash of the password */
494 InitMD5(&p_struct_md5);
495 AddMD5(&p_struct_md5, (uint8_t*) psz_password, strlen(psz_password));
496 EndMD5(&p_struct_md5);
500 char *psz_password_md5 = psz_md5_hash(&p_struct_md5);
501 if (!psz_password_md5)
507 snprintf(psz_timestamp, sizeof(psz_timestamp), "%"PRIu64,
508 (uint64_t)timestamp);
510 /* generates a md5 hash of :
511 * - md5 hash of the password, plus
512 * - timestamp in clear text
514 InitMD5(&p_struct_md5);
515 AddMD5(&p_struct_md5, (uint8_t*) psz_password_md5, 32);
516 AddMD5(&p_struct_md5, (uint8_t*) psz_timestamp, strlen(psz_timestamp));
517 EndMD5(&p_struct_md5);
518 free(psz_password_md5);
520 char *psz_auth_token = psz_md5_hash(&p_struct_md5);
527 psz_scrobbler_url = var_InheritString(p_this, "scrobbler-url");
528 if (!psz_scrobbler_url)
530 free(psz_auth_token);
535 i_ret = asprintf(&psz_handshake_url,
536 "http://%s/?hs=true&p=1.2&c="CLIENT_NAME"&v="CLIENT_VERSION"&u=%s&t=%s&a=%s"
537 , psz_scrobbler_url, psz_username, psz_timestamp, psz_auth_token);
539 free(psz_auth_token);
540 free(psz_scrobbler_url);
545 /* send the http handshake request */
546 p_stream = stream_UrlNew(p_intf, psz_handshake_url);
547 free(psz_handshake_url);
553 i_ret = stream_Read(p_stream, p_buffer, sizeof(p_buffer) - 1);
556 stream_Delete(p_stream);
559 p_buffer[i_ret] = '\0';
560 stream_Delete(p_stream);
562 p_buffer_pos = strstr((char*) p_buffer, "FAILED ");
565 /* handshake request failed, sorry */
566 msg_Err(p_this, "last.fm handshake failed: %s", p_buffer_pos + 7);
570 if (strstr((char*) p_buffer, "BADAUTH"))
572 /* authentication failed, bad username/password combination */
574 _("last.fm: Authentication failed"),
575 "%s", _("last.fm username or password is incorrect. "
576 "Please verify your settings and relaunch VLC."));
577 return VLC_AUDIOSCROBBLER_EFATAL;
580 if (strstr((char*) p_buffer, "BANNED"))
582 /* oops, our version of vlc has been banned by last.fm servers */
583 msg_Err(p_intf, "This version of VLC has been banned by last.fm. "
584 "You should upgrade VLC, or disable the last.fm plugin.");
585 return VLC_AUDIOSCROBBLER_EFATAL;
588 if (strstr((char*) p_buffer, "BADTIME"))
590 /* The system clock isn't good */
591 msg_Err(p_intf, "last.fm handshake failed because your clock is too "
592 "much shifted. Please correct it, and relaunch VLC.");
593 return VLC_AUDIOSCROBBLER_EFATAL;
596 p_buffer_pos = strstr((char*) p_buffer, "OK");
600 p_buffer_pos = strstr(p_buffer_pos, "\n");
601 if (!p_buffer_pos || strlen(p_buffer_pos) < 33)
603 p_buffer_pos++; /* we skip the '\n' */
605 /* save the session ID */
606 memcpy(p_sys->psz_auth_token, p_buffer_pos, 32);
607 p_sys->psz_auth_token[32] = '\0';
609 p_buffer_pos = strstr(p_buffer_pos, "http://");
610 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
613 /* We need to read the nowplaying url */
614 p_buffer_pos += 7; /* we skip "http://" */
616 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
620 switch(ParseURL(psz_url, &p_sys->psz_nowp_host,
621 &p_sys->psz_nowp_file, &p_sys->i_nowp_port))
632 p_buffer_pos = strstr(p_buffer_pos, "http://");
633 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
636 /* We need to read the submission url */
637 p_buffer_pos += 7; /* we skip "http://" */
638 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
642 /* parse the submission url */
643 vlc_UrlParse(&p_sys->p_submit_url, psz_url, 0);
652 msg_Err(p_intf, "Handshake: can't recognize server protocol");
656 static void HandleInterval(mtime_t *next, unsigned int *i_interval)
658 if (*i_interval == 0)
660 /* first interval is 1 minute */
665 /* else we double the previous interval, up to 120 minutes */
667 if (*i_interval > 120)
670 *next = mdate() + (*i_interval * 1000000 * 60);
673 /*****************************************************************************
674 * Run : call Handshake() then submit songs
675 *****************************************************************************/
676 static void *Run(void *data)
678 intf_thread_t *p_intf = data;
679 uint8_t p_buffer[1024];
680 int canc = vlc_savecancel();
681 bool b_handshaked = false;
683 /* data about audioscrobbler session */
684 mtime_t next_exchange = -1; /**< when can we send data */
685 unsigned int i_interval = 0; /**< waiting interval (secs)*/
687 intf_sys_t *p_sys = p_intf->p_sys;
692 vlc_restorecancel(canc);
693 vlc_mutex_lock(&p_sys->lock);
694 mutex_cleanup_push(&p_sys->lock);
697 vlc_cond_wait(&p_sys->wait, &p_sys->lock);
698 while (mdate() < next_exchange);
701 canc = vlc_savecancel();
703 /* handshake if needed */
706 msg_Dbg(p_intf, "Handshaking with last.fm ...");
708 switch(Handshake(p_intf))
714 /* username not set */
716 _("Last.fm username not set"),
717 "%s", _("Please set a username or disable the "
718 "audioscrobbler plugin, and restart VLC.\n"
719 "Visit http://www.last.fm/join/ to get an account."));
723 msg_Dbg(p_intf, "Handshake successful :)");
726 next_exchange = mdate();
729 case VLC_AUDIOSCROBBLER_EFATAL:
730 msg_Warn(p_intf, "Exiting...");
735 /* protocol error : we'll try later */
736 HandleInterval(&next_exchange, &i_interval);
739 /* if handshake failed let's restart the loop */
744 msg_Dbg(p_intf, "Going to submit some data...");
746 if (asprintf(&psz_submit, "s=%s", p_sys->psz_auth_token) == -1)
749 /* forge the HTTP POST request */
750 vlc_mutex_lock(&p_sys->lock);
751 audioscrobbler_song_t *p_song;
752 for (int i_song = 0 ; i_song < p_sys->i_songs ; i_song++)
754 char *psz_submit_song, *psz_submit_tmp;
755 p_song = &p_sys->p_queue[i_song];
756 if (asprintf(&psz_submit_song,
766 i_song, p_song->psz_a,
767 i_song, p_song->psz_t,
768 i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
772 i_song, p_song->psz_b,
773 i_song, p_song->psz_n,
774 i_song, p_song->psz_m
776 { /* Out of memory */
777 vlc_mutex_unlock(&p_sys->lock);
780 psz_submit_tmp = psz_submit;
781 if (asprintf(&psz_submit, "%s%s",
782 psz_submit_tmp, psz_submit_song) == -1)
783 { /* Out of memory */
784 free(psz_submit_tmp);
785 free(psz_submit_song);
786 vlc_mutex_unlock(&p_sys->lock);
789 free(psz_submit_song);
790 free(psz_submit_tmp);
792 vlc_mutex_unlock(&p_sys->lock);
794 int i_post_socket = net_ConnectTCP(p_intf, p_sys->p_submit_url.psz_host,
795 p_sys->p_submit_url.i_port);
797 if (i_post_socket == -1)
799 /* If connection fails, we assume we must handshake again */
800 HandleInterval(&next_exchange, &i_interval);
801 b_handshaked = false;
806 /* we transmit the data */
807 int i_net_ret = net_Printf(p_intf, i_post_socket, NULL,
809 "Accept-Encoding: identity\n"
810 "Content-length: %zu\n"
811 "Connection: close\n"
812 "Content-type: application/x-www-form-urlencoded\n"
814 "User-agent: VLC media player/"VERSION"\r\n"
818 p_sys->p_submit_url.psz_path, strlen(psz_submit),
819 p_sys->p_submit_url.psz_host, psz_submit
825 /* If connection fails, we assume we must handshake again */
826 HandleInterval(&next_exchange, &i_interval);
827 b_handshaked = false;
831 i_net_ret = net_Read(p_intf, i_post_socket, NULL,
832 p_buffer, sizeof(p_buffer) - 1, false);
835 /* if we get no answer, something went wrong : try again */
839 net_Close(i_post_socket);
840 p_buffer[i_net_ret] = '\0';
842 char *failed = strstr((char *) p_buffer, "FAILED");
845 msg_Warn(p_intf, "%s", failed);
846 HandleInterval(&next_exchange, &i_interval);
850 if (strstr((char *) p_buffer, "BADSESSION"))
852 msg_Err(p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?");
853 b_handshaked = false;
854 HandleInterval(&next_exchange, &i_interval);
858 if (strstr((char *) p_buffer, "OK"))
860 for (int i = 0; i < p_sys->i_songs; i++)
861 DeleteSong(&p_sys->p_queue[i]);
864 next_exchange = mdate();
865 msg_Dbg(p_intf, "Submission successful!");
869 msg_Err(p_intf, "Authentication failed, handshaking again (%s)",
871 b_handshaked = false;
872 HandleInterval(&next_exchange, &i_interval);
876 vlc_restorecancel(canc);