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 #define VLC_MODULE_LICENSE VLC_LICENSE_GPL_2_PLUS
43 #include <vlc_common.h>
44 #include <vlc_plugin.h>
45 #include <vlc_interface.h>
46 #include <vlc_input.h>
47 #include <vlc_dialog.h>
50 #include <vlc_stream.h>
52 #include <vlc_network.h>
53 #include <vlc_playlist.h>
55 /*****************************************************************************
57 *****************************************************************************/
61 /* Keeps track of metadata to be submitted */
62 typedef struct audioscrobbler_song_t
64 char *psz_a; /**< track artist */
65 char *psz_t; /**< track title */
66 char *psz_b; /**< track album */
67 char *psz_n; /**< track number */
68 int i_l; /**< track length */
69 char *psz_m; /**< musicbrainz id */
70 time_t date; /**< date since epoch */
71 mtime_t i_start; /**< playing start */
72 } audioscrobbler_song_t;
76 audioscrobbler_song_t p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
77 int i_songs; /**< number of songs */
79 input_thread_t *p_input; /**< current input thread */
80 vlc_mutex_t lock; /**< p_sys mutex */
81 vlc_cond_t wait; /**< song to submit event */
82 vlc_thread_t thread; /**< thread to submit song */
84 /* submission of played songs */
85 vlc_url_t p_submit_url; /**< where to submit data */
87 /* submission of playing song */
89 char *psz_nowp_host; /**< where to submit data */
90 int i_nowp_port; /**< port to which submit */
91 char *psz_nowp_file; /**< file to which submit */
93 char psz_auth_token[33]; /**< Authentication token */
95 /* data about song currently playing */
96 audioscrobbler_song_t p_current_song; /**< song being played */
98 mtime_t time_pause; /**< time when vlc paused */
99 mtime_t time_total_pauses; /**< total time in pause */
101 bool b_submit; /**< do we have to submit ? */
103 bool b_meta_read; /**< if we read the song's
104 * metadata already */
107 static int Open (vlc_object_t *);
108 static void Close (vlc_object_t *);
109 static void *Run (void *);
111 /*****************************************************************************
113 ****************************************************************************/
115 #define USERNAME_TEXT N_("Username")
116 #define USERNAME_LONGTEXT N_("The username of your last.fm account")
117 #define PASSWORD_TEXT N_("Password")
118 #define PASSWORD_LONGTEXT N_("The password of your last.fm account")
119 #define URL_TEXT N_("Scrobbler URL")
120 #define URL_LONGTEXT N_("The URL set for an alternative scrobbler engine")
122 /* This error value is used when last.fm plugin has to be unloaded. */
123 #define VLC_AUDIOSCROBBLER_EFATAL -69
125 /* last.fm client identifier */
126 #define CLIENT_NAME PACKAGE
127 #define CLIENT_VERSION VERSION
130 set_category(CAT_INTERFACE)
131 set_subcategory(SUBCAT_INTERFACE_CONTROL)
132 set_shortname(N_("Audioscrobbler"))
133 set_description(N_("Submission of played songs to last.fm"))
134 add_string("lastfm-username", "",
135 USERNAME_TEXT, USERNAME_LONGTEXT, false)
136 add_password("lastfm-password", "",
137 PASSWORD_TEXT, PASSWORD_LONGTEXT, false)
138 add_string("scrobbler-url", "post.audioscrobbler.com",
139 URL_TEXT, URL_LONGTEXT, false)
140 set_capability("interface", 0)
141 set_callbacks(Open, Close)
144 /*****************************************************************************
145 * DeleteSong : Delete the char pointers in a song
146 *****************************************************************************/
147 static void DeleteSong(audioscrobbler_song_t* p_song)
149 FREENULL(p_song->psz_a);
150 FREENULL(p_song->psz_b);
151 FREENULL(p_song->psz_t);
152 FREENULL(p_song->psz_m);
153 FREENULL(p_song->psz_n);
156 /*****************************************************************************
157 * ReadMetaData : Read meta data when parsed by vlc
158 *****************************************************************************/
159 static void ReadMetaData(intf_thread_t *p_this, input_thread_t *p_input)
161 intf_sys_t *p_sys = p_this->p_sys;
163 assert(p_input != NULL);
165 input_item_t *p_item = input_GetItem(p_input);
169 #define ALLOC_ITEM_META(a, b) do { \
170 char *psz_meta = input_item_Get##b(p_item); \
171 if (psz_meta && *psz_meta) \
172 a = encode_URI_component(psz_meta); \
176 vlc_mutex_lock(&p_sys->lock);
178 p_sys->b_meta_read = true;
180 ALLOC_ITEM_META(p_sys->p_current_song.psz_a, Artist);
181 if (!p_sys->p_current_song.psz_a)
183 msg_Dbg(p_this, "No artist..");
184 DeleteSong(&p_sys->p_current_song);
188 ALLOC_ITEM_META(p_sys->p_current_song.psz_t, Title);
189 if (!p_sys->p_current_song.psz_t)
191 msg_Dbg(p_this, "No track name..");
192 DeleteSong(&p_sys->p_current_song);
196 /* Now we have read the mandatory meta data, so we can submit that info */
197 p_sys->b_submit = true;
199 ALLOC_ITEM_META(p_sys->p_current_song.psz_b, Album);
200 if (!p_sys->p_current_song.psz_b)
201 p_sys->p_current_song.psz_b = calloc(1, 1);
203 ALLOC_ITEM_META(p_sys->p_current_song.psz_m, TrackID);
204 if (!p_sys->p_current_song.psz_m)
205 p_sys->p_current_song.psz_m = calloc(1, 1);
207 p_sys->p_current_song.i_l = input_item_GetDuration(p_item) / 1000000;
209 ALLOC_ITEM_META(p_sys->p_current_song.psz_n, TrackNum);
210 if (!p_sys->p_current_song.psz_n)
211 p_sys->p_current_song.psz_n = calloc(1, 1);
212 #undef ALLOC_ITEM_META
214 msg_Dbg(p_this, "Meta data registered");
217 vlc_mutex_unlock(&p_sys->lock);
220 /*****************************************************************************
221 * AddToQueue: Add the played song to the queue to be submitted
222 *****************************************************************************/
223 static void AddToQueue (intf_thread_t *p_this)
226 intf_sys_t *p_sys = p_this->p_sys;
228 vlc_mutex_lock(&p_sys->lock);
229 if (!p_sys->b_submit)
232 /* wait for the user to listen enough before submitting */
233 played_time = mdate() - p_sys->p_current_song.i_start -
234 p_sys->time_total_pauses;
235 played_time /= 1000000; /* µs → s */
237 /*HACK: it seam that the preparsing sometime fail,
238 so use the playing time as the song length */
239 if (p_sys->p_current_song.i_l == 0)
240 p_sys->p_current_song.i_l = played_time;
242 /* Don't send song shorter than 30s */
243 if (p_sys->p_current_song.i_l < 30)
245 msg_Dbg(p_this, "Song too short (< 30s), not submitting");
249 /* Send if the user had listen more than 240s OR half the track length */
250 if ((played_time < 240) &&
251 (played_time < (p_sys->p_current_song.i_l / 2)))
253 msg_Dbg(p_this, "Song not listened long enough, not submitting");
257 /* Check that all meta are present */
258 if (!p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
259 !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t)
261 msg_Dbg(p_this, "Missing artist or title, not submitting");
265 if (p_sys->i_songs >= QUEUE_MAX)
267 msg_Warn(p_this, "Submission queue is full, not submitting");
271 msg_Dbg(p_this, "Song will be submitted.");
273 #define QUEUE_COPY(a) \
274 p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
276 #define QUEUE_COPY_NULL(a) \
278 p_sys->p_current_song.a = NULL
281 QUEUE_COPY_NULL(psz_n);
282 QUEUE_COPY_NULL(psz_a);
283 QUEUE_COPY_NULL(psz_t);
284 QUEUE_COPY_NULL(psz_b);
285 QUEUE_COPY_NULL(psz_m);
287 #undef QUEUE_COPY_NULL
292 /* signal the main loop we have something to submit */
293 vlc_cond_signal(&p_sys->wait);
296 DeleteSong(&p_sys->p_current_song);
297 p_sys->b_submit = false;
298 vlc_mutex_unlock(&p_sys->lock);
301 /*****************************************************************************
302 * PlayingChange: Playing status change callback
303 *****************************************************************************/
304 static int PlayingChange(vlc_object_t *p_this, const char *psz_var,
305 vlc_value_t oldval, vlc_value_t newval, void *p_data)
309 intf_thread_t *p_intf = (intf_thread_t*) p_data;
310 intf_sys_t *p_sys = p_intf->p_sys;
311 input_thread_t *p_input = (input_thread_t*)p_this;
316 if (newval.i_int != INPUT_EVENT_STATE) return VLC_SUCCESS;
318 if (var_CountChoices(p_input, "video-es"))
320 msg_Dbg(p_this, "Not an audio-only input, not submitting");
324 state = var_GetInteger(p_input, "state");
326 if (!p_sys->b_meta_read && state >= PLAYING_S)
328 ReadMetaData(p_intf, p_input);
335 else if (state == PAUSE_S)
336 p_sys->time_pause = mdate();
337 else if (p_sys->time_pause > 0 && state == PLAYING_S)
339 p_sys->time_total_pauses += (mdate() - p_sys->time_pause);
340 p_sys->time_pause = 0;
346 /*****************************************************************************
347 * ItemChange: Playlist item change callback
348 *****************************************************************************/
349 static int ItemChange(vlc_object_t *p_this, const char *psz_var,
350 vlc_value_t oldval, vlc_value_t newval, void *p_data)
352 intf_thread_t *p_intf = p_data;
353 intf_sys_t *p_sys = p_intf->p_sys;
354 input_thread_t *p_input = newval.p_address;
356 VLC_UNUSED(p_this); VLC_UNUSED(psz_var);
359 p_sys->b_meta_read = false;
360 p_sys->b_submit = false;
362 if (p_sys->p_input != NULL)
364 var_DelCallback(p_sys->p_input, "intf-event", PlayingChange, p_intf);
365 vlc_object_release(p_sys->p_input);
366 p_sys->p_input = NULL;
372 input_item_t *p_item = input_GetItem(p_input);
376 if (var_CountChoices(p_input, "video-es"))
378 msg_Dbg(p_this, "Not an audio-only input, not submitting");
382 p_sys->time_total_pauses = 0;
383 time(&p_sys->p_current_song.date); /* to be sent to last.fm */
384 p_sys->p_current_song.i_start = mdate(); /* only used locally */
386 p_sys->p_input = vlc_object_hold(p_input);
387 var_AddCallback(p_input, "intf-event", PlayingChange, p_intf);
389 if (input_item_IsPreparsed(p_item))
390 ReadMetaData(p_intf, p_input);
391 /* if the input item was not preparsed, we'll do it in PlayingChange()
392 * callback, when "state" == PLAYING_S */
397 /*****************************************************************************
398 * Open: initialize and create stuff
399 *****************************************************************************/
400 static int Open(vlc_object_t *p_this)
402 intf_thread_t *p_intf = (intf_thread_t*) p_this;
403 intf_sys_t *p_sys = calloc(1, sizeof(intf_sys_t));
408 p_intf->p_sys = p_sys;
410 vlc_mutex_init(&p_sys->lock);
411 vlc_cond_init(&p_sys->wait);
413 if (vlc_clone(&p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW))
415 vlc_cond_destroy(&p_sys->wait);
416 vlc_mutex_destroy(&p_sys->lock);
421 var_AddCallback(pl_Get(p_intf), "input-current", ItemChange, p_intf);
426 /*****************************************************************************
427 * Close: destroy interface stuff
428 *****************************************************************************/
429 static void Close(vlc_object_t *p_this)
431 intf_thread_t *p_intf = (intf_thread_t*) p_this;
432 intf_sys_t *p_sys = p_intf->p_sys;
434 vlc_cancel(p_sys->thread);
435 vlc_join(p_sys->thread, NULL);
437 var_DelCallback(pl_Get(p_intf), "input-current", ItemChange, p_intf);
439 if (p_sys->p_input != NULL)
441 var_DelCallback(p_sys->p_input, "intf-event", PlayingChange, p_intf);
442 vlc_object_release(p_sys->p_input);
446 for (i = 0; i < p_sys->i_songs; i++)
447 DeleteSong(&p_sys->p_queue[i]);
448 vlc_UrlClean(&p_sys->p_submit_url);
450 free(p_sys->psz_nowp_host);
451 free(p_sys->psz_nowp_file);
453 vlc_cond_destroy(&p_sys->wait);
454 vlc_mutex_destroy(&p_sys->lock);
458 /*****************************************************************************
459 * Handshake : Init audioscrobbler connection
460 *****************************************************************************/
461 static int Handshake(intf_thread_t *p_this)
463 char *psz_username, *psz_password;
464 char *psz_scrobbler_url;
466 char psz_timestamp[21];
468 struct md5_s p_struct_md5;
471 char *psz_handshake_url;
472 uint8_t p_buffer[1024];
478 intf_thread_t *p_intf = (intf_thread_t*) p_this;
479 intf_sys_t *p_sys = p_this->p_sys;
481 psz_username = var_InheritString(p_this, "lastfm-username");
482 psz_password = var_InheritString(p_this, "lastfm-password");
484 /* username or password have not been setup */
485 if (EMPTY_STR(psz_username) || EMPTY_STR(psz_password))
494 /* generates a md5 hash of the password */
495 InitMD5(&p_struct_md5);
496 AddMD5(&p_struct_md5, (uint8_t*) psz_password, strlen(psz_password));
497 EndMD5(&p_struct_md5);
501 char *psz_password_md5 = psz_md5_hash(&p_struct_md5);
502 if (!psz_password_md5)
508 snprintf(psz_timestamp, sizeof(psz_timestamp), "%"PRIu64,
509 (uint64_t)timestamp);
511 /* generates a md5 hash of :
512 * - md5 hash of the password, plus
513 * - timestamp in clear text
515 InitMD5(&p_struct_md5);
516 AddMD5(&p_struct_md5, (uint8_t*) psz_password_md5, 32);
517 AddMD5(&p_struct_md5, (uint8_t*) psz_timestamp, strlen(psz_timestamp));
518 EndMD5(&p_struct_md5);
519 free(psz_password_md5);
521 char *psz_auth_token = psz_md5_hash(&p_struct_md5);
528 psz_scrobbler_url = var_InheritString(p_this, "scrobbler-url");
529 if (!psz_scrobbler_url)
531 free(psz_auth_token);
536 i_ret = asprintf(&psz_handshake_url,
537 "http://%s/?hs=true&p=1.2&c="CLIENT_NAME"&v="CLIENT_VERSION"&u=%s&t=%s&a=%s"
538 , psz_scrobbler_url, psz_username, psz_timestamp, psz_auth_token);
540 free(psz_auth_token);
541 free(psz_scrobbler_url);
546 /* send the http handshake request */
547 p_stream = stream_UrlNew(p_intf, psz_handshake_url);
548 free(psz_handshake_url);
554 i_ret = stream_Read(p_stream, p_buffer, sizeof(p_buffer) - 1);
557 stream_Delete(p_stream);
560 p_buffer[i_ret] = '\0';
561 stream_Delete(p_stream);
563 p_buffer_pos = strstr((char*) p_buffer, "FAILED ");
566 /* handshake request failed, sorry */
567 msg_Err(p_this, "last.fm handshake failed: %s", p_buffer_pos + 7);
571 if (strstr((char*) p_buffer, "BADAUTH"))
573 /* authentication failed, bad username/password combination */
575 _("last.fm: Authentication failed"),
576 "%s", _("last.fm username or password is incorrect. "
577 "Please verify your settings and relaunch VLC."));
578 return VLC_AUDIOSCROBBLER_EFATAL;
581 if (strstr((char*) p_buffer, "BANNED"))
583 /* oops, our version of vlc has been banned by last.fm servers */
584 msg_Err(p_intf, "This version of VLC has been banned by last.fm. "
585 "You should upgrade VLC, or disable the last.fm plugin.");
586 return VLC_AUDIOSCROBBLER_EFATAL;
589 if (strstr((char*) p_buffer, "BADTIME"))
591 /* The system clock isn't good */
592 msg_Err(p_intf, "last.fm handshake failed because your clock is too "
593 "much shifted. Please correct it, and relaunch VLC.");
594 return VLC_AUDIOSCROBBLER_EFATAL;
597 p_buffer_pos = strstr((char*) p_buffer, "OK");
601 p_buffer_pos = strstr(p_buffer_pos, "\n");
602 if (!p_buffer_pos || strlen(p_buffer_pos) < 33)
604 p_buffer_pos++; /* we skip the '\n' */
606 /* save the session ID */
607 memcpy(p_sys->psz_auth_token, p_buffer_pos, 32);
608 p_sys->psz_auth_token[32] = '\0';
610 p_buffer_pos = strstr(p_buffer_pos, "http://");
611 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
614 /* We need to read the nowplaying url */
615 p_buffer_pos += 7; /* we skip "http://" */
617 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
621 switch(ParseURL(psz_url, &p_sys->psz_nowp_host,
622 &p_sys->psz_nowp_file, &p_sys->i_nowp_port))
633 p_buffer_pos = strstr(p_buffer_pos, "http://");
634 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
637 /* We need to read the submission url */
638 p_buffer_pos += 7; /* we skip "http://" */
639 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
643 /* parse the submission url */
644 vlc_UrlParse(&p_sys->p_submit_url, psz_url, 0);
653 msg_Err(p_intf, "Handshake: can't recognize server protocol");
657 static void HandleInterval(mtime_t *next, unsigned int *i_interval)
659 if (*i_interval == 0)
661 /* first interval is 1 minute */
666 /* else we double the previous interval, up to 120 minutes */
668 if (*i_interval > 120)
671 *next = mdate() + (*i_interval * 1000000 * 60);
674 /*****************************************************************************
675 * Run : call Handshake() then submit songs
676 *****************************************************************************/
677 static void *Run(void *data)
679 intf_thread_t *p_intf = data;
680 uint8_t p_buffer[1024];
681 int canc = vlc_savecancel();
682 bool b_handshaked = false;
684 /* data about audioscrobbler session */
685 mtime_t next_exchange = -1; /**< when can we send data */
686 unsigned int i_interval = 0; /**< waiting interval (secs)*/
688 intf_sys_t *p_sys = p_intf->p_sys;
693 vlc_restorecancel(canc);
694 vlc_mutex_lock(&p_sys->lock);
695 mutex_cleanup_push(&p_sys->lock);
698 vlc_cond_wait(&p_sys->wait, &p_sys->lock);
699 while (mdate() < next_exchange);
702 canc = vlc_savecancel();
704 /* handshake if needed */
707 msg_Dbg(p_intf, "Handshaking with last.fm ...");
709 switch(Handshake(p_intf))
715 /* username not set */
717 _("Last.fm username not set"),
718 "%s", _("Please set a username or disable the "
719 "audioscrobbler plugin, and restart VLC.\n"
720 "Visit http://www.last.fm/join/ to get an account."));
724 msg_Dbg(p_intf, "Handshake successful :)");
727 next_exchange = mdate();
730 case VLC_AUDIOSCROBBLER_EFATAL:
731 msg_Warn(p_intf, "Exiting...");
736 /* protocol error : we'll try later */
737 HandleInterval(&next_exchange, &i_interval);
740 /* if handshake failed let's restart the loop */
745 msg_Dbg(p_intf, "Going to submit some data...");
747 if (asprintf(&psz_submit, "s=%s", p_sys->psz_auth_token) == -1)
750 /* forge the HTTP POST request */
751 vlc_mutex_lock(&p_sys->lock);
752 audioscrobbler_song_t *p_song;
753 for (int i_song = 0 ; i_song < p_sys->i_songs ; i_song++)
755 char *psz_submit_song, *psz_submit_tmp;
756 p_song = &p_sys->p_queue[i_song];
757 if (asprintf(&psz_submit_song,
767 i_song, p_song->psz_a,
768 i_song, p_song->psz_t,
769 i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
773 i_song, p_song->psz_b,
774 i_song, p_song->psz_n,
775 i_song, p_song->psz_m
777 { /* Out of memory */
778 vlc_mutex_unlock(&p_sys->lock);
781 psz_submit_tmp = psz_submit;
782 if (asprintf(&psz_submit, "%s%s",
783 psz_submit_tmp, psz_submit_song) == -1)
784 { /* Out of memory */
785 free(psz_submit_tmp);
786 free(psz_submit_song);
787 vlc_mutex_unlock(&p_sys->lock);
790 free(psz_submit_song);
791 free(psz_submit_tmp);
793 vlc_mutex_unlock(&p_sys->lock);
795 int i_post_socket = net_ConnectTCP(p_intf, p_sys->p_submit_url.psz_host,
796 p_sys->p_submit_url.i_port);
798 if (i_post_socket == -1)
800 /* If connection fails, we assume we must handshake again */
801 HandleInterval(&next_exchange, &i_interval);
802 b_handshaked = false;
807 /* we transmit the data */
808 int i_net_ret = net_Printf(p_intf, i_post_socket, NULL,
810 "Accept-Encoding: identity\n"
811 "Content-length: %zu\n"
812 "Connection: close\n"
813 "Content-type: application/x-www-form-urlencoded\n"
815 "User-agent: VLC media player/"VERSION"\r\n"
819 p_sys->p_submit_url.psz_path, strlen(psz_submit),
820 p_sys->p_submit_url.psz_host, psz_submit
826 /* If connection fails, we assume we must handshake again */
827 HandleInterval(&next_exchange, &i_interval);
828 b_handshaked = false;
832 i_net_ret = net_Read(p_intf, i_post_socket, NULL,
833 p_buffer, sizeof(p_buffer) - 1, false);
836 /* if we get no answer, something went wrong : try again */
840 net_Close(i_post_socket);
841 p_buffer[i_net_ret] = '\0';
843 char *failed = strstr((char *) p_buffer, "FAILED");
846 msg_Warn(p_intf, "%s", failed);
847 HandleInterval(&next_exchange, &i_interval);
851 if (strstr((char *) p_buffer, "BADSESSION"))
853 msg_Err(p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?");
854 b_handshaked = false;
855 HandleInterval(&next_exchange, &i_interval);
859 if (strstr((char *) p_buffer, "OK"))
861 for (int i = 0; i < p_sys->i_songs; i++)
862 DeleteSong(&p_sys->p_queue[i]);
865 next_exchange = mdate();
866 msg_Dbg(p_intf, "Submission successful!");
870 msg_Err(p_intf, "Authentication failed, handshaking again (%s)",
872 b_handshaked = false;
873 HandleInterval(&next_exchange, &i_interval);
877 vlc_restorecancel(canc);